From 2739b66bdcf217f307310834558ecae4a13bcfd8 Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" Date: Wed, 27 Nov 2024 09:52:32 +0000 Subject: [PATCH] Add bundled code --- PR-259/COMMITHASH | 1 + PR-259/VERSION | 1 + PR-259/index.html | 30 + PR-259/lib/lightning-inspect.js | 866 + PR-259/main.bundle.72a56dd50d203bd4c160.js | 195609 +++++++++++++++ ...rtupScripts.bundle.72a56dd50d203bd4c160.js | 173 + 6 files changed, 196680 insertions(+) create mode 100644 PR-259/COMMITHASH create mode 100644 PR-259/VERSION create mode 100644 PR-259/index.html create mode 100644 PR-259/lib/lightning-inspect.js create mode 100644 PR-259/main.bundle.72a56dd50d203bd4c160.js create mode 100644 PR-259/startupScripts.bundle.72a56dd50d203bd4c160.js diff --git a/PR-259/COMMITHASH b/PR-259/COMMITHASH new file mode 100644 index 00000000..a0c6e347 --- /dev/null +++ b/PR-259/COMMITHASH @@ -0,0 +1 @@ +96c9249601b5e2f8a58f59309f3deadd7cdc8692 \ No newline at end of file diff --git a/PR-259/VERSION b/PR-259/VERSION new file mode 100644 index 00000000..b1c725df --- /dev/null +++ b/PR-259/VERSION @@ -0,0 +1 @@ +96c9249 \ No newline at end of file diff --git a/PR-259/index.html b/PR-259/index.html new file mode 100644 index 00000000..eb5259e3 --- /dev/null +++ b/PR-259/index.html @@ -0,0 +1,30 @@ + + + + + + 1.4.1 - Firebolt Certification App - version 1.4.1 + + + + + + + + + diff --git a/PR-259/lib/lightning-inspect.js b/PR-259/lib/lightning-inspect.js new file mode 100644 index 00000000..e1ba5238 --- /dev/null +++ b/PR-259/lib/lightning-inspect.js @@ -0,0 +1,866 @@ +/* + * If not stated otherwise in this file or this component's LICENSE file the + * following copyright and licenses apply: + * + * Copyright 2020 Metrological + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +window.attachInspector = function({Application, Element, ElementCore, Stage, Component, ElementTexturizer, Texture}) { + + const isAlreadyAttached = window.hasOwnProperty('mutationCounter'); + if (isAlreadyAttached) { + return; + } + + window.mutationCounter = 0; + window.mutatingChildren = false; + var observer = new MutationObserver(function(mutations) { + var fa = ["x", "y", "w", "h", "alpha", "mountX", "mountY", "pivotX", "pivotY", "scaleX", "scaleY", "rotation", "visible", "clipping", "rect", "colorUl", "colorUr", "colorBl", "colorBr", "color", "borderWidthLeft", "borderWidthRight", "borderWidthTop", "borderWidthBottom", "borderWidth", "borderColorLeft", "borderColorRight", "borderColorTop", "borderColorBottom", "borderColor", "zIndex", "forceZIndexContext", "renderToTexture", "renderToTextureLazy", "renderOffscreen", "colorizeResultTexture", "texture"]; + var fac = fa.map(function(v) {return v.toLowerCase()}); + + mutations.forEach(function(mutation) { + if (mutation.type == 'childList') { + + var node = mutation.target; + var c = mutation.target.element; + } + + if (mutation.type == 'attributes' && mutation.attributeName !== 'style' && mutation.attributeName !== 'class') { + var n = mutation.attributeName.toLowerCase(); + var c = mutation.target.element; + + if (c.__ignore_attrib_changes === window.mutationCounter) { + // Ignore attribute changes that were caused by actual value modifications by js. + return; + } + + var v = mutation.target.getAttribute(mutation.attributeName); + + if (n.startsWith("texture-")) { + if (c.displayedTexture) { + const att = n.substr(8).split("_") + const camelCaseAtt = att[0] + att.slice(1).map(a => { + return a.substr(0,1).toUpperCase() + a.substr(1).toLowerCase() + }).join() + + c.displayedTexture[camelCaseAtt] = v + } + return + } + + var index = fac.indexOf(n); + if (index !== -1) { + var rn = fa[index]; + var pv; + try { + if (v === null) { + switch(rn) { + case "pivotX": + case "pivotY": + pv = 0.5; + break; + case "alpha": + case "scaleX": + case "scaleY": + pv = 1; + break; + case "visible": + pv = true; + break; + case "clipping": + pv = false; + break; + case "rect": + pv = false; + break; + case "zIndex": + pv = 0; + break; + case "forceZIndexContext": + pv = false; + break; + case "color": + pv = 0xffffffff; + break; + case "colorUl": + case "colorUr": + case "colorBl": + case "colorBr": + if (mutation.target.hasAttribute("color")) { + // This may happen when the separate values are combined. + return; + } + pv = 0xffffffff; + break; + case "renderToTexture": + pv = false + break; + case "renderToTextureLazy": + pv = false + break; + case "renderOffscreen": + pv = false + break; + case "colorizeResultTexture": + pv = false + break; + default: + pv = 0; + } + } else { + switch(rn) { + case "color": + case "colorUl": + case "colorUr": + case "colorBl": + case "colorBr": + pv = parseInt(v, 16); + break; + case "visible": + case "clipping": + case "rect": + case "forceZIndexContext": + case "renderToTexture": + case "renderToTextureLazy": + case "renderOffscreen": + case "colorizeResultTexture": + pv = (v === "true"); + break; + case "texture": + pv = JSON.parse(v) + break + default: + pv = parseFloat(v); + if (isNaN(pv)) throw "e"; + } + } + + var fv; + switch(rn) { + case "color": + var f = ['colorUl','colorUr','colorBl','colorBr'].map(function(q) { + return mutation.target.hasAttribute(q); + }); + + if (!f[0]) c["colorUl"] = pv; + if (!f[1]) c["colorUr"] = pv; + if (!f[2]) c["colorBl"] = pv; + if (!f[3]) c["colorBr"] = pv; + break; + default: + c[rn] = pv; + } + + // Set final value, not the transitioned value. + } catch(e) { + console.error('Bad (ignored) attribute value', rn); + } + } + } + }); + + window.mutationCounter++; + }); + + ElementCore.prototype.dhtml = function() { + return this._element.dhtml(); + } + + Element.prototype.dhtml = function() { + if (!this.debugElement) { + this.debugElement = document.createElement('DIV'); + this.debugElement.setAttribute('type', this.constructor.name); + this.debugElement.element = this; + this.debugElement.style.position = 'absolute'; + + this.debugElement.id = "" + this.id; + observer.observe(this.debugElement, {attributes: true}); + } + if (this.stage.root === this && !this.dhtml_root) { + // Root element. + var root = document.createElement('DIV'); + document.body.appendChild(root); + var self = this; + let updateRootStyleFromCanvas = function (bcr) { + const p = self.stage.getRenderPrecision() / self.stage.getOption('devicePixelRatio'); + root.style.left = bcr.left + 'px'; + root.style.top = bcr.top + 'px'; + root.style.width = Math.ceil(bcr.width / p) + 'px'; + root.style.height = Math.ceil(bcr.height / p) + 'px'; + root.style.transformOrigin = '0 0 0'; + root.style.transform = 'scale(' + p + ',' + p + ')'; + } + + if (window.ResizeObserver != null) { + const resize_ob = new ResizeObserver(function (entries) { + updateRootStyleFromCanvas(entries[0].target.getBoundingClientRect()); + }); + // start observing for resize + resize_ob.observe(this.stage.getCanvas()); + } else { + setTimeout(function () { + updateRootStyleFromCanvas(self.stage.getCanvas().getBoundingClientRect()); + }, 1000); + } + + root.style.position = 'absolute'; + root.style.overflow = 'hidden'; + root.style.zIndex = '65535'; + root.appendChild(this.debugElement); + + this.dhtml_root = root; + } + return this.debugElement; + }; + + var oElement = Element; + + var oSetParent = oElement.prototype._setParent; + Element.prototype._setParent = function(parent) { + var prevParent = this.parent; + oSetParent.apply(this, arguments); + + if (!window.mutatingChildren) { + if (parent && parent.dhtml) { + var index = parent._children.getIndex(this); + if (index == parent._children.get().length - 1) { + parent.dhtml().appendChild(this.dhtml()); + } else { + parent.dhtml().insertBefore(this.dhtml(), parent.dhtml().children[index]); + } + } else { + if (prevParent && prevParent.dhtml) { + prevParent.dhtml().removeChild(this.dhtml()); + } + } + } + }; + + var oInit = Stage.prototype.init; + Stage.prototype.init = function() { + oInit.apply(this, arguments); + + // Apply stage scaling. + this.root.core.updateDebugTransforms(); + }; + + var oAddTag = oElement.prototype.addTag; + Element.prototype.addTag = function(tag) { + oAddTag.apply(this, arguments); + + if (tag) { + this.dhtml().classList.add(tag); + } + }; + + var oRemoveTag = oElement.prototype.removeTag; + Element.prototype.removeTag = function(tag) { + oRemoveTag.apply(this, arguments); + + if (tag) { + this.dhtml().classList.remove(tag); + } + }; + +// Change an attribute due to new value inputs. + var val = function(c, n, v, dv) { + if (c._element) { + c = c._element; + } + if (v == dv) { + if (c.dhtmlRemoveAttribute) { + c.dhtmlRemoveAttribute(n); + } + } else { + if (c.dhtmlSetAttribute) { + c.dhtmlSetAttribute(n, v); + } + } + }; + + var valStrict = function(c, n, v, dv) { + if (c._element) { + c = c._element; + } + if (v === dv) { + if (c.dhtmlRemoveAttribute) { + c.dhtmlRemoveAttribute(n); + } + } else { + if (c.dhtmlSetAttribute) { + c.dhtmlSetAttribute(n, v); + } + } + }; + + Element.prototype.dhtmlRemoveAttribute = function() { + // We don't want the attribute listeners to be called during the next observer cycle. + this.__ignore_attrib_changes = window.mutationCounter; + this.dhtml().removeAttribute.apply(this.dhtml(), arguments); + }; + + Element.prototype.dhtmlSetAttribute = function() { + this.__ignore_attrib_changes = window.mutationCounter; + this.dhtml().setAttribute.apply(this.dhtml(), arguments); + }; + + if (typeof Component !== "undefined") { + Object.defineProperty(Component.prototype, '_state', { + get: function() { + return this.__state; + }, + set: function(v) { + if (this.__state !== v) { + if (this.__state !== null) { // Ignore initial. + val(this, 'state', v ? v.__path : "", ""); + } + this.__state = v; + } + } + }); + } + + Element.prototype.$ref = Element.prototype.__ref; + Object.defineProperty(Element.prototype, '__ref', { + get: function() { + return this.$ref; + }, + set: function(v) { + if (this.$ref !== v) { + val(this, 'ref', v, null); + this.$ref = v; + } + } + }); + + ElementCore.prototype.$x = ElementCore.prototype._x; + Object.defineProperty(ElementCore.prototype, '_x', { + get: function() { + return this.$x; + }, + set: function(v) { + if (this.$x !== v) { + val(this, 'x', v, 0); + this.$x = v; + this.updateLeft(); + } + } + }); + + ElementCore.prototype.$y = ElementCore.prototype._y; + Object.defineProperty(ElementCore.prototype, '_y', { + get: function() { + return this.$y; + }, + set: function(v) { + if (this.$y !== v) { + val(this, 'y', v, 0); + this.$y = v; + this.updateTop(); + } + } + }); + + Element.prototype.$w = Element.prototype._w; + Object.defineProperty(Element.prototype, '_w', { + get: function() { + return this.$w; + }, + set: function(v) { + if (this.$w !== v) { + val(this, 'w', v, 0); + this.$w = v; + } + } + }); + + Element.prototype.$h = Element.prototype._h; + Object.defineProperty(Element.prototype, '_h', { + get: function() { + return this.$h; + }, + set: function(v) { + if (this.$h !== v) { + val(this, 'h', v, 0); + this.$h = v; + } + } + }); + + ElementCore.prototype.updateLeft = function() { + var mx = this._mountX * this._w; + var x = this._x - mx; + this.dhtml().style.left = x + 'px'; + }; + + ElementCore.prototype.updateTop = function() { + var my = this._mountY * this._h; + var y = this._y - my; + this.dhtml().style.top = y + 'px'; + }; + + ElementCore.prototype.__w = 0; + Object.defineProperty(ElementCore.prototype, '_w', { + get: function() { + return this.__w; + }, + set: function(v) { + this.__w = v; + this.dhtml().style.width = v + 'px'; + this.updateLeft(); + } + }); + + ElementCore.prototype.__h = 0; + Object.defineProperty(ElementCore.prototype, '_h', { + get: function() { + return this.__h; + }, + set: function(v) { + this.__h = v; + this.dhtml().style.height = v + 'px'; + this.updateTop(); + } + }); + + ElementCore.prototype.$alpha = 1; + Object.defineProperty(ElementCore.prototype, '_alpha', { + get: function() { + return this.$alpha; + }, + set: function(v) { + if (this.$alpha !== v) { + val(this, 'alpha', v, 1); + this.$alpha = v; + this.dhtml().style.opacity = v; + this.dhtml().style.display = this.$visible && this.$alpha ? 'block' : 'none'; + } + } + }); + + ElementCore.prototype.$visible = true; + Object.defineProperty(ElementCore.prototype, '_visible', { + get: function() { + return this.$visible; + }, + set: function(v) { + if (this.$visible !== v) { + val(this, 'visible', v, true); + this.$visible = v; + this.dhtml().style.visibility = v ? 'visible' : 'hidden'; + this.dhtml().style.display = this.$visible && this.$alpha ? 'block' : 'none'; + } + } + }); + + ElementCore.prototype.$rotation = 0; + Object.defineProperty(ElementCore.prototype, '_rotation', { + get: function() { + return this.$rotation; + }, + set: function(v) { + if (this.$rotation !== v) { + val(this, 'rotation', v, 0); + this.$rotation = v; + this.updateDebugTransforms(); + } + } + }); + + + ElementCore.prototype.$scaleX = 1; + Object.defineProperty(ElementCore.prototype, '_scaleX', { + get: function() { + return this.$scaleX; + }, + set: function(v) { + if (this.$scaleX !== v) { + val(this, 'scaleX', v, 1); + this.$scaleX = v; + this.updateDebugTransforms(); + } + } + }); + + ElementCore.prototype.$scaleY = 1; + Object.defineProperty(ElementCore.prototype, '_scaleY', { + get: function() { + return this.$scaleY; + }, + set: function(v) { + if (this.$scaleY !== v) { + val(this, 'scaleY', v, 1); + this.$scaleY = v; + this.updateDebugTransforms(); + } + } + }); + + ElementCore.prototype.$pivotX = 0.5; + Object.defineProperty(ElementCore.prototype, '_pivotX', { + get: function() { + return this.$pivotX; + }, + set: function(v) { + if (this.$pivotX !== v) { + val(this, 'pivotX', v, 0.5); + this.$pivotX = v; + this.updateDebugTransforms(); + } + } + }); + + ElementCore.prototype.$pivotY = 0.5; + Object.defineProperty(ElementCore.prototype, '_pivotY', { + get: function() { + return this.$pivotY; + }, + set: function(v) { + if (this.$pivotY !== v) { + val(this, 'pivotY', v, 0.5); + this.$pivotY = v; + this.updateDebugTransforms(); + } + } + }); + + ElementCore.prototype.$mountX = 0; + Object.defineProperty(ElementCore.prototype, '_mountX', { + get: function() { + return this.$mountX; + }, + set: function(v) { + if (this.$mountX !== v) { + val(this, 'mountX', v, 0); + this.$mountX = v; + this.updateLeft(); + } + } + }); + + ElementCore.prototype.$mountY = 0; + Object.defineProperty(ElementCore.prototype, '_mountY', { + get: function() { + return this.$mountY; + }, + set: function(v) { + if (this.$mountY !== v) { + val(this, 'mountY', v, 0); + this.$mountY = v; + this.updateTop(); + } + } + }); + + ElementCore.prototype.__zIndex = 0; + Object.defineProperty(ElementCore.prototype, '_zIndex', { + get: function() { + return this.__zIndex; + }, + set: function(v) { + if (this.__zIndex !== v) { + val(this, 'zIndex', v, 0); + this.__zIndex = v; + if (this.__zIndex || v) { + this.dhtml().style.zIndex = v; + } + } + } + }); + + ElementCore.prototype.__forceZIndexContext = false; + Object.defineProperty(ElementCore.prototype, '_forceZIndexContext', { + get: function() { + return this.__forceZIndexContext; + }, + set: function(v) { + if (this.__forceZIndexContext !== v) { + val(this, 'forceZIndexContext', v, false); + this.__forceZIndexContext = v; + } + } + }); + + ElementCore.prototype.__clipping = false; + Object.defineProperty(ElementCore.prototype, '_clipping', { + get: function() { + return this.__clipping; + }, + set: function(v) { + if (this.__clipping !== v) { + val(this, 'clipping', v, false); + this.__clipping = v; + var nv = v ? 'hidden' : 'visible'; + if (v || !v && (this.dhtml().style.overflow == 'hidden')) { + this.dhtml().style.overflow = nv; + } + } + } + }); + + ElementCore.prototype.__withinBoundsMargin = false; + Object.defineProperty(ElementCore.prototype, '_withinBoundsMargin', { + get: function() { + return this.__withinBoundsMargin; + }, + set: function(v) { + if (this.__withinBoundsMargin !== v) { + val(this, 'withinBoundsMargin', v, false); + this.__withinBoundsMargin = v; + } + } + }); + + ElementCore.prototype.__colorUl = 0xFFFFFFFF; + Object.defineProperty(ElementCore.prototype, '_colorUl', { + get: function() { + return this.__colorUl; + }, + set: function(v) { + if (this.__colorUl !== v) { + val(this, 'colorUl', v.toString(16), "ffffffff"); + this.__colorUl = v; + checkColors(this); + } + } + }); + + ElementCore.prototype.__colorUr = 0xFFFFFFFF; + Object.defineProperty(ElementCore.prototype, '_colorUr', { + get: function() { + return this.__colorUr; + }, + set: function(v) { + if (this.__colorUr !== v) { + val(this, 'colorUr', v.toString(16), "ffffffff"); + this.__colorUr = v; + checkColors(this); + } + } + }); + + ElementCore.prototype.__colorBl = 0xFFFFFFFF; + Object.defineProperty(ElementCore.prototype, '_colorBl', { + get: function() { + return this.__colorBl; + }, + set: function(v) { + if (this.__colorBl !== v) { + val(this, 'colorBl', v.toString(16), "ffffffff"); + this.__colorBl = v; + checkColors(this); + } + } + }); + + ElementCore.prototype.__colorBr = 0xFFFFFFFF; + Object.defineProperty(ElementCore.prototype, '_colorBr', { + get: function() { + return this.__colorBr; + }, + set: function(v) { + if (this.__colorBr !== v) { + val(this, 'colorBr', v.toString(16), "ffffffff"); + this.__colorBr = v; + checkColors(this); + } + } + }); + + Element.prototype.$texture = null; + Object.defineProperty(Element.prototype, '__texture', { + get: function() { + return this.$texture; + }, + set: function(v) { + this.$texture = v; + + val(this, 'rect', this.rect, false); + val(this, 'src', this.src, null); + } + }); + + Element.prototype.$testId = null; + Object.defineProperty(Element.prototype, 'testId', { + get: function() { + return this.$testId; + }, + set: function(v) { + if (this.$testId !== v) { + this.$testId = v; + val(this, 'data-testid', v, null); + } + } + }); + + var checkColors = function(elementRenderer) { + let element = elementRenderer._element; + if (elementRenderer._colorBr === undefined) { + // Element initialization. + return; + } + + if (elementRenderer._colorUl === elementRenderer._colorUr && elementRenderer._colorUl === elementRenderer._colorBl && elementRenderer._colorUl === elementRenderer._colorBr) { + if (elementRenderer._colorUl !== 0xffffffff) { + element.dhtmlSetAttribute('color', elementRenderer._colorUl.toString(16)); + } else { + element.dhtmlRemoveAttribute('color'); + } + element.dhtmlRemoveAttribute('colorul'); + element.dhtmlRemoveAttribute('colorur'); + element.dhtmlRemoveAttribute('colorbl'); + element.dhtmlRemoveAttribute('colorbr'); + } else { + val(element, 'colorUr', elementRenderer.colorUr.toString(16), "ffffffff"); + val(element, 'colorUl', elementRenderer.colorUl.toString(16), "ffffffff"); + val(element, 'colorBr', elementRenderer.colorBr.toString(16), "ffffffff"); + val(element, 'colorBl', elementRenderer.colorBl.toString(16), "ffffffff"); + element.dhtmlRemoveAttribute('color'); + } + }; + + ElementTexturizer.prototype.__enabled = false; + Object.defineProperty(ElementTexturizer.prototype, '_enabled', { + get: function() { + return this.__enabled; + }, + set: function(v) { + if (this.__enabled !== v) { + val(this, 'renderToTexture', v, false); + this.__enabled = v; + } + } + }); + + ElementTexturizer.prototype.__lazy = false; + Object.defineProperty(ElementTexturizer.prototype, '_lazy', { + get: function() { + return this.__lazy; + }, + set: function(v) { + if (this.__lazy !== v) { + val(this, 'renderToTextureLazy', v, false); + this.__lazy = v; + } + } + }); + + ElementTexturizer.prototype.__colorize = false; + Object.defineProperty(ElementTexturizer.prototype, '_colorize', { + get: function() { + return this.__colorize; + }, + set: function(v) { + if (this.__colorize !== v) { + val(this, 'colorizeResultTexture', v, false); + this.__colorize = v; + } + } + }); + + ElementTexturizer.prototype.__renderOffscreen = false; + Object.defineProperty(ElementTexturizer.prototype, '_renderOffscreen', { + get: function() { + return this.__renderOffscreen; + }, + set: function(v) { + if (this.__renderOffscreen !== v) { + val(this, 'renderOffscreen', v, false); + this.__renderOffscreen = v; + } + } + }); + + ElementCore.prototype.updateDebugTransforms = function() { + const stage = this._element.stage + + if (this._pivotX !== 0.5 || this._pivotY !== 0.5) { + this.dhtml().style.transformOrigin = (this._pivotX * 100) + '% ' + (this._pivotY * 100) + '%'; + } else if (this.dhtml().style.transformOrigin) { + this.dhtml().style.transformOrigin = '50% 50%'; + } + + var r = this._rotation; + var sx = this._scaleX; + var sy = this._scaleY; + + if ((sx !== undefined && sy !== undefined) && (this._element.id === 0)) { + // Root element: must be scaled. + if (stage.options.w !== stage.options.renderWidth || stage.options.h !== stage.options.renderHeight) { + sx *= (stage.options.w / stage.options.renderWidth); + sy *= (stage.options.h / stage.options.renderHeight); + } + } + var parts = []; + if (r) parts.push('rotate(' + r + 'rad)'); + if ((sx !== undefined && sy !== undefined) && (sx !== 1 || sy !== 1)) parts.push('scale(' + sx + ', ' + sy + ')'); + + this.dhtml().style.transform = parts.join(' '); + }; + + var updateTextureAttribs = function(element) { + if (element.texture) { + const nonDefaults = element.texture.getNonDefaults() + const keys = Object.keys(nonDefaults) + keys.forEach(key => { + let f = "" + for (let i = 0, n = key.length; i < n; i++) { + const c = key.charAt(i) + if (c !== c.toLowerCase()) { + f += "_" + c.toLowerCase() + } else { + f += c + } + } + valStrict(element, `texture-${f}`, nonDefaults[key], false); + }) + } + } + + const _performUpdateSource = Texture.prototype._performUpdateSource + Texture.prototype._performUpdateSource = function() { + _performUpdateSource.apply(this, arguments) + this.elements.forEach(v => { + updateTextureAttribs(v) + }) + } + + const _setDisplayedTexture = Element.prototype._setDisplayedTexture + Element.prototype._setDisplayedTexture = function() { + _setDisplayedTexture.apply(this, arguments) + updateTextureAttribs(this) + } + + const _updateFocus = Application.prototype.__updateFocus + Application.prototype.__updateFocus = function() { + const prev = this._focusPath && this._focusPath.length ? this._focusPath[this._focusPath.length - 1] : null; + _updateFocus.apply(this, arguments) + const focused = this._focusPath && this._focusPath.length ? this._focusPath[this._focusPath.length - 1] : null; + + if (prev != focused) { + if (prev) { + val(prev, 'focused', false, false); + } + if (focused) { + val(focused, 'focused', true, false); + } + } + } +}; + +if (window.lng) { + // Automatically attach inspector if lng was already loaded. + attachInspector(lng); +} diff --git a/PR-259/main.bundle.72a56dd50d203bd4c160.js b/PR-259/main.bundle.72a56dd50d203bd4c160.js new file mode 100644 index 00000000..1de98e23 --- /dev/null +++ b/PR-259/main.bundle.72a56dd50d203bd4c160.js @@ -0,0 +1,195609 @@ +/*! version 1.4.1 */ +/******/ (function(modules) { // webpackBootstrap +/******/ // The module cache +/******/ var installedModules = {}; +/******/ +/******/ // The require function +/******/ function __webpack_require__(moduleId) { +/******/ +/******/ // Check if module is in cache +/******/ if(installedModules[moduleId]) { +/******/ return installedModules[moduleId].exports; +/******/ } +/******/ // Create a new module (and put it into the cache) +/******/ var module = installedModules[moduleId] = { +/******/ i: moduleId, +/******/ l: false, +/******/ exports: {} +/******/ }; +/******/ +/******/ // Execute the module function +/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); +/******/ +/******/ // Flag the module as loaded +/******/ module.l = true; +/******/ +/******/ // Return the exports of the module +/******/ return module.exports; +/******/ } +/******/ +/******/ +/******/ // expose the modules object (__webpack_modules__) +/******/ __webpack_require__.m = modules; +/******/ +/******/ // expose the module cache +/******/ __webpack_require__.c = installedModules; +/******/ +/******/ // define getter function for harmony exports +/******/ __webpack_require__.d = function(exports, name, getter) { +/******/ if(!__webpack_require__.o(exports, name)) { +/******/ Object.defineProperty(exports, name, { enumerable: true, get: getter }); +/******/ } +/******/ }; +/******/ +/******/ // define __esModule on exports +/******/ __webpack_require__.r = function(exports) { +/******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) { +/******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); +/******/ } +/******/ Object.defineProperty(exports, '__esModule', { value: true }); +/******/ }; +/******/ +/******/ // create a fake namespace object +/******/ // mode & 1: value is a module id, require it +/******/ // mode & 2: merge all properties of value into the ns +/******/ // mode & 4: return value when already ns object +/******/ // mode & 8|1: behave like require +/******/ __webpack_require__.t = function(value, mode) { +/******/ if(mode & 1) value = __webpack_require__(value); +/******/ if(mode & 8) return value; +/******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value; +/******/ var ns = Object.create(null); +/******/ __webpack_require__.r(ns); +/******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value }); +/******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key)); +/******/ return ns; +/******/ }; +/******/ +/******/ // getDefaultExport function for compatibility with non-harmony modules +/******/ __webpack_require__.n = function(module) { +/******/ var getter = module && module.__esModule ? +/******/ function getDefault() { return module['default']; } : +/******/ function getModuleExports() { return module; }; +/******/ __webpack_require__.d(getter, 'a', getter); +/******/ return getter; +/******/ }; +/******/ +/******/ // Object.prototype.hasOwnProperty.call +/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; +/******/ +/******/ // __webpack_public_path__ +/******/ __webpack_require__.p = ""; +/******/ +/******/ +/******/ // Load entry module and return exports +/******/ return __webpack_require__(__webpack_require__.s = "./src/index.js"); +/******/ }) +/************************************************************************/ +/******/ ({ + +/***/ "./node_modules/@apidevtools/json-schema-ref-parser/lib/bundle.js": +/*!************************************************************************!*\ + !*** ./node_modules/@apidevtools/json-schema-ref-parser/lib/bundle.js ***! + \************************************************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +const $Ref = __webpack_require__(/*! ./ref */ "./node_modules/@apidevtools/json-schema-ref-parser/lib/ref.js"); +const Pointer = __webpack_require__(/*! ./pointer */ "./node_modules/@apidevtools/json-schema-ref-parser/lib/pointer.js"); +const url = __webpack_require__(/*! ./util/url */ "./node_modules/@apidevtools/json-schema-ref-parser/lib/util/url.js"); + +module.exports = bundle; + +/** + * Bundles all external JSON references into the main JSON schema, thus resulting in a schema that + * only has *internal* references, not any *external* references. + * This method mutates the JSON schema object, adding new references and re-mapping existing ones. + * + * @param {$RefParser} parser + * @param {$RefParserOptions} options + */ +function bundle (parser, options) { + // console.log('Bundling $ref pointers in %s', parser.$refs._root$Ref.path); + + // Build an inventory of all $ref pointers in the JSON Schema + let inventory = []; + crawl(parser, "schema", parser.$refs._root$Ref.path + "#", "#", 0, inventory, parser.$refs, options); + + // Remap all $ref pointers + remap(inventory); +} + +/** + * Recursively crawls the given value, and inventories all JSON references. + * + * @param {object} parent - The object containing the value to crawl. If the value is not an object or array, it will be ignored. + * @param {string} key - The property key of `parent` to be crawled + * @param {string} path - The full path of the property being crawled, possibly with a JSON Pointer in the hash + * @param {string} pathFromRoot - The path of the property being crawled, from the schema root + * @param {object[]} inventory - An array of already-inventoried $ref pointers + * @param {$Refs} $refs + * @param {$RefParserOptions} options + */ +function crawl (parent, key, path, pathFromRoot, indirections, inventory, $refs, options) { + let obj = key === null ? parent : parent[key]; + + if (obj && typeof obj === "object" && !ArrayBuffer.isView(obj)) { + if ($Ref.isAllowed$Ref(obj)) { + inventory$Ref(parent, key, path, pathFromRoot, indirections, inventory, $refs, options); + } + else { + // Crawl the object in a specific order that's optimized for bundling. + // This is important because it determines how `pathFromRoot` gets built, + // which later determines which keys get dereferenced and which ones get remapped + let keys = Object.keys(obj) + .sort((a, b) => { + // Most people will expect references to be bundled into the the "definitions" property, + // so we always crawl that property first, if it exists. + if (a === "definitions") { + return -1; + } + else if (b === "definitions") { + return 1; + } + else { + // Otherwise, crawl the keys based on their length. + // This produces the shortest possible bundled references + return a.length - b.length; + } + }); + + // eslint-disable-next-line no-shadow + for (let key of keys) { + let keyPath = Pointer.join(path, key); + let keyPathFromRoot = Pointer.join(pathFromRoot, key); + let value = obj[key]; + + if ($Ref.isAllowed$Ref(value)) { + inventory$Ref(obj, key, path, keyPathFromRoot, indirections, inventory, $refs, options); + } + else { + crawl(obj, key, keyPath, keyPathFromRoot, indirections, inventory, $refs, options); + } + } + } + } +} + +/** + * Inventories the given JSON Reference (i.e. records detailed information about it so we can + * optimize all $refs in the schema), and then crawls the resolved value. + * + * @param {object} $refParent - The object that contains a JSON Reference as one of its keys + * @param {string} $refKey - The key in `$refParent` that is a JSON Reference + * @param {string} path - The full path of the JSON Reference at `$refKey`, possibly with a JSON Pointer in the hash + * @param {string} pathFromRoot - The path of the JSON Reference at `$refKey`, from the schema root + * @param {object[]} inventory - An array of already-inventoried $ref pointers + * @param {$Refs} $refs + * @param {$RefParserOptions} options + */ +function inventory$Ref ($refParent, $refKey, path, pathFromRoot, indirections, inventory, $refs, options) { + let $ref = $refKey === null ? $refParent : $refParent[$refKey]; + let $refPath = url.resolve(path, $ref.$ref); + let pointer = $refs._resolve($refPath, pathFromRoot, options); + if (pointer === null) { + return; + } + + let depth = Pointer.parse(pathFromRoot).length; + let file = url.stripHash(pointer.path); + let hash = url.getHash(pointer.path); + let external = file !== $refs._root$Ref.path; + let extended = $Ref.isExtended$Ref($ref); + indirections += pointer.indirections; + + let existingEntry = findInInventory(inventory, $refParent, $refKey); + if (existingEntry) { + // This $Ref has already been inventoried, so we don't need to process it again + if (depth < existingEntry.depth || indirections < existingEntry.indirections) { + removeFromInventory(inventory, existingEntry); + } + else { + return; + } + } + + inventory.push({ + $ref, // The JSON Reference (e.g. {$ref: string}) + parent: $refParent, // The object that contains this $ref pointer + key: $refKey, // The key in `parent` that is the $ref pointer + pathFromRoot, // The path to the $ref pointer, from the JSON Schema root + depth, // How far from the JSON Schema root is this $ref pointer? + file, // The file that the $ref pointer resolves to + hash, // The hash within `file` that the $ref pointer resolves to + value: pointer.value, // The resolved value of the $ref pointer + circular: pointer.circular, // Is this $ref pointer DIRECTLY circular? (i.e. it references itself) + extended, // Does this $ref extend its resolved value? (i.e. it has extra properties, in addition to "$ref") + external, // Does this $ref pointer point to a file other than the main JSON Schema file? + indirections, // The number of indirect references that were traversed to resolve the value + }); + + // Recursively crawl the resolved value + if (!existingEntry) { + crawl(pointer.value, null, pointer.path, pathFromRoot, indirections + 1, inventory, $refs, options); + } +} + +/** + * Re-maps every $ref pointer, so that they're all relative to the root of the JSON Schema. + * Each referenced value is dereferenced EXACTLY ONCE. All subsequent references to the same + * value are re-mapped to point to the first reference. + * + * @example: + * { + * first: { $ref: somefile.json#/some/part }, + * second: { $ref: somefile.json#/another/part }, + * third: { $ref: somefile.json }, + * fourth: { $ref: somefile.json#/some/part/sub/part } + * } + * + * In this example, there are four references to the same file, but since the third reference points + * to the ENTIRE file, that's the only one we need to dereference. The other three can just be + * remapped to point inside the third one. + * + * On the other hand, if the third reference DIDN'T exist, then the first and second would both need + * to be dereferenced, since they point to different parts of the file. The fourth reference does NOT + * need to be dereferenced, because it can be remapped to point inside the first one. + * + * @param {object[]} inventory + */ +function remap (inventory) { + // Group & sort all the $ref pointers, so they're in the order that we need to dereference/remap them + inventory.sort((a, b) => { + if (a.file !== b.file) { + // Group all the $refs that point to the same file + return a.file < b.file ? -1 : +1; + } + else if (a.hash !== b.hash) { + // Group all the $refs that point to the same part of the file + return a.hash < b.hash ? -1 : +1; + } + else if (a.circular !== b.circular) { + // If the $ref points to itself, then sort it higher than other $refs that point to this $ref + return a.circular ? -1 : +1; + } + else if (a.extended !== b.extended) { + // If the $ref extends the resolved value, then sort it lower than other $refs that don't extend the value + return a.extended ? +1 : -1; + } + else if (a.indirections !== b.indirections) { + // Sort direct references higher than indirect references + return a.indirections - b.indirections; + } + else if (a.depth !== b.depth) { + // Sort $refs by how close they are to the JSON Schema root + return a.depth - b.depth; + } + else { + // Determine how far each $ref is from the "definitions" property. + // Most people will expect references to be bundled into the the "definitions" property if possible. + let aDefinitionsIndex = a.pathFromRoot.lastIndexOf("/definitions"); + let bDefinitionsIndex = b.pathFromRoot.lastIndexOf("/definitions"); + + if (aDefinitionsIndex !== bDefinitionsIndex) { + // Give higher priority to the $ref that's closer to the "definitions" property + return bDefinitionsIndex - aDefinitionsIndex; + } + else { + // All else is equal, so use the shorter path, which will produce the shortest possible reference + return a.pathFromRoot.length - b.pathFromRoot.length; + } + } + }); + + let file, hash, pathFromRoot; + for (let entry of inventory) { + // console.log('Re-mapping $ref pointer "%s" at %s', entry.$ref.$ref, entry.pathFromRoot); + + if (!entry.external) { + // This $ref already resolves to the main JSON Schema file + entry.$ref.$ref = entry.hash; + } + else if (entry.file === file && entry.hash === hash) { + // This $ref points to the same value as the prevous $ref, so remap it to the same path + entry.$ref.$ref = pathFromRoot; + } + else if (entry.file === file && entry.hash.indexOf(hash + "/") === 0) { + // This $ref points to a sub-value of the prevous $ref, so remap it beneath that path + entry.$ref.$ref = Pointer.join(pathFromRoot, Pointer.parse(entry.hash.replace(hash, "#"))); + } + else { + // We've moved to a new file or new hash + file = entry.file; + hash = entry.hash; + pathFromRoot = entry.pathFromRoot; + + // This is the first $ref to point to this value, so dereference the value. + // Any other $refs that point to the same value will point to this $ref instead + entry.$ref = entry.parent[entry.key] = $Ref.dereference(entry.$ref, entry.value); + + if (entry.circular) { + // This $ref points to itself + entry.$ref.$ref = entry.pathFromRoot; + } + } + + // console.log(' new value: %s', (entry.$ref && entry.$ref.$ref) ? entry.$ref.$ref : '[object Object]'); + } +} + +/** + * TODO + */ +function findInInventory (inventory, $refParent, $refKey) { + for (let i = 0; i < inventory.length; i++) { + let existingEntry = inventory[i]; + if (existingEntry.parent === $refParent && existingEntry.key === $refKey) { + return existingEntry; + } + } +} + +function removeFromInventory (inventory, entry) { + let index = inventory.indexOf(entry); + inventory.splice(index, 1); +} + + +/***/ }), + +/***/ "./node_modules/@apidevtools/json-schema-ref-parser/lib/dereference.js": +/*!*****************************************************************************!*\ + !*** ./node_modules/@apidevtools/json-schema-ref-parser/lib/dereference.js ***! + \*****************************************************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +const $Ref = __webpack_require__(/*! ./ref */ "./node_modules/@apidevtools/json-schema-ref-parser/lib/ref.js"); +const Pointer = __webpack_require__(/*! ./pointer */ "./node_modules/@apidevtools/json-schema-ref-parser/lib/pointer.js"); +const { ono } = __webpack_require__(/*! @jsdevtools/ono */ "./node_modules/@jsdevtools/ono/esm/index.js"); +const url = __webpack_require__(/*! ./util/url */ "./node_modules/@apidevtools/json-schema-ref-parser/lib/util/url.js"); + +module.exports = dereference; + +/** + * Crawls the JSON schema, finds all JSON references, and dereferences them. + * This method mutates the JSON schema object, replacing JSON references with their resolved value. + * + * @param {$RefParser} parser + * @param {$RefParserOptions} options + */ +function dereference (parser, options) { + // console.log('Dereferencing $ref pointers in %s', parser.$refs._root$Ref.path); + let dereferenced = crawl(parser.schema, parser.$refs._root$Ref.path, "#", new Set(), new Set(), new Map(), parser.$refs, options); + parser.$refs.circular = dereferenced.circular; + parser.schema = dereferenced.value; +} + +/** + * Recursively crawls the given value, and dereferences any JSON references. + * + * @param {*} obj - The value to crawl. If it's not an object or array, it will be ignored. + * @param {string} path - The full path of `obj`, possibly with a JSON Pointer in the hash + * @param {string} pathFromRoot - The path of `obj` from the schema root + * @param {Set} parents - An array of the parent objects that have already been dereferenced + * @param {Set} processedObjects - An array of all the objects that have already been processed + * @param {Map} dereferencedCache - An map of all the dereferenced objects + * @param {$Refs} $refs + * @param {$RefParserOptions} options + * @returns {{value: object, circular: boolean}} + */ +function crawl (obj, path, pathFromRoot, parents, processedObjects, dereferencedCache, $refs, options) { + let dereferenced; + let result = { + value: obj, + circular: false + }; + + let isExcludedPath = options.dereference.excludedPathMatcher; + + if (options.dereference.circular === "ignore" || !processedObjects.has(obj)) { + if (obj && typeof obj === "object" && !ArrayBuffer.isView(obj) && !isExcludedPath(pathFromRoot)) { + parents.add(obj); + processedObjects.add(obj); + + if ($Ref.isAllowed$Ref(obj, options)) { + dereferenced = dereference$Ref(obj, path, pathFromRoot, parents, processedObjects, dereferencedCache, $refs, options); + result.circular = dereferenced.circular; + result.value = dereferenced.value; + } + else { + for (const key of Object.keys(obj)) { + let keyPath = Pointer.join(path, key); + let keyPathFromRoot = Pointer.join(pathFromRoot, key); + + if (isExcludedPath(keyPathFromRoot)) { + continue; + } + + let value = obj[key]; + let circular = false; + + if ($Ref.isAllowed$Ref(value, options)) { + dereferenced = dereference$Ref(value, keyPath, keyPathFromRoot, parents, processedObjects, dereferencedCache, $refs, options); + circular = dereferenced.circular; + // Avoid pointless mutations; breaks frozen objects to no profit + if (obj[key] !== dereferenced.value) { + obj[key] = dereferenced.value; + } + } + else { + if (!parents.has(value)) { + dereferenced = crawl(value, keyPath, keyPathFromRoot, parents, processedObjects, dereferencedCache, $refs, options); + circular = dereferenced.circular; + // Avoid pointless mutations; breaks frozen objects to no profit + if (obj[key] !== dereferenced.value) { + obj[key] = dereferenced.value; + } + } + else { + circular = foundCircularReference(keyPath, $refs, options); + } + } + + // Set the "isCircular" flag if this or any other property is circular + result.circular = result.circular || circular; + } + } + + parents.delete(obj); + } + } + + return result; +} + +/** + * Dereferences the given JSON Reference, and then crawls the resulting value. + * + * @param {{$ref: string}} $ref - The JSON Reference to resolve + * @param {string} path - The full path of `$ref`, possibly with a JSON Pointer in the hash + * @param {string} pathFromRoot - The path of `$ref` from the schema root + * @param {Set} parents - An array of the parent objects that have already been dereferenced + * @param {Set} processedObjects - An array of all the objects that have already been dereferenced + * @param {Map} dereferencedCache - An map of all the dereferenced objects + * @param {$Refs} $refs + * @param {$RefParserOptions} options + * @returns {{value: object, circular: boolean}} + */ +function dereference$Ref ($ref, path, pathFromRoot, parents, processedObjects, dereferencedCache, $refs, options) { + // console.log('Dereferencing $ref pointer "%s" at %s', $ref.$ref, path); + + let $refPath = url.resolve(path, $ref.$ref); + + const cache = dereferencedCache.get($refPath); + if (cache) { + const refKeys = Object.keys($ref); + if (refKeys.length > 1) { + const extraKeys = {}; + for (let key of refKeys) { + if (key !== "$ref" && !(key in cache.value)) { + extraKeys[key] = $ref[key]; + } + } + return { + circular: cache.circular, + value: Object.assign({}, cache.value, extraKeys), + }; + } + + return cache; + } + + + let pointer = $refs._resolve($refPath, path, options); + + if (pointer === null) { + return { + circular: false, + value: null, + }; + } + + // Check for circular references + let directCircular = pointer.circular; + let circular = directCircular || parents.has(pointer.value); + circular && foundCircularReference(path, $refs, options); + + // Dereference the JSON reference + let dereferencedValue = $Ref.dereference($ref, pointer.value); + + // Crawl the dereferenced value (unless it's circular) + if (!circular) { + // Determine if the dereferenced value is circular + let dereferenced = crawl(dereferencedValue, pointer.path, pathFromRoot, parents, processedObjects, dereferencedCache, $refs, options); + circular = dereferenced.circular; + dereferencedValue = dereferenced.value; + } + + if (circular && !directCircular && options.dereference.circular === "ignore") { + // The user has chosen to "ignore" circular references, so don't change the value + dereferencedValue = $ref; + } + + if (directCircular) { + // The pointer is a DIRECT circular reference (i.e. it references itself). + // So replace the $ref path with the absolute path from the JSON Schema root + dereferencedValue.$ref = pathFromRoot; + } + + + const dereferencedObject = { + circular, + value: dereferencedValue + }; + + // only cache if no extra properties than $ref + if (Object.keys($ref).length === 1) { + dereferencedCache.set($refPath, dereferencedObject); + } + + return dereferencedObject; +} + +/** + * Called when a circular reference is found. + * It sets the {@link $Refs#circular} flag, and throws an error if options.dereference.circular is false. + * + * @param {string} keyPath - The JSON Reference path of the circular reference + * @param {$Refs} $refs + * @param {$RefParserOptions} options + * @returns {boolean} - always returns true, to indicate that a circular reference was found + */ +function foundCircularReference (keyPath, $refs, options) { + $refs.circular = true; + if (!options.dereference.circular) { + throw ono.reference(`Circular $ref pointer found at ${keyPath}`); + } + return true; +} + + +/***/ }), + +/***/ "./node_modules/@apidevtools/json-schema-ref-parser/lib/index.js": +/*!***********************************************************************!*\ + !*** ./node_modules/@apidevtools/json-schema-ref-parser/lib/index.js ***! + \***********************************************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/* WEBPACK VAR INJECTION */(function(Buffer) {/* eslint-disable no-unused-vars */ + + +const $Refs = __webpack_require__(/*! ./refs */ "./node_modules/@apidevtools/json-schema-ref-parser/lib/refs.js"); +const _parse = __webpack_require__(/*! ./parse */ "./node_modules/@apidevtools/json-schema-ref-parser/lib/parse.js"); +const normalizeArgs = __webpack_require__(/*! ./normalize-args */ "./node_modules/@apidevtools/json-schema-ref-parser/lib/normalize-args.js"); +const resolveExternal = __webpack_require__(/*! ./resolve-external */ "./node_modules/@apidevtools/json-schema-ref-parser/lib/resolve-external.js"); +const _bundle = __webpack_require__(/*! ./bundle */ "./node_modules/@apidevtools/json-schema-ref-parser/lib/bundle.js"); +const _dereference = __webpack_require__(/*! ./dereference */ "./node_modules/@apidevtools/json-schema-ref-parser/lib/dereference.js"); +const url = __webpack_require__(/*! ./util/url */ "./node_modules/@apidevtools/json-schema-ref-parser/lib/util/url.js"); +const { JSONParserError, InvalidPointerError, MissingPointerError, ResolverError, ParserError, UnmatchedParserError, UnmatchedResolverError, isHandledError, JSONParserErrorGroup } = __webpack_require__(/*! ./util/errors */ "./node_modules/@apidevtools/json-schema-ref-parser/lib/util/errors.js"); +const maybe = __webpack_require__(/*! call-me-maybe */ "./node_modules/call-me-maybe/src/maybe.js"); +const { ono } = __webpack_require__(/*! @jsdevtools/ono */ "./node_modules/@jsdevtools/ono/esm/index.js"); + +module.exports = $RefParser; +module.exports.default = $RefParser; +module.exports.JSONParserError = JSONParserError; +module.exports.InvalidPointerError = InvalidPointerError; +module.exports.MissingPointerError = MissingPointerError; +module.exports.ResolverError = ResolverError; +module.exports.ParserError = ParserError; +module.exports.UnmatchedParserError = UnmatchedParserError; +module.exports.UnmatchedResolverError = UnmatchedResolverError; + +/** + * This class parses a JSON schema, builds a map of its JSON references and their resolved values, + * and provides methods for traversing, manipulating, and dereferencing those references. + * + * @constructor + */ +function $RefParser () { + /** + * The parsed (and possibly dereferenced) JSON schema object + * + * @type {object} + * @readonly + */ + this.schema = null; + + /** + * The resolved JSON references + * + * @type {$Refs} + * @readonly + */ + this.$refs = new $Refs(); +} + +/** + * Parses the given JSON schema. + * This method does not resolve any JSON references. + * It just reads a single file in JSON or YAML format, and parse it as a JavaScript object. + * + * @param {string} [path] - The file path or URL of the JSON schema + * @param {object} [schema] - A JSON schema object. This object will be used instead of reading from `path`. + * @param {$RefParserOptions} [options] - Options that determine how the schema is parsed + * @param {function} [callback] - An error-first callback. The second parameter is the parsed JSON schema object. + * @returns {Promise} - The returned promise resolves with the parsed JSON schema object. + */ +$RefParser.parse = function parse (path, schema, options, callback) { + let Class = this; // eslint-disable-line consistent-this + let instance = new Class(); + return instance.parse.apply(instance, arguments); +}; + +/** + * Parses the given JSON schema. + * This method does not resolve any JSON references. + * It just reads a single file in JSON or YAML format, and parse it as a JavaScript object. + * + * @param {string} [path] - The file path or URL of the JSON schema + * @param {object} [schema] - A JSON schema object. This object will be used instead of reading from `path`. + * @param {$RefParserOptions} [options] - Options that determine how the schema is parsed + * @param {function} [callback] - An error-first callback. The second parameter is the parsed JSON schema object. + * @returns {Promise} - The returned promise resolves with the parsed JSON schema object. + */ +$RefParser.prototype.parse = async function parse (path, schema, options, callback) { + let args = normalizeArgs(arguments); + let promise; + + if (!args.path && !args.schema) { + let err = ono(`Expected a file path, URL, or object. Got ${args.path || args.schema}`); + return maybe(args.callback, Promise.reject(err)); + } + + // Reset everything + this.schema = null; + this.$refs = new $Refs(); + + // If the path is a filesystem path, then convert it to a URL. + // NOTE: According to the JSON Reference spec, these should already be URLs, + // but, in practice, many people use local filesystem paths instead. + // So we're being generous here and doing the conversion automatically. + // This is not intended to be a 100% bulletproof solution. + // If it doesn't work for your use-case, then use a URL instead. + let pathType = "http"; + if (url.isFileSystemPath(args.path)) { + args.path = url.fromFileSystemPath(args.path); + pathType = "file"; + } + + // Resolve the absolute path of the schema + args.path = url.resolve(url.cwd(), args.path); + + if (args.schema && typeof args.schema === "object") { + // A schema object was passed-in. + // So immediately add a new $Ref with the schema object as its value + let $ref = this.$refs._add(args.path); + $ref.value = args.schema; + $ref.pathType = pathType; + promise = Promise.resolve(args.schema); + } + else { + // Parse the schema file/url + promise = _parse(args.path, this.$refs, args.options); + } + + let me = this; + try { + let result = await promise; + + if (result !== null && typeof result === "object" && !Buffer.isBuffer(result)) { + me.schema = result; + return maybe(args.callback, Promise.resolve(me.schema)); + } + else if (args.options.continueOnError) { + me.schema = null; // it's already set to null at line 79, but let's set it again for the sake of readability + return maybe(args.callback, Promise.resolve(me.schema)); + } + else { + throw ono.syntax(`"${me.$refs._root$Ref.path || result}" is not a valid JSON Schema`); + } + } + catch (err) { + if (!args.options.continueOnError || !isHandledError(err)) { + return maybe(args.callback, Promise.reject(err)); + } + + if (this.$refs._$refs[url.stripHash(args.path)]) { + this.$refs._$refs[url.stripHash(args.path)].addError(err); + } + + return maybe(args.callback, Promise.resolve(null)); + } +}; + +/** + * Parses the given JSON schema and resolves any JSON references, including references in + * externally-referenced files. + * + * @param {string} [path] - The file path or URL of the JSON schema + * @param {object} [schema] - A JSON schema object. This object will be used instead of reading from `path`. + * @param {$RefParserOptions} [options] - Options that determine how the schema is parsed and resolved + * @param {function} [callback] + * - An error-first callback. The second parameter is a {@link $Refs} object containing the resolved JSON references + * + * @returns {Promise} + * The returned promise resolves with a {@link $Refs} object containing the resolved JSON references + */ +$RefParser.resolve = function resolve (path, schema, options, callback) { + let Class = this; // eslint-disable-line consistent-this + let instance = new Class(); + return instance.resolve.apply(instance, arguments); +}; + +/** + * Parses the given JSON schema and resolves any JSON references, including references in + * externally-referenced files. + * + * @param {string} [path] - The file path or URL of the JSON schema + * @param {object} [schema] - A JSON schema object. This object will be used instead of reading from `path`. + * @param {$RefParserOptions} [options] - Options that determine how the schema is parsed and resolved + * @param {function} [callback] + * - An error-first callback. The second parameter is a {@link $Refs} object containing the resolved JSON references + * + * @returns {Promise} + * The returned promise resolves with a {@link $Refs} object containing the resolved JSON references + */ +$RefParser.prototype.resolve = async function resolve (path, schema, options, callback) { + let me = this; + let args = normalizeArgs(arguments); + + try { + await this.parse(args.path, args.schema, args.options); + await resolveExternal(me, args.options); + finalize(me); + return maybe(args.callback, Promise.resolve(me.$refs)); + } + catch (err) { + return maybe(args.callback, Promise.reject(err)); + } +}; + +/** + * Parses the given JSON schema, resolves any JSON references, and bundles all external references + * into the main JSON schema. This produces a JSON schema that only has *internal* references, + * not any *external* references. + * + * @param {string} [path] - The file path or URL of the JSON schema + * @param {object} [schema] - A JSON schema object. This object will be used instead of reading from `path`. + * @param {$RefParserOptions} [options] - Options that determine how the schema is parsed, resolved, and dereferenced + * @param {function} [callback] - An error-first callback. The second parameter is the bundled JSON schema object + * @returns {Promise} - The returned promise resolves with the bundled JSON schema object. + */ +$RefParser.bundle = function bundle (path, schema, options, callback) { + let Class = this; // eslint-disable-line consistent-this + let instance = new Class(); + return instance.bundle.apply(instance, arguments); +}; + +/** + * Parses the given JSON schema, resolves any JSON references, and bundles all external references + * into the main JSON schema. This produces a JSON schema that only has *internal* references, + * not any *external* references. + * + * @param {string} [path] - The file path or URL of the JSON schema + * @param {object} [schema] - A JSON schema object. This object will be used instead of reading from `path`. + * @param {$RefParserOptions} [options] - Options that determine how the schema is parsed, resolved, and dereferenced + * @param {function} [callback] - An error-first callback. The second parameter is the bundled JSON schema object + * @returns {Promise} - The returned promise resolves with the bundled JSON schema object. + */ +$RefParser.prototype.bundle = async function bundle (path, schema, options, callback) { + let me = this; + let args = normalizeArgs(arguments); + + try { + await this.resolve(args.path, args.schema, args.options); + _bundle(me, args.options); + finalize(me); + return maybe(args.callback, Promise.resolve(me.schema)); + } + catch (err) { + return maybe(args.callback, Promise.reject(err)); + } +}; + +/** + * Parses the given JSON schema, resolves any JSON references, and dereferences the JSON schema. + * That is, all JSON references are replaced with their resolved values. + * + * @param {string} [path] - The file path or URL of the JSON schema + * @param {object} [schema] - A JSON schema object. This object will be used instead of reading from `path`. + * @param {$RefParserOptions} [options] - Options that determine how the schema is parsed, resolved, and dereferenced + * @param {function} [callback] - An error-first callback. The second parameter is the dereferenced JSON schema object + * @returns {Promise} - The returned promise resolves with the dereferenced JSON schema object. + */ +$RefParser.dereference = function dereference (path, schema, options, callback) { + let Class = this; // eslint-disable-line consistent-this + let instance = new Class(); + return instance.dereference.apply(instance, arguments); +}; + +/** + * Parses the given JSON schema, resolves any JSON references, and dereferences the JSON schema. + * That is, all JSON references are replaced with their resolved values. + * + * @param {string} [path] - The file path or URL of the JSON schema + * @param {object} [schema] - A JSON schema object. This object will be used instead of reading from `path`. + * @param {$RefParserOptions} [options] - Options that determine how the schema is parsed, resolved, and dereferenced + * @param {function} [callback] - An error-first callback. The second parameter is the dereferenced JSON schema object + * @returns {Promise} - The returned promise resolves with the dereferenced JSON schema object. + */ +$RefParser.prototype.dereference = async function dereference (path, schema, options, callback) { + let me = this; + let args = normalizeArgs(arguments); + + try { + await this.resolve(args.path, args.schema, args.options); + _dereference(me, args.options); + finalize(me); + return maybe(args.callback, Promise.resolve(me.schema)); + } + catch (err) { + return maybe(args.callback, Promise.reject(err)); + } +}; + +function finalize (parser) { + const errors = JSONParserErrorGroup.getParserErrors(parser); + if (errors.length > 0) { + throw new JSONParserErrorGroup(parser); + } +} + +/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../../../buffer/index.js */ "./node_modules/buffer/index.js").Buffer)) + +/***/ }), + +/***/ "./node_modules/@apidevtools/json-schema-ref-parser/lib/normalize-args.js": +/*!********************************************************************************!*\ + !*** ./node_modules/@apidevtools/json-schema-ref-parser/lib/normalize-args.js ***! + \********************************************************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +const Options = __webpack_require__(/*! ./options */ "./node_modules/@apidevtools/json-schema-ref-parser/lib/options.js"); + +module.exports = normalizeArgs; + +/** + * Normalizes the given arguments, accounting for optional args. + * + * @param {Arguments} args + * @returns {object} + */ +function normalizeArgs (args) { + let path, schema, options, callback; + args = Array.prototype.slice.call(args); + + if (typeof args[args.length - 1] === "function") { + // The last parameter is a callback function + callback = args.pop(); + } + + if (typeof args[0] === "string") { + // The first parameter is the path + path = args[0]; + if (typeof args[2] === "object") { + // The second parameter is the schema, and the third parameter is the options + schema = args[1]; + options = args[2]; + } + else { + // The second parameter is the options + schema = undefined; + options = args[1]; + } + } + else { + // The first parameter is the schema + path = ""; + schema = args[0]; + options = args[1]; + } + + if (!(options instanceof Options)) { + options = new Options(options); + } + + return { + path, + schema, + options, + callback + }; +} + + +/***/ }), + +/***/ "./node_modules/@apidevtools/json-schema-ref-parser/lib/options.js": +/*!*************************************************************************!*\ + !*** ./node_modules/@apidevtools/json-schema-ref-parser/lib/options.js ***! + \*************************************************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/* eslint lines-around-comment: [2, {beforeBlockComment: false}] */ + + +const jsonParser = __webpack_require__(/*! ./parsers/json */ "./node_modules/@apidevtools/json-schema-ref-parser/lib/parsers/json.js"); +const yamlParser = __webpack_require__(/*! ./parsers/yaml */ "./node_modules/@apidevtools/json-schema-ref-parser/lib/parsers/yaml.js"); +const textParser = __webpack_require__(/*! ./parsers/text */ "./node_modules/@apidevtools/json-schema-ref-parser/lib/parsers/text.js"); +const binaryParser = __webpack_require__(/*! ./parsers/binary */ "./node_modules/@apidevtools/json-schema-ref-parser/lib/parsers/binary.js"); +const fileResolver = __webpack_require__(/*! ./resolvers/file */ "./node_modules/@apidevtools/json-schema-ref-parser/lib/resolvers/file.js"); +const httpResolver = __webpack_require__(/*! ./resolvers/http */ "./node_modules/@apidevtools/json-schema-ref-parser/lib/resolvers/http.js"); + +module.exports = $RefParserOptions; + +/** + * Options that determine how JSON schemas are parsed, resolved, and dereferenced. + * + * @param {object|$RefParserOptions} [options] - Overridden options + * @constructor + */ +function $RefParserOptions (options) { + merge(this, $RefParserOptions.defaults); + merge(this, options); +} + +$RefParserOptions.defaults = { + /** + * Determines how different types of files will be parsed. + * + * You can add additional parsers of your own, replace an existing one with + * your own implementation, or disable any parser by setting it to false. + */ + parse: { + json: jsonParser, + yaml: yamlParser, + text: textParser, + binary: binaryParser, + }, + + /** + * Determines how JSON References will be resolved. + * + * You can add additional resolvers of your own, replace an existing one with + * your own implementation, or disable any resolver by setting it to false. + */ + resolve: { + file: fileResolver, + http: httpResolver, + + /** + * Determines whether external $ref pointers will be resolved. + * If this option is disabled, then none of above resolvers will be called. + * Instead, external $ref pointers will simply be ignored. + * + * @type {boolean} + */ + external: true, + }, + + /** + * By default, JSON Schema $Ref Parser throws the first error it encounters. Setting `continueOnError` to `true` + * causes it to keep processing as much as possible and then throw a single error that contains all errors + * that were encountered. + */ + continueOnError: false, + + /** + * Determines the types of JSON references that are allowed. + */ + dereference: { + /** + * Dereference circular (recursive) JSON references? + * If false, then a {@link ReferenceError} will be thrown if a circular reference is found. + * If "ignore", then circular references will not be dereferenced. + * + * @type {boolean|string} + */ + circular: true, + + /** + * A function, called for each path, which can return true to stop this path and all + * subpaths from being dereferenced further. This is useful in schemas where some + * subpaths contain literal $ref keys that should not be dereferenced. + * + * @type {function} + */ + excludedPathMatcher: () => false + }, +}; + +/** + * Merges the properties of the source object into the target object. + * + * @param {object} target - The object that we're populating + * @param {?object} source - The options that are being merged + * @returns {object} + */ +function merge (target, source) { + if (isMergeable(source)) { + let keys = Object.keys(source); + for (let i = 0; i < keys.length; i++) { + let key = keys[i]; + let sourceSetting = source[key]; + let targetSetting = target[key]; + + if (isMergeable(sourceSetting)) { + // It's a nested object, so merge it recursively + target[key] = merge(targetSetting || {}, sourceSetting); + } + else if (sourceSetting !== undefined) { + // It's a scalar value, function, or array. No merging necessary. Just overwrite the target value. + target[key] = sourceSetting; + } + } + } + return target; +} + +/** + * Determines whether the given value can be merged, + * or if it is a scalar value that should just override the target value. + * + * @param {*} val + * @returns {Boolean} + */ +function isMergeable (val) { + return val && + (typeof val === "object") && + !Array.isArray(val) && + !(val instanceof RegExp) && + !(val instanceof Date); +} + + +/***/ }), + +/***/ "./node_modules/@apidevtools/json-schema-ref-parser/lib/parse.js": +/*!***********************************************************************!*\ + !*** ./node_modules/@apidevtools/json-schema-ref-parser/lib/parse.js ***! + \***********************************************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/* WEBPACK VAR INJECTION */(function(Buffer) { + +const { ono } = __webpack_require__(/*! @jsdevtools/ono */ "./node_modules/@jsdevtools/ono/esm/index.js"); +const url = __webpack_require__(/*! ./util/url */ "./node_modules/@apidevtools/json-schema-ref-parser/lib/util/url.js"); +const plugins = __webpack_require__(/*! ./util/plugins */ "./node_modules/@apidevtools/json-schema-ref-parser/lib/util/plugins.js"); +const { ResolverError, ParserError, UnmatchedParserError, UnmatchedResolverError, isHandledError } = __webpack_require__(/*! ./util/errors */ "./node_modules/@apidevtools/json-schema-ref-parser/lib/util/errors.js"); + +module.exports = parse; + +/** + * Reads and parses the specified file path or URL. + * + * @param {string} path - This path MUST already be resolved, since `read` doesn't know the resolution context + * @param {$Refs} $refs + * @param {$RefParserOptions} options + * + * @returns {Promise} + * The promise resolves with the parsed file contents, NOT the raw (Buffer) contents. + */ +async function parse (path, $refs, options) { + // Remove the URL fragment, if any + path = url.stripHash(path); + + // Add a new $Ref for this file, even though we don't have the value yet. + // This ensures that we don't simultaneously read & parse the same file multiple times + let $ref = $refs._add(path); + + // This "file object" will be passed to all resolvers and parsers. + let file = { + url: path, + extension: url.getExtension(path), + }; + + // Read the file and then parse the data + try { + const resolver = await readFile(file, options, $refs); + $ref.pathType = resolver.plugin.name; + file.data = resolver.result; + + const parser = await parseFile(file, options, $refs); + $ref.value = parser.result; + + return parser.result; + } + catch (err) { + if (isHandledError(err)) { + $ref.value = err; + } + + throw err; + } +} + +/** + * Reads the given file, using the configured resolver plugins + * + * @param {object} file - An object containing information about the referenced file + * @param {string} file.url - The full URL of the referenced file + * @param {string} file.extension - The lowercased file extension (e.g. ".txt", ".html", etc.) + * @param {$RefParserOptions} options + * + * @returns {Promise} + * The promise resolves with the raw file contents and the resolver that was used. + */ +function readFile (file, options, $refs) { + return new Promise(((resolve, reject) => { + // console.log('Reading %s', file.url); + + // Find the resolvers that can read this file + let resolvers = plugins.all(options.resolve); + resolvers = plugins.filter(resolvers, "canRead", file); + + // Run the resolvers, in order, until one of them succeeds + plugins.sort(resolvers); + plugins.run(resolvers, "read", file, $refs) + .then(resolve, onError); + + function onError (err) { + if (!err && options.continueOnError) { + // No resolver could be matched + reject(new UnmatchedResolverError(file.url)); + } + else if (!err || !("error" in err)) { + // Throw a generic, friendly error. + reject(ono.syntax(`Unable to resolve $ref pointer "${file.url}"`)); + } + // Throw the original error, if it's one of our own (user-friendly) errors. + else if (err.error instanceof ResolverError) { + reject(err.error); + } + else { + reject(new ResolverError(err, file.url)); + } + } + })); +} + +/** + * Parses the given file's contents, using the configured parser plugins. + * + * @param {object} file - An object containing information about the referenced file + * @param {string} file.url - The full URL of the referenced file + * @param {string} file.extension - The lowercased file extension (e.g. ".txt", ".html", etc.) + * @param {*} file.data - The file contents. This will be whatever data type was returned by the resolver + * @param {$RefParserOptions} options + * + * @returns {Promise} + * The promise resolves with the parsed file contents and the parser that was used. + */ +function parseFile (file, options, $refs) { + return new Promise(((resolve, reject) => { + // console.log('Parsing %s', file.url); + + // Find the parsers that can read this file type. + // If none of the parsers are an exact match for this file, then we'll try ALL of them. + // This handles situations where the file IS a supported type, just with an unknown extension. + let allParsers = plugins.all(options.parse); + let filteredParsers = plugins.filter(allParsers, "canParse", file); + let parsers = filteredParsers.length > 0 ? filteredParsers : allParsers; + + // Run the parsers, in order, until one of them succeeds + plugins.sort(parsers); + plugins.run(parsers, "parse", file, $refs) + .then(onParsed, onError); + + function onParsed (parser) { + if (!parser.plugin.allowEmpty && isEmpty(parser.result)) { + reject(ono.syntax(`Error parsing "${file.url}" as ${parser.plugin.name}. \nParsed value is empty`)); + } + else { + resolve(parser); + } + } + + function onError (err) { + if (!err && options.continueOnError) { + // No resolver could be matched + reject(new UnmatchedParserError(file.url)); + } + else if (!err || !("error" in err)) { + reject(ono.syntax(`Unable to parse ${file.url}`)); + } + else if (err.error instanceof ParserError) { + reject(err.error); + } + else { + reject(new ParserError(err.error.message, file.url)); + } + } + })); +} + +/** + * Determines whether the parsed value is "empty". + * + * @param {*} value + * @returns {boolean} + */ +function isEmpty (value) { + return value === undefined || + (typeof value === "object" && Object.keys(value).length === 0) || + (typeof value === "string" && value.trim().length === 0) || + (Buffer.isBuffer(value) && value.length === 0); +} + +/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../../../buffer/index.js */ "./node_modules/buffer/index.js").Buffer)) + +/***/ }), + +/***/ "./node_modules/@apidevtools/json-schema-ref-parser/lib/parsers/binary.js": +/*!********************************************************************************!*\ + !*** ./node_modules/@apidevtools/json-schema-ref-parser/lib/parsers/binary.js ***! + \********************************************************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/* WEBPACK VAR INJECTION */(function(Buffer) { + +let BINARY_REGEXP = /\.(jpeg|jpg|gif|png|bmp|ico)$/i; + +module.exports = { + /** + * The order that this parser will run, in relation to other parsers. + * + * @type {number} + */ + order: 400, + + /** + * Whether to allow "empty" files (zero bytes). + * + * @type {boolean} + */ + allowEmpty: true, + + /** + * Determines whether this parser can parse a given file reference. + * Parsers that return true will be tried, in order, until one successfully parses the file. + * Parsers that return false will be skipped, UNLESS all parsers returned false, in which case + * every parser will be tried. + * + * @param {object} file - An object containing information about the referenced file + * @param {string} file.url - The full URL of the referenced file + * @param {string} file.extension - The lowercased file extension (e.g. ".txt", ".html", etc.) + * @param {*} file.data - The file contents. This will be whatever data type was returned by the resolver + * @returns {boolean} + */ + canParse (file) { + // Use this parser if the file is a Buffer, and has a known binary extension + return Buffer.isBuffer(file.data) && BINARY_REGEXP.test(file.url); + }, + + /** + * Parses the given data as a Buffer (byte array). + * + * @param {object} file - An object containing information about the referenced file + * @param {string} file.url - The full URL of the referenced file + * @param {string} file.extension - The lowercased file extension (e.g. ".txt", ".html", etc.) + * @param {*} file.data - The file contents. This will be whatever data type was returned by the resolver + * @returns {Buffer} + */ + parse (file) { + if (Buffer.isBuffer(file.data)) { + return file.data; + } + else { + // This will reject if data is anything other than a string or typed array + return Buffer.from(file.data); + } + } +}; + +/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../../../../buffer/index.js */ "./node_modules/buffer/index.js").Buffer)) + +/***/ }), + +/***/ "./node_modules/@apidevtools/json-schema-ref-parser/lib/parsers/json.js": +/*!******************************************************************************!*\ + !*** ./node_modules/@apidevtools/json-schema-ref-parser/lib/parsers/json.js ***! + \******************************************************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/* WEBPACK VAR INJECTION */(function(Buffer) { + +const { ParserError } = __webpack_require__(/*! ../util/errors */ "./node_modules/@apidevtools/json-schema-ref-parser/lib/util/errors.js"); + +module.exports = { + /** + * The order that this parser will run, in relation to other parsers. + * + * @type {number} + */ + order: 100, + + /** + * Whether to allow "empty" files. This includes zero-byte files, as well as empty JSON objects. + * + * @type {boolean} + */ + allowEmpty: true, + + /** + * Determines whether this parser can parse a given file reference. + * Parsers that match will be tried, in order, until one successfully parses the file. + * Parsers that don't match will be skipped, UNLESS none of the parsers match, in which case + * every parser will be tried. + * + * @type {RegExp|string|string[]|function} + */ + canParse: ".json", + + /** + * Parses the given file as JSON + * + * @param {object} file - An object containing information about the referenced file + * @param {string} file.url - The full URL of the referenced file + * @param {string} file.extension - The lowercased file extension (e.g. ".txt", ".html", etc.) + * @param {*} file.data - The file contents. This will be whatever data type was returned by the resolver + * @returns {Promise} + */ + async parse (file) { // eslint-disable-line require-await + let data = file.data; + if (Buffer.isBuffer(data)) { + data = data.toString(); + } + + if (typeof data === "string") { + if (data.trim().length === 0) { + return; // This mirrors the YAML behavior + } + else { + try { + return JSON.parse(data); + } + catch (e) { + throw new ParserError(e.message, file.url); + } + } + } + else { + // data is already a JavaScript value (object, array, number, null, NaN, etc.) + return data; + } + } +}; + +/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../../../../buffer/index.js */ "./node_modules/buffer/index.js").Buffer)) + +/***/ }), + +/***/ "./node_modules/@apidevtools/json-schema-ref-parser/lib/parsers/text.js": +/*!******************************************************************************!*\ + !*** ./node_modules/@apidevtools/json-schema-ref-parser/lib/parsers/text.js ***! + \******************************************************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/* WEBPACK VAR INJECTION */(function(Buffer) { + +const { ParserError } = __webpack_require__(/*! ../util/errors */ "./node_modules/@apidevtools/json-schema-ref-parser/lib/util/errors.js"); + +let TEXT_REGEXP = /\.(txt|htm|html|md|xml|js|min|map|css|scss|less|svg)$/i; + +module.exports = { + /** + * The order that this parser will run, in relation to other parsers. + * + * @type {number} + */ + order: 300, + + /** + * Whether to allow "empty" files (zero bytes). + * + * @type {boolean} + */ + allowEmpty: true, + + /** + * The encoding that the text is expected to be in. + * + * @type {string} + */ + encoding: "utf8", + + /** + * Determines whether this parser can parse a given file reference. + * Parsers that return true will be tried, in order, until one successfully parses the file. + * Parsers that return false will be skipped, UNLESS all parsers returned false, in which case + * every parser will be tried. + * + * @param {object} file - An object containing information about the referenced file + * @param {string} file.url - The full URL of the referenced file + * @param {string} file.extension - The lowercased file extension (e.g. ".txt", ".html", etc.) + * @param {*} file.data - The file contents. This will be whatever data type was returned by the resolver + * @returns {boolean} + */ + canParse (file) { + // Use this parser if the file is a string or Buffer, and has a known text-based extension + return (typeof file.data === "string" || Buffer.isBuffer(file.data)) && TEXT_REGEXP.test(file.url); + }, + + /** + * Parses the given file as text + * + * @param {object} file - An object containing information about the referenced file + * @param {string} file.url - The full URL of the referenced file + * @param {string} file.extension - The lowercased file extension (e.g. ".txt", ".html", etc.) + * @param {*} file.data - The file contents. This will be whatever data type was returned by the resolver + * @returns {string} + */ + parse (file) { + if (typeof file.data === "string") { + return file.data; + } + else if (Buffer.isBuffer(file.data)) { + return file.data.toString(this.encoding); + } + else { + throw new ParserError("data is not text", file.url); + } + } +}; + +/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../../../../buffer/index.js */ "./node_modules/buffer/index.js").Buffer)) + +/***/ }), + +/***/ "./node_modules/@apidevtools/json-schema-ref-parser/lib/parsers/yaml.js": +/*!******************************************************************************!*\ + !*** ./node_modules/@apidevtools/json-schema-ref-parser/lib/parsers/yaml.js ***! + \******************************************************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/* WEBPACK VAR INJECTION */(function(Buffer) { + +const { ParserError } = __webpack_require__(/*! ../util/errors */ "./node_modules/@apidevtools/json-schema-ref-parser/lib/util/errors.js"); +const yaml = __webpack_require__(/*! js-yaml */ "./node_modules/js-yaml/dist/js-yaml.mjs"); +const { JSON_SCHEMA } = __webpack_require__(/*! js-yaml */ "./node_modules/js-yaml/dist/js-yaml.mjs"); + +module.exports = { + /** + * The order that this parser will run, in relation to other parsers. + * + * @type {number} + */ + order: 200, + + /** + * Whether to allow "empty" files. This includes zero-byte files, as well as empty JSON objects. + * + * @type {boolean} + */ + allowEmpty: true, + + /** + * Determines whether this parser can parse a given file reference. + * Parsers that match will be tried, in order, until one successfully parses the file. + * Parsers that don't match will be skipped, UNLESS none of the parsers match, in which case + * every parser will be tried. + * + * @type {RegExp|string[]|function} + */ + canParse: [".yaml", ".yml", ".json"], // JSON is valid YAML + + /** + * Parses the given file as YAML + * + * @param {object} file - An object containing information about the referenced file + * @param {string} file.url - The full URL of the referenced file + * @param {string} file.extension - The lowercased file extension (e.g. ".txt", ".html", etc.) + * @param {*} file.data - The file contents. This will be whatever data type was returned by the resolver + * @returns {Promise} + */ + async parse (file) { // eslint-disable-line require-await + let data = file.data; + if (Buffer.isBuffer(data)) { + data = data.toString(); + } + + if (typeof data === "string") { + try { + return yaml.load(data, { schema: JSON_SCHEMA }); + } + catch (e) { + throw new ParserError(e.message, file.url); + } + } + else { + // data is already a JavaScript value (object, array, number, null, NaN, etc.) + return data; + } + } +}; + +/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../../../../buffer/index.js */ "./node_modules/buffer/index.js").Buffer)) + +/***/ }), + +/***/ "./node_modules/@apidevtools/json-schema-ref-parser/lib/pointer.js": +/*!*************************************************************************!*\ + !*** ./node_modules/@apidevtools/json-schema-ref-parser/lib/pointer.js ***! + \*************************************************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +module.exports = Pointer; + +const $Ref = __webpack_require__(/*! ./ref */ "./node_modules/@apidevtools/json-schema-ref-parser/lib/ref.js"); +const url = __webpack_require__(/*! ./util/url */ "./node_modules/@apidevtools/json-schema-ref-parser/lib/util/url.js"); +const { JSONParserError, InvalidPointerError, MissingPointerError, isHandledError } = __webpack_require__(/*! ./util/errors */ "./node_modules/@apidevtools/json-schema-ref-parser/lib/util/errors.js"); +const slashes = /\//g; +const tildes = /~/g; +const escapedSlash = /~1/g; +const escapedTilde = /~0/g; + +/** + * This class represents a single JSON pointer and its resolved value. + * + * @param {$Ref} $ref + * @param {string} path + * @param {string} [friendlyPath] - The original user-specified path (used for error messages) + * @constructor + */ +function Pointer ($ref, path, friendlyPath) { + /** + * The {@link $Ref} object that contains this {@link Pointer} object. + * @type {$Ref} + */ + this.$ref = $ref; + + /** + * The file path or URL, containing the JSON pointer in the hash. + * This path is relative to the path of the main JSON schema file. + * @type {string} + */ + this.path = path; + + /** + * The original path or URL, used for error messages. + * @type {string} + */ + this.originalPath = friendlyPath || path; + + /** + * The value of the JSON pointer. + * Can be any JSON type, not just objects. Unknown file types are represented as Buffers (byte arrays). + * @type {?*} + */ + this.value = undefined; + + /** + * Indicates whether the pointer references itself. + * @type {boolean} + */ + this.circular = false; + + /** + * The number of indirect references that were traversed to resolve the value. + * Resolving a single pointer may require resolving multiple $Refs. + * @type {number} + */ + this.indirections = 0; +} + +/** + * Resolves the value of a nested property within the given object. + * + * @param {*} obj - The object that will be crawled + * @param {$RefParserOptions} options + * @param {string} pathFromRoot - the path of place that initiated resolving + * + * @returns {Pointer} + * Returns a JSON pointer whose {@link Pointer#value} is the resolved value. + * If resolving this value required resolving other JSON references, then + * the {@link Pointer#$ref} and {@link Pointer#path} will reflect the resolution path + * of the resolved value. + */ +Pointer.prototype.resolve = function (obj, options, pathFromRoot) { + let tokens = Pointer.parse(this.path, this.originalPath); + + // Crawl the object, one token at a time + this.value = unwrapOrThrow(obj); + + for (let i = 0; i < tokens.length; i++) { + if (resolveIf$Ref(this, options)) { + // The $ref path has changed, so append the remaining tokens to the path + this.path = Pointer.join(this.path, tokens.slice(i)); + } + + if (typeof this.value === "object" && this.value !== null && "$ref" in this.value) { + return this; + } + + let token = tokens[i]; + if (this.value[token] === undefined || this.value[token] === null) { + this.value = null; + throw new MissingPointerError(token, decodeURI(this.originalPath)); + } + else { + this.value = this.value[token]; + } + } + + // Resolve the final value + if (!this.value || this.value.$ref && url.resolve(this.path, this.value.$ref) !== pathFromRoot) { + resolveIf$Ref(this, options); + } + + return this; +}; + +/** + * Sets the value of a nested property within the given object. + * + * @param {*} obj - The object that will be crawled + * @param {*} value - the value to assign + * @param {$RefParserOptions} options + * + * @returns {*} + * Returns the modified object, or an entirely new object if the entire object is overwritten. + */ +Pointer.prototype.set = function (obj, value, options) { + let tokens = Pointer.parse(this.path); + let token; + + if (tokens.length === 0) { + // There are no tokens, replace the entire object with the new value + this.value = value; + return value; + } + + // Crawl the object, one token at a time + this.value = unwrapOrThrow(obj); + + for (let i = 0; i < tokens.length - 1; i++) { + resolveIf$Ref(this, options); + + token = tokens[i]; + if (this.value && this.value[token] !== undefined) { + // The token exists + this.value = this.value[token]; + } + else { + // The token doesn't exist, so create it + this.value = setValue(this, token, {}); + } + } + + // Set the value of the final token + resolveIf$Ref(this, options); + token = tokens[tokens.length - 1]; + setValue(this, token, value); + + // Return the updated object + return obj; +}; + +/** + * Parses a JSON pointer (or a path containing a JSON pointer in the hash) + * and returns an array of the pointer's tokens. + * (e.g. "schema.json#/definitions/person/name" => ["definitions", "person", "name"]) + * + * The pointer is parsed according to RFC 6901 + * {@link https://tools.ietf.org/html/rfc6901#section-3} + * + * @param {string} path + * @param {string} [originalPath] + * @returns {string[]} + */ +Pointer.parse = function (path, originalPath) { + // Get the JSON pointer from the path's hash + let pointer = url.getHash(path).substr(1); + + // If there's no pointer, then there are no tokens, + // so return an empty array + if (!pointer) { + return []; + } + + // Split into an array + pointer = pointer.split("/"); + + // Decode each part, according to RFC 6901 + for (let i = 0; i < pointer.length; i++) { + pointer[i] = decodeURIComponent(pointer[i].replace(escapedSlash, "/").replace(escapedTilde, "~")); + } + + if (pointer[0] !== "") { + throw new InvalidPointerError(pointer, originalPath === undefined ? path : originalPath); + } + + return pointer.slice(1); +}; + +/** + * Creates a JSON pointer path, by joining one or more tokens to a base path. + * + * @param {string} base - The base path (e.g. "schema.json#/definitions/person") + * @param {string|string[]} tokens - The token(s) to append (e.g. ["name", "first"]) + * @returns {string} + */ +Pointer.join = function (base, tokens) { + // Ensure that the base path contains a hash + if (base.indexOf("#") === -1) { + base += "#"; + } + + // Append each token to the base path + tokens = Array.isArray(tokens) ? tokens : [tokens]; + for (let i = 0; i < tokens.length; i++) { + let token = tokens[i]; + // Encode the token, according to RFC 6901 + base += "/" + encodeURIComponent(token.replace(tildes, "~0").replace(slashes, "~1")); + } + + return base; +}; + +/** + * If the given pointer's {@link Pointer#value} is a JSON reference, + * then the reference is resolved and {@link Pointer#value} is replaced with the resolved value. + * In addition, {@link Pointer#path} and {@link Pointer#$ref} are updated to reflect the + * resolution path of the new value. + * + * @param {Pointer} pointer + * @param {$RefParserOptions} options + * @returns {boolean} - Returns `true` if the resolution path changed + */ +function resolveIf$Ref (pointer, options) { + // Is the value a JSON reference? (and allowed?) + + if ($Ref.isAllowed$Ref(pointer.value, options)) { + let $refPath = url.resolve(pointer.path, pointer.value.$ref); + + if ($refPath === pointer.path) { + // The value is a reference to itself, so there's nothing to do. + pointer.circular = true; + } + else { + let resolved = pointer.$ref.$refs._resolve($refPath, pointer.path, options); + if (resolved === null) { + return false; + } + + pointer.indirections += resolved.indirections + 1; + + if ($Ref.isExtended$Ref(pointer.value)) { + // This JSON reference "extends" the resolved value, rather than simply pointing to it. + // So the resolved path does NOT change. Just the value does. + pointer.value = $Ref.dereference(pointer.value, resolved.value); + return false; + } + else { + // Resolve the reference + pointer.$ref = resolved.$ref; + pointer.path = resolved.path; + pointer.value = resolved.value; + } + + return true; + } + } +} + +/** + * Sets the specified token value of the {@link Pointer#value}. + * + * The token is evaluated according to RFC 6901. + * {@link https://tools.ietf.org/html/rfc6901#section-4} + * + * @param {Pointer} pointer - The JSON Pointer whose value will be modified + * @param {string} token - A JSON Pointer token that indicates how to modify `obj` + * @param {*} value - The value to assign + * @returns {*} - Returns the assigned value + */ +function setValue (pointer, token, value) { + if (pointer.value && typeof pointer.value === "object") { + if (token === "-" && Array.isArray(pointer.value)) { + pointer.value.push(value); + } + else { + pointer.value[token] = value; + } + } + else { + throw new JSONParserError(`Error assigning $ref pointer "${pointer.path}". \nCannot set "${token}" of a non-object.`); + } + return value; +} + + +function unwrapOrThrow (value) { + if (isHandledError(value)) { + throw value; + } + + return value; +} + + +/***/ }), + +/***/ "./node_modules/@apidevtools/json-schema-ref-parser/lib/ref.js": +/*!*********************************************************************!*\ + !*** ./node_modules/@apidevtools/json-schema-ref-parser/lib/ref.js ***! + \*********************************************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +module.exports = $Ref; + +const Pointer = __webpack_require__(/*! ./pointer */ "./node_modules/@apidevtools/json-schema-ref-parser/lib/pointer.js"); +const { InvalidPointerError, isHandledError, normalizeError } = __webpack_require__(/*! ./util/errors */ "./node_modules/@apidevtools/json-schema-ref-parser/lib/util/errors.js"); +const { safePointerToPath, stripHash, getHash } = __webpack_require__(/*! ./util/url */ "./node_modules/@apidevtools/json-schema-ref-parser/lib/util/url.js"); + +/** + * This class represents a single JSON reference and its resolved value. + * + * @class + */ +function $Ref () { + /** + * The file path or URL of the referenced file. + * This path is relative to the path of the main JSON schema file. + * + * This path does NOT contain document fragments (JSON pointers). It always references an ENTIRE file. + * Use methods such as {@link $Ref#get}, {@link $Ref#resolve}, and {@link $Ref#exists} to get + * specific JSON pointers within the file. + * + * @type {string} + */ + this.path = undefined; + + /** + * The resolved value of the JSON reference. + * Can be any JSON type, not just objects. Unknown file types are represented as Buffers (byte arrays). + * + * @type {?*} + */ + this.value = undefined; + + /** + * The {@link $Refs} object that contains this {@link $Ref} object. + * + * @type {$Refs} + */ + this.$refs = undefined; + + /** + * Indicates the type of {@link $Ref#path} (e.g. "file", "http", etc.) + * + * @type {?string} + */ + this.pathType = undefined; + + /** + * List of all errors. Undefined if no errors. + * + * @type {Array} + */ + this.errors = undefined; +} + +/** + * Pushes an error to errors array. + * + * @param {Array} err - The error to be pushed + * @returns {void} + */ +$Ref.prototype.addError = function (err) { + if (this.errors === undefined) { + this.errors = []; + } + + const existingErrors = this.errors.map(({ footprint }) => footprint); + + // the path has been almost certainly set at this point, + // but just in case something went wrong, normalizeError injects path if necessary + // moreover, certain errors might point at the same spot, so filter them out to reduce noise + if (Array.isArray(err.errors)) { + this.errors.push(...err.errors + .map(normalizeError) + .filter(({ footprint }) => !existingErrors.includes(footprint)), + ); + } + else if (!existingErrors.includes(err.footprint)) { + this.errors.push(normalizeError(err)); + } +}; + +/** + * Determines whether the given JSON reference exists within this {@link $Ref#value}. + * + * @param {string} path - The full path being resolved, optionally with a JSON pointer in the hash + * @param {$RefParserOptions} options + * @returns {boolean} + */ +$Ref.prototype.exists = function (path, options) { + try { + this.resolve(path, options); + return true; + } + catch (e) { + return false; + } +}; + +/** + * Resolves the given JSON reference within this {@link $Ref#value} and returns the resolved value. + * + * @param {string} path - The full path being resolved, optionally with a JSON pointer in the hash + * @param {$RefParserOptions} options + * @returns {*} - Returns the resolved value + */ +$Ref.prototype.get = function (path, options) { + return this.resolve(path, options).value; +}; + +/** + * Resolves the given JSON reference within this {@link $Ref#value}. + * + * @param {string} path - The full path being resolved, optionally with a JSON pointer in the hash + * @param {$RefParserOptions} options + * @param {string} friendlyPath - The original user-specified path (used for error messages) + * @param {string} pathFromRoot - The path of `obj` from the schema root + * @returns {Pointer | null} + */ +$Ref.prototype.resolve = function (path, options, friendlyPath, pathFromRoot) { + let pointer = new Pointer(this, path, friendlyPath); + try { + return pointer.resolve(this.value, options, pathFromRoot); + } + catch (err) { + if (!options || !options.continueOnError || !isHandledError(err)) { + throw err; + } + + if (err.path === null) { + err.path = safePointerToPath(getHash(pathFromRoot)); + } + + if (err instanceof InvalidPointerError) { + // this is a special case - InvalidPointerError is thrown when dereferencing external file, + // but the issue is caused by the source file that referenced the file that undergoes dereferencing + err.source = decodeURI(stripHash(pathFromRoot)); + } + + this.addError(err); + return null; + } +}; + +/** + * Sets the value of a nested property within this {@link $Ref#value}. + * If the property, or any of its parents don't exist, they will be created. + * + * @param {string} path - The full path of the property to set, optionally with a JSON pointer in the hash + * @param {*} value - The value to assign + */ +$Ref.prototype.set = function (path, value) { + let pointer = new Pointer(this, path); + this.value = pointer.set(this.value, value); +}; + +/** + * Determines whether the given value is a JSON reference. + * + * @param {*} value - The value to inspect + * @returns {boolean} + */ +$Ref.is$Ref = function (value) { + return value && typeof value === "object" && typeof value.$ref === "string" && value.$ref.length > 0; +}; + +/** + * Determines whether the given value is an external JSON reference. + * + * @param {*} value - The value to inspect + * @returns {boolean} + */ +$Ref.isExternal$Ref = function (value) { + return $Ref.is$Ref(value) && value.$ref[0] !== "#"; +}; + +/** + * Determines whether the given value is a JSON reference, and whether it is allowed by the options. + * For example, if it references an external file, then options.resolve.external must be true. + * + * @param {*} value - The value to inspect + * @param {$RefParserOptions} options + * @returns {boolean} + */ +$Ref.isAllowed$Ref = function (value, options) { + if ($Ref.is$Ref(value)) { + if (value.$ref.substr(0, 2) === "#/" || value.$ref === "#") { + // It's a JSON Pointer reference, which is always allowed + return true; + } + else if (value.$ref[0] !== "#" && (!options || options.resolve.external)) { + // It's an external reference, which is allowed by the options + return true; + } + } +}; + +/** + * Determines whether the given value is a JSON reference that "extends" its resolved value. + * That is, it has extra properties (in addition to "$ref"), so rather than simply pointing to + * an existing value, this $ref actually creates a NEW value that is a shallow copy of the resolved + * value, plus the extra properties. + * + * @example: + * { + * person: { + * properties: { + * firstName: { type: string } + * lastName: { type: string } + * } + * } + * employee: { + * properties: { + * $ref: #/person/properties + * salary: { type: number } + * } + * } + * } + * + * In this example, "employee" is an extended $ref, since it extends "person" with an additional + * property (salary). The result is a NEW value that looks like this: + * + * { + * properties: { + * firstName: { type: string } + * lastName: { type: string } + * salary: { type: number } + * } + * } + * + * @param {*} value - The value to inspect + * @returns {boolean} + */ +$Ref.isExtended$Ref = function (value) { + return $Ref.is$Ref(value) && Object.keys(value).length > 1; +}; + +/** + * Returns the resolved value of a JSON Reference. + * If necessary, the resolved value is merged with the JSON Reference to create a new object + * + * @example: + * { + * person: { + * properties: { + * firstName: { type: string } + * lastName: { type: string } + * } + * } + * employee: { + * properties: { + * $ref: #/person/properties + * salary: { type: number } + * } + * } + * } + * + * When "person" and "employee" are merged, you end up with the following object: + * + * { + * properties: { + * firstName: { type: string } + * lastName: { type: string } + * salary: { type: number } + * } + * } + * + * @param {object} $ref - The JSON reference object (the one with the "$ref" property) + * @param {*} resolvedValue - The resolved value, which can be any type + * @returns {*} - Returns the dereferenced value + */ +$Ref.dereference = function ($ref, resolvedValue) { + if (resolvedValue && typeof resolvedValue === "object" && $Ref.isExtended$Ref($ref)) { + let merged = {}; + for (let key of Object.keys($ref)) { + if (key !== "$ref") { + merged[key] = $ref[key]; + } + } + + for (let key of Object.keys(resolvedValue)) { + if (!(key in merged)) { + merged[key] = resolvedValue[key]; + } + } + + return merged; + } + else { + // Completely replace the original reference with the resolved value + return resolvedValue; + } +}; + + +/***/ }), + +/***/ "./node_modules/@apidevtools/json-schema-ref-parser/lib/refs.js": +/*!**********************************************************************!*\ + !*** ./node_modules/@apidevtools/json-schema-ref-parser/lib/refs.js ***! + \**********************************************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +const { ono } = __webpack_require__(/*! @jsdevtools/ono */ "./node_modules/@jsdevtools/ono/esm/index.js"); +const $Ref = __webpack_require__(/*! ./ref */ "./node_modules/@apidevtools/json-schema-ref-parser/lib/ref.js"); +const url = __webpack_require__(/*! ./util/url */ "./node_modules/@apidevtools/json-schema-ref-parser/lib/util/url.js"); + +module.exports = $Refs; + +/** + * This class is a map of JSON references and their resolved values. + */ +function $Refs () { + /** + * Indicates whether the schema contains any circular references. + * + * @type {boolean} + */ + this.circular = false; + + /** + * A map of paths/urls to {@link $Ref} objects + * + * @type {object} + * @protected + */ + this._$refs = {}; + + /** + * The {@link $Ref} object that is the root of the JSON schema. + * + * @type {$Ref} + * @protected + */ + this._root$Ref = null; +} + +/** + * Returns the paths of all the files/URLs that are referenced by the JSON schema, + * including the schema itself. + * + * @param {...string|string[]} [types] - Only return paths of the given types ("file", "http", etc.) + * @returns {string[]} + */ +$Refs.prototype.paths = function (types) { // eslint-disable-line no-unused-vars + let paths = getPaths(this._$refs, arguments); + return paths.map((path) => { + return path.decoded; + }); +}; + +/** + * Returns the map of JSON references and their resolved values. + * + * @param {...string|string[]} [types] - Only return references of the given types ("file", "http", etc.) + * @returns {object} + */ +$Refs.prototype.values = function (types) { // eslint-disable-line no-unused-vars + let $refs = this._$refs; + let paths = getPaths($refs, arguments); + return paths.reduce((obj, path) => { + obj[path.decoded] = $refs[path.encoded].value; + return obj; + }, {}); +}; + +/** + * Returns a POJO (plain old JavaScript object) for serialization as JSON. + * + * @returns {object} + */ +$Refs.prototype.toJSON = $Refs.prototype.values; + +/** + * Determines whether the given JSON reference exists. + * + * @param {string} path - The path being resolved, optionally with a JSON pointer in the hash + * @param {$RefParserOptions} [options] + * @returns {boolean} + */ +$Refs.prototype.exists = function (path, options) { + try { + this._resolve(path, "", options); + return true; + } + catch (e) { + return false; + } +}; + +/** + * Resolves the given JSON reference and returns the resolved value. + * + * @param {string} path - The path being resolved, with a JSON pointer in the hash + * @param {$RefParserOptions} [options] + * @returns {*} - Returns the resolved value + */ +$Refs.prototype.get = function (path, options) { + return this._resolve(path, "", options).value; +}; + +/** + * Sets the value of a nested property within this {@link $Ref#value}. + * If the property, or any of its parents don't exist, they will be created. + * + * @param {string} path - The path of the property to set, optionally with a JSON pointer in the hash + * @param {*} value - The value to assign + */ +$Refs.prototype.set = function (path, value) { + let absPath = url.resolve(this._root$Ref.path, path); + let withoutHash = url.stripHash(absPath); + let $ref = this._$refs[withoutHash]; + + if (!$ref) { + throw ono(`Error resolving $ref pointer "${path}". \n"${withoutHash}" not found.`); + } + + $ref.set(absPath, value); +}; + +/** + * Creates a new {@link $Ref} object and adds it to this {@link $Refs} object. + * + * @param {string} path - The file path or URL of the referenced file + */ +$Refs.prototype._add = function (path) { + let withoutHash = url.stripHash(path); + + let $ref = new $Ref(); + $ref.path = withoutHash; + $ref.$refs = this; + + this._$refs[withoutHash] = $ref; + this._root$Ref = this._root$Ref || $ref; + + return $ref; +}; + +/** + * Resolves the given JSON reference. + * + * @param {string} path - The path being resolved, optionally with a JSON pointer in the hash + * @param {string} pathFromRoot - The path of `obj` from the schema root + * @param {$RefParserOptions} [options] + * @returns {Pointer} + * @protected + */ +$Refs.prototype._resolve = function (path, pathFromRoot, options) { + let absPath = url.resolve(this._root$Ref.path, path); + let withoutHash = url.stripHash(absPath); + let $ref = this._$refs[withoutHash]; + + if (!$ref) { + throw ono(`Error resolving $ref pointer "${path}". \n"${withoutHash}" not found.`); + } + + return $ref.resolve(absPath, options, path, pathFromRoot); +}; + +/** + * Returns the specified {@link $Ref} object, or undefined. + * + * @param {string} path - The path being resolved, optionally with a JSON pointer in the hash + * @returns {$Ref|undefined} + * @protected + */ +$Refs.prototype._get$Ref = function (path) { + path = url.resolve(this._root$Ref.path, path); + let withoutHash = url.stripHash(path); + return this._$refs[withoutHash]; +}; + +/** + * Returns the encoded and decoded paths keys of the given object. + * + * @param {object} $refs - The object whose keys are URL-encoded paths + * @param {...string|string[]} [types] - Only return paths of the given types ("file", "http", etc.) + * @returns {object[]} + */ +function getPaths ($refs, types) { + let paths = Object.keys($refs); + + // Filter the paths by type + types = Array.isArray(types[0]) ? types[0] : Array.prototype.slice.call(types); + if (types.length > 0 && types[0]) { + paths = paths.filter((key) => { + return types.indexOf($refs[key].pathType) !== -1; + }); + } + + // Decode local filesystem paths + return paths.map((path) => { + return { + encoded: path, + decoded: $refs[path].pathType === "file" ? url.toFileSystemPath(path, true) : path + }; + }); +} + + +/***/ }), + +/***/ "./node_modules/@apidevtools/json-schema-ref-parser/lib/resolve-external.js": +/*!**********************************************************************************!*\ + !*** ./node_modules/@apidevtools/json-schema-ref-parser/lib/resolve-external.js ***! + \**********************************************************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +const $Ref = __webpack_require__(/*! ./ref */ "./node_modules/@apidevtools/json-schema-ref-parser/lib/ref.js"); +const Pointer = __webpack_require__(/*! ./pointer */ "./node_modules/@apidevtools/json-schema-ref-parser/lib/pointer.js"); +const parse = __webpack_require__(/*! ./parse */ "./node_modules/@apidevtools/json-schema-ref-parser/lib/parse.js"); +const url = __webpack_require__(/*! ./util/url */ "./node_modules/@apidevtools/json-schema-ref-parser/lib/util/url.js"); +const { isHandledError } = __webpack_require__(/*! ./util/errors */ "./node_modules/@apidevtools/json-schema-ref-parser/lib/util/errors.js"); + +module.exports = resolveExternal; + +/** + * Crawls the JSON schema, finds all external JSON references, and resolves their values. + * This method does not mutate the JSON schema. The resolved values are added to {@link $RefParser#$refs}. + * + * NOTE: We only care about EXTERNAL references here. INTERNAL references are only relevant when dereferencing. + * + * @param {$RefParser} parser + * @param {$RefParserOptions} options + * + * @returns {Promise} + * The promise resolves once all JSON references in the schema have been resolved, + * including nested references that are contained in externally-referenced files. + */ +function resolveExternal (parser, options) { + if (!options.resolve.external) { + // Nothing to resolve, so exit early + return Promise.resolve(); + } + + try { + // console.log('Resolving $ref pointers in %s', parser.$refs._root$Ref.path); + let promises = crawl(parser.schema, parser.$refs._root$Ref.path + "#", parser.$refs, options); + return Promise.all(promises); + } + catch (e) { + return Promise.reject(e); + } +} + +/** + * Recursively crawls the given value, and resolves any external JSON references. + * + * @param {*} obj - The value to crawl. If it's not an object or array, it will be ignored. + * @param {string} path - The full path of `obj`, possibly with a JSON Pointer in the hash + * @param {$Refs} $refs + * @param {$RefParserOptions} options + * @param {Set} seen - Internal. + * + * @returns {Promise[]} + * Returns an array of promises. There will be one promise for each JSON reference in `obj`. + * If `obj` does not contain any JSON references, then the array will be empty. + * If any of the JSON references point to files that contain additional JSON references, + * then the corresponding promise will internally reference an array of promises. + */ +function crawl (obj, path, $refs, options, seen) { + seen = seen || new Set(); + let promises = []; + + if (obj && typeof obj === "object" && !ArrayBuffer.isView(obj) && !seen.has(obj)) { + seen.add(obj); // Track previously seen objects to avoid infinite recursion + if ($Ref.isExternal$Ref(obj)) { + promises.push(resolve$Ref(obj, path, $refs, options)); + } + else { + for (let key of Object.keys(obj)) { + let keyPath = Pointer.join(path, key); + let value = obj[key]; + + if ($Ref.isExternal$Ref(value)) { + promises.push(resolve$Ref(value, keyPath, $refs, options)); + } + else { + promises = promises.concat(crawl(value, keyPath, $refs, options, seen)); + } + } + } + } + + return promises; +} + +/** + * Resolves the given JSON Reference, and then crawls the resulting value. + * + * @param {{$ref: string}} $ref - The JSON Reference to resolve + * @param {string} path - The full path of `$ref`, possibly with a JSON Pointer in the hash + * @param {$Refs} $refs + * @param {$RefParserOptions} options + * + * @returns {Promise} + * The promise resolves once all JSON references in the object have been resolved, + * including nested references that are contained in externally-referenced files. + */ +async function resolve$Ref ($ref, path, $refs, options) { + // console.log('Resolving $ref pointer "%s" at %s', $ref.$ref, path); + + let resolvedPath = url.resolve(path, $ref.$ref); + let withoutHash = url.stripHash(resolvedPath); + + // Do we already have this $ref? + $ref = $refs._$refs[withoutHash]; + if ($ref) { + // We've already parsed this $ref, so use the existing value + return Promise.resolve($ref.value); + } + + // Parse the $referenced file/url + try { + const result = await parse(resolvedPath, $refs, options); + + // Crawl the parsed value + // console.log('Resolving $ref pointers in %s', withoutHash); + let promises = crawl(result, withoutHash + "#", $refs, options); + + return Promise.all(promises); + } + catch (err) { + if (!options.continueOnError || !isHandledError(err)) { + throw err; + } + + if ($refs._$refs[withoutHash]) { + err.source = decodeURI(url.stripHash(path)); + err.path = url.safePointerToPath(url.getHash(path)); + } + + return []; + } +} + + +/***/ }), + +/***/ "./node_modules/@apidevtools/json-schema-ref-parser/lib/resolvers/file.js": +/*!********************************************************************************!*\ + !*** ./node_modules/@apidevtools/json-schema-ref-parser/lib/resolvers/file.js ***! + \********************************************************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +const fs = __webpack_require__(/*! fs */ 8); +const { ono } = __webpack_require__(/*! @jsdevtools/ono */ "./node_modules/@jsdevtools/ono/esm/index.js"); +const url = __webpack_require__(/*! ../util/url */ "./node_modules/@apidevtools/json-schema-ref-parser/lib/util/url.js"); +const { ResolverError } = __webpack_require__(/*! ../util/errors */ "./node_modules/@apidevtools/json-schema-ref-parser/lib/util/errors.js"); + +module.exports = { + /** + * The order that this resolver will run, in relation to other resolvers. + * + * @type {number} + */ + order: 100, + + /** + * Determines whether this resolver can read a given file reference. + * Resolvers that return true will be tried, in order, until one successfully resolves the file. + * Resolvers that return false will not be given a chance to resolve the file. + * + * @param {object} file - An object containing information about the referenced file + * @param {string} file.url - The full URL of the referenced file + * @param {string} file.extension - The lowercased file extension (e.g. ".txt", ".html", etc.) + * @returns {boolean} + */ + canRead (file) { + return url.isFileSystemPath(file.url); + }, + + /** + * Reads the given file and returns its raw contents as a Buffer. + * + * @param {object} file - An object containing information about the referenced file + * @param {string} file.url - The full URL of the referenced file + * @param {string} file.extension - The lowercased file extension (e.g. ".txt", ".html", etc.) + * @returns {Promise} + */ + read (file) { + return new Promise(((resolve, reject) => { + let path; + try { + path = url.toFileSystemPath(file.url); + } + catch (err) { + reject(new ResolverError(ono.uri(err, `Malformed URI: ${file.url}`), file.url)); + } + + // console.log('Opening file: %s', path); + + try { + fs.readFile(path, (err, data) => { + if (err) { + reject(new ResolverError(ono(err, `Error opening file "${path}"`), path)); + } + else { + resolve(data); + } + }); + } + catch (err) { + reject(new ResolverError(ono(err, `Error opening file "${path}"`), path)); + } + })); + } +}; + + +/***/ }), + +/***/ "./node_modules/@apidevtools/json-schema-ref-parser/lib/resolvers/http.js": +/*!********************************************************************************!*\ + !*** ./node_modules/@apidevtools/json-schema-ref-parser/lib/resolvers/http.js ***! + \********************************************************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/* WEBPACK VAR INJECTION */(function(process, Buffer) { + +const http = __webpack_require__(/*! http */ "./node_modules/stream-http/index.js"); +const https = __webpack_require__(/*! https */ "./node_modules/https-browserify/index.js"); +const { ono } = __webpack_require__(/*! @jsdevtools/ono */ "./node_modules/@jsdevtools/ono/esm/index.js"); +const url = __webpack_require__(/*! ../util/url */ "./node_modules/@apidevtools/json-schema-ref-parser/lib/util/url.js"); +const { ResolverError } = __webpack_require__(/*! ../util/errors */ "./node_modules/@apidevtools/json-schema-ref-parser/lib/util/errors.js"); + +module.exports = { + /** + * The order that this resolver will run, in relation to other resolvers. + * + * @type {number} + */ + order: 200, + + /** + * HTTP headers to send when downloading files. + * + * @example: + * { + * "User-Agent": "JSON Schema $Ref Parser", + * Accept: "application/json" + * } + * + * @type {object} + */ + headers: null, + + /** + * HTTP request timeout (in milliseconds). + * + * @type {number} + */ + timeout: 5000, // 5 seconds + + /** + * The maximum number of HTTP redirects to follow. + * To disable automatic following of redirects, set this to zero. + * + * @type {number} + */ + redirects: 5, + + /** + * The `withCredentials` option of XMLHttpRequest. + * Set this to `true` if you're downloading files from a CORS-enabled server that requires authentication + * + * @type {boolean} + */ + withCredentials: false, + + /** + * Determines whether this resolver can read a given file reference. + * Resolvers that return true will be tried in order, until one successfully resolves the file. + * Resolvers that return false will not be given a chance to resolve the file. + * + * @param {object} file - An object containing information about the referenced file + * @param {string} file.url - The full URL of the referenced file + * @param {string} file.extension - The lowercased file extension (e.g. ".txt", ".html", etc.) + * @returns {boolean} + */ + canRead (file) { + return url.isHttp(file.url); + }, + + /** + * Reads the given URL and returns its raw contents as a Buffer. + * + * @param {object} file - An object containing information about the referenced file + * @param {string} file.url - The full URL of the referenced file + * @param {string} file.extension - The lowercased file extension (e.g. ".txt", ".html", etc.) + * @returns {Promise} + */ + read (file) { + let u = url.parse(file.url); + + if (process.browser && !u.protocol) { + // Use the protocol of the current page + u.protocol = url.parse(location.href).protocol; + } + + return download(u, this); + } +}; + +/** + * Downloads the given file. + * + * @param {Url|string} u - The url to download (can be a parsed {@link Url} object) + * @param {object} httpOptions - The `options.resolve.http` object + * @param {number} [redirects] - The redirect URLs that have already been followed + * + * @returns {Promise} + * The promise resolves with the raw downloaded data, or rejects if there is an HTTP error. + */ +function download (u, httpOptions, redirects) { + return new Promise(((resolve, reject) => { + u = url.parse(u); + redirects = redirects || []; + redirects.push(u.href); + + get(u, httpOptions) + .then((res) => { + if (res.statusCode >= 400) { + throw ono({ status: res.statusCode }, `HTTP ERROR ${res.statusCode}`); + } + else if (res.statusCode >= 300) { + if (redirects.length > httpOptions.redirects) { + reject(new ResolverError(ono({ status: res.statusCode }, + `Error downloading ${redirects[0]}. \nToo many redirects: \n ${redirects.join(" \n ")}`))); + } + else if (!res.headers.location) { + throw ono({ status: res.statusCode }, `HTTP ${res.statusCode} redirect with no location header`); + } + else { + // console.log('HTTP %d redirect %s -> %s', res.statusCode, u.href, res.headers.location); + let redirectTo = url.resolve(u, res.headers.location); + download(redirectTo, httpOptions, redirects).then(resolve, reject); + } + } + else { + resolve(res.body || Buffer.alloc(0)); + } + }) + .catch((err) => { + reject(new ResolverError(ono(err, `Error downloading ${u.href}`), u.href)); + }); + })); +} + +/** + * Sends an HTTP GET request. + * + * @param {Url} u - A parsed {@link Url} object + * @param {object} httpOptions - The `options.resolve.http` object + * + * @returns {Promise} + * The promise resolves with the HTTP Response object. + */ +function get (u, httpOptions) { + return new Promise(((resolve, reject) => { + // console.log('GET', u.href); + + let protocol = u.protocol === "https:" ? https : http; + let req = protocol.get({ + hostname: u.hostname, + port: u.port, + path: u.path, + auth: u.auth, + protocol: u.protocol, + headers: httpOptions.headers || {}, + withCredentials: httpOptions.withCredentials + }); + + if (typeof req.setTimeout === "function") { + req.setTimeout(httpOptions.timeout); + } + + req.on("timeout", () => { + req.abort(); + }); + + req.on("error", reject); + + req.once("response", (res) => { + res.body = Buffer.alloc(0); + + res.on("data", (data) => { + res.body = Buffer.concat([res.body, Buffer.from(data)]); + }); + + res.on("error", reject); + + res.on("end", () => { + resolve(res); + }); + }); + })); +} + +/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../../../../process/browser.js */ "./node_modules/process/browser.js"), __webpack_require__(/*! ./../../../../buffer/index.js */ "./node_modules/buffer/index.js").Buffer)) + +/***/ }), + +/***/ "./node_modules/@apidevtools/json-schema-ref-parser/lib/util/errors.js": +/*!*****************************************************************************!*\ + !*** ./node_modules/@apidevtools/json-schema-ref-parser/lib/util/errors.js ***! + \*****************************************************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +const { Ono } = __webpack_require__(/*! @jsdevtools/ono */ "./node_modules/@jsdevtools/ono/esm/index.js"); + +const { stripHash, toFileSystemPath } = __webpack_require__(/*! ./url */ "./node_modules/@apidevtools/json-schema-ref-parser/lib/util/url.js"); + +const JSONParserError = exports.JSONParserError = class JSONParserError extends Error { + constructor (message, source) { + super(); + + this.code = "EUNKNOWN"; + this.message = message; + this.source = source; + this.path = null; + + Ono.extend(this); + } + + get footprint () { + return `${this.path}+${this.source}+${this.code}+${this.message}`; + } +}; + +setErrorName(JSONParserError); + +const JSONParserErrorGroup = exports.JSONParserErrorGroup = class JSONParserErrorGroup extends Error { + constructor (parser) { + super(); + + this.files = parser; + this.message = `${this.errors.length} error${this.errors.length > 1 ? "s" : ""} occurred while reading '${toFileSystemPath(parser.$refs._root$Ref.path)}'`; + + Ono.extend(this); + } + + static getParserErrors (parser) { + const errors = []; + + for (const $ref of Object.values(parser.$refs._$refs)) { + if ($ref.errors) { + errors.push(...$ref.errors); + } + } + + return errors; + } + + get errors () { + return JSONParserErrorGroup.getParserErrors(this.files); + } +}; + +setErrorName(JSONParserErrorGroup); + +const ParserError = exports.ParserError = class ParserError extends JSONParserError { + constructor (message, source) { + super(`Error parsing ${source}: ${message}`, source); + + this.code = "EPARSER"; + } +}; + +setErrorName(ParserError); + +const UnmatchedParserError = exports.UnmatchedParserError = class UnmatchedParserError extends JSONParserError { + constructor (source) { + super(`Could not find parser for "${source}"`, source); + + this.code = "EUNMATCHEDPARSER"; + } +}; + +setErrorName(UnmatchedParserError); + +const ResolverError = exports.ResolverError = class ResolverError extends JSONParserError { + constructor (ex, source) { + super(ex.message || `Error reading file "${source}"`, source); + + this.code = "ERESOLVER"; + + if ("code" in ex) { + this.ioErrorCode = String(ex.code); + } + } +}; + +setErrorName(ResolverError); + +const UnmatchedResolverError = exports.UnmatchedResolverError = class UnmatchedResolverError extends JSONParserError { + constructor (source) { + super(`Could not find resolver for "${source}"`, source); + + this.code = "EUNMATCHEDRESOLVER"; + } +}; + +setErrorName(UnmatchedResolverError); + +const MissingPointerError = exports.MissingPointerError = class MissingPointerError extends JSONParserError { + constructor (token, path) { + super(`Token "${token}" does not exist.`, stripHash(path)); + + this.code = "EMISSINGPOINTER"; + } +}; + +setErrorName(MissingPointerError); + +const InvalidPointerError = exports.InvalidPointerError = class InvalidPointerError extends JSONParserError { + constructor (pointer, path) { + super(`Invalid $ref pointer "${pointer}". Pointers must begin with "#/"`, stripHash(path)); + + this.code = "EINVALIDPOINTER"; + } +}; + +setErrorName(InvalidPointerError); + +function setErrorName (err) { + Object.defineProperty(err.prototype, "name", { + value: err.name, + enumerable: true, + }); +} + +exports.isHandledError = function (err) { + return err instanceof JSONParserError || err instanceof JSONParserErrorGroup; +}; + +exports.normalizeError = function (err) { + if (err.path === null) { + err.path = []; + } + + return err; +}; + + +/***/ }), + +/***/ "./node_modules/@apidevtools/json-schema-ref-parser/lib/util/plugins.js": +/*!******************************************************************************!*\ + !*** ./node_modules/@apidevtools/json-schema-ref-parser/lib/util/plugins.js ***! + \******************************************************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +/** + * Returns the given plugins as an array, rather than an object map. + * All other methods in this module expect an array of plugins rather than an object map. + * + * @param {object} plugins - A map of plugin objects + * @return {object[]} + */ +exports.all = function (plugins) { + return Object.keys(plugins) + .filter((key) => { + return typeof plugins[key] === "object"; + }) + .map((key) => { + plugins[key].name = key; + return plugins[key]; + }); +}; + +/** + * Filters the given plugins, returning only the ones return `true` for the given method. + * + * @param {object[]} plugins - An array of plugin objects + * @param {string} method - The name of the filter method to invoke for each plugin + * @param {object} file - A file info object, which will be passed to each method + * @return {object[]} + */ +exports.filter = function (plugins, method, file) { + return plugins + .filter((plugin) => { + return !!getResult(plugin, method, file); + }); +}; + +/** + * Sorts the given plugins, in place, by their `order` property. + * + * @param {object[]} plugins - An array of plugin objects + * @returns {object[]} + */ +exports.sort = function (plugins) { + for (let plugin of plugins) { + plugin.order = plugin.order || Number.MAX_SAFE_INTEGER; + } + + return plugins.sort((a, b) => { return a.order - b.order; }); +}; + +/** + * Runs the specified method of the given plugins, in order, until one of them returns a successful result. + * Each method can return a synchronous value, a Promise, or call an error-first callback. + * If the promise resolves successfully, or the callback is called without an error, then the result + * is immediately returned and no further plugins are called. + * If the promise rejects, or the callback is called with an error, then the next plugin is called. + * If ALL plugins fail, then the last error is thrown. + * + * @param {object[]} plugins - An array of plugin objects + * @param {string} method - The name of the method to invoke for each plugin + * @param {object} file - A file info object, which will be passed to each method + * @returns {Promise} + */ +exports.run = function (plugins, method, file, $refs) { + let plugin, lastError, index = 0; + + return new Promise(((resolve, reject) => { + runNextPlugin(); + + function runNextPlugin () { + plugin = plugins[index++]; + if (!plugin) { + // There are no more functions, so re-throw the last error + return reject(lastError); + } + + try { + // console.log(' %s', plugin.name); + let result = getResult(plugin, method, file, callback, $refs); + if (result && typeof result.then === "function") { + // A promise was returned + result.then(onSuccess, onError); + } + else if (result !== undefined) { + // A synchronous result was returned + onSuccess(result); + } + else if (index === plugins.length) { + throw new Error("No promise has been returned or callback has been called."); + } + } + catch (e) { + onError(e); + } + } + + function callback (err, result) { + if (err) { + onError(err); + } + else { + onSuccess(result); + } + } + + function onSuccess (result) { + // console.log(' success'); + resolve({ + plugin, + result + }); + } + + function onError (error) { + // console.log(' %s', err.message || err); + lastError = { + plugin, + error, + }; + runNextPlugin(); + } + })); +}; + +/** + * Returns the value of the given property. + * If the property is a function, then the result of the function is returned. + * If the value is a RegExp, then it will be tested against the file URL. + * If the value is an aray, then it will be compared against the file extension. + * + * @param {object} obj - The object whose property/method is called + * @param {string} prop - The name of the property/method to invoke + * @param {object} file - A file info object, which will be passed to the method + * @param {function} [callback] - A callback function, which will be passed to the method + * @returns {*} + */ +function getResult (obj, prop, file, callback, $refs) { + let value = obj[prop]; + + if (typeof value === "function") { + return value.apply(obj, [file, callback, $refs]); + } + + if (!callback) { + // The synchronous plugin functions (canParse and canRead) + // allow a "shorthand" syntax, where the user can match + // files by RegExp or by file extension. + if (value instanceof RegExp) { + return value.test(file.url); + } + else if (typeof value === "string") { + return value === file.extension; + } + else if (Array.isArray(value)) { + return value.indexOf(file.extension) !== -1; + } + } + + return value; +} + + +/***/ }), + +/***/ "./node_modules/@apidevtools/json-schema-ref-parser/lib/util/url.js": +/*!**************************************************************************!*\ + !*** ./node_modules/@apidevtools/json-schema-ref-parser/lib/util/url.js ***! + \**************************************************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/* WEBPACK VAR INJECTION */(function(process) { + +let isWindows = /^win/.test(process.platform), + forwardSlashPattern = /\//g, + protocolPattern = /^(\w{2,}):\/\//i, + url = module.exports, + jsonPointerSlash = /~1/g, + jsonPointerTilde = /~0/g; + +// RegExp patterns to URL-encode special characters in local filesystem paths +let urlEncodePatterns = [ + /\?/g, "%3F", + /\#/g, "%23", +]; + +// RegExp patterns to URL-decode special characters for local filesystem paths +let urlDecodePatterns = [ + /\%23/g, "#", + /\%24/g, "$", + /\%26/g, "&", + /\%2C/g, ",", + /\%40/g, "@" +]; + +exports.parse = __webpack_require__(/*! url */ "./node_modules/url/url.js").parse; +exports.resolve = __webpack_require__(/*! url */ "./node_modules/url/url.js").resolve; + +/** + * Returns the current working directory (in Node) or the current page URL (in browsers). + * + * @returns {string} + */ +exports.cwd = function cwd () { + if (process.browser) { + return location.href; + } + + let path = process.cwd(); + + let lastChar = path.slice(-1); + if (lastChar === "/" || lastChar === "\\") { + return path; + } + else { + return path + "/"; + } +}; + +/** + * Returns the protocol of the given URL, or `undefined` if it has no protocol. + * + * @param {string} path + * @returns {?string} + */ +exports.getProtocol = function getProtocol (path) { + let match = protocolPattern.exec(path); + if (match) { + return match[1].toLowerCase(); + } +}; + +/** + * Returns the lowercased file extension of the given URL, + * or an empty string if it has no extension. + * + * @param {string} path + * @returns {string} + */ +exports.getExtension = function getExtension (path) { + let lastDot = path.lastIndexOf("."); + if (lastDot >= 0) { + return url.stripQuery(path.substr(lastDot).toLowerCase()); + } + return ""; +}; + +/** + * Removes the query, if any, from the given path. + * + * @param {string} path + * @returns {string} + */ +exports.stripQuery = function stripQuery (path) { + let queryIndex = path.indexOf("?"); + if (queryIndex >= 0) { + path = path.substr(0, queryIndex); + } + return path; +}; + +/** + * Returns the hash (URL fragment), of the given path. + * If there is no hash, then the root hash ("#") is returned. + * + * @param {string} path + * @returns {string} + */ +exports.getHash = function getHash (path) { + let hashIndex = path.indexOf("#"); + if (hashIndex >= 0) { + return path.substr(hashIndex); + } + return "#"; +}; + +/** + * Removes the hash (URL fragment), if any, from the given path. + * + * @param {string} path + * @returns {string} + */ +exports.stripHash = function stripHash (path) { + let hashIndex = path.indexOf("#"); + if (hashIndex >= 0) { + path = path.substr(0, hashIndex); + } + return path; +}; + +/** + * Determines whether the given path is an HTTP(S) URL. + * + * @param {string} path + * @returns {boolean} + */ +exports.isHttp = function isHttp (path) { + let protocol = url.getProtocol(path); + if (protocol === "http" || protocol === "https") { + return true; + } + else if (protocol === undefined) { + // There is no protocol. If we're running in a browser, then assume it's HTTP. + return process.browser; + } + else { + // It's some other protocol, such as "ftp://", "mongodb://", etc. + return false; + } +}; + +/** + * Determines whether the given path is a filesystem path. + * This includes "file://" URLs. + * + * @param {string} path + * @returns {boolean} + */ +exports.isFileSystemPath = function isFileSystemPath (path) { + if (process.browser) { + // We're running in a browser, so assume that all paths are URLs. + // This way, even relative paths will be treated as URLs rather than as filesystem paths + return false; + } + + let protocol = url.getProtocol(path); + return protocol === undefined || protocol === "file"; +}; + +/** + * Converts a filesystem path to a properly-encoded URL. + * + * This is intended to handle situations where JSON Schema $Ref Parser is called + * with a filesystem path that contains characters which are not allowed in URLs. + * + * @example + * The following filesystem paths would be converted to the following URLs: + * + * <"!@#$%^&*+=?'>.json ==> %3C%22!@%23$%25%5E&*+=%3F\'%3E.json + * C:\\My Documents\\File (1).json ==> C:/My%20Documents/File%20(1).json + * file://Project #42/file.json ==> file://Project%20%2342/file.json + * + * @param {string} path + * @returns {string} + */ +exports.fromFileSystemPath = function fromFileSystemPath (path) { + // Step 1: On Windows, replace backslashes with forward slashes, + // rather than encoding them as "%5C" + if (isWindows) { + path = path.replace(/\\/g, "/"); + } + + // Step 2: `encodeURI` will take care of MOST characters + path = encodeURI(path); + + // Step 3: Manually encode characters that are not encoded by `encodeURI`. + // This includes characters such as "#" and "?", which have special meaning in URLs, + // but are just normal characters in a filesystem path. + for (let i = 0; i < urlEncodePatterns.length; i += 2) { + path = path.replace(urlEncodePatterns[i], urlEncodePatterns[i + 1]); + } + + return path; +}; + +/** + * Converts a URL to a local filesystem path. + * + * @param {string} path + * @param {boolean} [keepFileProtocol] - If true, then "file://" will NOT be stripped + * @returns {string} + */ +exports.toFileSystemPath = function toFileSystemPath (path, keepFileProtocol) { + // Step 1: `decodeURI` will decode characters such as Cyrillic characters, spaces, etc. + path = decodeURI(path); + + // Step 2: Manually decode characters that are not decoded by `decodeURI`. + // This includes characters such as "#" and "?", which have special meaning in URLs, + // but are just normal characters in a filesystem path. + for (let i = 0; i < urlDecodePatterns.length; i += 2) { + path = path.replace(urlDecodePatterns[i], urlDecodePatterns[i + 1]); + } + + // Step 3: If it's a "file://" URL, then format it consistently + // or convert it to a local filesystem path + let isFileUrl = path.substr(0, 7).toLowerCase() === "file://"; + if (isFileUrl) { + // Strip-off the protocol, and the initial "/", if there is one + path = path[7] === "/" ? path.substr(8) : path.substr(7); + + // insert a colon (":") after the drive letter on Windows + if (isWindows && path[1] === "/") { + path = path[0] + ":" + path.substr(1); + } + + if (keepFileProtocol) { + // Return the consistently-formatted "file://" URL + path = "file:///" + path; + } + else { + // Convert the "file://" URL to a local filesystem path. + // On Windows, it will start with something like "C:/". + // On Posix, it will start with "/" + isFileUrl = false; + path = isWindows ? path : "/" + path; + } + } + + // Step 4: Normalize Windows paths (unless it's a "file://" URL) + if (isWindows && !isFileUrl) { + // Replace forward slashes with backslashes + path = path.replace(forwardSlashPattern, "\\"); + + // Capitalize the drive letter + if (path.substr(1, 2) === ":\\") { + path = path[0].toUpperCase() + path.substr(1); + } + } + + return path; +}; + +/** + * Converts a $ref pointer to a valid JSON Path. + * + * @param {string} pointer + * @returns {Array} + */ +exports.safePointerToPath = function safePointerToPath (pointer) { + if (pointer.length <= 1 || pointer[0] !== "#" || pointer[1] !== "/") { + return []; + } + + return pointer + .slice(2) + .split("/") + .map((value) => { + return decodeURIComponent(value) + .replace(jsonPointerSlash, "/") + .replace(jsonPointerTilde, "~"); + }); +}; + +/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../../../../process/browser.js */ "./node_modules/process/browser.js"))) + +/***/ }), + +/***/ "./node_modules/@colors/colors/lib/colors.js": +/*!***************************************************!*\ + !*** ./node_modules/@colors/colors/lib/colors.js ***! + \***************************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +/* + +The MIT License (MIT) + +Original Library + - Copyright (c) Marak Squires + +Additional functionality + - Copyright (c) Sindre Sorhus (sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + +*/ + +var colors = {}; +module['exports'] = colors; + +colors.themes = {}; + +var util = __webpack_require__(/*! util */ "./node_modules/util/util.js"); +var ansiStyles = colors.styles = __webpack_require__(/*! ./styles */ "./node_modules/@colors/colors/lib/styles.js"); +var defineProps = Object.defineProperties; +var newLineRegex = new RegExp(/[\r\n]+/g); + +colors.supportsColor = __webpack_require__(/*! ./system/supports-colors */ "./node_modules/@colors/colors/lib/system/supports-colors.js").supportsColor; + +if (typeof colors.enabled === 'undefined') { + colors.enabled = colors.supportsColor() !== false; +} + +colors.enable = function() { + colors.enabled = true; +}; + +colors.disable = function() { + colors.enabled = false; +}; + +colors.stripColors = colors.strip = function(str) { + return ('' + str).replace(/\x1B\[\d+m/g, ''); +}; + +// eslint-disable-next-line no-unused-vars +var stylize = colors.stylize = function stylize(str, style) { + if (!colors.enabled) { + return str+''; + } + + var styleMap = ansiStyles[style]; + + // Stylize should work for non-ANSI styles, too + if (!styleMap && style in colors) { + // Style maps like trap operate as functions on strings; + // they don't have properties like open or close. + return colors[style](str); + } + + return styleMap.open + str + styleMap.close; +}; + +var matchOperatorsRe = /[|\\{}()[\]^$+*?.]/g; +var escapeStringRegexp = function(str) { + if (typeof str !== 'string') { + throw new TypeError('Expected a string'); + } + return str.replace(matchOperatorsRe, '\\$&'); +}; + +function build(_styles) { + var builder = function builder() { + return applyStyle.apply(builder, arguments); + }; + builder._styles = _styles; + // __proto__ is used because we must return a function, but there is + // no way to create a function with a different prototype. + builder.__proto__ = proto; + return builder; +} + +var styles = (function() { + var ret = {}; + ansiStyles.grey = ansiStyles.gray; + Object.keys(ansiStyles).forEach(function(key) { + ansiStyles[key].closeRe = + new RegExp(escapeStringRegexp(ansiStyles[key].close), 'g'); + ret[key] = { + get: function() { + return build(this._styles.concat(key)); + }, + }; + }); + return ret; +})(); + +var proto = defineProps(function colors() {}, styles); + +function applyStyle() { + var args = Array.prototype.slice.call(arguments); + + var str = args.map(function(arg) { + // Use weak equality check so we can colorize null/undefined in safe mode + if (arg != null && arg.constructor === String) { + return arg; + } else { + return util.inspect(arg); + } + }).join(' '); + + if (!colors.enabled || !str) { + return str; + } + + var newLinesPresent = str.indexOf('\n') != -1; + + var nestedStyles = this._styles; + + var i = nestedStyles.length; + while (i--) { + var code = ansiStyles[nestedStyles[i]]; + str = code.open + str.replace(code.closeRe, code.open) + code.close; + if (newLinesPresent) { + str = str.replace(newLineRegex, function(match) { + return code.close + match + code.open; + }); + } + } + + return str; +} + +colors.setTheme = function(theme) { + if (typeof theme === 'string') { + console.log('colors.setTheme now only accepts an object, not a string. ' + + 'If you are trying to set a theme from a file, it is now your (the ' + + 'caller\'s) responsibility to require the file. The old syntax ' + + 'looked like colors.setTheme(__dirname + ' + + '\'/../themes/generic-logging.js\'); The new syntax looks like '+ + 'colors.setTheme(require(__dirname + ' + + '\'/../themes/generic-logging.js\'));'); + return; + } + for (var style in theme) { + (function(style) { + colors[style] = function(str) { + if (typeof theme[style] === 'object') { + var out = str; + for (var i in theme[style]) { + out = colors[theme[style][i]](out); + } + return out; + } + return colors[theme[style]](str); + }; + })(style); + } +}; + +function init() { + var ret = {}; + Object.keys(styles).forEach(function(name) { + ret[name] = { + get: function() { + return build([name]); + }, + }; + }); + return ret; +} + +var sequencer = function sequencer(map, str) { + var exploded = str.split(''); + exploded = exploded.map(map); + return exploded.join(''); +}; + +// custom formatter methods +colors.trap = __webpack_require__(/*! ./custom/trap */ "./node_modules/@colors/colors/lib/custom/trap.js"); +colors.zalgo = __webpack_require__(/*! ./custom/zalgo */ "./node_modules/@colors/colors/lib/custom/zalgo.js"); + +// maps +colors.maps = {}; +colors.maps.america = __webpack_require__(/*! ./maps/america */ "./node_modules/@colors/colors/lib/maps/america.js")(colors); +colors.maps.zebra = __webpack_require__(/*! ./maps/zebra */ "./node_modules/@colors/colors/lib/maps/zebra.js")(colors); +colors.maps.rainbow = __webpack_require__(/*! ./maps/rainbow */ "./node_modules/@colors/colors/lib/maps/rainbow.js")(colors); +colors.maps.random = __webpack_require__(/*! ./maps/random */ "./node_modules/@colors/colors/lib/maps/random.js")(colors); + +for (var map in colors.maps) { + (function(map) { + colors[map] = function(str) { + return sequencer(colors.maps[map], str); + }; + })(map); +} + +defineProps(colors, init()); + + +/***/ }), + +/***/ "./node_modules/@colors/colors/lib/custom/trap.js": +/*!********************************************************!*\ + !*** ./node_modules/@colors/colors/lib/custom/trap.js ***! + \********************************************************/ +/*! no static exports found */ +/***/ (function(module, exports) { + +module['exports'] = function runTheTrap(text, options) { + var result = ''; + text = text || 'Run the trap, drop the bass'; + text = text.split(''); + var trap = { + a: ['\u0040', '\u0104', '\u023a', '\u0245', '\u0394', '\u039b', '\u0414'], + b: ['\u00df', '\u0181', '\u0243', '\u026e', '\u03b2', '\u0e3f'], + c: ['\u00a9', '\u023b', '\u03fe'], + d: ['\u00d0', '\u018a', '\u0500', '\u0501', '\u0502', '\u0503'], + e: ['\u00cb', '\u0115', '\u018e', '\u0258', '\u03a3', '\u03be', '\u04bc', + '\u0a6c'], + f: ['\u04fa'], + g: ['\u0262'], + h: ['\u0126', '\u0195', '\u04a2', '\u04ba', '\u04c7', '\u050a'], + i: ['\u0f0f'], + j: ['\u0134'], + k: ['\u0138', '\u04a0', '\u04c3', '\u051e'], + l: ['\u0139'], + m: ['\u028d', '\u04cd', '\u04ce', '\u0520', '\u0521', '\u0d69'], + n: ['\u00d1', '\u014b', '\u019d', '\u0376', '\u03a0', '\u048a'], + o: ['\u00d8', '\u00f5', '\u00f8', '\u01fe', '\u0298', '\u047a', '\u05dd', + '\u06dd', '\u0e4f'], + p: ['\u01f7', '\u048e'], + q: ['\u09cd'], + r: ['\u00ae', '\u01a6', '\u0210', '\u024c', '\u0280', '\u042f'], + s: ['\u00a7', '\u03de', '\u03df', '\u03e8'], + t: ['\u0141', '\u0166', '\u0373'], + u: ['\u01b1', '\u054d'], + v: ['\u05d8'], + w: ['\u0428', '\u0460', '\u047c', '\u0d70'], + x: ['\u04b2', '\u04fe', '\u04fc', '\u04fd'], + y: ['\u00a5', '\u04b0', '\u04cb'], + z: ['\u01b5', '\u0240'], + }; + text.forEach(function(c) { + c = c.toLowerCase(); + var chars = trap[c] || [' ']; + var rand = Math.floor(Math.random() * chars.length); + if (typeof trap[c] !== 'undefined') { + result += trap[c][rand]; + } else { + result += c; + } + }); + return result; +}; + + +/***/ }), + +/***/ "./node_modules/@colors/colors/lib/custom/zalgo.js": +/*!*********************************************************!*\ + !*** ./node_modules/@colors/colors/lib/custom/zalgo.js ***! + \*********************************************************/ +/*! no static exports found */ +/***/ (function(module, exports) { + +// please no +module['exports'] = function zalgo(text, options) { + text = text || ' he is here '; + var soul = { + 'up': [ + '̍', '̎', '̄', '̅', + '̿', '̑', '̆', '̐', + '͒', '͗', '͑', '̇', + '̈', '̊', '͂', '̓', + '̈', '͊', '͋', '͌', + '̃', '̂', '̌', '͐', + '̀', '́', '̋', '̏', + '̒', '̓', '̔', '̽', + '̉', 'ͣ', 'ͤ', 'ͥ', + 'ͦ', 'ͧ', 'ͨ', 'ͩ', + 'ͪ', 'ͫ', 'ͬ', 'ͭ', + 'ͮ', 'ͯ', '̾', '͛', + '͆', '̚', + ], + 'down': [ + '̖', '̗', '̘', '̙', + '̜', '̝', '̞', '̟', + '̠', '̤', '̥', '̦', + '̩', '̪', '̫', '̬', + '̭', '̮', '̯', '̰', + '̱', '̲', '̳', '̹', + '̺', '̻', '̼', 'ͅ', + '͇', '͈', '͉', '͍', + '͎', '͓', '͔', '͕', + '͖', '͙', '͚', '̣', + ], + 'mid': [ + '̕', '̛', '̀', '́', + '͘', '̡', '̢', '̧', + '̨', '̴', '̵', '̶', + '͜', '͝', '͞', + '͟', '͠', '͢', '̸', + '̷', '͡', ' ҉', + ], + }; + var all = [].concat(soul.up, soul.down, soul.mid); + + function randomNumber(range) { + var r = Math.floor(Math.random() * range); + return r; + } + + function isChar(character) { + var bool = false; + all.filter(function(i) { + bool = (i === character); + }); + return bool; + } + + + function heComes(text, options) { + var result = ''; + var counts; + var l; + options = options || {}; + options['up'] = + typeof options['up'] !== 'undefined' ? options['up'] : true; + options['mid'] = + typeof options['mid'] !== 'undefined' ? options['mid'] : true; + options['down'] = + typeof options['down'] !== 'undefined' ? options['down'] : true; + options['size'] = + typeof options['size'] !== 'undefined' ? options['size'] : 'maxi'; + text = text.split(''); + for (l in text) { + if (isChar(l)) { + continue; + } + result = result + text[l]; + counts = {'up': 0, 'down': 0, 'mid': 0}; + switch (options.size) { + case 'mini': + counts.up = randomNumber(8); + counts.mid = randomNumber(2); + counts.down = randomNumber(8); + break; + case 'maxi': + counts.up = randomNumber(16) + 3; + counts.mid = randomNumber(4) + 1; + counts.down = randomNumber(64) + 3; + break; + default: + counts.up = randomNumber(8) + 1; + counts.mid = randomNumber(6) / 2; + counts.down = randomNumber(8) + 1; + break; + } + + var arr = ['up', 'mid', 'down']; + for (var d in arr) { + var index = arr[d]; + for (var i = 0; i <= counts[index]; i++) { + if (options[index]) { + result = result + soul[index][randomNumber(soul[index].length)]; + } + } + } + } + return result; + } + // don't summon him + return heComes(text, options); +}; + + + +/***/ }), + +/***/ "./node_modules/@colors/colors/lib/maps/america.js": +/*!*********************************************************!*\ + !*** ./node_modules/@colors/colors/lib/maps/america.js ***! + \*********************************************************/ +/*! no static exports found */ +/***/ (function(module, exports) { + +module['exports'] = function(colors) { + return function(letter, i, exploded) { + if (letter === ' ') return letter; + switch (i%3) { + case 0: return colors.red(letter); + case 1: return colors.white(letter); + case 2: return colors.blue(letter); + } + }; +}; + + +/***/ }), + +/***/ "./node_modules/@colors/colors/lib/maps/rainbow.js": +/*!*********************************************************!*\ + !*** ./node_modules/@colors/colors/lib/maps/rainbow.js ***! + \*********************************************************/ +/*! no static exports found */ +/***/ (function(module, exports) { + +module['exports'] = function(colors) { + // RoY G BiV + var rainbowColors = ['red', 'yellow', 'green', 'blue', 'magenta']; + return function(letter, i, exploded) { + if (letter === ' ') { + return letter; + } else { + return colors[rainbowColors[i++ % rainbowColors.length]](letter); + } + }; +}; + + + +/***/ }), + +/***/ "./node_modules/@colors/colors/lib/maps/random.js": +/*!********************************************************!*\ + !*** ./node_modules/@colors/colors/lib/maps/random.js ***! + \********************************************************/ +/*! no static exports found */ +/***/ (function(module, exports) { + +module['exports'] = function(colors) { + var available = ['underline', 'inverse', 'grey', 'yellow', 'red', 'green', + 'blue', 'white', 'cyan', 'magenta', 'brightYellow', 'brightRed', + 'brightGreen', 'brightBlue', 'brightWhite', 'brightCyan', 'brightMagenta']; + return function(letter, i, exploded) { + return letter === ' ' ? letter : + colors[ + available[Math.round(Math.random() * (available.length - 2))] + ](letter); + }; +}; + + +/***/ }), + +/***/ "./node_modules/@colors/colors/lib/maps/zebra.js": +/*!*******************************************************!*\ + !*** ./node_modules/@colors/colors/lib/maps/zebra.js ***! + \*******************************************************/ +/*! no static exports found */ +/***/ (function(module, exports) { + +module['exports'] = function(colors) { + return function(letter, i, exploded) { + return i % 2 === 0 ? letter : colors.inverse(letter); + }; +}; + + +/***/ }), + +/***/ "./node_modules/@colors/colors/lib/styles.js": +/*!***************************************************!*\ + !*** ./node_modules/@colors/colors/lib/styles.js ***! + \***************************************************/ +/*! no static exports found */ +/***/ (function(module, exports) { + +/* +The MIT License (MIT) + +Copyright (c) Sindre Sorhus (sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + +*/ + +var styles = {}; +module['exports'] = styles; + +var codes = { + reset: [0, 0], + + bold: [1, 22], + dim: [2, 22], + italic: [3, 23], + underline: [4, 24], + inverse: [7, 27], + hidden: [8, 28], + strikethrough: [9, 29], + + black: [30, 39], + red: [31, 39], + green: [32, 39], + yellow: [33, 39], + blue: [34, 39], + magenta: [35, 39], + cyan: [36, 39], + white: [37, 39], + gray: [90, 39], + grey: [90, 39], + + brightRed: [91, 39], + brightGreen: [92, 39], + brightYellow: [93, 39], + brightBlue: [94, 39], + brightMagenta: [95, 39], + brightCyan: [96, 39], + brightWhite: [97, 39], + + bgBlack: [40, 49], + bgRed: [41, 49], + bgGreen: [42, 49], + bgYellow: [43, 49], + bgBlue: [44, 49], + bgMagenta: [45, 49], + bgCyan: [46, 49], + bgWhite: [47, 49], + bgGray: [100, 49], + bgGrey: [100, 49], + + bgBrightRed: [101, 49], + bgBrightGreen: [102, 49], + bgBrightYellow: [103, 49], + bgBrightBlue: [104, 49], + bgBrightMagenta: [105, 49], + bgBrightCyan: [106, 49], + bgBrightWhite: [107, 49], + + // legacy styles for colors pre v1.0.0 + blackBG: [40, 49], + redBG: [41, 49], + greenBG: [42, 49], + yellowBG: [43, 49], + blueBG: [44, 49], + magentaBG: [45, 49], + cyanBG: [46, 49], + whiteBG: [47, 49], + +}; + +Object.keys(codes).forEach(function(key) { + var val = codes[key]; + var style = styles[key] = []; + style.open = '\u001b[' + val[0] + 'm'; + style.close = '\u001b[' + val[1] + 'm'; +}); + + +/***/ }), + +/***/ "./node_modules/@colors/colors/lib/system/has-flag.js": +/*!************************************************************!*\ + !*** ./node_modules/@colors/colors/lib/system/has-flag.js ***! + \************************************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/* WEBPACK VAR INJECTION */(function(process) {/* +MIT License + +Copyright (c) Sindre Sorhus (sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +of the Software, and to permit persons to whom the Software is furnished to do +so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. +*/ + + + +module.exports = function(flag, argv) { + argv = argv || process.argv || []; + + var terminatorPos = argv.indexOf('--'); + var prefix = /^-{1,2}/.test(flag) ? '' : '--'; + var pos = argv.indexOf(prefix + flag); + + return pos !== -1 && (terminatorPos === -1 ? true : pos < terminatorPos); +}; + +/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../../../../process/browser.js */ "./node_modules/process/browser.js"))) + +/***/ }), + +/***/ "./node_modules/@colors/colors/lib/system/supports-colors.js": +/*!*******************************************************************!*\ + !*** ./node_modules/@colors/colors/lib/system/supports-colors.js ***! + \*******************************************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/* WEBPACK VAR INJECTION */(function(process) {/* +The MIT License (MIT) + +Copyright (c) Sindre Sorhus (sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + +*/ + + + +var os = __webpack_require__(/*! os */ "./node_modules/os-browserify/browser.js"); +var hasFlag = __webpack_require__(/*! ./has-flag.js */ "./node_modules/@colors/colors/lib/system/has-flag.js"); + +var env = process.env; + +var forceColor = void 0; +if (hasFlag('no-color') || hasFlag('no-colors') || hasFlag('color=false')) { + forceColor = false; +} else if (hasFlag('color') || hasFlag('colors') || hasFlag('color=true') + || hasFlag('color=always')) { + forceColor = true; +} +if ('FORCE_COLOR' in env) { + forceColor = env.FORCE_COLOR.length === 0 + || parseInt(env.FORCE_COLOR, 10) !== 0; +} + +function translateLevel(level) { + if (level === 0) { + return false; + } + + return { + level: level, + hasBasic: true, + has256: level >= 2, + has16m: level >= 3, + }; +} + +function supportsColor(stream) { + if (forceColor === false) { + return 0; + } + + if (hasFlag('color=16m') || hasFlag('color=full') + || hasFlag('color=truecolor')) { + return 3; + } + + if (hasFlag('color=256')) { + return 2; + } + + if (stream && !stream.isTTY && forceColor !== true) { + return 0; + } + + var min = forceColor ? 1 : 0; + + if (process.platform === 'win32') { + // Node.js 7.5.0 is the first version of Node.js to include a patch to + // libuv that enables 256 color output on Windows. Anything earlier and it + // won't work. However, here we target Node.js 8 at minimum as it is an LTS + // release, and Node.js 7 is not. Windows 10 build 10586 is the first + // Windows release that supports 256 colors. Windows 10 build 14931 is the + // first release that supports 16m/TrueColor. + var osRelease = os.release().split('.'); + if (Number(process.versions.node.split('.')[0]) >= 8 + && Number(osRelease[0]) >= 10 && Number(osRelease[2]) >= 10586) { + return Number(osRelease[2]) >= 14931 ? 3 : 2; + } + + return 1; + } + + if ('CI' in env) { + if (['TRAVIS', 'CIRCLECI', 'APPVEYOR', 'GITLAB_CI'].some(function(sign) { + return sign in env; + }) || env.CI_NAME === 'codeship') { + return 1; + } + + return min; + } + + if ('TEAMCITY_VERSION' in env) { + return (/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0 + ); + } + + if ('TERM_PROGRAM' in env) { + var version = parseInt((env.TERM_PROGRAM_VERSION || '').split('.')[0], 10); + + switch (env.TERM_PROGRAM) { + case 'iTerm.app': + return version >= 3 ? 3 : 2; + case 'Hyper': + return 3; + case 'Apple_Terminal': + return 2; + // No default + } + } + + if (/-256(color)?$/i.test(env.TERM)) { + return 2; + } + + if (/^screen|^xterm|^vt100|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) { + return 1; + } + + if ('COLORTERM' in env) { + return 1; + } + + if (env.TERM === 'dumb') { + return min; + } + + return min; +} + +function getSupportLevel(stream) { + var level = supportsColor(stream); + return translateLevel(level); +} + +module.exports = { + supportsColor: getSupportLevel, + stdout: getSupportLevel(process.stdout), + stderr: getSupportLevel(process.stderr), +}; + +/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../../../../process/browser.js */ "./node_modules/process/browser.js"))) + +/***/ }), + +/***/ "./node_modules/@colors/colors/safe.js": +/*!*********************************************!*\ + !*** ./node_modules/@colors/colors/safe.js ***! + \*********************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +// +// Remark: Requiring this file will use the "safe" colors API, +// which will not touch String.prototype. +// +// var colors = require('colors/safe'); +// colors.red("foo") +// +// +var colors = __webpack_require__(/*! ./lib/colors */ "./node_modules/@colors/colors/lib/colors.js"); +module['exports'] = colors; + + +/***/ }), + +/***/ "./node_modules/@dabh/diagnostics/adapters/index.js": +/*!**********************************************************!*\ + !*** ./node_modules/@dabh/diagnostics/adapters/index.js ***! + \**********************************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +var enabled = __webpack_require__(/*! enabled */ "./node_modules/enabled/index.js"); + +/** + * Creates a new Adapter. + * + * @param {Function} fn Function that returns the value. + * @returns {Function} The adapter logic. + * @public + */ +module.exports = function create(fn) { + return function adapter(namespace) { + try { + return enabled(namespace, fn()); + } catch (e) { /* Any failure means that we found nothing */ } + + return false; + }; +} + + +/***/ }), + +/***/ "./node_modules/@dabh/diagnostics/adapters/process.env.js": +/*!****************************************************************!*\ + !*** ./node_modules/@dabh/diagnostics/adapters/process.env.js ***! + \****************************************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +/* WEBPACK VAR INJECTION */(function(process) {var adapter = __webpack_require__(/*! ./ */ "./node_modules/@dabh/diagnostics/adapters/index.js"); + +/** + * Extracts the values from process.env. + * + * @type {Function} + * @public + */ +module.exports = adapter(function processenv() { + return process.env.DEBUG || process.env.DIAGNOSTICS; +}); + +/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../../../process/browser.js */ "./node_modules/process/browser.js"))) + +/***/ }), + +/***/ "./node_modules/@dabh/diagnostics/diagnostics.js": +/*!*******************************************************!*\ + !*** ./node_modules/@dabh/diagnostics/diagnostics.js ***! + \*******************************************************/ +/*! no static exports found */ +/***/ (function(module, exports) { + +/** + * Contains all configured adapters for the given environment. + * + * @type {Array} + * @public + */ +var adapters = []; + +/** + * Contains all modifier functions. + * + * @typs {Array} + * @public + */ +var modifiers = []; + +/** + * Our default logger. + * + * @public + */ +var logger = function devnull() {}; + +/** + * Register a new adapter that will used to find environments. + * + * @param {Function} adapter A function that will return the possible env. + * @returns {Boolean} Indication of a successful add. + * @public + */ +function use(adapter) { + if (~adapters.indexOf(adapter)) return false; + + adapters.push(adapter); + return true; +} + +/** + * Assign a new log method. + * + * @param {Function} custom The log method. + * @public + */ +function set(custom) { + logger = custom; +} + +/** + * Check if the namespace is allowed by any of our adapters. + * + * @param {String} namespace The namespace that needs to be enabled + * @returns {Boolean|Promise} Indication if the namespace is enabled by our adapters. + * @public + */ +function enabled(namespace) { + var async = []; + + for (var i = 0; i < adapters.length; i++) { + if (adapters[i].async) { + async.push(adapters[i]); + continue; + } + + if (adapters[i](namespace)) return true; + } + + if (!async.length) return false; + + // + // Now that we know that we Async functions, we know we run in an ES6 + // environment and can use all the API's that they offer, in this case + // we want to return a Promise so that we can `await` in React-Native + // for an async adapter. + // + return new Promise(function pinky(resolve) { + Promise.all( + async.map(function prebind(fn) { + return fn(namespace); + }) + ).then(function resolved(values) { + resolve(values.some(Boolean)); + }); + }); +} + +/** + * Add a new message modifier to the debugger. + * + * @param {Function} fn Modification function. + * @returns {Boolean} Indication of a successful add. + * @public + */ +function modify(fn) { + if (~modifiers.indexOf(fn)) return false; + + modifiers.push(fn); + return true; +} + +/** + * Write data to the supplied logger. + * + * @param {Object} meta Meta information about the log. + * @param {Array} args Arguments for console.log. + * @public + */ +function write() { + logger.apply(logger, arguments); +} + +/** + * Process the message with the modifiers. + * + * @param {Mixed} message The message to be transformed by modifers. + * @returns {String} Transformed message. + * @public + */ +function process(message) { + for (var i = 0; i < modifiers.length; i++) { + message = modifiers[i].apply(modifiers[i], arguments); + } + + return message; +} + +/** + * Introduce options to the logger function. + * + * @param {Function} fn Calback function. + * @param {Object} options Properties to introduce on fn. + * @returns {Function} The passed function + * @public + */ +function introduce(fn, options) { + var has = Object.prototype.hasOwnProperty; + + for (var key in options) { + if (has.call(options, key)) { + fn[key] = options[key]; + } + } + + return fn; +} + +/** + * Nope, we're not allowed to write messages. + * + * @returns {Boolean} false + * @public + */ +function nope(options) { + options.enabled = false; + options.modify = modify; + options.set = set; + options.use = use; + + return introduce(function diagnopes() { + return false; + }, options); +} + +/** + * Yep, we're allowed to write debug messages. + * + * @param {Object} options The options for the process. + * @returns {Function} The function that does the logging. + * @public + */ +function yep(options) { + /** + * The function that receives the actual debug information. + * + * @returns {Boolean} indication that we're logging. + * @public + */ + function diagnostics() { + var args = Array.prototype.slice.call(arguments, 0); + + write.call(write, options, process(args, options)); + return true; + } + + options.enabled = true; + options.modify = modify; + options.set = set; + options.use = use; + + return introduce(diagnostics, options); +} + +/** + * Simple helper function to introduce various of helper methods to our given + * diagnostics function. + * + * @param {Function} diagnostics The diagnostics function. + * @returns {Function} diagnostics + * @public + */ +module.exports = function create(diagnostics) { + diagnostics.introduce = introduce; + diagnostics.enabled = enabled; + diagnostics.process = process; + diagnostics.modify = modify; + diagnostics.write = write; + diagnostics.nope = nope; + diagnostics.yep = yep; + diagnostics.set = set; + diagnostics.use = use; + + return diagnostics; +} + + +/***/ }), + +/***/ "./node_modules/@dabh/diagnostics/logger/console.js": +/*!**********************************************************!*\ + !*** ./node_modules/@dabh/diagnostics/logger/console.js ***! + \**********************************************************/ +/*! no static exports found */ +/***/ (function(module, exports) { + +/** + * An idiot proof logger to be used as default. We've wrapped it in a try/catch + * statement to ensure the environments without the `console` API do not crash + * as well as an additional fix for ancient browsers like IE8 where the + * `console.log` API doesn't have an `apply`, so we need to use the Function's + * apply functionality to apply the arguments. + * + * @param {Object} meta Options of the logger. + * @param {Array} messages The actuall message that needs to be logged. + * @public + */ +module.exports = function (meta, messages) { + // + // So yea. IE8 doesn't have an apply so we need a work around to puke the + // arguments in place. + // + try { Function.prototype.apply.call(console.log, console, messages); } + catch (e) {} +} + + +/***/ }), + +/***/ "./node_modules/@dabh/diagnostics/modifiers/namespace-ansi.js": +/*!********************************************************************!*\ + !*** ./node_modules/@dabh/diagnostics/modifiers/namespace-ansi.js ***! + \********************************************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +var colorspace = __webpack_require__(/*! colorspace */ "./node_modules/colorspace/index.js"); +var kuler = __webpack_require__(/*! kuler */ "./node_modules/kuler/index.js"); + +/** + * Prefix the messages with a colored namespace. + * + * @param {Array} args The messages array that is getting written. + * @param {Object} options Options for diagnostics. + * @returns {Array} Altered messages array. + * @public + */ +module.exports = function ansiModifier(args, options) { + var namespace = options.namespace; + var ansi = options.colors !== false + ? kuler(namespace +':', colorspace(namespace)) + : namespace +':'; + + args[0] = ansi +' '+ args[0]; + return args; +}; + + +/***/ }), + +/***/ "./node_modules/@dabh/diagnostics/node/development.js": +/*!************************************************************!*\ + !*** ./node_modules/@dabh/diagnostics/node/development.js ***! + \************************************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +var create = __webpack_require__(/*! ../diagnostics */ "./node_modules/@dabh/diagnostics/diagnostics.js"); +var tty = __webpack_require__(/*! tty */ "./node_modules/tty-browserify/index.js").isatty(1); + +/** + * Create a new diagnostics logger. + * + * @param {String} namespace The namespace it should enable. + * @param {Object} options Additional options. + * @returns {Function} The logger. + * @public + */ +var diagnostics = create(function dev(namespace, options) { + options = options || {}; + options.colors = 'colors' in options ? options.colors : tty; + options.namespace = namespace; + options.prod = false; + options.dev = true; + + if (!dev.enabled(namespace) && !(options.force || dev.force)) { + return dev.nope(options); + } + + return dev.yep(options); +}); + +// +// Configure the logger for the given environment. +// +diagnostics.modify(__webpack_require__(/*! ../modifiers/namespace-ansi */ "./node_modules/@dabh/diagnostics/modifiers/namespace-ansi.js")); +diagnostics.use(__webpack_require__(/*! ../adapters/process.env */ "./node_modules/@dabh/diagnostics/adapters/process.env.js")); +diagnostics.set(__webpack_require__(/*! ../logger/console */ "./node_modules/@dabh/diagnostics/logger/console.js")); + +// +// Expose the diagnostics logger. +// +module.exports = diagnostics; + + +/***/ }), + +/***/ "./node_modules/@dabh/diagnostics/node/index.js": +/*!******************************************************!*\ + !*** ./node_modules/@dabh/diagnostics/node/index.js ***! + \******************************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +// +// Select the correct build version depending on the environment. +// +if (false) {} else { + module.exports = __webpack_require__(/*! ./development.js */ "./node_modules/@dabh/diagnostics/node/development.js"); +} + + +/***/ }), + +/***/ "./node_modules/@firebolt-js/discovery-sdk/dist/firebolt-discovery-open-rpc.json": +/*!***************************************************************************************!*\ + !*** ./node_modules/@firebolt-js/discovery-sdk/dist/firebolt-discovery-open-rpc.json ***! + \***************************************************************************************/ +/*! exports provided: openrpc, info, methods, components, x-schemas, default */ +/***/ (function(module) { + +module.exports = JSON.parse("{\"openrpc\":\"1.2.4\",\"info\":{\"title\":\"Firebolt Discovery SDK\",\"version\":\"1.4.1\",\"x-module-descriptions\":{}},\"methods\":[{\"name\":\"Content.requestUserInterest\",\"tags\":[{\"name\":\"capabilities\",\"x-provided-by\":\"Discovery.onRequestUserInterest\",\"x-uses\":[\"xrn:firebolt:capability:discovery:interest\"]}],\"summary\":\"Provide information about the entity currently displayed or selected on the screen.\",\"description\":\"Provide information about the entity currently displayed or selected on the screen.\",\"params\":[{\"name\":\"type\",\"required\":true,\"schema\":{\"$ref\":\"#/x-schemas/Discovery/InterestType\"}},{\"name\":\"reason\",\"required\":true,\"schema\":{\"$ref\":\"#/x-schemas/Discovery/InterestReason\"}}],\"result\":{\"name\":\"interest\",\"schema\":{\"$ref\":\"#/components/schemas/InterestResult\"},\"summary\":\"The EntityDetails data.\"},\"examples\":[{\"name\":\"Default Example\",\"params\":[{\"name\":\"type\",\"value\":\"interest\"},{\"name\":\"reason\",\"value\":\"playlist\"}],\"result\":{\"name\":\"interest\",\"value\":{\"appId\":\"cool-app\",\"entity\":{\"identifiers\":{\"entityId\":\"345\",\"entityType\":\"program\",\"programType\":\"movie\"},\"info\":{\"title\":\"Cool Runnings\",\"synopsis\":\"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Pulvinar sapien et ligula ullamcorper malesuada proin libero nunc.\",\"releaseDate\":\"1993-01-01T00:00:00.000Z\",\"contentRatings\":[{\"scheme\":\"US-Movie\",\"rating\":\"PG\"},{\"scheme\":\"CA-Movie\",\"rating\":\"G\"}]}}}}}]},{\"name\":\"Content.onUserInterest\",\"tags\":[{\"name\":\"event\"},{\"name\":\"capabilities\",\"x-provided-by\":\"Discovery.userInterest\",\"x-uses\":[\"xrn:firebolt:capability:discovery:interest\"]}],\"summary\":\"Provide information about the entity currently displayed or selected on the screen.\",\"description\":\"Provide information about the entity currently displayed or selected on the screen.\",\"params\":[{\"name\":\"listen\",\"required\":true,\"schema\":{\"type\":\"boolean\"}}],\"result\":{\"name\":\"interest\",\"schema\":{\"anyOf\":[{\"$ref\":\"#/x-schemas/Types/ListenResponse\"},{\"$ref\":\"#/components/schemas/InterestEvent\"}]},\"summary\":\"The EntityDetails data.\"},\"examples\":[{\"name\":\"Default Example\",\"params\":[{\"name\":\"listen\",\"value\":true}],\"result\":{\"name\":\"interest\",\"value\":{\"appId\":\"cool-app\",\"type\":\"interest\",\"reason\":\"playlist\",\"entity\":{\"identifiers\":{\"entityId\":\"345\",\"entityType\":\"program\",\"programType\":\"movie\"},\"info\":{\"title\":\"Cool Runnings\",\"synopsis\":\"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Pulvinar sapien et ligula ullamcorper malesuada proin libero nunc.\",\"releaseDate\":\"1993-01-01T00:00:00.000Z\",\"contentRatings\":[{\"scheme\":\"US-Movie\",\"rating\":\"PG\"},{\"scheme\":\"CA-Movie\",\"rating\":\"G\"}]}}}}}]}],\"components\":{\"schemas\":{\"ChallengeRequestor\":{\"title\":\"ChallengeRequestor\",\"type\":\"object\",\"required\":[\"id\",\"name\"],\"properties\":{\"id\":{\"type\":\"string\",\"description\":\"The id of the app that requested the challenge\"},\"name\":{\"type\":\"string\",\"description\":\"The name of the app that requested the challenge\"}}},\"Challenge\":{\"title\":\"Challenge\",\"type\":\"object\",\"required\":[\"capability\",\"requestor\"],\"properties\":{\"capability\":{\"type\":\"string\",\"description\":\"The capability that is being requested by the user to approve\"},\"requestor\":{\"description\":\"The identity of which app is requesting access to this capability\",\"$ref\":\"#/components/schemas/ChallengeRequestor\"}}},\"InterestResult\":{\"title\":\"InterestResult\",\"type\":\"object\",\"properties\":{\"appId\":{\"type\":\"string\"},\"entity\":{\"$ref\":\"#/x-schemas/Entity/EntityDetails\"}},\"required\":[\"appId\",\"entity\"]},\"InterestEvent\":{\"title\":\"InterestEvent\",\"type\":\"object\",\"properties\":{\"appId\":{\"type\":\"string\"},\"type\":{\"$ref\":\"#/x-schemas/Discovery/InterestType\"},\"reason\":{\"$ref\":\"#/x-schemas/Discovery/InterestReason\"},\"entity\":{\"$ref\":\"#/x-schemas/Entity/EntityDetails\"}},\"required\":[\"appId\",\"entity\",\"type\",\"reason\"]},\"NetworkType\":{\"title\":\"NetworkType\",\"type\":\"string\",\"enum\":[\"wifi\",\"ethernet\",\"hybrid\"],\"description\":\"The type of network that is currently active\"},\"NetworkState\":{\"title\":\"NetworkState\",\"type\":\"string\",\"enum\":[\"connected\",\"disconnected\"],\"description\":\"The type of network that is currently active\"},\"FederatedRequest\":{\"title\":\"FederatedRequest\",\"type\":\"object\",\"properties\":{\"correlationId\":{\"type\":\"string\"}},\"required\":[\"correlationId\"],\"propertyNames\":{\"enum\":[\"correlationId\",\"parameters\"]},\"examples\":[{\"correlationId\":\"xyz\"}]},\"FederatedResponse\":{\"title\":\"FederatedResponse\",\"type\":\"object\",\"properties\":{\"correlationId\":{\"type\":\"string\"}},\"required\":[\"correlationId\",\"result\"],\"propertyNames\":{\"enum\":[\"correlationId\",\"result\"]},\"examples\":[{\"correlationId\":\"xyz\"}]},\"EntityInfoParameters\":{\"title\":\"EntityInfoParameters\",\"type\":\"object\",\"properties\":{\"entityId\":{\"type\":\"string\"},\"assetId\":{\"type\":\"string\"}},\"required\":[\"entityId\"],\"additionalProperties\":false,\"examples\":[{\"entityId\":\"345\"}]},\"PurchasedContentParameters\":{\"title\":\"PurchasedContentParameters\",\"type\":\"object\",\"properties\":{\"limit\":{\"type\":\"integer\",\"minimum\":-1},\"offeringType\":{\"$ref\":\"#/x-schemas/Entertainment/OfferingType\"},\"programType\":{\"$ref\":\"#/x-schemas/Entertainment/ProgramType\"}},\"required\":[\"limit\"],\"additionalProperties\":false,\"examples\":[{\"limit\":100}]},\"Availability\":{\"title\":\"Availability\",\"type\":\"object\",\"properties\":{\"type\":{\"type\":\"string\",\"enum\":[\"channel-lineup\",\"program-lineup\"]},\"id\":{\"type\":\"string\"},\"catalogId\":{\"type\":\"string\"},\"startTime\":{\"type\":\"string\",\"format\":\"date-time\"},\"endTime\":{\"type\":\"string\",\"format\":\"date-time\"}},\"required\":[\"type\",\"id\"]},\"HDMIPortId\":{\"type\":\"string\",\"pattern\":\"^HDMI[0-9]+$\"},\"EDIDVersion\":{\"title\":\"EDIDVersion\",\"type\":\"string\",\"enum\":[\"1.4\",\"2.0\",\"unknown\"]},\"HDMISignalStatus\":{\"type\":\"string\",\"enum\":[\"none\",\"stable\",\"unstable\",\"unsupported\",\"unknown\"]},\"KeyboardParameters\":{\"title\":\"KeyboardParameters\",\"type\":\"object\",\"required\":[\"message\"],\"properties\":{\"message\":{\"description\":\"The message to display to the user so the user knows what they are entering\",\"type\":\"string\"}},\"examples\":[{\"type\":\"standard\",\"message\":\"Enter your user name.\"}]},\"EventObjectPrimitives\":{\"title\":\"EventObjectPrimitives\",\"anyOf\":[{\"type\":\"string\",\"maxLength\":256},{\"type\":\"number\"},{\"type\":\"integer\"},{\"type\":\"boolean\"},{\"type\":\"null\"}]},\"EventObject\":{\"title\":\"EventObject\",\"type\":\"object\",\"maxProperties\":256,\"additionalProperties\":{\"anyOf\":[{\"$ref\":\"#/components/schemas/EventObjectPrimitives\"},{\"type\":\"array\",\"maxItems\":256,\"items\":{\"anyOf\":[{\"$ref\":\"#/components/schemas/EventObjectPrimitives\"},{\"$ref\":\"#/components/schemas/EventObject\"}]}},{\"$ref\":\"#/components/schemas/EventObject\"}]}},\"PinChallenge\":{\"title\":\"PinChallenge\",\"type\":\"object\",\"required\":[\"requestor\",\"pinSpace\"],\"properties\":{\"pinSpace\":{\"type\":\"string\",\"description\":\"The pin space that this challenge is for\",\"enum\":[\"purchase\",\"content\"]},\"capability\":{\"type\":\"string\",\"description\":\"The capability that is gated by a pin challenge\"},\"requestor\":{\"description\":\"The identity of which app is requesting access to this capability\",\"$ref\":\"#/components/schemas/ChallengeRequestor\"}}},\"ResultReason\":{\"title\":\"ResultReason\",\"type\":\"string\",\"description\":\"The reason for the result of challenging the user\",\"enum\":[\"noPinRequired\",\"noPinRequiredWindow\",\"exceededPinFailures\",\"correctPin\",\"cancelled\"]},\"AppInfo\":{\"description\":\"Information about an app that a grant was for\",\"type\":\"object\",\"properties\":{\"id\":{\"type\":\"string\"},\"title\":{\"type\":\"string\"}},\"additionalProperties\":false,\"required\":[\"id\"]},\"GrantState\":{\"description\":\"The state the grant is in\",\"type\":\"string\",\"enum\":[\"granted\",\"denied\"]},\"WifiSecurityMode\":{\"title\":\"WifiSecurityMode\",\"description\":\"Security Mode supported for Wifi\",\"type\":\"string\",\"enum\":[\"none\",\"wep64\",\"wep128\",\"wpaPskTkip\",\"wpaPskAes\",\"wpa2PskTkip\",\"wpa2PskAes\",\"wpaEnterpriseTkip\",\"wpaEnterpriseAes\",\"wpa2EnterpriseTkip\",\"wpa2EnterpriseAes\",\"wpa2Psk\",\"wpa2Enterprise\",\"wpa3PskAes\",\"wpa3Sae\"]},\"WifiSignalStrength\":{\"title\":\"WifiSignalStrength\",\"description\":\"Strength of Wifi signal, value is negative based on RSSI specification.\",\"type\":\"integer\",\"default\":-255,\"minimum\":-255,\"maximum\":0},\"WifiFrequency\":{\"title\":\"WifiFrequency\",\"description\":\"Wifi Frequency in Ghz, example 2.4Ghz and 5Ghz.\",\"type\":\"number\",\"default\":0,\"minimum\":0},\"AccessPoint\":{\"title\":\"AccessPoint\",\"description\":\"Properties of a scanned wifi list item.\",\"type\":\"object\",\"properties\":{\"ssid\":{\"type\":\"string\",\"description\":\"Name of the wifi.\"},\"securityMode\":{\"$ref\":\"#/components/schemas/WifiSecurityMode\"},\"signalStrength\":{\"$ref\":\"#/components/schemas/WifiSignalStrength\"},\"frequency\":{\"$ref\":\"#/components/schemas/WifiFrequency\"}}}}},\"x-schemas\":{\"Types\":{\"uri\":\"https://meta.comcast.com/firebolt/types\",\"SemanticVersion\":{\"title\":\"SemanticVersion\",\"type\":\"object\",\"properties\":{\"major\":{\"type\":\"integer\",\"minimum\":0},\"minor\":{\"type\":\"integer\",\"minimum\":0},\"patch\":{\"type\":\"integer\",\"minimum\":0},\"readable\":{\"type\":\"string\"}},\"required\":[\"major\",\"minor\",\"patch\",\"readable\"],\"additionalProperties\":false},\"ListenResponse\":{\"title\":\"ListenResponse\",\"type\":\"object\",\"required\":[\"event\",\"listening\"],\"properties\":{\"event\":{\"type\":\"string\",\"pattern\":\"[a-zA-Z]+\\\\.on[A-Z][a-zA-Z]+\"},\"listening\":{\"type\":\"boolean\"}},\"additionalProperties\":false},\"ProviderRequest\":{\"title\":\"ProviderRequest\",\"type\":\"object\",\"required\":[\"correlationId\"],\"additionalProperties\":false,\"properties\":{\"correlationId\":{\"type\":\"string\",\"description\":\"The id that was passed in to the event that triggered a provider method to be called\"},\"parameters\":{\"description\":\"The result of the provider response.\",\"type\":[\"object\",\"null\"]}}},\"AudioProfile\":{\"title\":\"AudioProfile\",\"type\":\"string\",\"enum\":[\"stereo\",\"dolbyDigital5.1\",\"dolbyDigital5.1+\",\"dolbyAtmos\"]},\"LocalizedString\":{\"title\":\"LocalizedString\",\"description\":\"Localized string supports either a simple `string` or a Map of language codes to strings. When using a simple `string`, the current preferred langauge from `Localization.langauge()` is assumed.\",\"oneOf\":[{\"type\":\"string\"},{\"type\":\"object\",\"additionalProperties\":{\"type\":\"string\"}}],\"examples\":[\"A simple string, with no language code\",{\"en\":\"This is english\",\"es\":\"esto es español\"}]},\"FlatMap\":{\"type\":\"object\",\"additionalProperties\":{\"oneOf\":[{\"type\":\"string\"},{\"type\":\"number\"},{\"type\":\"boolean\"}]}},\"BooleanMap\":{\"title\":\"BooleanMap\",\"type\":\"object\",\"additionalProperties\":{\"type\":\"boolean\"}},\"Timeout\":{\"title\":\"Timeout\",\"description\":\"Defines the timeout in seconds. If the threshold for timeout is passed for any operation without a result it will throw an error.\",\"type\":\"integer\",\"default\":0,\"minimum\":0,\"maximum\":9999}},\"Accessibility\":{\"uri\":\"https://meta.comcast.com/firebolt/accessibility\",\"ClosedCaptionsSettings\":{\"title\":\"ClosedCaptionsSettings\",\"type\":\"object\",\"required\":[\"enabled\"],\"properties\":{\"enabled\":{\"type\":\"boolean\",\"description\":\"Whether or not closed-captions should be enabled by default\"},\"styles\":{\"$ref\":\"#/x-schemas/Accessibility/ClosedCaptionsStyles\"},\"preferredLanguages\":{\"type\":\"array\",\"items\":{\"$ref\":\"#/x-schemas/Localization/ISO639_2Language\"}}},\"examples\":[{\"enabled\":true,\"styles\":{\"fontFamily\":\"monospaced_serif\",\"fontSize\":1,\"fontColor\":\"#ffffff\",\"fontEdge\":\"none\",\"fontEdgeColor\":\"#7F7F7F\",\"fontOpacity\":100,\"backgroundColor\":\"#000000\",\"backgroundOpacity\":100,\"textAlign\":\"center\",\"textAlignVertical\":\"middle\",\"windowColor\":\"white\",\"windowOpacity\":50},\"preferredLanguages\":[\"eng\",\"spa\"]}]},\"VoiceGuidanceSettings\":{\"title\":\"VoiceGuidanceSettings\",\"type\":\"object\",\"required\":[\"enabled\"],\"properties\":{\"enabled\":{\"type\":\"boolean\",\"description\":\"Whether or not voice guidance should be enabled by default\"},\"speed\":{\"$ref\":\"#/x-schemas/Accessibility/VoiceSpeed\",\"description\":\"The speed at which voice guidance speech will be read back to the user\"}},\"examples\":[{\"enabled\":true,\"speed\":2}]},\"VoiceSpeed\":{\"title\":\"VoiceSpeed\",\"type\":\"number\",\"minimum\":0.5,\"maximum\":2},\"ClosedCaptionsStyles\":{\"title\":\"ClosedCaptionsStyles\",\"type\":\"object\",\"description\":\"The default styles to use when displaying closed-captions\",\"properties\":{\"fontFamily\":{\"$ref\":\"#/x-schemas/Accessibility/FontFamily\"},\"fontSize\":{\"$ref\":\"#/x-schemas/Accessibility/FontSize\"},\"fontColor\":{\"$ref\":\"#/x-schemas/Accessibility/Color\"},\"fontEdge\":{\"$ref\":\"#/x-schemas/Accessibility/FontEdge\"},\"fontEdgeColor\":{\"$ref\":\"#/x-schemas/Accessibility/Color\"},\"fontOpacity\":{\"$ref\":\"#/x-schemas/Accessibility/Opacity\"},\"backgroundColor\":{\"$ref\":\"#/x-schemas/Accessibility/Color\"},\"backgroundOpacity\":{\"$ref\":\"#/x-schemas/Accessibility/Opacity\"},\"textAlign\":{\"$ref\":\"#/x-schemas/Accessibility/HorizontalAlignment\"},\"textAlignVertical\":{\"$ref\":\"#/x-schemas/Accessibility/VerticalAlignment\"},\"windowColor\":{\"$ref\":\"#/x-schemas/Accessibility/Color\"},\"windowOpacity\":{\"$ref\":\"#/x-schemas/Accessibility/Opacity\"}}},\"FontFamily\":{\"type\":[\"string\",\"null\"],\"enum\":[\"monospaced_serif\",\"proportional_serif\",\"monospaced_sanserif\",\"proportional_sanserif\",\"smallcaps\",\"cursive\",\"casual\",null]},\"FontSize\":{\"type\":[\"number\",\"null\"],\"minimum\":0},\"Color\":{\"type\":[\"string\",\"null\"]},\"FontEdge\":{\"type\":[\"string\",\"null\"],\"enum\":[\"none\",\"raised\",\"depressed\",\"uniform\",\"drop_shadow_left\",\"drop_shadow_right\",null]},\"Opacity\":{\"type\":[\"number\",\"null\"],\"minimum\":0,\"maximum\":100},\"HorizontalAlignment\":{\"type\":[\"string\",\"null\"]},\"VerticalAlignment\":{\"type\":[\"string\",\"null\"]}},\"Localization\":{\"uri\":\"https://meta.comcast.com/firebolt/localization\",\"ISO639_2Language\":{\"type\":\"string\",\"pattern\":\"^[a-z]{3}$\"},\"Locality\":{\"type\":\"string\"},\"CountryCode\":{\"type\":\"string\",\"pattern\":\"^[A-Z]{2}$\"},\"Language\":{\"type\":\"string\",\"pattern\":\"^[A-Za-z]{2}$\"},\"Locale\":{\"type\":\"string\",\"pattern\":\"^[a-zA-Z]+([a-zA-Z0-9\\\\-]*)$\"},\"TimeZone\":{\"type\":\"string\",\"pattern\":\"^[-+_/ A-Za-z 0-9]*$\"}},\"Advertising\":{\"uri\":\"https://meta.comcast.com/firebolt/advertising\",\"SkipRestriction\":{\"title\":\"SkipRestriction\",\"$comment\":\"xrn:advertising:policy:skipRestriction:\",\"type\":\"string\",\"enum\":[\"none\",\"adsUnwatched\",\"adsAll\",\"all\"],\"description\":\"The advertisement skip restriction.\\n\\nApplies to fast-forward/rewind (e.g. trick mode), seeking over an entire opportunity (e.g. jump), seeking out of what's currently playing, and \\\"Skip this ad...\\\" features. Seeking over multiple ad opportunities only requires playback of the _last_ opportunity, not all opportunities, preceding the seek destination.\\n\\n| Value | Description |\\n|--------------|--------------------------------------------------------------------------------|\\n| none |No fast-forward, jump, or skip restrictions |\\n| adsUnwatched | Restrict fast-forward, jump, and skip for unwatched ad opportunities only. |\\n| adsAll | Restrict fast-forward, jump, and skip for all ad opportunities |\\n| all | Restrict fast-forward, jump, and skip for all ad opportunities and all content |\\n\\nNamespace: `xrn:advertising:policy:skipRestriction:`\\n\\n\"}},\"Capabilities\":{\"uri\":\"https://meta.comcast.com/firebolt/capabilities\",\"Capability\":{\"title\":\"Capability\",\"type\":\"string\",\"description\":\"A Capability is a discrete unit of functionality that a Firebolt device might be able to perform.\",\"pattern\":\"^xrn:firebolt:capability:([a-z0-9\\\\-]+)((:[a-z0-9\\\\-]+)?)$\"},\"CapabilityInfo\":{\"title\":\"CapabilityInfo\",\"type\":\"object\",\"required\":[\"supported\",\"available\",\"use\",\"manage\",\"provide\"],\"properties\":{\"capability\":{\"$ref\":\"#/x-schemas/Capabilities/Capability\"},\"supported\":{\"type\":\"boolean\",\"description\":\"Provides info whether the capability is supported\"},\"available\":{\"type\":\"boolean\",\"description\":\"Provides info whether the capability is available\"},\"use\":{\"$ref\":\"#/x-schemas/Capabilities/CapPermissionStatus\"},\"manage\":{\"$ref\":\"#/x-schemas/Capabilities/CapPermissionStatus\"},\"provide\":{\"$ref\":\"#/x-schemas/Capabilities/CapPermissionStatus\"},\"details\":{\"type\":\"array\",\"items\":{\"$ref\":\"#/x-schemas/Capabilities/DenyReason\"},\"minItems\":1,\"maxItems\":6}},\"additionalProperties\":false,\"examples\":[{\"capability\":\"xrn:firebolt:capability:keyboard\",\"supported\":true,\"available\":true,\"use\":{\"permitted\":true,\"granted\":true},\"manage\":{\"permitted\":true,\"granted\":true},\"provide\":{\"permitted\":true,\"granted\":true}}]},\"Permission\":{\"title\":\"Permission\",\"description\":\"A capability combined with a Role, which an app may be permitted (by a distributor) or granted (by an end user).\",\"type\":\"object\",\"required\":[\"capability\"],\"properties\":{\"role\":{\"$ref\":\"#/x-schemas/Capabilities/Role\"},\"capability\":{\"$ref\":\"#/x-schemas/Capabilities/Capability\"}},\"additionalProperties\":false},\"Role\":{\"title\":\"Role\",\"description\":\"Role provides access level for the app for a given capability.\",\"type\":\"string\",\"enum\":[\"use\",\"manage\",\"provide\"]},\"CapPermissionStatus\":{\"type\":\"object\",\"properties\":{\"permitted\":{\"type\":\"boolean\",\"description\":\"Provides info whether the capability is permitted\"},\"granted\":{\"oneOf\":[{\"type\":\"boolean\",\"description\":\"Provides info whether the capability is granted\"},{\"const\":null}]}},\"additionalProperties\":false},\"DenyReason\":{\"title\":\"DenyReason\",\"description\":\"Reasons why a Capability might not be invokable\",\"type\":\"string\",\"enum\":[\"unpermitted\",\"unsupported\",\"disabled\",\"unavailable\",\"grantDenied\",\"ungranted\"]}},\"Discovery\":{\"uri\":\"https://meta.comcast.com/firebolt/discovery\",\"InterestType\":{\"title\":\"InterestType\",\"type\":\"string\",\"enum\":[\"interest\",\"disinterest\"]},\"InterestReason\":{\"title\":\"InterestReason\",\"type\":\"string\",\"enum\":[\"playlist\",\"reaction\",\"recording\"]},\"EntityInfoResult\":{\"title\":\"EntityInfoResult\",\"description\":\"The result for an `entityInfo()` push or pull.\",\"type\":\"object\",\"properties\":{\"expires\":{\"type\":\"string\",\"format\":\"date-time\"},\"entity\":{\"$ref\":\"#/x-schemas/Entertainment/EntityInfo\"},\"related\":{\"type\":\"array\",\"items\":{\"$ref\":\"#/x-schemas/Entertainment/EntityInfo\"}}},\"required\":[\"expires\",\"entity\"],\"additionalProperties\":false},\"PurchasedContentResult\":{\"title\":\"PurchasedContentResult\",\"type\":\"object\",\"properties\":{\"expires\":{\"type\":\"string\",\"format\":\"date-time\"},\"totalCount\":{\"type\":\"integer\",\"minimum\":0},\"entries\":{\"type\":\"array\",\"items\":{\"$ref\":\"#/x-schemas/Entertainment/EntityInfo\"}}},\"required\":[\"expires\",\"totalCount\",\"entries\"],\"additionalProperties\":false}},\"Entity\":{\"uri\":\"https://meta.comcast.com/firebolt/entity\",\"EntityDetails\":{\"title\":\"EntityDetails\",\"type\":\"object\",\"required\":[\"identifiers\"],\"properties\":{\"identifiers\":{\"$ref\":\"#/x-schemas/Entity/Entity\"},\"info\":{\"$ref\":\"#/x-schemas/Entity/Metadata\"},\"waysToWatch\":{\"type\":\"array\",\"items\":{\"$ref\":\"#/x-schemas/Entertainment/WayToWatch\"},\"description\":\"An array of ways a user is might watch this entity, regardless of entitlements.\"}}},\"Entity\":{\"oneOf\":[{\"$ref\":\"#/x-schemas/Entity/ProgramEntity\"},{\"$ref\":\"#/x-schemas/Entity/MusicEntity\"},{\"$ref\":\"#/x-schemas/Entity/ChannelEntity\"},{\"$ref\":\"#/x-schemas/Entity/UntypedEntity\"},{\"$ref\":\"#/x-schemas/Entity/PlaylistEntity\"}]},\"Metadata\":{\"title\":\"Metadata\",\"type\":\"object\",\"properties\":{\"title\":{\"type\":\"string\",\"description\":\"Title of the entity.\"},\"synopsis\":{\"type\":\"string\",\"description\":\"Short description of the entity.\"},\"seasonNumber\":{\"type\":\"number\",\"description\":\"For TV seasons, the season number. For TV episodes, the season that the episode belongs to.\"},\"seasonCount\":{\"type\":\"number\",\"description\":\"For TV series, seasons, and episodes, the total number of seasons.\"},\"episodeNumber\":{\"type\":\"number\",\"description\":\"For TV episodes, the episode number.\"},\"episodeCount\":{\"type\":\"number\",\"description\":\"For TV seasons and episodes, the total number of episodes in the current season.\"},\"releaseDate\":{\"type\":\"string\",\"format\":\"date-time\",\"description\":\"The date that the program or entity was released or first aired.\"},\"contentRatings\":{\"type\":\"array\",\"items\":{\"$ref\":\"#/x-schemas/Entertainment/ContentRating\"},\"description\":\"A list of ContentRating objects, describing the entity's ratings in various rating schemes.\"}}},\"ProgramEntity\":{\"title\":\"ProgramEntity\",\"oneOf\":[{\"$ref\":\"#/x-schemas/Entity/MovieEntity\"},{\"$ref\":\"#/x-schemas/Entity/TVEpisodeEntity\"},{\"$ref\":\"#/x-schemas/Entity/TVSeasonEntity\"},{\"$ref\":\"#/x-schemas/Entity/TVSeriesEntity\"},{\"$ref\":\"#/x-schemas/Entity/AdditionalEntity\"}]},\"MusicEntity\":{\"title\":\"MusicEntity\",\"type\":\"object\",\"properties\":{\"entityType\":{\"const\":\"music\"},\"musicType\":{\"$ref\":\"#/x-schemas/Entertainment/MusicType\"},\"entityId\":{\"type\":\"string\"}},\"required\":[\"entityType\",\"musicType\",\"entityId\"]},\"ChannelEntity\":{\"title\":\"ChannelEntity\",\"type\":\"object\",\"properties\":{\"entityType\":{\"const\":\"channel\"},\"channelType\":{\"type\":\"string\",\"enum\":[\"streaming\",\"overTheAir\"]},\"entityId\":{\"type\":\"string\",\"description\":\"ID of the channel, in the target App's scope.\"},\"appContentData\":{\"type\":\"string\",\"maxLength\":256}},\"required\":[\"entityType\",\"channelType\",\"entityId\"],\"additionalProperties\":false},\"UntypedEntity\":{\"title\":\"UntypedEntity\",\"allOf\":[{\"description\":\"A Firebolt compliant representation of the remaining entity types.\",\"type\":\"object\",\"required\":[\"entityId\"],\"properties\":{\"entityId\":{\"type\":\"string\"},\"assetId\":{\"type\":\"string\"},\"appContentData\":{\"type\":\"string\",\"maxLength\":256}},\"additionalProperties\":false}],\"examples\":[{\"entityId\":\"an-entity\"}]},\"PlaylistEntity\":{\"title\":\"PlaylistEntity\",\"description\":\"A Firebolt compliant representation of a Playlist entity.\",\"type\":\"object\",\"required\":[\"entityType\",\"entityId\"],\"properties\":{\"entityType\":{\"const\":\"playlist\"},\"entityId\":{\"type\":\"string\"},\"assetId\":{\"type\":\"string\"},\"appContentData\":{\"type\":\"string\",\"maxLength\":256}},\"additionalProperties\":false,\"examples\":[{\"entityType\":\"playlist\",\"entityId\":\"playlist/xyz\"}]},\"MovieEntity\":{\"title\":\"MovieEntity\",\"description\":\"A Firebolt compliant representation of a Movie entity.\",\"type\":\"object\",\"required\":[\"entityType\",\"programType\",\"entityId\"],\"properties\":{\"entityType\":{\"const\":\"program\"},\"programType\":{\"const\":\"movie\"},\"entityId\":{\"type\":\"string\"},\"assetId\":{\"type\":\"string\"},\"appContentData\":{\"type\":\"string\",\"maxLength\":256}},\"additionalProperties\":false,\"examples\":[{\"entityType\":\"program\",\"programType\":\"movie\",\"entityId\":\"el-camino\"}]},\"TVEpisodeEntity\":{\"title\":\"TVEpisodeEntity\",\"description\":\"A Firebolt compliant representation of a TV Episode entity.\",\"type\":\"object\",\"required\":[\"entityType\",\"programType\",\"entityId\",\"seriesId\",\"seasonId\"],\"properties\":{\"entityType\":{\"const\":\"program\"},\"programType\":{\"const\":\"episode\"},\"entityId\":{\"type\":\"string\"},\"seriesId\":{\"type\":\"string\"},\"seasonId\":{\"type\":\"string\"},\"assetId\":{\"type\":\"string\"},\"appContentData\":{\"type\":\"string\",\"maxLength\":256}},\"additionalProperties\":false,\"examples\":[{\"entityType\":\"program\",\"programType\":\"episode\",\"entityId\":\"breaking-bad-pilot\",\"seriesId\":\"breaking-bad\",\"seasonId\":\"breaking-bad-season-1\"}]},\"TVSeasonEntity\":{\"title\":\"TVSeasonEntity\",\"description\":\"A Firebolt compliant representation of a TV Season entity.\",\"type\":\"object\",\"required\":[\"entityType\",\"programType\",\"entityId\",\"seriesId\"],\"properties\":{\"entityType\":{\"const\":\"program\"},\"programType\":{\"const\":\"season\"},\"entityId\":{\"type\":\"string\"},\"seriesId\":{\"type\":\"string\"},\"assetId\":{\"type\":\"string\"},\"appContentData\":{\"type\":\"string\",\"maxLength\":256}},\"additionalProperties\":false,\"examples\":[{\"entityType\":\"program\",\"programType\":\"season\",\"entityId\":\"breaking-bad-season-1\",\"seriesId\":\"breaking-bad\"}]},\"TVSeriesEntity\":{\"title\":\"TVSeriesEntity\",\"description\":\"A Firebolt compliant representation of a TV Series entity.\",\"type\":\"object\",\"required\":[\"entityType\",\"programType\",\"entityId\"],\"properties\":{\"entityType\":{\"const\":\"program\"},\"programType\":{\"const\":\"series\"},\"entityId\":{\"type\":\"string\"},\"assetId\":{\"type\":\"string\"},\"appContentData\":{\"type\":\"string\",\"maxLength\":256}},\"additionalProperties\":false,\"examples\":[{\"entityType\":\"program\",\"programType\":\"series\",\"entityId\":\"breaking-bad\"}]},\"AdditionalEntity\":{\"title\":\"AdditionalEntity\",\"description\":\"A Firebolt compliant representation of the remaining program entity types.\",\"type\":\"object\",\"required\":[\"entityType\",\"programType\",\"entityId\"],\"properties\":{\"entityType\":{\"const\":\"program\"},\"programType\":{\"type\":\"string\",\"enum\":[\"concert\",\"sportingEvent\",\"preview\",\"other\",\"advertisement\",\"musicVideo\",\"minisode\",\"extra\"]},\"entityId\":{\"type\":\"string\"},\"assetId\":{\"type\":\"string\"},\"appContentData\":{\"type\":\"string\",\"maxLength\":256}},\"additionalProperties\":false,\"examples\":[{\"entityType\":\"program\",\"programType\":\"concert\",\"entityId\":\"live-aid\"}]},\"PlayableEntity\":{\"title\":\"PlayableEntity\",\"anyOf\":[{\"$ref\":\"#/x-schemas/Entity/MovieEntity\"},{\"$ref\":\"#/x-schemas/Entity/TVEpisodeEntity\"},{\"$ref\":\"#/x-schemas/Entity/PlaylistEntity\"},{\"$ref\":\"#/x-schemas/Entity/MusicEntity\"},{\"$ref\":\"#/x-schemas/Entity/AdditionalEntity\"}]}},\"Entertainment\":{\"uri\":\"https://meta.comcast.com/firebolt/entertainment\",\"WayToWatch\":{\"title\":\"WayToWatch\",\"type\":\"object\",\"required\":[\"identifiers\",\"audioProfile\"],\"properties\":{\"identifiers\":{\"$ref\":\"#/x-schemas/Entertainment/ContentIdentifiers\"},\"expires\":{\"type\":\"string\",\"format\":\"date-time\",\"description\":\"Time when the WayToWatch is no longer available.\"},\"entitled\":{\"type\":\"boolean\",\"description\":\"Specify if the user is entitled to watch the entity.\"},\"entitledExpires\":{\"type\":\"string\",\"format\":\"date-time\",\"description\":\"Time when the entity is no longer entitled.\"},\"offeringType\":{\"$ref\":\"#/x-schemas/Entertainment/OfferingType\"},\"hasAds\":{\"type\":\"boolean\",\"description\":\"True if the streamable asset contains ads.\"},\"price\":{\"type\":\"number\",\"description\":\"For \\\"buy\\\" and \\\"rent\\\" WayToWatch, the price to buy or rent in the user's preferred currency.\"},\"videoQuality\":{\"type\":\"array\",\"items\":{\"type\":\"string\",\"enum\":[\"SD\",\"HD\",\"UHD\"]},\"description\":\"List of the video qualities available via the WayToWatch.\"},\"audioProfile\":{\"type\":\"array\",\"items\":{\"$ref\":\"#/x-schemas/Types/AudioProfile\"},\"description\":\"List of the audio types available via the WayToWatch.\"},\"audioLanguages\":{\"type\":\"array\",\"items\":{\"type\":\"string\"},\"description\":\"List of audio track languages available on the WayToWatch. The first is considered the primary language. Languages are expressed as ISO 639 1/2 codes.\"},\"closedCaptions\":{\"type\":\"array\",\"items\":{\"type\":\"string\"},\"description\":\"List of languages for which closed captions are available on the WayToWatch. Languages are expressed as ISO 639 1/2 codes.\"},\"subtitles\":{\"type\":\"array\",\"items\":{\"type\":\"string\"},\"description\":\"List of languages for which subtitles are available on the WayToWatch. Languages are expressed as ISO 639 1/2 codes.\"},\"audioDescriptions\":{\"type\":\"array\",\"items\":{\"type\":\"string\"},\"description\":\"List of languages for which audio descriptions (DVD) as available on the WayToWatch. Languages are expressed as ISO 639 1/2 codes.\"}},\"description\":\"A WayToWatch describes a way to watch a video program. It may describe a single\\nstreamable asset or a set of streamable assets. For example, an app provider may\\ndescribe HD, SD, and UHD assets as individual WayToWatch objects or rolled into\\na single WayToWatch.\\n\\nIf the WayToWatch represents a single streamable asset, the provided\\nContentIdentifiers must be sufficient to play back the specific asset when sent\\nvia a playback intent or deep link. If the WayToWatch represents multiple\\nstreamable assets, the provided ContentIdentifiers must be sufficient to\\nplayback one of the assets represented with no user action. In this scenario,\\nthe app SHOULD choose the best asset for the user based on their device and\\nsettings. The ContentIdentifiers MUST also be sufficient for navigating the user\\nto the appropriate entity or detail screen via an entity intent.\\n\\nThe app should set the `entitled` property to indicate if the user can watch, or\\nnot watch, the asset without making a purchase. If the entitlement is known to\\nexpire at a certain time (e.g., a rental), the app should also provide the\\n`entitledExpires` property. If the entitlement is not expired, the UI will use\\nthe `entitled` property to display watchable assets to the user, adjust how\\nassets are presented to the user, and how intents into the app are generated.\\nFor example, the the Aggregated Experience could render a \\\"Watch\\\" button for an\\nentitled asset versus a \\\"Subscribe\\\" button for an non-entitled asset.\\n\\nThe app should set the `offeringType` to define how the content may be\\nauthorized. The UI will use this to adjust how content is presented to the user.\\n\\nA single WayToWatch cannot represent streamable assets available via multiple\\npurchase paths. If, for example, an asset has both Buy, Rent and Subscription\\navailability, the three different entitlement paths MUST be represented as\\nmultiple WayToWatch objects.\\n\\n`price` should be populated for WayToWatch objects with `buy` or `rent`\\n`offeringType`. If the WayToWatch represents a set of assets with various price\\npoints, the `price` provided must be the lowest available price.\"},\"OfferingType\":{\"title\":\"OfferingType\",\"type\":\"string\",\"enum\":[\"free\",\"subscribe\",\"buy\",\"rent\"],\"description\":\"The offering type of the WayToWatch.\"},\"ContentIdentifiers\":{\"title\":\"ContentIdentifiers\",\"type\":\"object\",\"properties\":{\"assetId\":{\"type\":\"string\",\"description\":\"Identifies a particular playable asset. For example, the HD version of a particular movie separate from the UHD version.\"},\"entityId\":{\"type\":\"string\",\"description\":\"Identifies an entity, such as a Movie, TV Series or TV Episode.\"},\"seasonId\":{\"type\":\"string\",\"description\":\"The TV Season for a TV Episode.\"},\"seriesId\":{\"type\":\"string\",\"description\":\"The TV Series for a TV Episode or TV Season.\"},\"appContentData\":{\"type\":\"string\",\"description\":\"App-specific content identifiers.\",\"maxLength\":1024}},\"description\":\"The ContentIdentifiers object is how the app identifies an entity or asset to\\nthe Firebolt platform. These ids are used to look up metadata and deep link into\\nthe app.\\n\\nApps do not need to provide all ids. They only need to provide the minimum\\nrequired to target a playable stream or an entity detail screen via a deep link.\\nIf an id isn't needed to get to those pages, it doesn't need to be included.\"},\"ContentRating\":{\"title\":\"ContentRating\",\"type\":\"object\",\"required\":[\"scheme\",\"rating\"],\"properties\":{\"scheme\":{\"type\":\"string\",\"enum\":[\"CA-Movie\",\"CA-TV\",\"CA-Movie-Fr\",\"CA-TV-Fr\",\"US-Movie\",\"US-TV\"],\"description\":\"The rating scheme.\"},\"rating\":{\"type\":\"string\",\"description\":\"The content rating.\"},\"advisories\":{\"type\":\"array\",\"items\":{\"type\":\"string\"},\"description\":\"Optional list of subratings or content advisories.\"}},\"description\":\"A ContentRating represents an age or content based of an entity. Supported rating schemes and associated types are below.\\n\\n## United States\\n\\n`US-Movie` (MPAA):\\n\\nRatings: `NR`, `G`, `PG`, `PG13`, `R`, `NC17`\\n\\nAdvisories: `AT`, `BN`, `SL`, `SS`, `N`, `V`\\n\\n`US-TV` (Vchip):\\n\\nRatings: `TVY`, `TVY7`, `TVG`, `TVPG`, `TV14`, `TVMA`\\n\\nAdvisories: `FV`, `D`, `L`, `S`, `V`\\n\\n## Canada\\n\\n`CA-Movie` (OFRB):\\n\\nRatings: `G`, `PG`, `14A`, `18A`, `R`, `E`\\n\\n`CA-TV` (AGVOT)\\n\\nRatings: `E`, `C`, `C8`, `G`, `PG`, `14+`, `18+`\\n\\nAdvisories: `C`, `C8`, `G`, `PG`, `14+`, `18+`\\n\\n`CA-Movie-Fr` (Canadian French language movies):\\n\\nRatings: `G`, `8+`, `13+`, `16+`, `18+`\\n\\n`CA-TV-Fr` (Canadian French language TV):\\n\\nRatings: `G`, `8+`, `13+`, `16+`, `18+`\\n\"},\"MusicType\":{\"title\":\"MusicType\",\"type\":\"string\",\"description\":\"In the case of a music `entityType`, specifies the type of music entity.\",\"enum\":[\"song\",\"album\"]},\"Entitlement\":{\"title\":\"Entitlement\",\"type\":\"object\",\"properties\":{\"entitlementId\":{\"type\":\"string\"},\"startTime\":{\"type\":\"string\",\"format\":\"date-time\"},\"endTime\":{\"type\":\"string\",\"format\":\"date-time\"}},\"required\":[\"entitlementId\"]},\"EntityInfo\":{\"title\":\"EntityInfo\",\"description\":\"An EntityInfo object represents an \\\"entity\\\" on the platform. Currently, only entities of type `program` are supported. `programType` must be supplied to identify the program type.\\n\\nAdditionally, EntityInfo objects must specify a properly formed\\nContentIdentifiers object, `entityType`, and `title`. The app should provide\\nthe `synopsis` property for a good user experience if the content\\nmetadata is not available another way.\\n\\nThe ContentIdentifiers must be sufficient for navigating the user to the\\nappropriate entity or detail screen via a `detail` intent or deep link.\\n\\nEntityInfo objects must provide at least one WayToWatch object when returned as\\npart of an `entityInfo` method and a streamable asset is available to the user.\\nIt is optional for the `purchasedContent` method, but recommended because the UI\\nmay use those data.\",\"type\":\"object\",\"required\":[\"identifiers\",\"entityType\",\"title\"],\"properties\":{\"identifiers\":{\"$ref\":\"#/x-schemas/Entertainment/ContentIdentifiers\"},\"title\":{\"type\":\"string\",\"description\":\"Title of the entity.\"},\"entityType\":{\"type\":\"string\",\"enum\":[\"program\",\"music\"],\"description\":\"The type of the entity, e.g. `program` or `music`.\"},\"programType\":{\"$ref\":\"#/x-schemas/Entertainment/ProgramType\"},\"musicType\":{\"$ref\":\"#/x-schemas/Entertainment/MusicType\"},\"synopsis\":{\"type\":\"string\",\"description\":\"Short description of the entity.\"},\"seasonNumber\":{\"type\":\"number\",\"description\":\"For TV seasons, the season number. For TV episodes, the season that the episode belongs to.\"},\"seasonCount\":{\"type\":\"number\",\"description\":\"For TV series, seasons, and episodes, the total number of seasons.\"},\"episodeNumber\":{\"type\":\"number\",\"description\":\"For TV episodes, the episode number.\"},\"episodeCount\":{\"type\":\"number\",\"description\":\"For TV seasons and episodes, the total number of episodes in the current season.\"},\"releaseDate\":{\"type\":\"string\",\"format\":\"date-time\",\"description\":\"The date that the program or entity was released or first aired.\"},\"contentRatings\":{\"type\":\"array\",\"items\":{\"$ref\":\"#/x-schemas/Entertainment/ContentRating\"},\"description\":\"A list of ContentRating objects, describing the entity's ratings in various rating schemes.\"},\"waysToWatch\":{\"type\":\"array\",\"items\":{\"$ref\":\"#/x-schemas/Entertainment/WayToWatch\"},\"description\":\"An array of ways a user is might watch this entity, regardless of entitlements.\"}},\"if\":{\"properties\":{\"entityType\":{\"const\":\"program\"}}},\"then\":{\"required\":[\"programType\"],\"not\":{\"required\":[\"musicType\"]}},\"else\":{\"required\":[\"musicType\"],\"not\":{\"required\":[\"programType\"]}}},\"ProgramType\":{\"title\":\"ProgramType\",\"type\":\"string\",\"description\":\"In the case of a program `entityType`, specifies the program type.\",\"enum\":[\"movie\",\"episode\",\"season\",\"series\",\"other\",\"preview\",\"extra\",\"concert\",\"sportingEvent\",\"advertisement\",\"musicVideo\",\"minisode\"]}},\"Intents\":{\"uri\":\"https://meta.comcast.com/firebolt/intents\",\"NavigationIntent\":{\"title\":\"NavigationIntent\",\"description\":\"A Firebolt compliant representation of a user intention to navigate to a specific place in an app.\",\"anyOf\":[{\"$ref\":\"#/x-schemas/Intents/HomeIntent\"},{\"$ref\":\"#/x-schemas/Intents/LaunchIntent\"},{\"$ref\":\"#/x-schemas/Intents/EntityIntent\"},{\"$ref\":\"#/x-schemas/Intents/PlaybackIntent\"},{\"$ref\":\"#/x-schemas/Intents/SearchIntent\"},{\"$ref\":\"#/x-schemas/Intents/SectionIntent\"},{\"$ref\":\"#/x-schemas/Intents/TuneIntent\"},{\"$ref\":\"#/x-schemas/Intents/PlayEntityIntent\"},{\"$ref\":\"#/x-schemas/Intents/PlayQueryIntent\"}]},\"HomeIntent\":{\"description\":\"A Firebolt compliant representation of a user intention to navigate an app to it's home screen, and bring that app to the foreground if needed.\",\"title\":\"HomeIntent\",\"allOf\":[{\"title\":\"HomeIntent\",\"$ref\":\"#/x-schemas/Intents/Intent\"},{\"title\":\"HomeIntent\",\"$ref\":\"#/x-schemas/Intents/IntentProperties\"},{\"title\":\"HomeIntent\",\"type\":\"object\",\"properties\":{\"action\":{\"const\":\"home\"}},\"not\":{\"required\":[\"data\"]}}],\"examples\":[{\"action\":\"home\",\"context\":{\"source\":\"voice\"}}]},\"LaunchIntent\":{\"description\":\"A Firebolt compliant representation of a user intention to launch an app.\",\"title\":\"LaunchIntent\",\"allOf\":[{\"$ref\":\"#/x-schemas/Intents/Intent\"},{\"$ref\":\"#/x-schemas/Intents/IntentProperties\"},{\"type\":\"object\",\"properties\":{\"action\":{\"const\":\"launch\"}},\"not\":{\"required\":[\"data\"]}}],\"examples\":[{\"action\":\"launch\",\"context\":{\"source\":\"voice\"}}]},\"EntityIntent\":{\"description\":\"A Firebolt compliant representation of a user intention to navigate an app to a specific entity page, and bring that app to the foreground if needed.\",\"title\":\"EntityIntent\",\"allOf\":[{\"$ref\":\"#/x-schemas/Intents/Intent\"},{\"$ref\":\"#/x-schemas/Intents/IntentProperties\"},{\"type\":\"object\",\"required\":[\"data\"],\"properties\":{\"action\":{\"const\":\"entity\"},\"data\":{\"$ref\":\"#/x-schemas/Entity/Entity\"}}}],\"examples\":[{\"action\":\"entity\",\"context\":{\"source\":\"voice\"},\"data\":{\"entityType\":\"program\",\"programType\":\"movie\",\"entityId\":\"el-camino\"}}]},\"PlaybackIntent\":{\"description\":\"A Firebolt compliant representation of a user intention to navigate an app to a the video player for a specific, playable entity, and bring that app to the foreground if needed.\",\"title\":\"PlaybackIntent\",\"allOf\":[{\"$ref\":\"#/x-schemas/Intents/Intent\"},{\"$ref\":\"#/x-schemas/Intents/IntentProperties\"},{\"type\":\"object\",\"required\":[\"data\"],\"properties\":{\"action\":{\"const\":\"playback\"},\"data\":{\"$ref\":\"#/x-schemas/Entity/PlayableEntity\"}}}],\"examples\":[{\"action\":\"playback\",\"data\":{\"entityType\":\"program\",\"programType\":\"episode\",\"entityId\":\"breaking-bad-pilot\",\"seriesId\":\"breaking-bad\",\"seasonId\":\"breaking-bad-season-1\"},\"context\":{\"source\":\"voice\"}}]},\"SearchIntent\":{\"description\":\"A Firebolt compliant representation of a user intention to navigate an app to it's search UI with a search term populated, and bring that app to the foreground if needed.\",\"title\":\"SearchIntent\",\"allOf\":[{\"$ref\":\"#/x-schemas/Intents/Intent\"},{\"$ref\":\"#/x-schemas/Intents/IntentProperties\"},{\"type\":\"object\",\"properties\":{\"action\":{\"const\":\"search\"},\"data\":{\"type\":\"object\",\"required\":[\"query\"],\"properties\":{\"query\":{\"type\":\"string\"},\"suggestions\":{\"type\":\"array\",\"items\":{\"$ref\":\"#/x-schemas/Entity/Entity\"}}},\"additionalProperties\":false}}}],\"examples\":[{\"action\":\"search\",\"data\":{\"query\":\"walter white\"},\"context\":{\"source\":\"voice\"}}]},\"SectionIntent\":{\"description\":\"A Firebolt compliant representation of a user intention to navigate an app to a section not covered by `home`, `entity`, `player`, or `search`, and bring that app to the foreground if needed.\",\"title\":\"SectionIntent\",\"allOf\":[{\"$ref\":\"#/x-schemas/Intents/Intent\"},{\"$ref\":\"#/x-schemas/Intents/IntentProperties\"},{\"type\":\"object\",\"properties\":{\"action\":{\"const\":\"section\"},\"data\":{\"type\":\"object\",\"required\":[\"sectionName\"],\"properties\":{\"sectionName\":{\"type\":\"string\"}},\"additionalProperties\":false}},\"required\":[\"data\"]}],\"examples\":[{\"action\":\"section\",\"data\":{\"sectionName\":\"settings\"},\"context\":{\"source\":\"voice\"}}]},\"TuneIntent\":{\"description\":\"A Firebolt compliant representation of a user intention to 'tune' to a traditional over-the-air broadcast, or an OTT Stream from an OTT or vMVPD App.\",\"title\":\"TuneIntent\",\"allOf\":[{\"$ref\":\"#/x-schemas/Intents/Intent\"},{\"$ref\":\"#/x-schemas/Intents/IntentProperties\"},{\"type\":\"object\",\"required\":[\"data\"],\"properties\":{\"action\":{\"const\":\"tune\"},\"data\":{\"type\":\"object\",\"required\":[\"entity\"],\"additionalProperties\":false,\"properties\":{\"entity\":{\"$ref\":\"#/x-schemas/Entity/ChannelEntity\"},\"options\":{\"description\":\"The options property of the data property MUST have only one of the following fields.\",\"type\":\"object\",\"required\":[],\"additionalProperties\":false,\"minProperties\":1,\"maxProperties\":1,\"properties\":{\"assetId\":{\"type\":\"string\",\"description\":\"The ID of a specific 'listing', as scoped by the target App's ID-space, which the App should begin playback from.\"},\"restartCurrentProgram\":{\"type\":\"boolean\",\"description\":\"Denotes that the App should start playback at the most recent program boundary, rather than 'live.'\"},\"time\":{\"type\":\"string\",\"format\":\"date-time\",\"description\":\"ISO 8601 Date/Time where the App should begin playback from.\"}}}}}}}],\"examples\":[{\"action\":\"tune\",\"data\":{\"entity\":{\"entityType\":\"channel\",\"channelType\":\"streaming\",\"entityId\":\"an-ott-channel\"},\"options\":{\"restartCurrentProgram\":true}},\"context\":{\"source\":\"voice\"}}]},\"PlayEntityIntent\":{\"description\":\"A Firebolt compliant representation of a user intention to navigate an app to a the video player for a specific, playable entity, and bring that app to the foreground if needed.\",\"title\":\"PlayEntityIntent\",\"allOf\":[{\"$ref\":\"#/x-schemas/Intents/Intent\"},{\"$ref\":\"#/x-schemas/Intents/IntentProperties\"},{\"type\":\"object\",\"required\":[\"data\"],\"properties\":{\"action\":{\"const\":\"play-entity\"},\"data\":{\"type\":\"object\",\"properties\":{\"entity\":{\"$ref\":\"#/x-schemas/Entity/PlayableEntity\"},\"options\":{\"type\":\"object\",\"properties\":{\"playFirstId\":{\"type\":\"string\"},\"playFirstTrack\":{\"type\":\"integer\",\"minimum\":1}},\"additionalProperties\":false}},\"required\":[\"entity\"],\"propertyNames\":{\"enum\":[\"entity\",\"options\"]},\"if\":{\"properties\":{\"entity\":{\"type\":\"object\",\"required\":[\"entityType\"],\"properties\":{\"entityType\":{\"const\":\"playlist\"}}}}},\"then\":{\"type\":\"object\",\"properties\":{\"options\":{\"type\":\"object\",\"maxProperties\":1}}},\"else\":{\"type\":\"object\",\"properties\":{\"options\":{\"type\":\"object\",\"maxProperties\":0}}}}}}],\"examples\":[{\"action\":\"play-entity\",\"data\":{\"entity\":{\"entityType\":\"playlist\",\"entityId\":\"playlist/xyz\"},\"options\":{\"playFirstId\":\"song/xyz\"}},\"context\":{\"source\":\"voice\"}},{\"action\":\"play-entity\",\"data\":{\"entity\":{\"entityType\":\"playlist\",\"entityId\":\"playlist/xyz\"},\"options\":{\"playFirstTrack\":3}},\"context\":{\"source\":\"voice\"}}]},\"PlayQueryIntent\":{\"description\":\"A Firebolt compliant representation of a user intention to navigate an app to a the video player for an abstract query to be searched for and played by the app.\",\"title\":\"PlayQueryIntent\",\"allOf\":[{\"$ref\":\"#/x-schemas/Intents/Intent\"},{\"$ref\":\"#/x-schemas/Intents/IntentProperties\"},{\"type\":\"object\",\"required\":[\"data\"],\"properties\":{\"action\":{\"const\":\"play-query\"},\"data\":{\"type\":\"object\",\"properties\":{\"query\":{\"type\":\"string\"},\"options\":{\"type\":\"object\",\"properties\":{\"programTypes\":{\"type\":\"array\",\"items\":{\"$ref\":\"#/x-schemas/Entertainment/ProgramType\"}},\"musicTypes\":{\"type\":\"array\",\"items\":{\"$ref\":\"#/x-schemas/Entertainment/MusicType\"}}},\"additionalProperties\":false}},\"required\":[\"query\"],\"propertyNames\":{\"enum\":[\"query\",\"options\"]}}}}],\"examples\":[{\"action\":\"play-query\",\"data\":{\"query\":\"Ed Sheeran\"},\"context\":{\"source\":\"voice\"}},{\"action\":\"play-query\",\"data\":{\"query\":\"Ed Sheeran\",\"options\":{\"programTypes\":[\"movie\"]}},\"context\":{\"source\":\"voice\"}},{\"action\":\"play-query\",\"data\":{\"query\":\"Ed Sheeran\",\"options\":{\"programTypes\":[\"movie\"],\"musicTypes\":[\"song\"]}},\"context\":{\"source\":\"voice\"}}]},\"Intent\":{\"description\":\"A Firebolt compliant representation of a user intention.\",\"type\":\"object\",\"required\":[\"action\",\"context\"],\"properties\":{\"action\":{\"type\":\"string\"},\"context\":{\"type\":\"object\",\"required\":[\"source\"],\"properties\":{\"source\":{\"type\":\"string\"}}}}},\"IntentProperties\":{\"type\":\"object\",\"propertyNames\":{\"enum\":[\"action\",\"data\",\"context\"]}}},\"Lifecycle\":{\"uri\":\"https://meta.comcast.com/firebolt/lifecycle\",\"CloseReason\":{\"title\":\"CloseReason\",\"description\":\"The application close reason\",\"type\":\"string\",\"enum\":[\"remoteButton\",\"userExit\",\"done\",\"error\"]},\"LifecycleState\":{\"title\":\"LifecycleState\",\"description\":\"The application lifecycle state\",\"type\":\"string\",\"enum\":[\"initializing\",\"inactive\",\"foreground\",\"background\",\"unloading\",\"suspended\"]}},\"SecondScreen\":{\"uri\":\"https://meta.comcast.com/firebolt/secondscreen\",\"SecondScreenEvent\":{\"title\":\"SecondScreenEvent\",\"description\":\"An a message notification from a second screen device\",\"type\":\"object\",\"required\":[\"type\"],\"properties\":{\"type\":{\"type\":\"string\",\"enum\":[\"dial\"]},\"version\":{\"type\":\"string\"},\"data\":{\"type\":\"string\"}}}}}}"); + +/***/ }), + +/***/ "./node_modules/@firebolt-js/discovery-sdk/dist/lib/Content/defaults.mjs": +/*!*******************************************************************************!*\ + !*** ./node_modules/@firebolt-js/discovery-sdk/dist/lib/Content/defaults.mjs ***! + \*******************************************************************************/ +/*! exports provided: default */ +/***/ (function(__webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var _Prop_MockProps_mjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Prop/MockProps.mjs */ "./node_modules/@firebolt-js/discovery-sdk/dist/lib/Prop/MockProps.mjs"); +/* + * Copyright 2021 Comcast Cable Communications Management, LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + */ + + +/* harmony default export */ __webpack_exports__["default"] = ({ + requestUserInterest: { + appId: 'cool-app', + entity: { + identifiers: { + entityId: '345', + entityType: 'program', + programType: 'movie', + }, + info: { + title: 'Cool Runnings', + synopsis: + 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Pulvinar sapien et ligula ullamcorper malesuada proin libero nunc.', + releaseDate: '1993-01-01T00:00:00.000Z', + contentRatings: [ + { scheme: 'US-Movie', rating: 'PG' }, + { scheme: 'CA-Movie', rating: 'G' }, + ], + }, + }, + }, +}); + + +/***/ }), + +/***/ "./node_modules/@firebolt-js/discovery-sdk/dist/lib/Content/index.mjs": +/*!****************************************************************************!*\ + !*** ./node_modules/@firebolt-js/discovery-sdk/dist/lib/Content/index.mjs ***! + \****************************************************************************/ +/*! exports provided: default */ +/***/ (function(__webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var _Transport_index_mjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Transport/index.mjs */ "./node_modules/@firebolt-js/discovery-sdk/dist/lib/Transport/index.mjs"); +/* harmony import */ var _Events_index_mjs__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Events/index.mjs */ "./node_modules/@firebolt-js/discovery-sdk/dist/lib/Events/index.mjs"); +/* + * Copyright 2021 Comcast Cable Communications Management, LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + */ + + + + + +Object(_Events_index_mjs__WEBPACK_IMPORTED_MODULE_1__["registerEvents"])('Content', ['userInterest']) + +// onUserInterest is accessed via listen('userInterest, ...) + +// Methods +function clear(...args) { + return _Events_index_mjs__WEBPACK_IMPORTED_MODULE_1__["default"].clear('Content', ...args) +} + +function listen(...args) { + return _Events_index_mjs__WEBPACK_IMPORTED_MODULE_1__["default"].listen('Content', ...args) +} + +function once(...args) { + return _Events_index_mjs__WEBPACK_IMPORTED_MODULE_1__["default"].once('Content', ...args) +} + +function requestUserInterest(type, reason) { + const transforms = null + + return _Transport_index_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].send( + 'Content', + 'requestUserInterest', + { type, reason }, + transforms, + ) +} + +/* harmony default export */ __webpack_exports__["default"] = ({ + Events: { + USER_INTEREST: 'userInterest', + }, + + /** + * + */ + InterestType: { + INTEREST: 'interest', + DISINTEREST: 'disinterest', + }, + + /** + * + */ + InterestReason: { + PLAYLIST: 'playlist', + REACTION: 'reaction', + RECORDING: 'recording', + }, + + /** + * The offering type of the WayToWatch. + */ + OfferingType: { + FREE: 'free', + SUBSCRIBE: 'subscribe', + BUY: 'buy', + RENT: 'rent', + }, + + /** + * + */ + AudioProfile: { + STEREO: 'stereo', + DOLBY_DIGITAL_5_1: 'dolbyDigital5.1', + DOLBY_DIGITAL_5_1_PLUS: 'dolbyDigital5.1+', + DOLBY_ATMOS: 'dolbyAtmos', + }, + + /** + * In the case of a music `entityType`, specifies the type of music entity. + */ + MusicType: { + SONG: 'song', + ALBUM: 'album', + }, + + clear, + listen, + once, + requestUserInterest, +}); + + +/***/ }), + +/***/ "./node_modules/@firebolt-js/discovery-sdk/dist/lib/Events/index.mjs": +/*!***************************************************************************!*\ + !*** ./node_modules/@firebolt-js/discovery-sdk/dist/lib/Events/index.mjs ***! + \***************************************************************************/ +/*! exports provided: emit, registerEvents, registerEventContext, prioritize, default */ +/***/ (function(__webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "emit", function() { return emit; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "registerEvents", function() { return registerEvents; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "registerEventContext", function() { return registerEventContext; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "prioritize", function() { return prioritize; }); +/* harmony import */ var _Transport_index_mjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Transport/index.mjs */ "./node_modules/@firebolt-js/discovery-sdk/dist/lib/Transport/index.mjs"); +/* harmony import */ var _Transport_MockTransport_mjs__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Transport/MockTransport.mjs */ "./node_modules/@firebolt-js/discovery-sdk/dist/lib/Transport/MockTransport.mjs"); +/* + * Copyright 2021 Comcast Cable Communications Management, LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + */ + + + + +let listenerId = 0 + +// holds two maps of ${module}.${event} => listenerId, e.g. callback method id +// note that one callback can listen to multiple events, e.g. 'discovery.*' +// internal is only available via a private export that we use to ensure our modules know about +// events before the apps using the SDK (otherwise state errors can happen) +const listeners = { + internal: {}, + external: {}, + + // Several convenience functions below for checking both internal & external lists w/ one operation + + // gets a merge list of ids for a single event key + get: (key) => { + return Object.assign( + Object.assign({}, listeners.internal[key]), + listeners.external[key], + ) + }, + // adds a callback/id to a key on the external list only + set: (key, id, value) => { + listeners.external[key] = listeners.external[key] || {} + listeners.external[key][id] = value + }, + // adds a callback/id to a key on the internal list only + setInternal: (key, id, value) => { + listeners.internal[key] = listeners.internal[key] || {} + listeners.internal[key][id] = value + }, + // finds the key for an id in either list (it can only be in one) + find: (id) => { + let key + ;[listeners.internal, listeners.external].find((group) => { + key = Object.keys(group).find((key) => group[key][id]) + if (key) return true + }) + return key + }, + // removes an id from either list + remove: (id) => { + ;[listeners.internal, listeners.external].forEach((group) => { + Object.keys(group).forEach((key) => { + if (group[key] && group[key][id]) { + delete group[key][id] + if (Object.values(group[key]).length === 0) { + delete group[key] + } + } + }) + }) + }, + // removes a key from both lists if _internal is true, otherwise only the external list + removeKey: (key, _internal = false) => { + _internal && listeners.internal[key] && delete listeners.internal[key] + listeners.external[key] && delete listeners.external[key] + }, + // gives a list of all keys + keys: () => { + return Array.from( + new Set( + Object.keys(listeners.internal).concat(Object.keys(listeners.external)), + ), + ) + }, + // counts how many listeners are in a key across both lists + count: (key) => { + return Object.values(listeners.get(key)).length + }, +} + +// holds a map of RPC Ids => Context Key, e.g. the RPC id of an onEvent call mapped to the corresponding context parameters key for that RPC call +const keys = {} + +// holds a map of ${module}.${event} => Transport.send calls (only called once per event) +// note that the keys here MUST NOT contain wild cards +const oncers = [] +const validEvents = {} +const validContext = {} + +let transportInitialized = false + +const emit = (id, value) => { + callCallbacks(listeners.internal[keys[id]], [value]) + callCallbacks(listeners.external[keys[id]], [value]) +} + +const registerEvents = (module, events) => { + validEvents[module.toLowerCase()] = events.concat() +} + +const registerEventContext = (module, event, context) => { + validContext[module.toLowerCase()] = validContext[module.toLowerCase()] || {} + validContext[module.toLowerCase()][event] = context.concat() +} + +const callCallbacks = (cbs, args) => { + cbs && + Object.keys(cbs).forEach((listenerId) => { + let callback = cbs[listenerId] + if (oncers.indexOf(parseInt(listenerId)) >= 0) { + oncers.splice(oncers.indexOf(parseInt(listenerId)), 1) + delete cbs[listenerId] + } + callback.apply(null, args) + }) +} + +const doListen = function ( + module, + event, + callback, + context, + once, + internal = false, +) { + init() + + if (typeof callback !== 'function') { + return Promise.reject('No valid callback function provided.') + } else { + if (module === '*') { + return Promise.reject('No valid module name provided') + } + + const wildcard = event === '*' + const events = wildcard ? validEvents[module] : [event] // explodes wildcards into an array + const promises = [] + const hasContext = Object.values(context).length > 0 + const contextKey = Object.keys(context) + .sort() + .map((key) => key + '=' + JSON.stringify(context[key])) + .join('&') + + listenerId++ + + if (once) { + oncers.push(listenerId) + } + + events.forEach((event) => { + const key = module + '.' + event + (hasContext ? `.${contextKey}` : '') + + if (Object.values(listeners.get(key)).length === 0) { + const args = Object.assign({ listen: true }, context) + const { id, promise } = _Transport_index_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].listen( + module, + 'on' + event[0].toUpperCase() + event.substring(1), + args, + ) + keys[id] = key + promises.push(promise) + } + + const setter = internal ? listeners.setInternal : listeners.set + + if (wildcard) { + setter(key, '' + listenerId, (value) => callback(event, value)) + } else { + setter(key, '' + listenerId, callback) + } + }) + + let resolve, reject + let p = new Promise((res, rej) => { + resolve = res + reject = rej + }) + + if (promises.length) { + Promise.all(promises) + .then((responses) => { + resolve(listenerId) + }) + .catch((error) => { + // Promise.all rejects if at least one promise rejects... we don't want that behavior here + // TODO: Do something better than fail silently + if (event === '*') { + resolve(listenerId) + } else { + reject(error) + } + }) + } else { + resolve(listenerId) + } + return p + } +} + +const getListenArgs = function (...args) { + const callback = args.pop() + const [module, event, context] = getClearArgs(...args) + + return [module, event, callback, context] +} + +const getClearArgs = function (...args) { + const module = (args.shift() || '*').toLowerCase() + const event = args.shift() || '*' + const context = {} + + for (let i = 0; args.length; i++) { + context[validContext[module][event][i]] = args.shift() + } + + return [module, event, context] +} + +const once = function (...args) { + const [module, event, callback, context] = getListenArgs(...args) + return doListen(module, event, callback, context, true) +} + +const listen = function (...args) { + const [module, event, callback, context] = getListenArgs(...args) + return doListen(module, event, callback, context, false) +} + +const clear = function (...args) { + if (args && args.length && typeof args[0] === 'number') { + return doClear(args[0]) + } else if (args && args.length && typeof args[1] === 'number') { + return doClear(args[1]) + } else { + const [moduleOrId, event, context] = getClearArgs(...args) + return doClear(moduleOrId, event, context) + } +} + +// calls doListen with a priority flag for internal listeners to get priority +const prioritize = function (...args) { + const [module, event, callback, context] = getListenArgs(...args) + return doListen(module, event, callback, context, false, true) +} + +const unsubscribe = (key, context) => { + const [module, event] = key.split('.').slice(0, 2) + const args = Object.assign({ listen: false }, context) + _Transport_index_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].send(module, 'on' + event[0].toUpperCase() + event.substr(1), args) +} + +// TODO: clear needs to go through Transport Layer +const doClear = function (moduleOrId = false, event = false, context) { + if (event === '*') { + event = false + } + + if (typeof moduleOrId === 'number') { + const searchId = moduleOrId.toString() + const key = listeners.find(searchId) + + if (key) { + listeners.remove(searchId) + if (listeners.count(key) === 0) { + unsubscribe(key) + } + return true + } + return false + } else { + if (!moduleOrId && !event) { + listeners.keys().forEach((key) => { + listeners.removeKey(key) + unsubscribe(key) + }) + } else if (!event) { + listeners.keys().forEach((key) => { + if (key.indexOf(moduleOrId.toLowerCase()) === 0) { + listeners.removeKey(key) + unsubscribe(key) + } + }) + } else { + const hasContext = Object.values(context).length > 0 + const contextKey = Object.keys(context) + .sort() + .map((key) => key + '=' + JSON.stringify(context[key])) + .join('&') + const key = + moduleOrId + '.' + event + (hasContext ? `.${contextKey}` : '') + + listeners.removeKey(key) + unsubscribe(key, context) + } + } +} + +const init = () => { + if (!transportInitialized) { + _Transport_index_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].addEventEmitter(emit) + Object(_Transport_MockTransport_mjs__WEBPACK_IMPORTED_MODULE_1__["setMockListener"])(listen) + transportInitialized = true + } +} + +/* harmony default export */ __webpack_exports__["default"] = ({ + listen: listen, + once: once, + clear: clear, + broadcast(event, value) { + emit(Object.entries(keys).find(([k, v]) => v === 'app.' + event)[0], value) + }, +}); + + +/***/ }), + +/***/ "./node_modules/@firebolt-js/discovery-sdk/dist/lib/Log/index.mjs": +/*!************************************************************************!*\ + !*** ./node_modules/@firebolt-js/discovery-sdk/dist/lib/Log/index.mjs ***! + \************************************************************************/ +/*! exports provided: default */ +/***/ (function(__webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var _Settings_index_mjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Settings/index.mjs */ "./node_modules/@firebolt-js/discovery-sdk/dist/lib/Settings/index.mjs"); +/* + * Copyright 2021 Comcast Cable Communications Management, LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + */ + + + +const prepLog = (type, args) => { + const colors = { + Info: 'green', + Debug: 'gray', + Warn: 'orange', + Error: 'red', + } + + args = Array.from(args) + return [ + '%c' + + (args.length > 1 && typeof args[0] === 'string' ? args.shift() : type), + 'background-color: ' + + colors[type] + + '; color: white; padding: 2px 4px; border-radius: 2px', + args, + ] +} + +/* harmony default export */ __webpack_exports__["default"] = ({ + info() { + _Settings_index_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].get('platform', 'log') && + console.log.apply(console, prepLog('Info', arguments)) + }, + debug() { + _Settings_index_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].get('platform', 'log') && + console.debug.apply(console, prepLog('Debug', arguments)) + }, + error() { + _Settings_index_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].get('platform', 'log') && + console.error.apply(console, prepLog('Error', arguments)) + }, + warn() { + _Settings_index_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].get('platform', 'log') && + console.warn.apply(console, prepLog('Warn', arguments)) + }, +}); + + +/***/ }), + +/***/ "./node_modules/@firebolt-js/discovery-sdk/dist/lib/Prop/MockProps.mjs": +/*!*****************************************************************************!*\ + !*** ./node_modules/@firebolt-js/discovery-sdk/dist/lib/Prop/MockProps.mjs ***! + \*****************************************************************************/ +/*! exports provided: default */ +/***/ (function(__webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var _Transport_MockTransport_mjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Transport/MockTransport.mjs */ "./node_modules/@firebolt-js/discovery-sdk/dist/lib/Transport/MockTransport.mjs"); +/* harmony import */ var _Router_mjs__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./Router.mjs */ "./node_modules/@firebolt-js/discovery-sdk/dist/lib/Prop/Router.mjs"); + + + +const mocks = {} + +function mock(module, method, params, value, contextParameterCount, def) { + const type = Object(_Router_mjs__WEBPACK_IMPORTED_MODULE_1__["default"])(params, value, contextParameterCount) + const hash = contextParameterCount + ? '.' + + Object.keys(params) + .filter((key) => key !== 'value') + .map((key) => params[key]) + .join('.') + : '' + const key = `${module}.${method}${hash}` + + if (type === 'getter') { + const value = mocks.hasOwnProperty(key) ? mocks[key] : def + return value + } else if (type === 'subscriber') { + } else if (type === 'setter') { + mocks[key] = value + _Transport_MockTransport_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].event(module, `${method}Changed`, { value }) + return null + } +} + +/* harmony default export */ __webpack_exports__["default"] = ({ + mock: mock, +}); + + +/***/ }), + +/***/ "./node_modules/@firebolt-js/discovery-sdk/dist/lib/Prop/Router.mjs": +/*!**************************************************************************!*\ + !*** ./node_modules/@firebolt-js/discovery-sdk/dist/lib/Prop/Router.mjs ***! + \**************************************************************************/ +/*! exports provided: default */ +/***/ (function(__webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony default export */ __webpack_exports__["default"] = (function (params, callbackOrValue, contextParameterCount) { + const numArgs = params ? Object.values(params).length : 0 + + if (numArgs === contextParameterCount && callbackOrValue === undefined) { + // getter + return 'getter' + } else if ( + numArgs === contextParameterCount && + typeof callbackOrValue === 'function' + ) { + // subscribe + return 'subscriber' + } else if (numArgs === 0 && typeof callbackOrValue === 'function') { + // for x-subscriber-type: global + return 'subscriber' + } else if ( + numArgs === contextParameterCount && + callbackOrValue !== undefined + ) { + // setter + return 'setter' + } + + return null +}); + + +/***/ }), + +/***/ "./node_modules/@firebolt-js/discovery-sdk/dist/lib/Results/index.mjs": +/*!****************************************************************************!*\ + !*** ./node_modules/@firebolt-js/discovery-sdk/dist/lib/Results/index.mjs ***! + \****************************************************************************/ +/*! exports provided: default */ +/***/ (function(__webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var _Transport_index_mjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Transport/index.mjs */ "./node_modules/@firebolt-js/discovery-sdk/dist/lib/Transport/index.mjs"); + + +/* +methods = Map +*/ + +function transform(result, transforms) { + if (!transforms || !transforms.methods) { + return result + } + + const { methods } = transforms + const transformed = JSON.parse(JSON.stringify(result)) + + Object.keys(methods).forEach((key) => { + const method_info = methods[key] + const rpc_method = method_info['x-method'] + const [module, method] = rpc_method.split('.') + const params = {} + params[method_info['x-this-param']] = transformed + transformed[key] = (...args) => { + // copy the args into the correct RPC param names + for (var i = 0; i < args.length; i++) { + params[method_info['x-additional-params'][i]] = args[i] + } + return _Transport_index_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].send(module.toLowerCase(), method, params) + } + }) + return transformed +} + +/* harmony default export */ __webpack_exports__["default"] = ({ + transform, +}); + + +/***/ }), + +/***/ "./node_modules/@firebolt-js/discovery-sdk/dist/lib/Settings/index.mjs": +/*!*****************************************************************************!*\ + !*** ./node_modules/@firebolt-js/discovery-sdk/dist/lib/Settings/index.mjs ***! + \*****************************************************************************/ +/*! exports provided: initSettings, default */ +/***/ (function(__webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "initSettings", function() { return initSettings; }); +/* + * Copyright 2021 Comcast Cable Communications Management, LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + */ + +const settings = {} +const subscribers = {} + +const initSettings = (appSettings, platformSettings) => { + settings['app'] = appSettings + settings['platform'] = { + logLevel: 'WARN', + ...platformSettings, + } + settings['user'] = {} +} + +const publish = (key, value) => { + subscribers[key] && + subscribers[key].forEach((subscriber) => subscriber(value)) +} + +const dotGrab = (obj = {}, key) => { + const keys = key.split('.') + for (let i = 0; i < keys.length; i++) { + obj = obj[keys[i]] = obj[keys[i]] !== undefined ? obj[keys[i]] : {} + } + return typeof obj === 'object' + ? Object.keys(obj).length + ? obj + : undefined + : obj +} + +/* harmony default export */ __webpack_exports__["default"] = ({ + get(type, key, fallback = undefined) { + const val = dotGrab(settings[type], key) + return val !== undefined ? val : fallback + }, + has(type, key) { + return !!this.get(type, key) + }, + set(key, value) { + settings['user'][key] = value + publish(key, value) + }, + subscribe(key, callback) { + subscribers[key] = subscribers[key] || [] + subscribers[key].push(callback) + }, + unsubscribe(key, callback) { + if (callback) { + const index = + subscribers[key] && subscribers[key].findIndex((cb) => cb === callback) + index > -1 && subscribers[key].splice(index, 1) + } else { + if (key in subscribers) { + subscribers[key] = [] + } + } + }, + clearSubscribers() { + for (const key of Object.getOwnPropertyNames(subscribers)) { + delete subscribers[key] + } + }, + setLogLevel(logLevel) { + settings.platform.logLevel = logLevel + }, + getLogLevel() { + return settings.platform.logLevel + }, +}); + + +/***/ }), + +/***/ "./node_modules/@firebolt-js/discovery-sdk/dist/lib/Transport/LegacyTransport.mjs": +/*!****************************************************************************************!*\ + !*** ./node_modules/@firebolt-js/discovery-sdk/dist/lib/Transport/LegacyTransport.mjs ***! + \****************************************************************************************/ +/*! exports provided: default */ +/***/ (function(__webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return LegacyTransport; }); +/* + * Copyright 2021 Comcast Cable Communications Management, LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + */ + +const win = typeof window !== 'undefined' ? window : {} + +class LegacyTransport { + constructor(bridge) { + this.bridge = bridge + } + + send(msg) { + this.bridge.JSMessageChanged(msg, () => {}) + } + + receive(callback) { + win.$badger = win.$badger || {} + /** Hold on to real $badger callback and event methods so they can be called for non-jsonrpc messages */ + const badgerCallback = win.$badger.callback + ? win.$badger.callback.bind(win.$badger) + : null + const badgerEvent = win.$badger.event + ? win.$badger.event.bind(win.$badger) + : null + win.$badger.callback = (pid, success, json) => { + if (json.jsonrpc) { + callback(JSON.stringify(json)) + } else if (badgerCallback) { + badgerCallback(pid, success, json) + } + } + win.$badger.event = (handlerId, json) => { + if (json.jsonrpc) { + callback(JSON.stringify(json)) + } else if (badgerEvent) { + badgerEvent(handlerId, json) + } + } + } + + static isLegacy(transport) { + return ( + LegacyTransport.isXREProxy(transport) || + (transport.send === undefined && transport.JSMessageChanged) + ) + } + + static isXREProxy(transport) { + /** Set top boxes running XRE has a "Proxy" transport + * native object that intercepts ALL method calls, so we + * cannot test for transport.send existence because it will return true + * even though it actually is not supported. Check if some obscure method + * name like "proxyObjectTest" is defined. If it is then we know we are using a + * Proxy object and thus is legacy transport. + */ + return transport.proxyObjectTest !== undefined + } +} + + +/***/ }), + +/***/ "./node_modules/@firebolt-js/discovery-sdk/dist/lib/Transport/MockTransport.mjs": +/*!**************************************************************************************!*\ + !*** ./node_modules/@firebolt-js/discovery-sdk/dist/lib/Transport/MockTransport.mjs ***! + \**************************************************************************************/ +/*! exports provided: setMockListener, setMockResponses, default */ +/***/ (function(__webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "setMockListener", function() { return setMockListener; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "setMockResponses", function() { return setMockResponses; }); +/* + * Copyright 2021 Comcast Cable Communications Management, LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + */ + +const win = typeof window !== 'undefined' ? window : {} + +let listener +const setMockListener = (func) => { + listener = func +} + +let mock +const pending = [] +const eventMap = {} + +let callback +let testHarness + +if (win.__firebolt && win.__firebolt.testHarness) { + testHarness = win.__firebolt.testHarness +} + +function send(message) { + console.debug('Sending message to transport: ' + message) + let json = JSON.parse(message) + + // handle bulk sends + if (Array.isArray(json)) { + json.forEach((j) => send(JSON.stringify(j))) + return + } + + let [module, method] = json.method.split('.') + + if (testHarness && testHarness.onSend) { + testHarness.onSend(module, method, json.params, json.id) + } + + // store the ID of the first listen for each event + if (method.match(/^on[A-Z]/)) { + if (json.params.listen) { + eventMap[json.id] = + module.toLowerCase() + '.' + method[2].toLowerCase() + method.substr(3) + } else { + Object.keys(eventMap).forEach((key) => { + if ( + eventMap[key] === + module.toLowerCase() + + '.' + + method[2].toLowerCase() + + method.substr(3) + ) { + delete eventMap[key] + } + }) + } + } + + if (mock) handle(json) + else pending.push(json) +} + +function handle(json) { + let result + try { + result = getResult(json.method, json.params) + } catch (error) { + setTimeout(() => + callback( + JSON.stringify({ + jsonrpc: '2.0', + error: { + code: -32602, + message: + 'Invalid params (this is a mock error from the mock transport layer)', + }, + id: json.id, + }), + ), + ) + } + + setTimeout(() => + callback( + JSON.stringify({ + jsonrpc: '2.0', + result: result, + id: json.id, + }), + ), + ) +} + +function receive(_callback) { + callback = _callback + + if (testHarness && typeof testHarness.initialize === 'function') { + testHarness.initialize({ + emit: event, + listen: function (...args) { + listener(...args) + }, + }) + } +} + +function event(module, event, value) { + const listener = Object.entries(eventMap).find( + ([k, v]) => + v.toLowerCase() === module.toLowerCase() + '.' + event.toLowerCase(), + ) + if (listener) { + let message = JSON.stringify({ + jsonrpc: '2.0', + id: parseInt(listener[0]), + result: value, + }) + callback(message) + } +} + +function dotGrab(obj = {}, key) { + const keys = key.split('.') + let ref = obj + for (let i = 0; i < keys.length; i++) { + ref = (Object.entries(ref).find( + ([k, v]) => k.toLowerCase() === keys[i].toLowerCase(), + ) || [null, {}])[1] + } + return ref +} + +function getResult(method, params) { + let api = dotGrab(mock, method) + + if (method.match(/^[a-zA-Z]+\.on[A-Za-z]+$/)) { + api = { + event: method, + listening: true, + } + } + + if (typeof api === 'function') { + return params == null ? api() : api(params) + } else return api +} + +function setMockResponses(m) { + mock = m + + pending.forEach((json) => handle(json)) + pending.length = 0 +} + +/* harmony default export */ __webpack_exports__["default"] = ({ + send: send, + receive: receive, + event: event, +}); + + +/***/ }), + +/***/ "./node_modules/@firebolt-js/discovery-sdk/dist/lib/Transport/WebsocketTransport.mjs": +/*!*******************************************************************************************!*\ + !*** ./node_modules/@firebolt-js/discovery-sdk/dist/lib/Transport/WebsocketTransport.mjs ***! + \*******************************************************************************************/ +/*! exports provided: default */ +/***/ (function(__webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return WebsocketTransport; }); +const MAX_QUEUED_MESSAGES = 100 + +class WebsocketTransport { + constructor(endpoint) { + this._endpoint = endpoint + this._ws = null + this._connected = false + this._queue = [] + this._callbacks = [] + } + + send(msg) { + this._connect() + + if (this._connected) { + this._ws.send(msg) + } else { + if (this._queue.length < MAX_QUEUED_MESSAGES) { + this._queue.push(msg) + } + } + } + + receive(callback) { + if (!callback) return + this._connect() + this._callbacks.push(callback) + } + + _notifyCallbacks(message) { + for (let i = 0; i < this._callbacks.length; i++) { + setTimeout(() => this._callbacks[i](message), 1) + } + } + + _connect() { + if (this._ws) return + this._ws = new WebSocket(this._endpoint, ['jsonrpc']) + this._ws.addEventListener('message', (message) => { + this._notifyCallbacks(message.data) + }) + this._ws.addEventListener('error', (message) => {}) + this._ws.addEventListener('close', (message) => { + this._ws = null + this._connected = false + }) + this._ws.addEventListener('open', (message) => { + this._connected = true + for (let i = 0; i < this._queue.length; i++) { + this._ws.send(this._queue[i]) + } + this._queue = [] + }) + } +} + + +/***/ }), + +/***/ "./node_modules/@firebolt-js/discovery-sdk/dist/lib/Transport/index.mjs": +/*!******************************************************************************!*\ + !*** ./node_modules/@firebolt-js/discovery-sdk/dist/lib/Transport/index.mjs ***! + \******************************************************************************/ +/*! exports provided: default */ +/***/ (function(__webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return Transport; }); +/* harmony import */ var _MockTransport_mjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./MockTransport.mjs */ "./node_modules/@firebolt-js/discovery-sdk/dist/lib/Transport/MockTransport.mjs"); +/* harmony import */ var _queue_mjs__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./queue.mjs */ "./node_modules/@firebolt-js/discovery-sdk/dist/lib/Transport/queue.mjs"); +/* harmony import */ var _Settings_index_mjs__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Settings/index.mjs */ "./node_modules/@firebolt-js/discovery-sdk/dist/lib/Settings/index.mjs"); +/* harmony import */ var _LegacyTransport_mjs__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./LegacyTransport.mjs */ "./node_modules/@firebolt-js/discovery-sdk/dist/lib/Transport/LegacyTransport.mjs"); +/* harmony import */ var _WebsocketTransport_mjs__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./WebsocketTransport.mjs */ "./node_modules/@firebolt-js/discovery-sdk/dist/lib/Transport/WebsocketTransport.mjs"); +/* harmony import */ var _Results_index_mjs__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../Results/index.mjs */ "./node_modules/@firebolt-js/discovery-sdk/dist/lib/Results/index.mjs"); +/* + * Copyright 2021 Comcast Cable Communications Management, LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + */ + + + + + + + + +const LEGACY_TRANSPORT_SERVICE_NAME = 'com.comcast.BridgeObject_1' +let moduleInstance = null + +const isEventSuccess = (x) => + x && typeof x.event === 'string' && typeof x.listening === 'boolean' + +const win = typeof window !== 'undefined' ? window : {} + +class Transport { + constructor() { + this._promises = [] + this._transport = null + this._id = 1 + this._eventEmitters = [] + this._eventIds = [] + this._queue = new _queue_mjs__WEBPACK_IMPORTED_MODULE_1__["default"]() + this._deprecated = {} + this.isMock = false + } + + static addEventEmitter(emitter) { + Transport.get()._eventEmitters.push(emitter) + } + + static registerDeprecatedMethod(module, method, alternative) { + Transport.get()._deprecated[ + module.toLowerCase() + '.' + method.toLowerCase() + ] = { + alternative: alternative || '', + } + } + + _endpoint() { + if (win.__firebolt && win.__firebolt.endpoint) { + return win.__firebolt.endpoint + } + return null + } + + constructTransportLayer() { + let transport + const endpoint = this._endpoint() + if ( + endpoint && + (endpoint.startsWith('ws://') || endpoint.startsWith('wss://')) + ) { + transport = new _WebsocketTransport_mjs__WEBPACK_IMPORTED_MODULE_4__["default"](endpoint) + transport.receive(this.receiveHandler.bind(this)) + } else if ( + typeof win.ServiceManager !== 'undefined' && + win.ServiceManager && + win.ServiceManager.version + ) { + // Wire up the queue + transport = this._queue + // get the default bridge service, and flush the queue + win.ServiceManager.getServiceForJavaScript( + LEGACY_TRANSPORT_SERVICE_NAME, + (service) => { + if (_LegacyTransport_mjs__WEBPACK_IMPORTED_MODULE_3__["default"].isLegacy(service)) { + transport = new _LegacyTransport_mjs__WEBPACK_IMPORTED_MODULE_3__["default"](service) + } else { + transport = service + } + this.setTransportLayer(transport) + }, + ) + } else { + this.isMock = true + transport = _MockTransport_mjs__WEBPACK_IMPORTED_MODULE_0__["default"] + transport.receive(this.receiveHandler.bind(this)) + } + return transport + } + + setTransportLayer(tl) { + this._transport = tl + this._queue.flush(tl) + } + + static send(module, method, params, transforms) { + /** Transport singleton across all SDKs to keep single id map */ + return Transport.get()._send(module, method, params, transforms) + } + + static listen(module, method, params, transforms) { + return Transport.get()._sendAndGetId(module, method, params, transforms) + } + + _send(module, method, params, transforms) { + if (Array.isArray(module) && !method && !params) { + return this._batch(module) + } else { + return this._sendAndGetId(module, method, params, transforms).promise + } + } + + _sendAndGetId(module, method, params, transforms) { + const { promise, json, id } = this._processRequest( + module, + method, + params, + transforms, + ) + const msg = JSON.stringify(json) + if (_Settings_index_mjs__WEBPACK_IMPORTED_MODULE_2__["default"].getLogLevel() === 'DEBUG') { + console.debug('Sending message to transport: ' + msg) + } + this._transport.send(msg) + + return { id, promise } + } + + _batch(requests) { + const results = [] + const json = [] + + requests.forEach(({ module, method, params, transforms }) => { + const result = this._processRequest(module, method, params, transforms) + results.push({ + promise: result.promise, + id: result.id, + }) + json.push(result.json) + }) + + const msg = JSON.stringify(json) + if (_Settings_index_mjs__WEBPACK_IMPORTED_MODULE_2__["default"].getLogLevel() === 'DEBUG') { + console.debug('Sending message to transport: ' + msg) + } + this._transport.send(msg) + + return results + } + + _processRequest(module, method, params, transforms) { + const p = this._addPromiseToQueue(module, method, params, transforms) + const json = this._createRequestJSON(module, method, params) + + const result = { + promise: p, + json: json, + id: this._id, + } + + this._id++ + + return result + } + + _createRequestJSON(module, method, params) { + return { + jsonrpc: '2.0', + method: module.toLowerCase() + '.' + method, + params: params, + id: this._id, + } + } + + _addPromiseToQueue(module, method, params, transforms) { + return new Promise((resolve, reject) => { + this._promises[this._id] = {} + this._promises[this._id].promise = this + this._promises[this._id].resolve = resolve + this._promises[this._id].reject = reject + this._promises[this._id].transforms = transforms + + const deprecated = + this._deprecated[module.toLowerCase() + '.' + method.toLowerCase()] + if (deprecated) { + console.warn( + `WARNING: ${module}.${method}() is deprecated. ` + + deprecated.alternative, + ) + } + + // store the ID of the first listen for each event + // TODO: what about wild cards? + if (method.match(/^on[A-Z]/)) { + if (params.listen) { + this._eventIds.push(this._id) + } else { + this._eventIds = this._eventIds.filter((id) => id !== this._id) + } + } + }) + } + + /** + * If we have a global transport, use that. Otherwise, use the module-scoped transport instance. + * @returns {Transport} + */ + static get() { + /** Set up singleton and initialize it */ + win.__firebolt = win.__firebolt || {} + if (win.__firebolt.transport == null && moduleInstance == null) { + const transport = new Transport() + transport.init() + if (transport.isMock) { + /** We should use the mock transport built with the SDK, not a global */ + moduleInstance = transport + } else { + win.__firebolt = win.__firebolt || {} + win.__firebolt.transport = transport + } + win.__firebolt.setTransportLayer = + transport.setTransportLayer.bind(transport) + } + return win.__firebolt.transport ? win.__firebolt.transport : moduleInstance + } + + receiveHandler(message) { + if (_Settings_index_mjs__WEBPACK_IMPORTED_MODULE_2__["default"].getLogLevel() === 'DEBUG') { + console.debug('Received message from transport: ' + message) + } + const json = JSON.parse(message) + const p = this._promises[json.id] + + if (p) { + if (json.error) p.reject(json.error) + else { + // Do any module-specific transforms on the result + let result = json.result + + if (p.transforms) { + if (Array.isArray(json.result)) { + result = result.map((x) => _Results_index_mjs__WEBPACK_IMPORTED_MODULE_5__["default"].transform(x, p.transforms)) + } else { + result = _Results_index_mjs__WEBPACK_IMPORTED_MODULE_5__["default"].transform(result, p.transforms) + } + } + + p.resolve(result) + } + delete this._promises[json.id] + } + + // event responses need to be emitted, even after the listen call is resolved + if (this._eventIds.includes(json.id) && !isEventSuccess(json.result)) { + this._eventEmitters.forEach((emit) => { + emit(json.id, json.result) + }) + } + } + + init() { + Object(_Settings_index_mjs__WEBPACK_IMPORTED_MODULE_2__["initSettings"])({}, { log: true }) + this._queue.receive(this.receiveHandler.bind(this)) + if (win.__firebolt) { + if (win.__firebolt.mockTransportLayer === true) { + this.isMock = true + this.setTransportLayer(_MockTransport_mjs__WEBPACK_IMPORTED_MODULE_0__["default"]) + } else if (win.__firebolt.getTransportLayer) { + this.setTransportLayer(win.__firebolt.getTransportLayer()) + } + } + if (this._transport == null) { + this._transport = this.constructTransportLayer() + } + } +} +win.__firebolt = win.__firebolt || {} +win.__firebolt.setTransportLayer = (transport) => { + Transport.get().setTransportLayer(transport) +} + + +/***/ }), + +/***/ "./node_modules/@firebolt-js/discovery-sdk/dist/lib/Transport/queue.mjs": +/*!******************************************************************************!*\ + !*** ./node_modules/@firebolt-js/discovery-sdk/dist/lib/Transport/queue.mjs ***! + \******************************************************************************/ +/*! exports provided: default */ +/***/ (function(__webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return Queue; }); +/* + * Copyright 2021 Comcast Cable Communications Management, LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + */ + +class Queue { + constructor() { + this._callback = null + this._queue = [] + } + + send(json) { + this._queue.push(json) + } + + receive(_callback) { + this._callback = _callback + } + + flush(transport) { + transport.receive(this._callback) + this._queue.forEach((item) => transport.send(item)) + } +} + + +/***/ }), + +/***/ "./node_modules/@firebolt-js/discovery-sdk/dist/lib/firebolt-discovery.mjs": +/*!*********************************************************************************!*\ + !*** ./node_modules/@firebolt-js/discovery-sdk/dist/lib/firebolt-discovery.mjs ***! + \*********************************************************************************/ +/*! exports provided: Content, Log, Events, Settings */ +/***/ (function(__webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var _Transport_MockTransport_mjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./Transport/MockTransport.mjs */ "./node_modules/@firebolt-js/discovery-sdk/dist/lib/Transport/MockTransport.mjs"); +/* harmony import */ var _Content_defaults_mjs__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./Content/defaults.mjs */ "./node_modules/@firebolt-js/discovery-sdk/dist/lib/Content/defaults.mjs"); +/* harmony import */ var _Content_index_mjs__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./Content/index.mjs */ "./node_modules/@firebolt-js/discovery-sdk/dist/lib/Content/index.mjs"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Content", function() { return _Content_index_mjs__WEBPACK_IMPORTED_MODULE_2__["default"]; }); + +/* harmony import */ var _Log_index_mjs__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./Log/index.mjs */ "./node_modules/@firebolt-js/discovery-sdk/dist/lib/Log/index.mjs"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Log", function() { return _Log_index_mjs__WEBPACK_IMPORTED_MODULE_3__["default"]; }); + +/* harmony import */ var _Events_index_mjs__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./Events/index.mjs */ "./node_modules/@firebolt-js/discovery-sdk/dist/lib/Events/index.mjs"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Events", function() { return _Events_index_mjs__WEBPACK_IMPORTED_MODULE_4__["default"]; }); + +/* harmony import */ var _Settings_index_mjs__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./Settings/index.mjs */ "./node_modules/@firebolt-js/discovery-sdk/dist/lib/Settings/index.mjs"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Settings", function() { return _Settings_index_mjs__WEBPACK_IMPORTED_MODULE_5__["default"]; }); + +/* + * Copyright 2021 Comcast Cable Communications Management, LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + */ + + + + + +Object(_Transport_MockTransport_mjs__WEBPACK_IMPORTED_MODULE_0__["setMockResponses"])({ + Content: _Content_defaults_mjs__WEBPACK_IMPORTED_MODULE_1__["default"], +}) + + + + + + + +/***/ }), + +/***/ "./node_modules/@firebolt-js/manage-sdk/dist/firebolt-manage-open-rpc.json": +/*!*********************************************************************************!*\ + !*** ./node_modules/@firebolt-js/manage-sdk/dist/firebolt-manage-open-rpc.json ***! + \*********************************************************************************/ +/*! exports provided: openrpc, info, methods, components, x-schemas, default */ +/***/ (function(module) { + +module.exports = JSON.parse("{\"openrpc\":\"1.2.4\",\"info\":{\"title\":\"Firebolt Manage SDK\",\"version\":\"1.4.1\",\"x-module-descriptions\":{\"Account\":\"A module for querying about the device account.\",\"AcknowledgeChallenge\":\"A module for registering as a provider for a user grant in which the user confirms access to a capability\",\"Advertising\":\"A module for platform provided advertising settings and functionality.\",\"AudioDescriptions\":\"A module for managing audio-description Settings.\",\"ClosedCaptions\":\"A module for managing closed-captions Settings.\",\"Device\":\"A module for querying about the device and it's capabilities.\",\"Discovery\":\"Your App likely wants to integrate with the Platform's discovery capabilities. For example to add a \\\"Watch Next\\\" tile that links to your app from the platform's home screen.\\n\\nGetting access to this information requires to connect to lower level APIs made available by the platform. Since implementations differ between operators and platforms, the Firebolt SDK offers a Discovery module, that exposes a generic, agnostic interface to the developer.\\n\\nUnder the hood, an underlaying transport layer will then take care of calling the right APIs for the actual platform implementation that your App is running on.\\n\\nThe Discovery plugin is used to _send_ information to the Platform.\\n\\n### Localization\\nApps should provide all user-facing strings in the device's language, as specified by the Firebolt `Localization.language` property.\\n\\nApps should provide prices in the same currency presented in the app. If multiple currencies are supported in the app, the app should provide prices in the user's current default currency.\",\"HDMIInput\":\"Methods for managing HDMI inputs on an HDMI sink device.\",\"Keyboard\":\"Methods for prompting users to enter text with task-oriented UX\",\"Localization\":\"Methods for accessessing location and language preferences\",\"Metrics\":\"Methods for sending metrics\",\"PinChallenge\":\"A module for registering as a provider for a user grant in which the user is prompted for a pin for access to a capability\",\"Privacy\":\"A module for managing device settings.\",\"SecureStorage\":\"A module for storing and retrieving secure data owned by the app\",\"UserGrants\":\"A module for managing grants given by the user\",\"VoiceGuidance\":\"A module for managing voice-guidance Settings.\",\"Wifi\":\"A module for providing support for Wifi.\"},\"x-interface-names\":{\"xrn:firebolt:capability:lifecycle:state\":\"StateProvider\"}},\"methods\":[{\"name\":\"Localization.locality\",\"tags\":[{\"name\":\"capabilities\",\"x-uses\":[\"xrn:firebolt:capability:localization:locality\"]},{\"name\":\"property\"}],\"summary\":\"Get the locality/city the device is located in\",\"params\":[],\"result\":{\"name\":\"locality\",\"summary\":\"the device city\",\"schema\":{\"$ref\":\"#/x-schemas/Localization/Locality\"}},\"examples\":[{\"name\":\"Default example #1\",\"params\":[],\"result\":{\"name\":\"Default Result\",\"value\":\"Philadelphia\"}},{\"name\":\"Default example #2\",\"params\":[],\"result\":{\"name\":\"Default Result\",\"value\":\"Rockville\"}}]},{\"name\":\"Localization.postalCode\",\"tags\":[{\"name\":\"property\"},{\"name\":\"capabilities\",\"x-uses\":[\"xrn:firebolt:capability:localization:postal-code\"]}],\"summary\":\"Get the postal code the device is located in\",\"params\":[],\"result\":{\"name\":\"postalCode\",\"summary\":\"the device postal code\",\"schema\":{\"type\":\"string\"}},\"examples\":[{\"name\":\"Default example #1\",\"params\":[],\"result\":{\"name\":\"Default Result\",\"value\":\"19103\"}},{\"name\":\"Default example #2\",\"params\":[],\"result\":{\"name\":\"Default Result\",\"value\":\"20850\"}}]},{\"name\":\"Localization.countryCode\",\"tags\":[{\"name\":\"property\"},{\"name\":\"capabilities\",\"x-uses\":[\"xrn:firebolt:capability:localization:country-code\"]}],\"summary\":\"Get the ISO 3166-1 alpha-2 code for the country device is located in\",\"params\":[],\"result\":{\"name\":\"code\",\"summary\":\"the device country code\",\"schema\":{\"$ref\":\"#/x-schemas/Localization/CountryCode\"}},\"examples\":[{\"name\":\"Default example #1\",\"params\":[],\"result\":{\"name\":\"Default Result\",\"value\":\"US\"}},{\"name\":\"Default example #2\",\"params\":[],\"result\":{\"name\":\"Default Result\",\"value\":\"UK\"}}]},{\"name\":\"Localization.language\",\"summary\":\"Get the ISO 639 1/2 code for the preferred language\",\"params\":[],\"tags\":[{\"name\":\"deprecated\",\"x-since\":\"0.17.0\",\"x-alternative\":\"Localization.locale\"},{\"name\":\"property\"},{\"name\":\"capabilities\",\"x-uses\":[\"xrn:firebolt:capability:localization:language\"]}],\"result\":{\"name\":\"lang\",\"summary\":\"the device language\",\"schema\":{\"$ref\":\"#/x-schemas/Localization/Language\"}},\"examples\":[{\"name\":\"Default example #1\",\"params\":[],\"result\":{\"name\":\"Default Result\",\"value\":\"en\"}},{\"name\":\"Default example #2\",\"params\":[],\"result\":{\"name\":\"Default Result\",\"value\":\"es\"}}]},{\"name\":\"Localization.preferredAudioLanguages\",\"summary\":\"A prioritized list of ISO 639 1/2 codes for the preferred audio languages on this device.\",\"params\":[],\"tags\":[{\"name\":\"property\"},{\"name\":\"capabilities\",\"x-uses\":[\"xrn:firebolt:capability:localization:language\"]}],\"result\":{\"name\":\"languages\",\"summary\":\"the preferred audio languages\",\"schema\":{\"type\":\"array\",\"items\":{\"$ref\":\"#/x-schemas/Localization/ISO639_2Language\"}}},\"examples\":[{\"name\":\"Default Example\",\"params\":[],\"result\":{\"name\":\"Default Result\",\"value\":[\"spa\",\"eng\"]}},{\"name\":\"Default Example #2\",\"params\":[],\"result\":{\"name\":\"Default Result\",\"value\":[\"eng\",\"spa\"]}}]},{\"name\":\"Localization.locale\",\"tags\":[{\"name\":\"property\"},{\"name\":\"capabilities\",\"x-uses\":[\"xrn:firebolt:capability:localization:locale\"]}],\"summary\":\"Get the *full* BCP 47 code, including script, region, variant, etc., for the preferred langauage/locale\",\"params\":[],\"result\":{\"name\":\"locale\",\"summary\":\"the device locale\",\"schema\":{\"$ref\":\"#/x-schemas/Localization/Locale\"}},\"examples\":[{\"name\":\"Default example #1\",\"params\":[],\"result\":{\"name\":\"Default Result\",\"value\":\"en-US\"}},{\"name\":\"Default example #2\",\"params\":[],\"result\":{\"name\":\"Default Result\",\"value\":\"es-US\"}}]},{\"name\":\"Localization.additionalInfo\",\"tags\":[{\"name\":\"capabilities\",\"x-uses\":[\"xrn:firebolt:capability:localization:additional-info\"]}],\"summary\":\"Get any platform-specific localization information\",\"params\":[],\"result\":{\"name\":\"info\",\"summary\":\"the additional info\",\"schema\":{\"type\":\"object\",\"additionalProperties\":{\"type\":[\"number\",\"string\",\"boolean\"],\"maxLength\":1024},\"maxProperties\":32}},\"examples\":[{\"name\":\"Default Example\",\"params\":[],\"result\":{\"name\":\"info\",\"value\":{}}}]},{\"name\":\"Localization.addAdditionalInfo\",\"tags\":[{\"name\":\"capabilities\",\"x-manages\":[\"xrn:firebolt:capability:localization:additional-info\"]}],\"summary\":\"Add any platform-specific localization information in key/value pair\",\"params\":[{\"name\":\"key\",\"summary\":\"Key to add additionalInfo\",\"schema\":{\"type\":\"string\"},\"required\":true},{\"name\":\"value\",\"summary\":\"Value to be set for additionalInfo. Value can be a number, string or boolean\",\"schema\":{\"type\":[\"number\",\"string\",\"boolean\"]},\"required\":true}],\"result\":{\"name\":\"result\",\"schema\":{\"const\":null}},\"examples\":[{\"name\":\"Add an additionalInfo for localization\",\"params\":[{\"name\":\"key\",\"value\":\"defaultKey\"},{\"name\":\"value\",\"value\":\"defaultValue=\"}],\"result\":{\"name\":\"defaultResult\",\"value\":null}}]},{\"name\":\"Localization.removeAdditionalInfo\",\"tags\":[{\"name\":\"capabilities\",\"x-manages\":[\"xrn:firebolt:capability:localization:additional-info\"]}],\"summary\":\"Remove any platform-specific localization information from map\",\"params\":[{\"name\":\"key\",\"summary\":\"Key to remove additionalInfo\",\"schema\":{\"type\":\"string\"},\"required\":true}],\"result\":{\"name\":\"result\",\"schema\":{\"const\":null}},\"examples\":[{\"name\":\"Remove an additionalInfo for localization\",\"params\":[{\"name\":\"key\",\"value\":\"defaultKey\"}],\"result\":{\"name\":\"defaultResult\",\"value\":null}}]},{\"name\":\"Localization.timeZone\",\"tags\":[{\"name\":\"property\"},{\"name\":\"capabilities\",\"x-uses\":[\"xrn:firebolt:capability:localization:time-zone\"]}],\"summary\":\"Set the IANA timezone for the device\",\"params\":[],\"result\":{\"name\":\"result\",\"schema\":{\"$ref\":\"#/x-schemas/Localization/TimeZone\"}},\"examples\":[{\"name\":\"Default Example\",\"params\":[],\"result\":{\"name\":\"Default Result\",\"value\":\"America/New_York\"}},{\"name\":\"Additional Example\",\"params\":[],\"result\":{\"name\":\"Default Result\",\"value\":\"America/Los_Angeles\"}}]},{\"name\":\"Localization.onLocalityChanged\",\"tags\":[{\"name\":\"subscriber\",\"x-subscriber-for\":\"Localization.locality\"},{\"name\":\"event\",\"x-alternative\":\"locality\"},{\"name\":\"capabilities\",\"x-uses\":[\"xrn:firebolt:capability:localization:locality\"]}],\"summary\":\"Get the locality/city the device is located in\",\"params\":[{\"name\":\"listen\",\"required\":true,\"schema\":{\"type\":\"boolean\"}}],\"result\":{\"name\":\"locality\",\"summary\":\"the device city\",\"schema\":{\"anyOf\":[{\"$ref\":\"#/x-schemas/Types/ListenResponse\"},{\"$ref\":\"#/x-schemas/Localization/Locality\"}]}},\"examples\":[{\"name\":\"Default example #1\",\"params\":[{\"name\":\"listen\",\"value\":true}],\"result\":{\"name\":\"Default Result\",\"value\":\"Philadelphia\"}},{\"name\":\"Default example #2\",\"params\":[{\"name\":\"listen\",\"value\":true}],\"result\":{\"name\":\"Default Result\",\"value\":\"Rockville\"}}]},{\"name\":\"Localization.onPostalCodeChanged\",\"tags\":[{\"name\":\"subscriber\",\"x-subscriber-for\":\"Localization.postalCode\"},{\"name\":\"event\",\"x-alternative\":\"postalCode\"},{\"name\":\"capabilities\",\"x-uses\":[\"xrn:firebolt:capability:localization:postal-code\"]}],\"summary\":\"Get the postal code the device is located in\",\"params\":[{\"name\":\"listen\",\"required\":true,\"schema\":{\"type\":\"boolean\"}}],\"result\":{\"name\":\"postalCode\",\"summary\":\"the device postal code\",\"schema\":{\"anyOf\":[{\"$ref\":\"#/x-schemas/Types/ListenResponse\"},{\"type\":\"string\"}]}},\"examples\":[{\"name\":\"Default example #1\",\"params\":[{\"name\":\"listen\",\"value\":true}],\"result\":{\"name\":\"Default Result\",\"value\":\"19103\"}},{\"name\":\"Default example #2\",\"params\":[{\"name\":\"listen\",\"value\":true}],\"result\":{\"name\":\"Default Result\",\"value\":\"20850\"}}]},{\"name\":\"Localization.onCountryCodeChanged\",\"tags\":[{\"name\":\"subscriber\",\"x-subscriber-for\":\"Localization.countryCode\"},{\"name\":\"event\",\"x-alternative\":\"countryCode\"},{\"name\":\"capabilities\",\"x-uses\":[\"xrn:firebolt:capability:localization:country-code\"]}],\"summary\":\"Get the ISO 3166-1 alpha-2 code for the country device is located in\",\"params\":[{\"name\":\"listen\",\"required\":true,\"schema\":{\"type\":\"boolean\"}}],\"result\":{\"name\":\"code\",\"summary\":\"the device country code\",\"schema\":{\"anyOf\":[{\"$ref\":\"#/x-schemas/Types/ListenResponse\"},{\"$ref\":\"#/x-schemas/Localization/CountryCode\"}]}},\"examples\":[{\"name\":\"Default example #1\",\"params\":[{\"name\":\"listen\",\"value\":true}],\"result\":{\"name\":\"Default Result\",\"value\":\"US\"}},{\"name\":\"Default example #2\",\"params\":[{\"name\":\"listen\",\"value\":true}],\"result\":{\"name\":\"Default Result\",\"value\":\"UK\"}}]},{\"name\":\"Localization.onLanguageChanged\",\"summary\":\"Get the ISO 639 1/2 code for the preferred language\",\"params\":[{\"name\":\"listen\",\"required\":true,\"schema\":{\"type\":\"boolean\"}}],\"tags\":[{\"name\":\"subscriber\",\"x-subscriber-for\":\"Localization.language\"},{\"name\":\"event\",\"x-alternative\":\"language\"},{\"name\":\"deprecated\",\"x-since\":\"0.17.0\",\"x-alternative\":\"Localization.locale\"},{\"name\":\"capabilities\",\"x-uses\":[\"xrn:firebolt:capability:localization:language\"]}],\"result\":{\"name\":\"lang\",\"summary\":\"the device language\",\"schema\":{\"anyOf\":[{\"$ref\":\"#/x-schemas/Types/ListenResponse\"},{\"$ref\":\"#/x-schemas/Localization/Language\"}]}},\"examples\":[{\"name\":\"Default example #1\",\"params\":[{\"name\":\"listen\",\"value\":true}],\"result\":{\"name\":\"Default Result\",\"value\":\"en\"}},{\"name\":\"Default example #2\",\"params\":[{\"name\":\"listen\",\"value\":true}],\"result\":{\"name\":\"Default Result\",\"value\":\"es\"}}]},{\"name\":\"Localization.onPreferredAudioLanguagesChanged\",\"summary\":\"A prioritized list of ISO 639 1/2 codes for the preferred audio languages on this device.\",\"params\":[{\"name\":\"listen\",\"required\":true,\"schema\":{\"type\":\"boolean\"}}],\"tags\":[{\"name\":\"subscriber\",\"x-subscriber-for\":\"Localization.preferredAudioLanguages\"},{\"name\":\"event\",\"x-alternative\":\"preferredAudioLanguages\"},{\"name\":\"capabilities\",\"x-uses\":[\"xrn:firebolt:capability:localization:language\"]}],\"result\":{\"name\":\"languages\",\"summary\":\"the preferred audio languages\",\"schema\":{\"anyOf\":[{\"$ref\":\"#/x-schemas/Types/ListenResponse\"},{\"type\":\"array\",\"items\":{\"$ref\":\"#/x-schemas/Localization/ISO639_2Language\"}}]}},\"examples\":[{\"name\":\"Default Example\",\"params\":[{\"name\":\"listen\",\"value\":true}],\"result\":{\"name\":\"Default Result\",\"value\":[\"spa\",\"eng\"]}},{\"name\":\"Default Example #2\",\"params\":[{\"name\":\"listen\",\"value\":true}],\"result\":{\"name\":\"Default Result\",\"value\":[\"eng\",\"spa\"]}}]},{\"name\":\"Localization.onLocaleChanged\",\"tags\":[{\"name\":\"subscriber\",\"x-subscriber-for\":\"Localization.locale\"},{\"name\":\"event\",\"x-alternative\":\"locale\"},{\"name\":\"capabilities\",\"x-uses\":[\"xrn:firebolt:capability:localization:locale\"]}],\"summary\":\"Get the *full* BCP 47 code, including script, region, variant, etc., for the preferred langauage/locale\",\"params\":[{\"name\":\"listen\",\"required\":true,\"schema\":{\"type\":\"boolean\"}}],\"result\":{\"name\":\"locale\",\"summary\":\"the device locale\",\"schema\":{\"anyOf\":[{\"$ref\":\"#/x-schemas/Types/ListenResponse\"},{\"$ref\":\"#/x-schemas/Localization/Locale\"}]}},\"examples\":[{\"name\":\"Default example #1\",\"params\":[{\"name\":\"listen\",\"value\":true}],\"result\":{\"name\":\"Default Result\",\"value\":\"en-US\"}},{\"name\":\"Default example #2\",\"params\":[{\"name\":\"listen\",\"value\":true}],\"result\":{\"name\":\"Default Result\",\"value\":\"es-US\"}}]},{\"name\":\"Localization.onTimeZoneChanged\",\"tags\":[{\"name\":\"subscriber\",\"x-subscriber-for\":\"Localization.timeZone\"},{\"name\":\"event\",\"x-alternative\":\"timeZone\"},{\"name\":\"capabilities\",\"x-uses\":[\"xrn:firebolt:capability:localization:time-zone\"]}],\"summary\":\"Set the IANA timezone for the device\",\"params\":[{\"name\":\"listen\",\"required\":true,\"schema\":{\"type\":\"boolean\"}}],\"result\":{\"name\":\"result\",\"schema\":{\"anyOf\":[{\"$ref\":\"#/x-schemas/Types/ListenResponse\"},{\"$ref\":\"#/x-schemas/Localization/TimeZone\"}]}},\"examples\":[{\"name\":\"Default Example\",\"params\":[{\"name\":\"listen\",\"value\":true}],\"result\":{\"name\":\"Default Result\",\"value\":\"America/New_York\"}},{\"name\":\"Additional Example\",\"params\":[{\"name\":\"listen\",\"value\":true}],\"result\":{\"name\":\"Default Result\",\"value\":\"America/Los_Angeles\"}}]},{\"name\":\"Localization.setLocality\",\"tags\":[{\"name\":\"setter\",\"x-setter-for\":\"locality\"},{\"name\":\"capabilities\",\"x-manages\":[\"xrn:firebolt:capability:localization:locality\"]}],\"summary\":\"Get the locality/city the device is located in\",\"params\":[{\"name\":\"value\",\"summary\":\"the device city\",\"schema\":{\"$ref\":\"#/x-schemas/Localization/Locality\"},\"required\":true}],\"result\":{\"name\":\"result\",\"schema\":{\"type\":\"null\"}},\"examples\":[{\"name\":\"Default example #1\",\"params\":[{\"name\":\"value\",\"value\":\"Philadelphia\"}],\"result\":{\"name\":\"Default Result\",\"value\":null}},{\"name\":\"Default example #2\",\"params\":[{\"name\":\"value\",\"value\":\"Rockville\"}],\"result\":{\"name\":\"Default Result\",\"value\":null}}]},{\"name\":\"Localization.setPostalCode\",\"tags\":[{\"name\":\"setter\",\"x-setter-for\":\"postalCode\"},{\"name\":\"capabilities\",\"x-manages\":[\"xrn:firebolt:capability:localization:postal-code\"]}],\"summary\":\"Get the postal code the device is located in\",\"params\":[{\"name\":\"value\",\"summary\":\"the device postal code\",\"schema\":{\"type\":\"string\"},\"required\":true}],\"result\":{\"name\":\"result\",\"schema\":{\"type\":\"null\"}},\"examples\":[{\"name\":\"Default example #1\",\"params\":[{\"name\":\"value\",\"value\":\"19103\"}],\"result\":{\"name\":\"Default Result\",\"value\":null}},{\"name\":\"Default example #2\",\"params\":[{\"name\":\"value\",\"value\":\"20850\"}],\"result\":{\"name\":\"Default Result\",\"value\":null}}]},{\"name\":\"Localization.setCountryCode\",\"tags\":[{\"name\":\"setter\",\"x-setter-for\":\"countryCode\"},{\"name\":\"capabilities\",\"x-manages\":[\"xrn:firebolt:capability:localization:country-code\"]}],\"summary\":\"Get the ISO 3166-1 alpha-2 code for the country device is located in\",\"params\":[{\"name\":\"value\",\"summary\":\"the device country code\",\"schema\":{\"$ref\":\"#/x-schemas/Localization/CountryCode\"},\"required\":true}],\"result\":{\"name\":\"result\",\"schema\":{\"type\":\"null\"}},\"examples\":[{\"name\":\"Default example #1\",\"params\":[{\"name\":\"value\",\"value\":\"US\"}],\"result\":{\"name\":\"Default Result\",\"value\":null}},{\"name\":\"Default example #2\",\"params\":[{\"name\":\"value\",\"value\":\"UK\"}],\"result\":{\"name\":\"Default Result\",\"value\":null}}]},{\"name\":\"Localization.setLanguage\",\"summary\":\"Get the ISO 639 1/2 code for the preferred language\",\"params\":[{\"name\":\"value\",\"summary\":\"the device language\",\"schema\":{\"$ref\":\"#/x-schemas/Localization/Language\"},\"required\":true}],\"tags\":[{\"name\":\"setter\",\"x-setter-for\":\"language\"},{\"name\":\"deprecated\",\"x-since\":\"0.17.0\",\"x-alternative\":\"Localization.locale\"},{\"name\":\"capabilities\",\"x-manages\":[\"xrn:firebolt:capability:localization:language\"]}],\"result\":{\"name\":\"result\",\"schema\":{\"type\":\"null\"}},\"examples\":[{\"name\":\"Default example #1\",\"params\":[{\"name\":\"value\",\"value\":\"en\"}],\"result\":{\"name\":\"Default Result\",\"value\":null}},{\"name\":\"Default example #2\",\"params\":[{\"name\":\"value\",\"value\":\"es\"}],\"result\":{\"name\":\"Default Result\",\"value\":null}}]},{\"name\":\"Localization.setPreferredAudioLanguages\",\"summary\":\"A prioritized list of ISO 639 1/2 codes for the preferred audio languages on this device.\",\"params\":[{\"name\":\"value\",\"summary\":\"the preferred audio languages\",\"schema\":{\"type\":\"array\",\"items\":{\"$ref\":\"#/x-schemas/Localization/ISO639_2Language\"}},\"required\":true}],\"tags\":[{\"name\":\"setter\",\"x-setter-for\":\"preferredAudioLanguages\"},{\"name\":\"capabilities\",\"x-manages\":[\"xrn:firebolt:capability:localization:language\"]}],\"result\":{\"name\":\"result\",\"schema\":{\"type\":\"null\"}},\"examples\":[{\"name\":\"Default Example\",\"params\":[{\"name\":\"value\",\"value\":[\"spa\",\"eng\"]}],\"result\":{\"name\":\"Default Result\",\"value\":null}},{\"name\":\"Default Example #2\",\"params\":[{\"name\":\"value\",\"value\":[\"eng\",\"spa\"]}],\"result\":{\"name\":\"Default Result\",\"value\":null}}]},{\"name\":\"Localization.setLocale\",\"tags\":[{\"name\":\"setter\",\"x-setter-for\":\"locale\"},{\"name\":\"capabilities\",\"x-manages\":[\"xrn:firebolt:capability:localization:locale\"]}],\"summary\":\"Get the *full* BCP 47 code, including script, region, variant, etc., for the preferred langauage/locale\",\"params\":[{\"name\":\"value\",\"summary\":\"the device locale\",\"schema\":{\"$ref\":\"#/x-schemas/Localization/Locale\"},\"required\":true}],\"result\":{\"name\":\"result\",\"schema\":{\"type\":\"null\"}},\"examples\":[{\"name\":\"Default example #1\",\"params\":[{\"name\":\"value\",\"value\":\"en-US\"}],\"result\":{\"name\":\"Default Result\",\"value\":null}},{\"name\":\"Default example #2\",\"params\":[{\"name\":\"value\",\"value\":\"es-US\"}],\"result\":{\"name\":\"Default Result\",\"value\":null}}]},{\"name\":\"Localization.setTimeZone\",\"tags\":[{\"name\":\"setter\",\"x-setter-for\":\"timeZone\"},{\"name\":\"capabilities\",\"x-manages\":[\"xrn:firebolt:capability:localization:time-zone\"]}],\"summary\":\"Set the IANA timezone for the device\",\"params\":[{\"name\":\"value\",\"schema\":{\"$ref\":\"#/x-schemas/Localization/TimeZone\"},\"required\":true}],\"result\":{\"name\":\"result\",\"schema\":{\"type\":\"null\"}},\"examples\":[{\"name\":\"Default Example\",\"params\":[{\"name\":\"value\",\"value\":\"America/New_York\"}],\"result\":{\"name\":\"Default Result\",\"value\":null}},{\"name\":\"Additional Example\",\"params\":[{\"name\":\"value\",\"value\":\"America/Los_Angeles\"}],\"result\":{\"name\":\"Default Result\",\"value\":null}}]},{\"name\":\"Metrics.event\",\"tags\":[{\"name\":\"capabilities\",\"x-uses\":[\"xrn:firebolt:capability:metrics:distributor\"]}],\"summary\":\"Inform the platform of 1st party distributor metrics.\",\"params\":[{\"name\":\"schema\",\"summary\":\"The schema URI of the metric type\",\"schema\":{\"type\":\"string\",\"format\":\"uri\"},\"required\":true},{\"name\":\"data\",\"summary\":\"A JSON payload conforming the the provided schema\",\"schema\":{\"$ref\":\"#/components/schemas/EventObject\"},\"required\":true}],\"result\":{\"name\":\"results\",\"schema\":{\"type\":\"null\"}},\"examples\":[{\"name\":\"Send foo event\",\"params\":[{\"name\":\"schema\",\"value\":\"http://meta.rdkcentral.com/some/schema\"},{\"name\":\"data\",\"value\":{\"foo\":\"foo\"}}],\"result\":{\"name\":\"result\",\"value\":null}}]},{\"name\":\"Wifi.scan\",\"summary\":\"Scan available wifi networks in the location.\",\"tags\":[{\"name\":\"capabilities\",\"x-uses\":[\"xrn:firebolt:capability:protocol:wifi\"]}],\"params\":[{\"name\":\"timeout\",\"schema\":{\"$ref\":\"#/x-schemas/Types/Timeout\"}}],\"result\":{\"name\":\"list\",\"summary\":\"Contains a list of wifi networks available near the device.\",\"schema\":{\"$ref\":\"#/components/schemas/AccessPointList\"}},\"examples\":[{\"name\":\"Successful Wifi List\",\"params\":[{\"name\":\"timeout\",\"value\":30}],\"result\":{\"name\":\"successfulWifiResultExample\",\"value\":{\"list\":[{\"ssid\":\"DND\",\"security\":\"wpa2Psk\",\"signalStrength\":-70,\"frequency\":2.4},{\"ssid\":\"Fortnite\",\"security\":\"WPA2_ENTERPRISE_AES\",\"signalStrength\":-70,\"frequency\":5},{\"ssid\":\"Guardian\",\"security\":\"none\",\"signalStrength\":-70,\"frequency\":2.4}]}}}]},{\"name\":\"Wifi.connect\",\"summary\":\"Connect the device to the specified SSID.\",\"tags\":[{\"name\":\"capabilities\",\"x-uses\":[\"xrn:firebolt:capability:protocol:wifi\"]}],\"params\":[{\"name\":\"ssid\",\"schema\":{\"type\":\"string\"},\"description\":\"Name of Wifi SSID to connect for the device.\"},{\"name\":\"passphrase\",\"schema\":{\"type\":\"string\"},\"description\":\"Password or Passphrase for the wifi.\"},{\"name\":\"security\",\"schema\":{\"$ref\":\"#/components/schemas/WifiSecurityMode\"}}],\"result\":{\"name\":\"connectedWifi\",\"summary\":\"Successful Response after connecting to the Wifi.\",\"schema\":{\"$ref\":\"#/components/schemas/AccessPoint\"}},\"examples\":[{\"name\":\"Connect to a wpa2Psk Wifi with password\",\"params\":[{\"name\":\"ssid\",\"value\":\"DND\"},{\"name\":\"passphrase\",\"value\":\"gargoyle\"},{\"name\":\"security\",\"value\":\"wpa2Psk\"}],\"result\":{\"name\":\"successfulWifiConnection\",\"value\":{\"ssid\":\"DND\",\"security\":\"wpa2Psk\",\"signalStrength\":-70,\"frequency\":2.4}}},{\"name\":\"Connect to a WPA2 PSK Wifi with password\",\"params\":[{\"name\":\"ssid\",\"value\":\"Guardian WIFI\"},{\"name\":\"passphrase\",\"value\":\"\"},{\"name\":\"security\",\"value\":\"none\"}],\"result\":{\"name\":\"successfulWifiConnection\",\"value\":{\"ssid\":\"Guardian WIFI\",\"security\":\"none\",\"signalStrength\":-70,\"frequency\":2.4}}}]},{\"name\":\"Wifi.disconnect\",\"summary\":\"Disconnect the device if connected via WIFI.\",\"tags\":[{\"name\":\"capabilities\",\"x-uses\":[\"xrn:firebolt:capability:protocol:wifi\"]}],\"params\":[],\"result\":{\"name\":\"result\",\"schema\":{\"const\":null}},\"examples\":[{\"name\":\"Disconnect\",\"params\":[],\"result\":{\"name\":\"defaultResult\",\"value\":null}}]},{\"name\":\"Wifi.wps\",\"summary\":\"Connect to WPS\",\"tags\":[{\"name\":\"capabilities\",\"x-uses\":[\"xrn:firebolt:capability:protocol:wifi\"]}],\"params\":[{\"name\":\"security\",\"schema\":{\"$ref\":\"#/components/schemas/WPSSecurityPin\"}}],\"result\":{\"name\":\"connectedWifi\",\"summary\":\"Successful Response after connecting to the Wifi.\",\"schema\":{\"$ref\":\"#/components/schemas/AccessPoint\"}},\"examples\":[{\"name\":\"Connect to a WPS Wifi router\",\"params\":[{\"name\":\"security\",\"value\":\"pushButton\"}],\"result\":{\"name\":\"successfulWifiConnection\",\"value\":{\"ssid\":\"DND\",\"security\":\"wpa2Psk\",\"signalStrength\":-70,\"frequency\":2.4}}}]},{\"name\":\"ClosedCaptions.enabled\",\"tags\":[{\"name\":\"property\"},{\"name\":\"capabilities\",\"x-uses\":[\"xrn:firebolt:capability:accessibility:closedcaptions\"]}],\"summary\":\"Whether or not closed-captions are enabled.\",\"params\":[],\"result\":{\"name\":\"enabled\",\"schema\":{\"type\":\"boolean\"}},\"examples\":[{\"name\":\"Default example #1\",\"params\":[],\"result\":{\"name\":\"enabled\",\"value\":true}},{\"name\":\"Default example #2\",\"params\":[],\"result\":{\"name\":\"enabled\",\"value\":false}}]},{\"name\":\"ClosedCaptions.fontFamily\",\"tags\":[{\"name\":\"property\"},{\"name\":\"capabilities\",\"x-uses\":[\"xrn:firebolt:capability:accessibility:closedcaptions\"]}],\"summary\":\"The preferred font family for displaying closed-captions.\",\"params\":[],\"result\":{\"name\":\"family\",\"schema\":{\"$ref\":\"#/x-schemas/Accessibility/FontFamily\"}},\"examples\":[{\"name\":\"Default example #1\",\"params\":[],\"result\":{\"name\":\"family\",\"value\":\"monospaced_sanserif\"}},{\"name\":\"Default example #2\",\"params\":[],\"result\":{\"name\":\"family\",\"value\":\"cursive\"}},{\"name\":\"Default example #3\",\"params\":[],\"result\":{\"name\":\"family\",\"value\":null}}]},{\"name\":\"ClosedCaptions.fontSize\",\"tags\":[{\"name\":\"property\"},{\"name\":\"capabilities\",\"x-uses\":[\"xrn:firebolt:capability:accessibility:closedcaptions\"]}],\"summary\":\"The preferred font size for displaying closed-captions.\",\"params\":[],\"result\":{\"name\":\"size\",\"schema\":{\"$ref\":\"#/x-schemas/Accessibility/FontSize\"}},\"examples\":[{\"name\":\"Default example #1\",\"params\":[],\"result\":{\"name\":\"size\",\"value\":1}},{\"name\":\"Default example #2\",\"params\":[],\"result\":{\"name\":\"size\",\"value\":1}},{\"name\":\"Default example #3\",\"params\":[],\"result\":{\"name\":\"size\",\"value\":null}}]},{\"name\":\"ClosedCaptions.fontColor\",\"tags\":[{\"name\":\"property\"},{\"name\":\"capabilities\",\"x-uses\":[\"xrn:firebolt:capability:accessibility:closedcaptions\"]}],\"summary\":\"The preferred font color for displaying closed-captions.\",\"params\":[],\"result\":{\"name\":\"color\",\"schema\":{\"$ref\":\"#/x-schemas/Accessibility/Color\"}},\"examples\":[{\"name\":\"Default example #1\",\"params\":[],\"result\":{\"name\":\"color\",\"value\":\"#ffffff\"}},{\"name\":\"Default example #2\",\"params\":[],\"result\":{\"name\":\"color\",\"value\":\"#000000\"}},{\"name\":\"Default example #3\",\"params\":[],\"result\":{\"name\":\"color\",\"value\":null}}]},{\"name\":\"ClosedCaptions.fontEdge\",\"tags\":[{\"name\":\"property\"},{\"name\":\"capabilities\",\"x-uses\":[\"xrn:firebolt:capability:accessibility:closedcaptions\"]}],\"summary\":\"The preferred font edge style for displaying closed-captions.\",\"params\":[],\"result\":{\"name\":\"edge\",\"schema\":{\"$ref\":\"#/x-schemas/Accessibility/FontEdge\"}},\"examples\":[{\"name\":\"Default example #1\",\"params\":[],\"result\":{\"name\":\"edge\",\"value\":\"none\"}},{\"name\":\"Default example #2\",\"params\":[],\"result\":{\"name\":\"edge\",\"value\":\"uniform\"}},{\"name\":\"Default example #3\",\"params\":[],\"result\":{\"name\":\"edge\",\"value\":null}}]},{\"name\":\"ClosedCaptions.fontEdgeColor\",\"tags\":[{\"name\":\"property\"},{\"name\":\"capabilities\",\"x-uses\":[\"xrn:firebolt:capability:accessibility:closedcaptions\"]}],\"summary\":\"The preferred font edge color for displaying closed-captions.\",\"params\":[],\"result\":{\"name\":\"color\",\"schema\":{\"$ref\":\"#/x-schemas/Accessibility/Color\"}},\"examples\":[{\"name\":\"Default example #1\",\"params\":[],\"result\":{\"name\":\"color\",\"value\":\"#000000\"}},{\"name\":\"Default example #2\",\"params\":[],\"result\":{\"name\":\"color\",\"value\":\"#ffffff\"}},{\"name\":\"Default example #3\",\"params\":[],\"result\":{\"name\":\"color\",\"value\":null}}]},{\"name\":\"ClosedCaptions.fontOpacity\",\"tags\":[{\"name\":\"property\"},{\"name\":\"capabilities\",\"x-uses\":[\"xrn:firebolt:capability:accessibility:closedcaptions\"]}],\"summary\":\"The preferred opacity for displaying closed-captions characters.\",\"params\":[],\"result\":{\"name\":\"opacity\",\"schema\":{\"$ref\":\"#/x-schemas/Accessibility/Opacity\"}},\"examples\":[{\"name\":\"Default example #1\",\"params\":[],\"result\":{\"name\":\"opacity\",\"value\":99}},{\"name\":\"Default example #2\",\"params\":[],\"result\":{\"name\":\"opacity\",\"value\":100}},{\"name\":\"Default example #3\",\"params\":[],\"result\":{\"name\":\"opacity\",\"value\":null}}]},{\"name\":\"ClosedCaptions.backgroundColor\",\"tags\":[{\"name\":\"property\"},{\"name\":\"capabilities\",\"x-uses\":[\"xrn:firebolt:capability:accessibility:closedcaptions\"]}],\"summary\":\"The preferred background color for displaying closed-captions, .\",\"params\":[],\"result\":{\"name\":\"color\",\"schema\":{\"$ref\":\"#/x-schemas/Accessibility/Color\"}},\"examples\":[{\"name\":\"Default example #1\",\"params\":[],\"result\":{\"name\":\"color\",\"value\":\"#000000\"}},{\"name\":\"Default example #2\",\"params\":[],\"result\":{\"name\":\"color\",\"value\":\"#ffffff\"}},{\"name\":\"Default example #3\",\"params\":[],\"result\":{\"name\":\"color\",\"value\":null}}]},{\"name\":\"ClosedCaptions.backgroundOpacity\",\"tags\":[{\"name\":\"property\"},{\"name\":\"capabilities\",\"x-uses\":[\"xrn:firebolt:capability:accessibility:closedcaptions\"]}],\"summary\":\"The preferred opacity for displaying closed-captions backgrounds.\",\"params\":[],\"result\":{\"name\":\"opacity\",\"schema\":{\"$ref\":\"#/x-schemas/Accessibility/Opacity\"}},\"examples\":[{\"name\":\"Default example #1\",\"params\":[],\"result\":{\"name\":\"opacity\",\"value\":99}},{\"name\":\"Default example #2\",\"params\":[],\"result\":{\"name\":\"opacity\",\"value\":100}},{\"name\":\"Default example #3\",\"params\":[],\"result\":{\"name\":\"opacity\",\"value\":null}}]},{\"name\":\"ClosedCaptions.textAlign\",\"tags\":[{\"name\":\"property\"},{\"name\":\"capabilities\",\"x-uses\":[\"xrn:firebolt:capability:accessibility:closedcaptions\"]}],\"summary\":\"The preferred horizontal alignment for displaying closed-captions characters.\",\"params\":[],\"result\":{\"name\":\"alignment\",\"schema\":{\"$ref\":\"#/x-schemas/Accessibility/HorizontalAlignment\"}},\"examples\":[{\"name\":\"Default example #1\",\"params\":[],\"result\":{\"name\":\"alignment\",\"value\":\"center\"}},{\"name\":\"Default example #2\",\"params\":[],\"result\":{\"name\":\"alignment\",\"value\":\"left\"}},{\"name\":\"Default example #3\",\"params\":[],\"result\":{\"name\":\"alignment\",\"value\":null}}]},{\"name\":\"ClosedCaptions.textAlignVertical\",\"tags\":[{\"name\":\"property\"},{\"name\":\"capabilities\",\"x-uses\":[\"xrn:firebolt:capability:accessibility:closedcaptions\"]}],\"summary\":\"The preferred horizontal alignment for displaying closed-captions characters.\",\"params\":[],\"result\":{\"name\":\"alignment\",\"schema\":{\"$ref\":\"#/x-schemas/Accessibility/VerticalAlignment\"}},\"examples\":[{\"name\":\"Default example #1\",\"params\":[],\"result\":{\"name\":\"alignment\",\"value\":\"middle\"}},{\"name\":\"Default example #2\",\"params\":[],\"result\":{\"name\":\"alignment\",\"value\":\"top\"}},{\"name\":\"Default example #3\",\"params\":[],\"result\":{\"name\":\"alignment\",\"value\":null}}]},{\"name\":\"ClosedCaptions.windowColor\",\"tags\":[{\"name\":\"property\"},{\"name\":\"capabilities\",\"x-uses\":[\"xrn:firebolt:capability:accessibility:closedcaptions\"]}],\"summary\":\"The preferred window color for displaying closed-captions, .\",\"params\":[],\"result\":{\"name\":\"color\",\"schema\":{\"$ref\":\"#/x-schemas/Accessibility/Color\"}},\"examples\":[{\"name\":\"Default example #1\",\"params\":[],\"result\":{\"name\":\"color\",\"value\":\"#000000\"}},{\"name\":\"Default example #2\",\"params\":[],\"result\":{\"name\":\"color\",\"value\":\"white\"}},{\"name\":\"Default example #3\",\"params\":[],\"result\":{\"name\":\"color\",\"value\":null}}]},{\"name\":\"ClosedCaptions.windowOpacity\",\"tags\":[{\"name\":\"property\"},{\"name\":\"capabilities\",\"x-uses\":[\"xrn:firebolt:capability:accessibility:closedcaptions\"]}],\"summary\":\"The preferred window opacity for displaying closed-captions backgrounds.\",\"params\":[],\"result\":{\"name\":\"opacity\",\"schema\":{\"$ref\":\"#/x-schemas/Accessibility/Opacity\"}},\"examples\":[{\"name\":\"Default example #1\",\"params\":[],\"result\":{\"name\":\"opacity\",\"value\":99}},{\"name\":\"Default example #2\",\"params\":[],\"result\":{\"name\":\"opacity\",\"value\":100}},{\"name\":\"Default example #3\",\"params\":[],\"result\":{\"name\":\"opacity\",\"value\":null}}]},{\"name\":\"ClosedCaptions.preferredLanguages\",\"summary\":\"A prioritized list of ISO 639-2/B codes for the preferred closed captions languages on this device.\",\"params\":[],\"tags\":[{\"name\":\"property\"},{\"name\":\"capabilities\",\"x-uses\":[\"xrn:firebolt:capability:accessibility:closedcaptions\"]}],\"result\":{\"name\":\"languages\",\"summary\":\"the preferred closed captions languages\",\"schema\":{\"type\":\"array\",\"items\":{\"$ref\":\"#/x-schemas/Localization/ISO639_2Language\"}}},\"examples\":[{\"name\":\"Default Example\",\"params\":[],\"result\":{\"name\":\"Default Result\",\"value\":[\"spa\",\"eng\"]}},{\"name\":\"Default Example #2\",\"params\":[],\"result\":{\"name\":\"Default Result\",\"value\":[\"eng\",\"spa\"]}}]},{\"name\":\"ClosedCaptions.onEnabledChanged\",\"tags\":[{\"name\":\"subscriber\",\"x-subscriber-for\":\"ClosedCaptions.enabled\"},{\"name\":\"event\",\"x-alternative\":\"enabled\"},{\"name\":\"capabilities\",\"x-uses\":[\"xrn:firebolt:capability:accessibility:closedcaptions\"]}],\"summary\":\"Whether or not closed-captions are enabled.\",\"params\":[{\"name\":\"listen\",\"required\":true,\"schema\":{\"type\":\"boolean\"}}],\"result\":{\"name\":\"enabled\",\"schema\":{\"anyOf\":[{\"$ref\":\"#/x-schemas/Types/ListenResponse\"},{\"type\":\"boolean\"}]}},\"examples\":[{\"name\":\"Default example #1\",\"params\":[{\"name\":\"listen\",\"value\":true}],\"result\":{\"name\":\"enabled\",\"value\":true}},{\"name\":\"Default example #2\",\"params\":[{\"name\":\"listen\",\"value\":true}],\"result\":{\"name\":\"enabled\",\"value\":false}}]},{\"name\":\"ClosedCaptions.onFontFamilyChanged\",\"tags\":[{\"name\":\"subscriber\",\"x-subscriber-for\":\"ClosedCaptions.fontFamily\"},{\"name\":\"event\",\"x-alternative\":\"fontFamily\"},{\"name\":\"capabilities\",\"x-uses\":[\"xrn:firebolt:capability:accessibility:closedcaptions\"]}],\"summary\":\"The preferred font family for displaying closed-captions.\",\"params\":[{\"name\":\"listen\",\"required\":true,\"schema\":{\"type\":\"boolean\"}}],\"result\":{\"name\":\"family\",\"schema\":{\"anyOf\":[{\"$ref\":\"#/x-schemas/Types/ListenResponse\"},{\"$ref\":\"#/x-schemas/Accessibility/FontFamily\"}]}},\"examples\":[{\"name\":\"Default example #1\",\"params\":[{\"name\":\"listen\",\"value\":true}],\"result\":{\"name\":\"family\",\"value\":\"monospaced_sanserif\"}},{\"name\":\"Default example #2\",\"params\":[{\"name\":\"listen\",\"value\":true}],\"result\":{\"name\":\"family\",\"value\":\"cursive\"}},{\"name\":\"Default example #3\",\"params\":[{\"name\":\"listen\",\"value\":true}],\"result\":{\"name\":\"family\",\"value\":null}}]},{\"name\":\"ClosedCaptions.onFontSizeChanged\",\"tags\":[{\"name\":\"subscriber\",\"x-subscriber-for\":\"ClosedCaptions.fontSize\"},{\"name\":\"event\",\"x-alternative\":\"fontSize\"},{\"name\":\"capabilities\",\"x-uses\":[\"xrn:firebolt:capability:accessibility:closedcaptions\"]}],\"summary\":\"The preferred font size for displaying closed-captions.\",\"params\":[{\"name\":\"listen\",\"required\":true,\"schema\":{\"type\":\"boolean\"}}],\"result\":{\"name\":\"size\",\"schema\":{\"anyOf\":[{\"$ref\":\"#/x-schemas/Types/ListenResponse\"},{\"$ref\":\"#/x-schemas/Accessibility/FontSize\"}]}},\"examples\":[{\"name\":\"Default example #1\",\"params\":[{\"name\":\"listen\",\"value\":true}],\"result\":{\"name\":\"size\",\"value\":1}},{\"name\":\"Default example #2\",\"params\":[{\"name\":\"listen\",\"value\":true}],\"result\":{\"name\":\"size\",\"value\":1}},{\"name\":\"Default example #3\",\"params\":[{\"name\":\"listen\",\"value\":true}],\"result\":{\"name\":\"size\",\"value\":null}}]},{\"name\":\"ClosedCaptions.onFontColorChanged\",\"tags\":[{\"name\":\"subscriber\",\"x-subscriber-for\":\"ClosedCaptions.fontColor\"},{\"name\":\"event\",\"x-alternative\":\"fontColor\"},{\"name\":\"capabilities\",\"x-uses\":[\"xrn:firebolt:capability:accessibility:closedcaptions\"]}],\"summary\":\"The preferred font color for displaying closed-captions.\",\"params\":[{\"name\":\"listen\",\"required\":true,\"schema\":{\"type\":\"boolean\"}}],\"result\":{\"name\":\"color\",\"schema\":{\"anyOf\":[{\"$ref\":\"#/x-schemas/Types/ListenResponse\"},{\"$ref\":\"#/x-schemas/Accessibility/Color\"}]}},\"examples\":[{\"name\":\"Default example #1\",\"params\":[{\"name\":\"listen\",\"value\":true}],\"result\":{\"name\":\"color\",\"value\":\"#ffffff\"}},{\"name\":\"Default example #2\",\"params\":[{\"name\":\"listen\",\"value\":true}],\"result\":{\"name\":\"color\",\"value\":\"#000000\"}},{\"name\":\"Default example #3\",\"params\":[{\"name\":\"listen\",\"value\":true}],\"result\":{\"name\":\"color\",\"value\":null}}]},{\"name\":\"ClosedCaptions.onFontEdgeChanged\",\"tags\":[{\"name\":\"subscriber\",\"x-subscriber-for\":\"ClosedCaptions.fontEdge\"},{\"name\":\"event\",\"x-alternative\":\"fontEdge\"},{\"name\":\"capabilities\",\"x-uses\":[\"xrn:firebolt:capability:accessibility:closedcaptions\"]}],\"summary\":\"The preferred font edge style for displaying closed-captions.\",\"params\":[{\"name\":\"listen\",\"required\":true,\"schema\":{\"type\":\"boolean\"}}],\"result\":{\"name\":\"edge\",\"schema\":{\"anyOf\":[{\"$ref\":\"#/x-schemas/Types/ListenResponse\"},{\"$ref\":\"#/x-schemas/Accessibility/FontEdge\"}]}},\"examples\":[{\"name\":\"Default example #1\",\"params\":[{\"name\":\"listen\",\"value\":true}],\"result\":{\"name\":\"edge\",\"value\":\"none\"}},{\"name\":\"Default example #2\",\"params\":[{\"name\":\"listen\",\"value\":true}],\"result\":{\"name\":\"edge\",\"value\":\"uniform\"}},{\"name\":\"Default example #3\",\"params\":[{\"name\":\"listen\",\"value\":true}],\"result\":{\"name\":\"edge\",\"value\":null}}]},{\"name\":\"ClosedCaptions.onFontEdgeColorChanged\",\"tags\":[{\"name\":\"subscriber\",\"x-subscriber-for\":\"ClosedCaptions.fontEdgeColor\"},{\"name\":\"event\",\"x-alternative\":\"fontEdgeColor\"},{\"name\":\"capabilities\",\"x-uses\":[\"xrn:firebolt:capability:accessibility:closedcaptions\"]}],\"summary\":\"The preferred font edge color for displaying closed-captions.\",\"params\":[{\"name\":\"listen\",\"required\":true,\"schema\":{\"type\":\"boolean\"}}],\"result\":{\"name\":\"color\",\"schema\":{\"anyOf\":[{\"$ref\":\"#/x-schemas/Types/ListenResponse\"},{\"$ref\":\"#/x-schemas/Accessibility/Color\"}]}},\"examples\":[{\"name\":\"Default example #1\",\"params\":[{\"name\":\"listen\",\"value\":true}],\"result\":{\"name\":\"color\",\"value\":\"#000000\"}},{\"name\":\"Default example #2\",\"params\":[{\"name\":\"listen\",\"value\":true}],\"result\":{\"name\":\"color\",\"value\":\"#ffffff\"}},{\"name\":\"Default example #3\",\"params\":[{\"name\":\"listen\",\"value\":true}],\"result\":{\"name\":\"color\",\"value\":null}}]},{\"name\":\"ClosedCaptions.onFontOpacityChanged\",\"tags\":[{\"name\":\"subscriber\",\"x-subscriber-for\":\"ClosedCaptions.fontOpacity\"},{\"name\":\"event\",\"x-alternative\":\"fontOpacity\"},{\"name\":\"capabilities\",\"x-uses\":[\"xrn:firebolt:capability:accessibility:closedcaptions\"]}],\"summary\":\"The preferred opacity for displaying closed-captions characters.\",\"params\":[{\"name\":\"listen\",\"required\":true,\"schema\":{\"type\":\"boolean\"}}],\"result\":{\"name\":\"opacity\",\"schema\":{\"anyOf\":[{\"$ref\":\"#/x-schemas/Types/ListenResponse\"},{\"$ref\":\"#/x-schemas/Accessibility/Opacity\"}]}},\"examples\":[{\"name\":\"Default example #1\",\"params\":[{\"name\":\"listen\",\"value\":true}],\"result\":{\"name\":\"opacity\",\"value\":99}},{\"name\":\"Default example #2\",\"params\":[{\"name\":\"listen\",\"value\":true}],\"result\":{\"name\":\"opacity\",\"value\":100}},{\"name\":\"Default example #3\",\"params\":[{\"name\":\"listen\",\"value\":true}],\"result\":{\"name\":\"opacity\",\"value\":null}}]},{\"name\":\"ClosedCaptions.onBackgroundColorChanged\",\"tags\":[{\"name\":\"subscriber\",\"x-subscriber-for\":\"ClosedCaptions.backgroundColor\"},{\"name\":\"event\",\"x-alternative\":\"backgroundColor\"},{\"name\":\"capabilities\",\"x-uses\":[\"xrn:firebolt:capability:accessibility:closedcaptions\"]}],\"summary\":\"The preferred background color for displaying closed-captions, .\",\"params\":[{\"name\":\"listen\",\"required\":true,\"schema\":{\"type\":\"boolean\"}}],\"result\":{\"name\":\"color\",\"schema\":{\"anyOf\":[{\"$ref\":\"#/x-schemas/Types/ListenResponse\"},{\"$ref\":\"#/x-schemas/Accessibility/Color\"}]}},\"examples\":[{\"name\":\"Default example #1\",\"params\":[{\"name\":\"listen\",\"value\":true}],\"result\":{\"name\":\"color\",\"value\":\"#000000\"}},{\"name\":\"Default example #2\",\"params\":[{\"name\":\"listen\",\"value\":true}],\"result\":{\"name\":\"color\",\"value\":\"#ffffff\"}},{\"name\":\"Default example #3\",\"params\":[{\"name\":\"listen\",\"value\":true}],\"result\":{\"name\":\"color\",\"value\":null}}]},{\"name\":\"ClosedCaptions.onBackgroundOpacityChanged\",\"tags\":[{\"name\":\"subscriber\",\"x-subscriber-for\":\"ClosedCaptions.backgroundOpacity\"},{\"name\":\"event\",\"x-alternative\":\"backgroundOpacity\"},{\"name\":\"capabilities\",\"x-uses\":[\"xrn:firebolt:capability:accessibility:closedcaptions\"]}],\"summary\":\"The preferred opacity for displaying closed-captions backgrounds.\",\"params\":[{\"name\":\"listen\",\"required\":true,\"schema\":{\"type\":\"boolean\"}}],\"result\":{\"name\":\"opacity\",\"schema\":{\"anyOf\":[{\"$ref\":\"#/x-schemas/Types/ListenResponse\"},{\"$ref\":\"#/x-schemas/Accessibility/Opacity\"}]}},\"examples\":[{\"name\":\"Default example #1\",\"params\":[{\"name\":\"listen\",\"value\":true}],\"result\":{\"name\":\"opacity\",\"value\":99}},{\"name\":\"Default example #2\",\"params\":[{\"name\":\"listen\",\"value\":true}],\"result\":{\"name\":\"opacity\",\"value\":100}},{\"name\":\"Default example #3\",\"params\":[{\"name\":\"listen\",\"value\":true}],\"result\":{\"name\":\"opacity\",\"value\":null}}]},{\"name\":\"ClosedCaptions.onTextAlignChanged\",\"tags\":[{\"name\":\"subscriber\",\"x-subscriber-for\":\"ClosedCaptions.textAlign\"},{\"name\":\"event\",\"x-alternative\":\"textAlign\"},{\"name\":\"capabilities\",\"x-uses\":[\"xrn:firebolt:capability:accessibility:closedcaptions\"]}],\"summary\":\"The preferred horizontal alignment for displaying closed-captions characters.\",\"params\":[{\"name\":\"listen\",\"required\":true,\"schema\":{\"type\":\"boolean\"}}],\"result\":{\"name\":\"alignment\",\"schema\":{\"anyOf\":[{\"$ref\":\"#/x-schemas/Types/ListenResponse\"},{\"$ref\":\"#/x-schemas/Accessibility/HorizontalAlignment\"}]}},\"examples\":[{\"name\":\"Default example #1\",\"params\":[{\"name\":\"listen\",\"value\":true}],\"result\":{\"name\":\"alignment\",\"value\":\"center\"}},{\"name\":\"Default example #2\",\"params\":[{\"name\":\"listen\",\"value\":true}],\"result\":{\"name\":\"alignment\",\"value\":\"left\"}},{\"name\":\"Default example #3\",\"params\":[{\"name\":\"listen\",\"value\":true}],\"result\":{\"name\":\"alignment\",\"value\":null}}]},{\"name\":\"ClosedCaptions.onTextAlignVerticalChanged\",\"tags\":[{\"name\":\"subscriber\",\"x-subscriber-for\":\"ClosedCaptions.textAlignVertical\"},{\"name\":\"event\",\"x-alternative\":\"textAlignVertical\"},{\"name\":\"capabilities\",\"x-uses\":[\"xrn:firebolt:capability:accessibility:closedcaptions\"]}],\"summary\":\"The preferred horizontal alignment for displaying closed-captions characters.\",\"params\":[{\"name\":\"listen\",\"required\":true,\"schema\":{\"type\":\"boolean\"}}],\"result\":{\"name\":\"alignment\",\"schema\":{\"anyOf\":[{\"$ref\":\"#/x-schemas/Types/ListenResponse\"},{\"$ref\":\"#/x-schemas/Accessibility/VerticalAlignment\"}]}},\"examples\":[{\"name\":\"Default example #1\",\"params\":[{\"name\":\"listen\",\"value\":true}],\"result\":{\"name\":\"alignment\",\"value\":\"middle\"}},{\"name\":\"Default example #2\",\"params\":[{\"name\":\"listen\",\"value\":true}],\"result\":{\"name\":\"alignment\",\"value\":\"top\"}},{\"name\":\"Default example #3\",\"params\":[{\"name\":\"listen\",\"value\":true}],\"result\":{\"name\":\"alignment\",\"value\":null}}]},{\"name\":\"ClosedCaptions.onWindowColorChanged\",\"tags\":[{\"name\":\"subscriber\",\"x-subscriber-for\":\"ClosedCaptions.windowColor\"},{\"name\":\"event\",\"x-alternative\":\"windowColor\"},{\"name\":\"capabilities\",\"x-uses\":[\"xrn:firebolt:capability:accessibility:closedcaptions\"]}],\"summary\":\"The preferred window color for displaying closed-captions, .\",\"params\":[{\"name\":\"listen\",\"required\":true,\"schema\":{\"type\":\"boolean\"}}],\"result\":{\"name\":\"color\",\"schema\":{\"anyOf\":[{\"$ref\":\"#/x-schemas/Types/ListenResponse\"},{\"$ref\":\"#/x-schemas/Accessibility/Color\"}]}},\"examples\":[{\"name\":\"Default example #1\",\"params\":[{\"name\":\"listen\",\"value\":true}],\"result\":{\"name\":\"color\",\"value\":\"#000000\"}},{\"name\":\"Default example #2\",\"params\":[{\"name\":\"listen\",\"value\":true}],\"result\":{\"name\":\"color\",\"value\":\"white\"}},{\"name\":\"Default example #3\",\"params\":[{\"name\":\"listen\",\"value\":true}],\"result\":{\"name\":\"color\",\"value\":null}}]},{\"name\":\"ClosedCaptions.onWindowOpacityChanged\",\"tags\":[{\"name\":\"subscriber\",\"x-subscriber-for\":\"ClosedCaptions.windowOpacity\"},{\"name\":\"event\",\"x-alternative\":\"windowOpacity\"},{\"name\":\"capabilities\",\"x-uses\":[\"xrn:firebolt:capability:accessibility:closedcaptions\"]}],\"summary\":\"The preferred window opacity for displaying closed-captions backgrounds.\",\"params\":[{\"name\":\"listen\",\"required\":true,\"schema\":{\"type\":\"boolean\"}}],\"result\":{\"name\":\"opacity\",\"schema\":{\"anyOf\":[{\"$ref\":\"#/x-schemas/Types/ListenResponse\"},{\"$ref\":\"#/x-schemas/Accessibility/Opacity\"}]}},\"examples\":[{\"name\":\"Default example #1\",\"params\":[{\"name\":\"listen\",\"value\":true}],\"result\":{\"name\":\"opacity\",\"value\":99}},{\"name\":\"Default example #2\",\"params\":[{\"name\":\"listen\",\"value\":true}],\"result\":{\"name\":\"opacity\",\"value\":100}},{\"name\":\"Default example #3\",\"params\":[{\"name\":\"listen\",\"value\":true}],\"result\":{\"name\":\"opacity\",\"value\":null}}]},{\"name\":\"ClosedCaptions.onPreferredLanguagesChanged\",\"summary\":\"A prioritized list of ISO 639-2/B codes for the preferred closed captions languages on this device.\",\"params\":[{\"name\":\"listen\",\"required\":true,\"schema\":{\"type\":\"boolean\"}}],\"tags\":[{\"name\":\"subscriber\",\"x-subscriber-for\":\"ClosedCaptions.preferredLanguages\"},{\"name\":\"event\",\"x-alternative\":\"preferredLanguages\"},{\"name\":\"capabilities\",\"x-uses\":[\"xrn:firebolt:capability:accessibility:closedcaptions\"]}],\"result\":{\"name\":\"languages\",\"summary\":\"the preferred closed captions languages\",\"schema\":{\"anyOf\":[{\"$ref\":\"#/x-schemas/Types/ListenResponse\"},{\"type\":\"array\",\"items\":{\"$ref\":\"#/x-schemas/Localization/ISO639_2Language\"}}]}},\"examples\":[{\"name\":\"Default Example\",\"params\":[{\"name\":\"listen\",\"value\":true}],\"result\":{\"name\":\"Default Result\",\"value\":[\"spa\",\"eng\"]}},{\"name\":\"Default Example #2\",\"params\":[{\"name\":\"listen\",\"value\":true}],\"result\":{\"name\":\"Default Result\",\"value\":[\"eng\",\"spa\"]}}]},{\"name\":\"ClosedCaptions.setEnabled\",\"tags\":[{\"name\":\"setter\",\"x-setter-for\":\"enabled\"},{\"name\":\"capabilities\",\"x-manages\":[\"xrn:firebolt:capability:accessibility:closedcaptions\"]}],\"summary\":\"Whether or not closed-captions are enabled.\",\"params\":[{\"name\":\"value\",\"schema\":{\"type\":\"boolean\"},\"required\":true}],\"result\":{\"name\":\"result\",\"schema\":{\"type\":\"null\"}},\"examples\":[{\"name\":\"Default example #1\",\"params\":[{\"name\":\"value\",\"value\":true}],\"result\":{\"name\":\"enabled\",\"value\":null}},{\"name\":\"Default example #2\",\"params\":[{\"name\":\"value\",\"value\":false}],\"result\":{\"name\":\"enabled\",\"value\":null}}]},{\"name\":\"ClosedCaptions.setFontFamily\",\"tags\":[{\"name\":\"setter\",\"x-setter-for\":\"fontFamily\"},{\"name\":\"capabilities\",\"x-manages\":[\"xrn:firebolt:capability:accessibility:closedcaptions\"]}],\"summary\":\"The preferred font family for displaying closed-captions.\",\"params\":[{\"name\":\"value\",\"schema\":{\"$ref\":\"#/x-schemas/Accessibility/FontFamily\"},\"required\":true}],\"result\":{\"name\":\"result\",\"schema\":{\"type\":\"null\"}},\"examples\":[{\"name\":\"Default example #1\",\"params\":[{\"name\":\"value\",\"value\":\"monospaced_sanserif\"}],\"result\":{\"name\":\"family\",\"value\":null}},{\"name\":\"Default example #2\",\"params\":[{\"name\":\"value\",\"value\":\"cursive\"}],\"result\":{\"name\":\"family\",\"value\":null}},{\"name\":\"Default example #3\",\"params\":[{\"name\":\"value\",\"value\":null}],\"result\":{\"name\":\"family\",\"value\":null}}]},{\"name\":\"ClosedCaptions.setFontSize\",\"tags\":[{\"name\":\"setter\",\"x-setter-for\":\"fontSize\"},{\"name\":\"capabilities\",\"x-manages\":[\"xrn:firebolt:capability:accessibility:closedcaptions\"]}],\"summary\":\"The preferred font size for displaying closed-captions.\",\"params\":[{\"name\":\"value\",\"schema\":{\"$ref\":\"#/x-schemas/Accessibility/FontSize\"},\"required\":true}],\"result\":{\"name\":\"result\",\"schema\":{\"type\":\"null\"}},\"examples\":[{\"name\":\"Default example #1\",\"params\":[{\"name\":\"value\",\"value\":1}],\"result\":{\"name\":\"size\",\"value\":null}},{\"name\":\"Default example #2\",\"params\":[{\"name\":\"value\",\"value\":1}],\"result\":{\"name\":\"size\",\"value\":null}},{\"name\":\"Default example #3\",\"params\":[{\"name\":\"value\",\"value\":null}],\"result\":{\"name\":\"size\",\"value\":null}}]},{\"name\":\"ClosedCaptions.setFontColor\",\"tags\":[{\"name\":\"setter\",\"x-setter-for\":\"fontColor\"},{\"name\":\"capabilities\",\"x-manages\":[\"xrn:firebolt:capability:accessibility:closedcaptions\"]}],\"summary\":\"The preferred font color for displaying closed-captions.\",\"params\":[{\"name\":\"value\",\"schema\":{\"$ref\":\"#/x-schemas/Accessibility/Color\"},\"required\":true}],\"result\":{\"name\":\"result\",\"schema\":{\"type\":\"null\"}},\"examples\":[{\"name\":\"Default example #1\",\"params\":[{\"name\":\"value\",\"value\":\"#ffffff\"}],\"result\":{\"name\":\"color\",\"value\":null}},{\"name\":\"Default example #2\",\"params\":[{\"name\":\"value\",\"value\":\"#000000\"}],\"result\":{\"name\":\"color\",\"value\":null}},{\"name\":\"Default example #3\",\"params\":[{\"name\":\"value\",\"value\":null}],\"result\":{\"name\":\"color\",\"value\":null}}]},{\"name\":\"ClosedCaptions.setFontEdge\",\"tags\":[{\"name\":\"setter\",\"x-setter-for\":\"fontEdge\"},{\"name\":\"capabilities\",\"x-manages\":[\"xrn:firebolt:capability:accessibility:closedcaptions\"]}],\"summary\":\"The preferred font edge style for displaying closed-captions.\",\"params\":[{\"name\":\"value\",\"schema\":{\"$ref\":\"#/x-schemas/Accessibility/FontEdge\"},\"required\":true}],\"result\":{\"name\":\"result\",\"schema\":{\"type\":\"null\"}},\"examples\":[{\"name\":\"Default example #1\",\"params\":[{\"name\":\"value\",\"value\":\"none\"}],\"result\":{\"name\":\"edge\",\"value\":null}},{\"name\":\"Default example #2\",\"params\":[{\"name\":\"value\",\"value\":\"uniform\"}],\"result\":{\"name\":\"edge\",\"value\":null}},{\"name\":\"Default example #3\",\"params\":[{\"name\":\"value\",\"value\":null}],\"result\":{\"name\":\"edge\",\"value\":null}}]},{\"name\":\"ClosedCaptions.setFontEdgeColor\",\"tags\":[{\"name\":\"setter\",\"x-setter-for\":\"fontEdgeColor\"},{\"name\":\"capabilities\",\"x-manages\":[\"xrn:firebolt:capability:accessibility:closedcaptions\"]}],\"summary\":\"The preferred font edge color for displaying closed-captions.\",\"params\":[{\"name\":\"value\",\"schema\":{\"$ref\":\"#/x-schemas/Accessibility/Color\"},\"required\":true}],\"result\":{\"name\":\"result\",\"schema\":{\"type\":\"null\"}},\"examples\":[{\"name\":\"Default example #1\",\"params\":[{\"name\":\"value\",\"value\":\"#000000\"}],\"result\":{\"name\":\"color\",\"value\":null}},{\"name\":\"Default example #2\",\"params\":[{\"name\":\"value\",\"value\":\"#ffffff\"}],\"result\":{\"name\":\"color\",\"value\":null}},{\"name\":\"Default example #3\",\"params\":[{\"name\":\"value\",\"value\":null}],\"result\":{\"name\":\"color\",\"value\":null}}]},{\"name\":\"ClosedCaptions.setFontOpacity\",\"tags\":[{\"name\":\"setter\",\"x-setter-for\":\"fontOpacity\"},{\"name\":\"capabilities\",\"x-manages\":[\"xrn:firebolt:capability:accessibility:closedcaptions\"]}],\"summary\":\"The preferred opacity for displaying closed-captions characters.\",\"params\":[{\"name\":\"value\",\"schema\":{\"$ref\":\"#/x-schemas/Accessibility/Opacity\"},\"required\":true}],\"result\":{\"name\":\"result\",\"schema\":{\"type\":\"null\"}},\"examples\":[{\"name\":\"Default example #1\",\"params\":[{\"name\":\"value\",\"value\":99}],\"result\":{\"name\":\"opacity\",\"value\":null}},{\"name\":\"Default example #2\",\"params\":[{\"name\":\"value\",\"value\":100}],\"result\":{\"name\":\"opacity\",\"value\":null}},{\"name\":\"Default example #3\",\"params\":[{\"name\":\"value\",\"value\":null}],\"result\":{\"name\":\"opacity\",\"value\":null}}]},{\"name\":\"ClosedCaptions.setBackgroundColor\",\"tags\":[{\"name\":\"setter\",\"x-setter-for\":\"backgroundColor\"},{\"name\":\"capabilities\",\"x-manages\":[\"xrn:firebolt:capability:accessibility:closedcaptions\"]}],\"summary\":\"The preferred background color for displaying closed-captions, .\",\"params\":[{\"name\":\"value\",\"schema\":{\"$ref\":\"#/x-schemas/Accessibility/Color\"},\"required\":true}],\"result\":{\"name\":\"result\",\"schema\":{\"type\":\"null\"}},\"examples\":[{\"name\":\"Default example #1\",\"params\":[{\"name\":\"value\",\"value\":\"#000000\"}],\"result\":{\"name\":\"color\",\"value\":null}},{\"name\":\"Default example #2\",\"params\":[{\"name\":\"value\",\"value\":\"#ffffff\"}],\"result\":{\"name\":\"color\",\"value\":null}},{\"name\":\"Default example #3\",\"params\":[{\"name\":\"value\",\"value\":null}],\"result\":{\"name\":\"color\",\"value\":null}}]},{\"name\":\"ClosedCaptions.setBackgroundOpacity\",\"tags\":[{\"name\":\"setter\",\"x-setter-for\":\"backgroundOpacity\"},{\"name\":\"capabilities\",\"x-manages\":[\"xrn:firebolt:capability:accessibility:closedcaptions\"]}],\"summary\":\"The preferred opacity for displaying closed-captions backgrounds.\",\"params\":[{\"name\":\"value\",\"schema\":{\"$ref\":\"#/x-schemas/Accessibility/Opacity\"},\"required\":true}],\"result\":{\"name\":\"result\",\"schema\":{\"type\":\"null\"}},\"examples\":[{\"name\":\"Default example #1\",\"params\":[{\"name\":\"value\",\"value\":99}],\"result\":{\"name\":\"opacity\",\"value\":null}},{\"name\":\"Default example #2\",\"params\":[{\"name\":\"value\",\"value\":100}],\"result\":{\"name\":\"opacity\",\"value\":null}},{\"name\":\"Default example #3\",\"params\":[{\"name\":\"value\",\"value\":null}],\"result\":{\"name\":\"opacity\",\"value\":null}}]},{\"name\":\"ClosedCaptions.setTextAlign\",\"tags\":[{\"name\":\"setter\",\"x-setter-for\":\"textAlign\"},{\"name\":\"capabilities\",\"x-manages\":[\"xrn:firebolt:capability:accessibility:closedcaptions\"]}],\"summary\":\"The preferred horizontal alignment for displaying closed-captions characters.\",\"params\":[{\"name\":\"value\",\"schema\":{\"$ref\":\"#/x-schemas/Accessibility/HorizontalAlignment\"},\"required\":true}],\"result\":{\"name\":\"result\",\"schema\":{\"type\":\"null\"}},\"examples\":[{\"name\":\"Default example #1\",\"params\":[{\"name\":\"value\",\"value\":\"center\"}],\"result\":{\"name\":\"alignment\",\"value\":null}},{\"name\":\"Default example #2\",\"params\":[{\"name\":\"value\",\"value\":\"left\"}],\"result\":{\"name\":\"alignment\",\"value\":null}},{\"name\":\"Default example #3\",\"params\":[{\"name\":\"value\",\"value\":null}],\"result\":{\"name\":\"alignment\",\"value\":null}}]},{\"name\":\"ClosedCaptions.setTextAlignVertical\",\"tags\":[{\"name\":\"setter\",\"x-setter-for\":\"textAlignVertical\"},{\"name\":\"capabilities\",\"x-manages\":[\"xrn:firebolt:capability:accessibility:closedcaptions\"]}],\"summary\":\"The preferred horizontal alignment for displaying closed-captions characters.\",\"params\":[{\"name\":\"value\",\"schema\":{\"$ref\":\"#/x-schemas/Accessibility/VerticalAlignment\"},\"required\":true}],\"result\":{\"name\":\"result\",\"schema\":{\"type\":\"null\"}},\"examples\":[{\"name\":\"Default example #1\",\"params\":[{\"name\":\"value\",\"value\":\"middle\"}],\"result\":{\"name\":\"alignment\",\"value\":null}},{\"name\":\"Default example #2\",\"params\":[{\"name\":\"value\",\"value\":\"top\"}],\"result\":{\"name\":\"alignment\",\"value\":null}},{\"name\":\"Default example #3\",\"params\":[{\"name\":\"value\",\"value\":null}],\"result\":{\"name\":\"alignment\",\"value\":null}}]},{\"name\":\"ClosedCaptions.setWindowColor\",\"tags\":[{\"name\":\"setter\",\"x-setter-for\":\"windowColor\"},{\"name\":\"capabilities\",\"x-manages\":[\"xrn:firebolt:capability:accessibility:closedcaptions\"]}],\"summary\":\"The preferred window color for displaying closed-captions, .\",\"params\":[{\"name\":\"value\",\"schema\":{\"$ref\":\"#/x-schemas/Accessibility/Color\"},\"required\":true}],\"result\":{\"name\":\"result\",\"schema\":{\"type\":\"null\"}},\"examples\":[{\"name\":\"Default example #1\",\"params\":[{\"name\":\"value\",\"value\":\"#000000\"}],\"result\":{\"name\":\"color\",\"value\":null}},{\"name\":\"Default example #2\",\"params\":[{\"name\":\"value\",\"value\":\"white\"}],\"result\":{\"name\":\"color\",\"value\":null}},{\"name\":\"Default example #3\",\"params\":[{\"name\":\"value\",\"value\":null}],\"result\":{\"name\":\"color\",\"value\":null}}]},{\"name\":\"ClosedCaptions.setWindowOpacity\",\"tags\":[{\"name\":\"setter\",\"x-setter-for\":\"windowOpacity\"},{\"name\":\"capabilities\",\"x-manages\":[\"xrn:firebolt:capability:accessibility:closedcaptions\"]}],\"summary\":\"The preferred window opacity for displaying closed-captions backgrounds.\",\"params\":[{\"name\":\"value\",\"schema\":{\"$ref\":\"#/x-schemas/Accessibility/Opacity\"},\"required\":true}],\"result\":{\"name\":\"result\",\"schema\":{\"type\":\"null\"}},\"examples\":[{\"name\":\"Default example #1\",\"params\":[{\"name\":\"value\",\"value\":99}],\"result\":{\"name\":\"opacity\",\"value\":null}},{\"name\":\"Default example #2\",\"params\":[{\"name\":\"value\",\"value\":100}],\"result\":{\"name\":\"opacity\",\"value\":null}},{\"name\":\"Default example #3\",\"params\":[{\"name\":\"value\",\"value\":null}],\"result\":{\"name\":\"opacity\",\"value\":null}}]},{\"name\":\"ClosedCaptions.setPreferredLanguages\",\"summary\":\"A prioritized list of ISO 639-2/B codes for the preferred closed captions languages on this device.\",\"params\":[{\"name\":\"value\",\"summary\":\"the preferred closed captions languages\",\"schema\":{\"type\":\"array\",\"items\":{\"$ref\":\"#/x-schemas/Localization/ISO639_2Language\"}},\"required\":true}],\"tags\":[{\"name\":\"setter\",\"x-setter-for\":\"preferredLanguages\"},{\"name\":\"capabilities\",\"x-manages\":[\"xrn:firebolt:capability:accessibility:closedcaptions\"]}],\"result\":{\"name\":\"result\",\"schema\":{\"type\":\"null\"}},\"examples\":[{\"name\":\"Default Example\",\"params\":[{\"name\":\"value\",\"value\":[\"spa\",\"eng\"]}],\"result\":{\"name\":\"Default Result\",\"value\":null}},{\"name\":\"Default Example #2\",\"params\":[{\"name\":\"value\",\"value\":[\"eng\",\"spa\"]}],\"result\":{\"name\":\"Default Result\",\"value\":null}}]},{\"name\":\"AudioDescriptions.enabled\",\"tags\":[{\"name\":\"property\"},{\"name\":\"capabilities\",\"x-uses\":[\"xrn:firebolt:capability:accessibility:audiodescriptions\"]}],\"summary\":\"Whether or not audio-descriptions are enabled.\",\"params\":[],\"result\":{\"name\":\"enabled\",\"schema\":{\"type\":\"boolean\"}},\"examples\":[{\"name\":\"Default example #1\",\"params\":[],\"result\":{\"name\":\"enabled\",\"value\":true}},{\"name\":\"Default example #2\",\"params\":[],\"result\":{\"name\":\"enabled\",\"value\":false}}]},{\"name\":\"AudioDescriptions.onEnabledChanged\",\"tags\":[{\"name\":\"subscriber\",\"x-subscriber-for\":\"AudioDescriptions.enabled\"},{\"name\":\"event\",\"x-alternative\":\"enabled\"},{\"name\":\"capabilities\",\"x-uses\":[\"xrn:firebolt:capability:accessibility:audiodescriptions\"]}],\"summary\":\"Whether or not audio-descriptions are enabled.\",\"params\":[{\"name\":\"listen\",\"required\":true,\"schema\":{\"type\":\"boolean\"}}],\"result\":{\"name\":\"enabled\",\"schema\":{\"anyOf\":[{\"$ref\":\"#/x-schemas/Types/ListenResponse\"},{\"type\":\"boolean\"}]}},\"examples\":[{\"name\":\"Default example #1\",\"params\":[{\"name\":\"listen\",\"value\":true}],\"result\":{\"name\":\"enabled\",\"value\":true}},{\"name\":\"Default example #2\",\"params\":[{\"name\":\"listen\",\"value\":true}],\"result\":{\"name\":\"enabled\",\"value\":false}}]},{\"name\":\"AudioDescriptions.setEnabled\",\"tags\":[{\"name\":\"setter\",\"x-setter-for\":\"enabled\"},{\"name\":\"capabilities\",\"x-manages\":[\"xrn:firebolt:capability:accessibility:audiodescriptions\"]}],\"summary\":\"Whether or not audio-descriptions are enabled.\",\"params\":[{\"name\":\"value\",\"schema\":{\"type\":\"boolean\"},\"required\":true}],\"result\":{\"name\":\"result\",\"schema\":{\"type\":\"null\"}},\"examples\":[{\"name\":\"Default example #1\",\"params\":[{\"name\":\"value\",\"value\":true}],\"result\":{\"name\":\"enabled\",\"value\":null}},{\"name\":\"Default example #2\",\"params\":[{\"name\":\"value\",\"value\":false}],\"result\":{\"name\":\"enabled\",\"value\":null}}]},{\"name\":\"VoiceGuidance.enabled\",\"tags\":[{\"name\":\"property\"},{\"name\":\"capabilities\",\"x-uses\":[\"xrn:firebolt:capability:accessibility:voiceguidance\"]}],\"summary\":\"Whether or not voice-guidance is enabled.\",\"params\":[],\"result\":{\"name\":\"enabled\",\"schema\":{\"type\":\"boolean\"}},\"examples\":[{\"name\":\"Default example #1\",\"params\":[],\"result\":{\"name\":\"enabled\",\"value\":true}},{\"name\":\"Default example #2\",\"params\":[],\"result\":{\"name\":\"enabled\",\"value\":false}}]},{\"name\":\"VoiceGuidance.speed\",\"tags\":[{\"name\":\"property\"},{\"name\":\"capabilities\",\"x-uses\":[\"xrn:firebolt:capability:accessibility:voiceguidance\"]}],\"summary\":\"The speed at which voice guidance speech will be read back to the user.\",\"params\":[],\"result\":{\"name\":\"speed\",\"schema\":{\"$ref\":\"#/x-schemas/Accessibility/VoiceSpeed\"}},\"examples\":[{\"name\":\"Voice guidance speed to 1\",\"params\":[],\"result\":{\"name\":\"speed\",\"value\":1}},{\"name\":\"Voice guidance speed to 2\",\"params\":[],\"result\":{\"name\":\"speed\",\"value\":2}}]},{\"name\":\"VoiceGuidance.onEnabledChanged\",\"tags\":[{\"name\":\"subscriber\",\"x-subscriber-for\":\"VoiceGuidance.enabled\"},{\"name\":\"event\",\"x-alternative\":\"enabled\"},{\"name\":\"capabilities\",\"x-uses\":[\"xrn:firebolt:capability:accessibility:voiceguidance\"]}],\"summary\":\"Whether or not voice-guidance is enabled.\",\"params\":[{\"name\":\"listen\",\"required\":true,\"schema\":{\"type\":\"boolean\"}}],\"result\":{\"name\":\"enabled\",\"schema\":{\"anyOf\":[{\"$ref\":\"#/x-schemas/Types/ListenResponse\"},{\"type\":\"boolean\"}]}},\"examples\":[{\"name\":\"Default example #1\",\"params\":[{\"name\":\"listen\",\"value\":true}],\"result\":{\"name\":\"enabled\",\"value\":true}},{\"name\":\"Default example #2\",\"params\":[{\"name\":\"listen\",\"value\":true}],\"result\":{\"name\":\"enabled\",\"value\":false}}]},{\"name\":\"VoiceGuidance.onSpeedChanged\",\"tags\":[{\"name\":\"subscriber\",\"x-subscriber-for\":\"VoiceGuidance.speed\"},{\"name\":\"event\",\"x-alternative\":\"speed\"},{\"name\":\"capabilities\",\"x-uses\":[\"xrn:firebolt:capability:accessibility:voiceguidance\"]}],\"summary\":\"The speed at which voice guidance speech will be read back to the user.\",\"params\":[{\"name\":\"listen\",\"required\":true,\"schema\":{\"type\":\"boolean\"}}],\"result\":{\"name\":\"speed\",\"schema\":{\"anyOf\":[{\"$ref\":\"#/x-schemas/Types/ListenResponse\"},{\"$ref\":\"#/x-schemas/Accessibility/VoiceSpeed\"}]}},\"examples\":[{\"name\":\"Voice guidance speed to 1\",\"params\":[{\"name\":\"listen\",\"value\":true}],\"result\":{\"name\":\"speed\",\"value\":1}},{\"name\":\"Voice guidance speed to 2\",\"params\":[{\"name\":\"listen\",\"value\":true}],\"result\":{\"name\":\"speed\",\"value\":2}}]},{\"name\":\"VoiceGuidance.setEnabled\",\"tags\":[{\"name\":\"setter\",\"x-setter-for\":\"enabled\"},{\"name\":\"capabilities\",\"x-manages\":[\"xrn:firebolt:capability:accessibility:voiceguidance\"]}],\"summary\":\"Whether or not voice-guidance is enabled.\",\"params\":[{\"name\":\"value\",\"schema\":{\"type\":\"boolean\"},\"required\":true}],\"result\":{\"name\":\"result\",\"schema\":{\"type\":\"null\"}},\"examples\":[{\"name\":\"Default example #1\",\"params\":[{\"name\":\"value\",\"value\":true}],\"result\":{\"name\":\"enabled\",\"value\":null}},{\"name\":\"Default example #2\",\"params\":[{\"name\":\"value\",\"value\":false}],\"result\":{\"name\":\"enabled\",\"value\":null}}]},{\"name\":\"VoiceGuidance.setSpeed\",\"tags\":[{\"name\":\"setter\",\"x-setter-for\":\"speed\"},{\"name\":\"capabilities\",\"x-manages\":[\"xrn:firebolt:capability:accessibility:voiceguidance\"]}],\"summary\":\"The speed at which voice guidance speech will be read back to the user.\",\"params\":[{\"name\":\"value\",\"schema\":{\"$ref\":\"#/x-schemas/Accessibility/VoiceSpeed\"},\"required\":true}],\"result\":{\"name\":\"result\",\"schema\":{\"type\":\"null\"}},\"examples\":[{\"name\":\"Voice guidance speed to 1\",\"params\":[{\"name\":\"value\",\"value\":1}],\"result\":{\"name\":\"speed\",\"value\":null}},{\"name\":\"Voice guidance speed to 2\",\"params\":[{\"name\":\"value\",\"value\":2}],\"result\":{\"name\":\"speed\",\"value\":null}}]},{\"name\":\"Device.name\",\"summary\":\"The human readable name of the device\",\"params\":[],\"tags\":[{\"name\":\"property\"},{\"name\":\"capabilities\",\"x-uses\":[\"xrn:firebolt:capability:device:name\"]}],\"result\":{\"name\":\"value\",\"summary\":\"the device friendly-name\",\"schema\":{\"type\":\"string\"}},\"examples\":[{\"name\":\"Default example #1\",\"params\":[],\"result\":{\"name\":\"Default Result\",\"value\":\"Living Room\"}},{\"name\":\"Default example #2\",\"params\":[],\"result\":{\"name\":\"Default Result\",\"value\":\"Kitchen\"}}]},{\"name\":\"Device.onDeviceNameChanged\",\"tags\":[{\"name\":\"event\"},{\"name\":\"deprecated\",\"x-since\":\"0.6.0\",\"x-alternative\":\"Device.name()\"},{\"name\":\"capabilities\",\"x-uses\":[\"xrn:firebolt:capability:device:name\"]}],\"summary\":\"Get the human readable name of the device\",\"params\":[{\"name\":\"listen\",\"required\":true,\"schema\":{\"type\":\"boolean\"}}],\"result\":{\"name\":\"value\",\"summary\":\"the device friendly-name\",\"schema\":{\"anyOf\":[{\"$ref\":\"#/x-schemas/Types/ListenResponse\"},{\"type\":\"string\"}]}},\"examples\":[{\"name\":\"Getting the device name\",\"params\":[{\"name\":\"listen\",\"value\":true}],\"result\":{\"name\":\"Default Result\",\"value\":\"Living Room\"}}]},{\"name\":\"Device.provision\",\"summary\":\"Used by a distributor to push provision info to firebolt.\",\"tags\":[{\"name\":\"capabilities\",\"x-manages\":[\"xrn:firebolt:capability:account:id\",\"xrn:firebolt:capability:device:id\",\"xrn:firebolt:capability:device:distributor\"]}],\"params\":[{\"name\":\"accountId\",\"summary\":\"The id of the account that is device is attached to in the back office.\",\"required\":true,\"schema\":{\"type\":\"string\"}},{\"name\":\"deviceId\",\"summary\":\"The id of the device in the back office.\",\"required\":true,\"schema\":{\"type\":\"string\"}},{\"name\":\"distributorId\",\"summary\":\"The id of the distributor in the back office.\",\"schema\":{\"type\":\"string\"}}],\"result\":{\"name\":\"result\",\"schema\":{\"const\":null}},\"examples\":[{\"name\":\"Default Example\",\"params\":[{\"name\":\"accountId\",\"value\":\"12345678910\"},{\"name\":\"deviceId\",\"value\":\"987654321111\"}],\"result\":{\"name\":\"defaultResult\",\"value\":null}},{\"name\":\"With distributor id\",\"params\":[{\"name\":\"accountId\",\"value\":\"12345678910\"},{\"name\":\"deviceId\",\"value\":\"987654321111\"},{\"name\":\"distributorId\",\"value\":\"global_partner\"}],\"result\":{\"name\":\"partnerResult\",\"value\":null}}]},{\"name\":\"Device.onNameChanged\",\"summary\":\"The human readable name of the device\",\"params\":[{\"name\":\"listen\",\"required\":true,\"schema\":{\"type\":\"boolean\"}}],\"tags\":[{\"name\":\"subscriber\",\"x-subscriber-for\":\"Device.name\"},{\"name\":\"event\",\"x-alternative\":\"name\"},{\"name\":\"capabilities\",\"x-uses\":[\"xrn:firebolt:capability:device:name\"]}],\"result\":{\"name\":\"value\",\"summary\":\"the device friendly-name\",\"schema\":{\"anyOf\":[{\"$ref\":\"#/x-schemas/Types/ListenResponse\"},{\"type\":\"string\"}]}},\"examples\":[{\"name\":\"Default example #1\",\"params\":[{\"name\":\"listen\",\"value\":true}],\"result\":{\"name\":\"Default Result\",\"value\":\"Living Room\"}},{\"name\":\"Default example #2\",\"params\":[{\"name\":\"listen\",\"value\":true}],\"result\":{\"name\":\"Default Result\",\"value\":\"Kitchen\"}}]},{\"name\":\"Device.setName\",\"summary\":\"The human readable name of the device\",\"params\":[{\"name\":\"value\",\"summary\":\"the device friendly-name\",\"schema\":{\"type\":\"string\"},\"required\":true}],\"tags\":[{\"name\":\"setter\",\"x-setter-for\":\"name\"},{\"name\":\"capabilities\",\"x-manages\":[\"xrn:firebolt:capability:device:name\"]}],\"result\":{\"name\":\"result\",\"schema\":{\"type\":\"null\"}},\"examples\":[{\"name\":\"Default example #1\",\"params\":[{\"name\":\"value\",\"value\":\"Living Room\"}],\"result\":{\"name\":\"Default Result\",\"value\":null}},{\"name\":\"Default example #2\",\"params\":[{\"name\":\"value\",\"value\":\"Kitchen\"}],\"result\":{\"name\":\"Default Result\",\"value\":null}}]},{\"name\":\"UserGrants.app\",\"summary\":\"Get all granted and denied user grants for the given app\",\"tags\":[{\"name\":\"capabilities\",\"x-uses\":[\"xrn:firebolt:capability:grants:state\"]}],\"params\":[{\"name\":\"appId\",\"schema\":{\"type\":\"string\"},\"required\":true}],\"result\":{\"name\":\"info\",\"summary\":\"The list of grants for this app\",\"schema\":{\"type\":\"array\",\"items\":{\"$ref\":\"#/components/schemas/GrantInfo\"}}},\"examples\":[{\"name\":\"Default Example\",\"params\":[{\"name\":\"appId\",\"value\":\"certapp\"}],\"result\":{\"name\":\"defaultResult\",\"value\":[{\"app\":{\"id\":\"certapp\",\"title\":\"Firebolt Certification\"},\"state\":\"granted\",\"capability\":\"xrn:firebolt:capability:data:app-usage\",\"role\":\"use\",\"lifespan\":\"seconds\",\"expires\":\"2022-12-14T20:20:39+00:00\"},{\"app\":{\"id\":\"certapp\",\"title\":\"Firebolt Certification\"},\"state\":\"denied\",\"capability\":\"xrn:firebolt:capability:localization:postal-code\",\"role\":\"use\",\"lifespan\":\"appActive\"}]}}]},{\"name\":\"UserGrants.device\",\"summary\":\"Get all granted and denied user grants for the device\",\"tags\":[{\"name\":\"capabilities\",\"x-uses\":[\"xrn:firebolt:capability:grants:state\"]}],\"params\":[],\"result\":{\"name\":\"info\",\"summary\":\"The list of grants for the device\",\"schema\":{\"type\":\"array\",\"items\":{\"$ref\":\"#/components/schemas/GrantInfo\"}}},\"examples\":[{\"name\":\"Default Example\",\"params\":[],\"result\":{\"name\":\"defaultResult\",\"value\":[{\"state\":\"granted\",\"capability\":\"xrn:firebolt:capability:localization:postal-code\",\"role\":\"use\",\"lifespan\":\"powerActive\"}]}}]},{\"name\":\"UserGrants.capability\",\"summary\":\"Get all granted and denied user grants for the given capability\",\"tags\":[{\"name\":\"capabilities\",\"x-uses\":[\"xrn:firebolt:capability:grants:state\"]}],\"params\":[{\"name\":\"capability\",\"schema\":{\"$ref\":\"#/x-schemas/Capabilities/Capability\"},\"required\":true}],\"result\":{\"name\":\"info\",\"summary\":\"The list of grants associated with the given capability\",\"schema\":{\"type\":\"array\",\"items\":{\"$ref\":\"#/components/schemas/GrantInfo\"}}},\"examples\":[{\"name\":\"Default Example\",\"params\":[{\"name\":\"capability\",\"value\":\"xrn:firebolt:capability:localization:postal-code\"}],\"result\":{\"name\":\"defaultResult\",\"value\":[{\"state\":\"granted\",\"capability\":\"xrn:firebolt:capability:localization:postal-code\",\"role\":\"use\",\"lifespan\":\"powerActive\"}]}}]},{\"name\":\"UserGrants.grant\",\"summary\":\"Grants a given capability to a specific app, if appropriate. Calling this results in a persisted active grant that lasts for the duration of the grant policy lifespan. \",\"tags\":[{\"name\":\"capabilities\",\"x-manages\":[\"xrn:firebolt:capability:grants:state\"]}],\"params\":[{\"name\":\"role\",\"schema\":{\"$ref\":\"#/x-schemas/Capabilities/Role\"},\"required\":true},{\"name\":\"capability\",\"schema\":{\"$ref\":\"#/x-schemas/Capabilities/Capability\"},\"required\":true},{\"name\":\"options\",\"schema\":{\"$ref\":\"#/components/schemas/GrantModificationOptions\"}}],\"result\":{\"name\":\"result\",\"schema\":{\"const\":null}},\"examples\":[{\"name\":\"Default Example\",\"params\":[{\"name\":\"role\",\"value\":\"use\"},{\"name\":\"capability\",\"value\":\"xrn:firebolt:capability:localization:postal-code\"},{\"name\":\"options\",\"value\":{\"appId\":\"certapp\"}}],\"result\":{\"name\":\"defaultResult\",\"value\":null}}]},{\"name\":\"UserGrants.deny\",\"summary\":\"Denies a given capability, to a specific app if appropriate. Calling this results in a persisted Denied Grant that lasts for the duration of the Grant Policy lifespan. \",\"tags\":[{\"name\":\"capabilities\",\"x-manages\":[\"xrn:firebolt:capability:grants:state\"]}],\"params\":[{\"name\":\"role\",\"schema\":{\"$ref\":\"#/x-schemas/Capabilities/Role\"},\"required\":true},{\"name\":\"capability\",\"schema\":{\"$ref\":\"#/x-schemas/Capabilities/Capability\"},\"required\":true},{\"name\":\"options\",\"schema\":{\"$ref\":\"#/components/schemas/GrantModificationOptions\"}}],\"result\":{\"name\":\"result\",\"schema\":{\"const\":null}},\"examples\":[{\"name\":\"Default Example\",\"params\":[{\"name\":\"role\",\"value\":\"use\"},{\"name\":\"capability\",\"value\":\"xrn:firebolt:capability:localization:postal-code\"},{\"name\":\"options\",\"value\":{\"appId\":\"certapp\"}}],\"result\":{\"name\":\"defaultResult\",\"value\":null}}]},{\"name\":\"UserGrants.clear\",\"summary\":\"Clears the grant for a given capability, to a specific app if appropriate. Calling this results in a persisted Denied Grant that lasts for the duration of the Grant Policy lifespan. \",\"tags\":[{\"name\":\"capabilities\",\"x-manages\":[\"xrn:firebolt:capability:grants:state\"]}],\"params\":[{\"name\":\"role\",\"schema\":{\"$ref\":\"#/x-schemas/Capabilities/Role\"},\"required\":true},{\"name\":\"capability\",\"schema\":{\"$ref\":\"#/x-schemas/Capabilities/Capability\"},\"required\":true},{\"name\":\"options\",\"schema\":{\"$ref\":\"#/components/schemas/GrantModificationOptions\"}}],\"result\":{\"name\":\"result\",\"schema\":{\"const\":null}},\"examples\":[{\"name\":\"Default Example\",\"params\":[{\"name\":\"role\",\"value\":\"use\"},{\"name\":\"capability\",\"value\":\"xrn:firebolt:capability:localization:postal-code\"},{\"name\":\"options\",\"value\":{\"appId\":\"certapp\"}}],\"result\":{\"name\":\"defaultResult\",\"value\":null}}]},{\"name\":\"UserGrants.request\",\"summary\":\"Requests Firebolt to carry out a set of user grants for a given application such that the user grant provider is notified or an existing user grant is reused.\",\"tags\":[{\"name\":\"capabilities\",\"x-manages\":[\"xrn:firebolt:capability:grants:state\"]}],\"params\":[{\"name\":\"appId\",\"schema\":{\"type\":\"string\"},\"required\":true},{\"name\":\"permissions\",\"schema\":{\"type\":\"array\",\"items\":{\"$ref\":\"#/x-schemas/Capabilities/Permission\"},\"minItems\":1},\"required\":true},{\"name\":\"options\",\"summary\":\"Request options\",\"schema\":{\"$ref\":\"#/components/schemas/RequestOptions\"},\"required\":false}],\"result\":{\"name\":\"info\",\"summary\":\"The result of all grants requested by this\",\"schema\":{\"type\":\"array\",\"items\":{\"$ref\":\"#/components/schemas/GrantInfo\"}}},\"examples\":[{\"name\":\"Default result #1\",\"params\":[{\"name\":\"appId\",\"value\":\"certapp\"},{\"name\":\"permissions\",\"value\":[{\"role\":\"use\",\"capability\":\"xrn:firebolt:capability:localization:postal-code\"}]}],\"result\":{\"name\":\"defaultResult\",\"value\":[{\"app\":{\"id\":\"certapp\",\"title\":\"Certification App\"},\"state\":\"granted\",\"capability\":\"xrn:firebolt:capability:localization:postal-code\",\"role\":\"use\",\"lifespan\":\"powerActive\"}]}},{\"name\":\"Default result #2\",\"params\":[{\"name\":\"appId\",\"value\":\"certapp\"},{\"name\":\"permissions\",\"value\":[{\"role\":\"use\",\"capability\":\"xrn:firebolt:capability:localization:postal-code\"}]},{\"name\":\"options\",\"value\":{\"force\":true}}],\"result\":{\"name\":\"defaultResult\",\"value\":[{\"app\":{\"id\":\"certapp\",\"title\":\"Certification App\"},\"state\":\"granted\",\"capability\":\"xrn:firebolt:capability:localization:postal-code\",\"role\":\"use\",\"lifespan\":\"powerActive\"}]}}]},{\"name\":\"Privacy.allowResumePoints\",\"tags\":[{\"name\":\"property\",\"x-allow-value\":true},{\"name\":\"capabilities\",\"x-uses\":[\"xrn:firebolt:capability:privacy:settings\"]}],\"summary\":\"Whether the user allows resume points for content to show in the main experience\",\"params\":[],\"result\":{\"name\":\"allow\",\"schema\":{\"type\":\"boolean\"}},\"examples\":[{\"name\":\"Default example #1\",\"params\":[],\"result\":{\"name\":\"allow\",\"value\":true}},{\"name\":\"Default example #2\",\"params\":[],\"result\":{\"name\":\"allow\",\"value\":false}}]},{\"name\":\"Privacy.allowUnentitledResumePoints\",\"tags\":[{\"name\":\"property\",\"x-allow-value\":true},{\"name\":\"capabilities\",\"x-uses\":[\"xrn:firebolt:capability:privacy:settings\"]}],\"summary\":\"Whether the user allows resume points for content from unentitled providers to show in the main experience\",\"params\":[],\"result\":{\"name\":\"allow\",\"schema\":{\"type\":\"boolean\"}},\"examples\":[{\"name\":\"Default example #1\",\"params\":[],\"result\":{\"name\":\"allow\",\"value\":true}},{\"name\":\"Default example #2\",\"params\":[],\"result\":{\"name\":\"allow\",\"value\":false}}]},{\"name\":\"Privacy.allowWatchHistory\",\"tags\":[{\"name\":\"property\",\"x-allow-value\":true},{\"name\":\"capabilities\",\"x-uses\":[\"xrn:firebolt:capability:privacy:settings\"]}],\"summary\":\"Whether the user allows their watch history from all sources to show in the main experience\",\"params\":[],\"result\":{\"name\":\"allow\",\"schema\":{\"type\":\"boolean\"}},\"examples\":[{\"name\":\"Default example #1\",\"params\":[],\"result\":{\"name\":\"allow\",\"value\":true}},{\"name\":\"Default example #2\",\"params\":[],\"result\":{\"name\":\"allow\",\"value\":false}}]},{\"name\":\"Privacy.allowProductAnalytics\",\"tags\":[{\"name\":\"property\",\"x-allow-value\":true},{\"name\":\"capabilities\",\"x-uses\":[\"xrn:firebolt:capability:privacy:settings\"]}],\"summary\":\"Whether the user allows their usage data can be used for analytics about the product\",\"params\":[],\"result\":{\"name\":\"allow\",\"schema\":{\"type\":\"boolean\"}},\"examples\":[{\"name\":\"Default example #1\",\"params\":[],\"result\":{\"name\":\"allow\",\"value\":true}},{\"name\":\"Default example #2\",\"params\":[],\"result\":{\"name\":\"allow\",\"value\":false}}]},{\"name\":\"Privacy.allowPersonalization\",\"tags\":[{\"name\":\"property\",\"x-allow-value\":true},{\"name\":\"capabilities\",\"x-uses\":[\"xrn:firebolt:capability:privacy:settings\"]}],\"summary\":\"Whether the user allows their usage data to be used for personalization and recommendations\",\"params\":[],\"result\":{\"name\":\"allow\",\"schema\":{\"type\":\"boolean\"}},\"examples\":[{\"name\":\"Default example #1\",\"params\":[],\"result\":{\"name\":\"allow\",\"value\":true}},{\"name\":\"Default example #2\",\"params\":[],\"result\":{\"name\":\"allow\",\"value\":false}}]},{\"name\":\"Privacy.allowUnentitledPersonalization\",\"tags\":[{\"name\":\"property\",\"x-allow-value\":true},{\"name\":\"capabilities\",\"x-uses\":[\"xrn:firebolt:capability:privacy:settings\"]}],\"summary\":\"Whether the user allows their usage data to be used for personalization and recommendations for unentitled content\",\"params\":[],\"result\":{\"name\":\"allow\",\"schema\":{\"type\":\"boolean\"}},\"examples\":[{\"name\":\"Default example #1\",\"params\":[],\"result\":{\"name\":\"allow\",\"value\":true}},{\"name\":\"Default example #2\",\"params\":[],\"result\":{\"name\":\"allow\",\"value\":false}}]},{\"name\":\"Privacy.allowRemoteDiagnostics\",\"tags\":[{\"name\":\"property\",\"x-allow-value\":true},{\"name\":\"capabilities\",\"x-uses\":[\"xrn:firebolt:capability:privacy:settings\"]}],\"summary\":\"Whether the user allows their personal data to be included in diagnostic telemetry. This also allows whether device logs can be remotely accessed from the client device\",\"params\":[],\"result\":{\"name\":\"allow\",\"schema\":{\"type\":\"boolean\"}},\"examples\":[{\"name\":\"Default example #1\",\"params\":[],\"result\":{\"name\":\"allow\",\"value\":true}},{\"name\":\"Default example #2\",\"params\":[],\"result\":{\"name\":\"allow\",\"value\":false}}]},{\"name\":\"Privacy.allowPrimaryContentAdTargeting\",\"tags\":[{\"name\":\"property\",\"x-allow-value\":true},{\"name\":\"capabilities\",\"x-uses\":[\"xrn:firebolt:capability:privacy:settings\"]}],\"summary\":\"Whether the user allows ads to be targeted to the user while watching content in the primary experience\",\"params\":[],\"result\":{\"name\":\"allow\",\"schema\":{\"type\":\"boolean\"}},\"examples\":[{\"name\":\"Default example #1\",\"params\":[],\"result\":{\"name\":\"allow\",\"value\":true}},{\"name\":\"Default example #2\",\"params\":[],\"result\":{\"name\":\"allow\",\"value\":false}}]},{\"name\":\"Privacy.allowPrimaryBrowseAdTargeting\",\"tags\":[{\"name\":\"property\",\"x-allow-value\":true},{\"name\":\"capabilities\",\"x-uses\":[\"xrn:firebolt:capability:privacy:settings\"]}],\"summary\":\"Whether the user allows ads to be targeted to the user while browsing in the primary experience\",\"params\":[],\"result\":{\"name\":\"allow\",\"schema\":{\"type\":\"boolean\"}},\"examples\":[{\"name\":\"Default example #1\",\"params\":[],\"result\":{\"name\":\"allow\",\"value\":true}},{\"name\":\"Default example #2\",\"params\":[],\"result\":{\"name\":\"allow\",\"value\":false}}]},{\"name\":\"Privacy.allowAppContentAdTargeting\",\"tags\":[{\"name\":\"property\",\"x-allow-value\":true},{\"name\":\"capabilities\",\"x-uses\":[\"xrn:firebolt:capability:privacy:settings\"]}],\"summary\":\"Whether the user allows ads to be targeted to the user while watching content in apps\",\"params\":[],\"result\":{\"name\":\"allow\",\"schema\":{\"type\":\"boolean\"}},\"examples\":[{\"name\":\"Default example #1\",\"params\":[],\"result\":{\"name\":\"allow\",\"value\":true}},{\"name\":\"Default example #2\",\"params\":[],\"result\":{\"name\":\"allow\",\"value\":false}}]},{\"name\":\"Privacy.allowACRCollection\",\"tags\":[{\"name\":\"property\",\"x-allow-value\":true},{\"name\":\"capabilities\",\"x-uses\":[\"xrn:firebolt:capability:privacy:settings\"]}],\"summary\":\"Whether the user allows their automatic content recognition data to be collected\",\"params\":[],\"result\":{\"name\":\"allow\",\"schema\":{\"type\":\"boolean\"}},\"examples\":[{\"name\":\"Default example #1\",\"params\":[],\"result\":{\"name\":\"allow\",\"value\":true}},{\"name\":\"Default example #2\",\"params\":[],\"result\":{\"name\":\"allow\",\"value\":false}}]},{\"name\":\"Privacy.allowCameraAnalytics\",\"tags\":[{\"name\":\"property\",\"x-allow-value\":true},{\"name\":\"capabilities\",\"x-uses\":[\"xrn:firebolt:capability:privacy:settings\"]}],\"summary\":\"Whether the user allows data from their camera to be used for Product Analytics\",\"params\":[],\"result\":{\"name\":\"allow\",\"schema\":{\"type\":\"boolean\"}},\"examples\":[{\"name\":\"Default example #1\",\"params\":[],\"result\":{\"name\":\"allow\",\"value\":true}},{\"name\":\"Default example #2\",\"params\":[],\"result\":{\"name\":\"allow\",\"value\":false}}]},{\"name\":\"Privacy.settings\",\"tags\":[{\"name\":\"capabilities\",\"x-uses\":[\"xrn:firebolt:capability:privacy:settings\"]}],\"summary\":\"Gets the allowed value for all privacy settings\",\"params\":[],\"result\":{\"name\":\"settings\",\"schema\":{\"$ref\":\"#/components/schemas/PrivacySettings\"}},\"examples\":[{\"name\":\"Default Example\",\"params\":[],\"result\":{\"name\":\"settings\",\"value\":{\"allowACRCollection\":true,\"allowResumePoints\":false,\"allowAppContentAdTargeting\":false,\"allowCameraAnalytics\":true,\"allowPersonalization\":true,\"allowPrimaryBrowseAdTargeting\":false,\"allowPrimaryContentAdTargeting\":false,\"allowProductAnalytics\":true,\"allowRemoteDiagnostics\":true,\"allowUnentitledPersonalization\":true,\"allowUnentitledResumePoints\":false,\"allowWatchHistory\":true}}}]},{\"name\":\"Privacy.onAllowResumePointsChanged\",\"tags\":[{\"name\":\"subscriber\",\"x-subscriber-for\":\"Privacy.allowResumePoints\"},{\"name\":\"event\",\"x-alternative\":\"allowResumePoints\"},{\"name\":\"capabilities\",\"x-uses\":[\"xrn:firebolt:capability:privacy:settings\"]}],\"summary\":\"Whether the user allows resume points for content to show in the main experience\",\"params\":[{\"name\":\"listen\",\"required\":true,\"schema\":{\"type\":\"boolean\"}}],\"result\":{\"name\":\"allow\",\"schema\":{\"anyOf\":[{\"$ref\":\"#/x-schemas/Types/ListenResponse\"},{\"type\":\"boolean\"}]}},\"examples\":[{\"name\":\"Default example #1\",\"params\":[{\"name\":\"listen\",\"value\":true}],\"result\":{\"name\":\"allow\",\"value\":true}},{\"name\":\"Default example #2\",\"params\":[{\"name\":\"listen\",\"value\":true}],\"result\":{\"name\":\"allow\",\"value\":false}}]},{\"name\":\"Privacy.onAllowUnentitledResumePointsChanged\",\"tags\":[{\"name\":\"subscriber\",\"x-subscriber-for\":\"Privacy.allowUnentitledResumePoints\"},{\"name\":\"event\",\"x-alternative\":\"allowUnentitledResumePoints\"},{\"name\":\"capabilities\",\"x-uses\":[\"xrn:firebolt:capability:privacy:settings\"]}],\"summary\":\"Whether the user allows resume points for content from unentitled providers to show in the main experience\",\"params\":[{\"name\":\"listen\",\"required\":true,\"schema\":{\"type\":\"boolean\"}}],\"result\":{\"name\":\"allow\",\"schema\":{\"anyOf\":[{\"$ref\":\"#/x-schemas/Types/ListenResponse\"},{\"type\":\"boolean\"}]}},\"examples\":[{\"name\":\"Default example #1\",\"params\":[{\"name\":\"listen\",\"value\":true}],\"result\":{\"name\":\"allow\",\"value\":true}},{\"name\":\"Default example #2\",\"params\":[{\"name\":\"listen\",\"value\":true}],\"result\":{\"name\":\"allow\",\"value\":false}}]},{\"name\":\"Privacy.onAllowWatchHistoryChanged\",\"tags\":[{\"name\":\"subscriber\",\"x-subscriber-for\":\"Privacy.allowWatchHistory\"},{\"name\":\"event\",\"x-alternative\":\"allowWatchHistory\"},{\"name\":\"capabilities\",\"x-uses\":[\"xrn:firebolt:capability:privacy:settings\"]}],\"summary\":\"Whether the user allows their watch history from all sources to show in the main experience\",\"params\":[{\"name\":\"listen\",\"required\":true,\"schema\":{\"type\":\"boolean\"}}],\"result\":{\"name\":\"allow\",\"schema\":{\"anyOf\":[{\"$ref\":\"#/x-schemas/Types/ListenResponse\"},{\"type\":\"boolean\"}]}},\"examples\":[{\"name\":\"Default example #1\",\"params\":[{\"name\":\"listen\",\"value\":true}],\"result\":{\"name\":\"allow\",\"value\":true}},{\"name\":\"Default example #2\",\"params\":[{\"name\":\"listen\",\"value\":true}],\"result\":{\"name\":\"allow\",\"value\":false}}]},{\"name\":\"Privacy.onAllowProductAnalyticsChanged\",\"tags\":[{\"name\":\"subscriber\",\"x-subscriber-for\":\"Privacy.allowProductAnalytics\"},{\"name\":\"event\",\"x-alternative\":\"allowProductAnalytics\"},{\"name\":\"capabilities\",\"x-uses\":[\"xrn:firebolt:capability:privacy:settings\"]}],\"summary\":\"Whether the user allows their usage data can be used for analytics about the product\",\"params\":[{\"name\":\"listen\",\"required\":true,\"schema\":{\"type\":\"boolean\"}}],\"result\":{\"name\":\"allow\",\"schema\":{\"anyOf\":[{\"$ref\":\"#/x-schemas/Types/ListenResponse\"},{\"type\":\"boolean\"}]}},\"examples\":[{\"name\":\"Default example #1\",\"params\":[{\"name\":\"listen\",\"value\":true}],\"result\":{\"name\":\"allow\",\"value\":true}},{\"name\":\"Default example #2\",\"params\":[{\"name\":\"listen\",\"value\":true}],\"result\":{\"name\":\"allow\",\"value\":false}}]},{\"name\":\"Privacy.onAllowPersonalizationChanged\",\"tags\":[{\"name\":\"subscriber\",\"x-subscriber-for\":\"Privacy.allowPersonalization\"},{\"name\":\"event\",\"x-alternative\":\"allowPersonalization\"},{\"name\":\"capabilities\",\"x-uses\":[\"xrn:firebolt:capability:privacy:settings\"]}],\"summary\":\"Whether the user allows their usage data to be used for personalization and recommendations\",\"params\":[{\"name\":\"listen\",\"required\":true,\"schema\":{\"type\":\"boolean\"}}],\"result\":{\"name\":\"allow\",\"schema\":{\"anyOf\":[{\"$ref\":\"#/x-schemas/Types/ListenResponse\"},{\"type\":\"boolean\"}]}},\"examples\":[{\"name\":\"Default example #1\",\"params\":[{\"name\":\"listen\",\"value\":true}],\"result\":{\"name\":\"allow\",\"value\":true}},{\"name\":\"Default example #2\",\"params\":[{\"name\":\"listen\",\"value\":true}],\"result\":{\"name\":\"allow\",\"value\":false}}]},{\"name\":\"Privacy.onAllowUnentitledPersonalizationChanged\",\"tags\":[{\"name\":\"subscriber\",\"x-subscriber-for\":\"Privacy.allowUnentitledPersonalization\"},{\"name\":\"event\",\"x-alternative\":\"allowUnentitledPersonalization\"},{\"name\":\"capabilities\",\"x-uses\":[\"xrn:firebolt:capability:privacy:settings\"]}],\"summary\":\"Whether the user allows their usage data to be used for personalization and recommendations for unentitled content\",\"params\":[{\"name\":\"listen\",\"required\":true,\"schema\":{\"type\":\"boolean\"}}],\"result\":{\"name\":\"allow\",\"schema\":{\"anyOf\":[{\"$ref\":\"#/x-schemas/Types/ListenResponse\"},{\"type\":\"boolean\"}]}},\"examples\":[{\"name\":\"Default example #1\",\"params\":[{\"name\":\"listen\",\"value\":true}],\"result\":{\"name\":\"allow\",\"value\":true}},{\"name\":\"Default example #2\",\"params\":[{\"name\":\"listen\",\"value\":true}],\"result\":{\"name\":\"allow\",\"value\":false}}]},{\"name\":\"Privacy.onAllowRemoteDiagnosticsChanged\",\"tags\":[{\"name\":\"subscriber\",\"x-subscriber-for\":\"Privacy.allowRemoteDiagnostics\"},{\"name\":\"event\",\"x-alternative\":\"allowRemoteDiagnostics\"},{\"name\":\"capabilities\",\"x-uses\":[\"xrn:firebolt:capability:privacy:settings\"]}],\"summary\":\"Whether the user allows their personal data to be included in diagnostic telemetry. This also allows whether device logs can be remotely accessed from the client device\",\"params\":[{\"name\":\"listen\",\"required\":true,\"schema\":{\"type\":\"boolean\"}}],\"result\":{\"name\":\"allow\",\"schema\":{\"anyOf\":[{\"$ref\":\"#/x-schemas/Types/ListenResponse\"},{\"type\":\"boolean\"}]}},\"examples\":[{\"name\":\"Default example #1\",\"params\":[{\"name\":\"listen\",\"value\":true}],\"result\":{\"name\":\"allow\",\"value\":true}},{\"name\":\"Default example #2\",\"params\":[{\"name\":\"listen\",\"value\":true}],\"result\":{\"name\":\"allow\",\"value\":false}}]},{\"name\":\"Privacy.onAllowPrimaryContentAdTargetingChanged\",\"tags\":[{\"name\":\"subscriber\",\"x-subscriber-for\":\"Privacy.allowPrimaryContentAdTargeting\"},{\"name\":\"event\",\"x-alternative\":\"allowPrimaryContentAdTargeting\"},{\"name\":\"capabilities\",\"x-uses\":[\"xrn:firebolt:capability:privacy:settings\"]}],\"summary\":\"Whether the user allows ads to be targeted to the user while watching content in the primary experience\",\"params\":[{\"name\":\"listen\",\"required\":true,\"schema\":{\"type\":\"boolean\"}}],\"result\":{\"name\":\"allow\",\"schema\":{\"anyOf\":[{\"$ref\":\"#/x-schemas/Types/ListenResponse\"},{\"type\":\"boolean\"}]}},\"examples\":[{\"name\":\"Default example #1\",\"params\":[{\"name\":\"listen\",\"value\":true}],\"result\":{\"name\":\"allow\",\"value\":true}},{\"name\":\"Default example #2\",\"params\":[{\"name\":\"listen\",\"value\":true}],\"result\":{\"name\":\"allow\",\"value\":false}}]},{\"name\":\"Privacy.onAllowPrimaryBrowseAdTargetingChanged\",\"tags\":[{\"name\":\"subscriber\",\"x-subscriber-for\":\"Privacy.allowPrimaryBrowseAdTargeting\"},{\"name\":\"event\",\"x-alternative\":\"allowPrimaryBrowseAdTargeting\"},{\"name\":\"capabilities\",\"x-uses\":[\"xrn:firebolt:capability:privacy:settings\"]}],\"summary\":\"Whether the user allows ads to be targeted to the user while browsing in the primary experience\",\"params\":[{\"name\":\"listen\",\"required\":true,\"schema\":{\"type\":\"boolean\"}}],\"result\":{\"name\":\"allow\",\"schema\":{\"anyOf\":[{\"$ref\":\"#/x-schemas/Types/ListenResponse\"},{\"type\":\"boolean\"}]}},\"examples\":[{\"name\":\"Default example #1\",\"params\":[{\"name\":\"listen\",\"value\":true}],\"result\":{\"name\":\"allow\",\"value\":true}},{\"name\":\"Default example #2\",\"params\":[{\"name\":\"listen\",\"value\":true}],\"result\":{\"name\":\"allow\",\"value\":false}}]},{\"name\":\"Privacy.onAllowAppContentAdTargetingChanged\",\"tags\":[{\"name\":\"subscriber\",\"x-subscriber-for\":\"Privacy.allowAppContentAdTargeting\"},{\"name\":\"event\",\"x-alternative\":\"allowAppContentAdTargeting\"},{\"name\":\"capabilities\",\"x-uses\":[\"xrn:firebolt:capability:privacy:settings\"]}],\"summary\":\"Whether the user allows ads to be targeted to the user while watching content in apps\",\"params\":[{\"name\":\"listen\",\"required\":true,\"schema\":{\"type\":\"boolean\"}}],\"result\":{\"name\":\"allow\",\"schema\":{\"anyOf\":[{\"$ref\":\"#/x-schemas/Types/ListenResponse\"},{\"type\":\"boolean\"}]}},\"examples\":[{\"name\":\"Default example #1\",\"params\":[{\"name\":\"listen\",\"value\":true}],\"result\":{\"name\":\"allow\",\"value\":true}},{\"name\":\"Default example #2\",\"params\":[{\"name\":\"listen\",\"value\":true}],\"result\":{\"name\":\"allow\",\"value\":false}}]},{\"name\":\"Privacy.onAllowACRCollectionChanged\",\"tags\":[{\"name\":\"subscriber\",\"x-subscriber-for\":\"Privacy.allowACRCollection\"},{\"name\":\"event\",\"x-alternative\":\"allowACRCollection\"},{\"name\":\"capabilities\",\"x-uses\":[\"xrn:firebolt:capability:privacy:settings\"]}],\"summary\":\"Whether the user allows their automatic content recognition data to be collected\",\"params\":[{\"name\":\"listen\",\"required\":true,\"schema\":{\"type\":\"boolean\"}}],\"result\":{\"name\":\"allow\",\"schema\":{\"anyOf\":[{\"$ref\":\"#/x-schemas/Types/ListenResponse\"},{\"type\":\"boolean\"}]}},\"examples\":[{\"name\":\"Default example #1\",\"params\":[{\"name\":\"listen\",\"value\":true}],\"result\":{\"name\":\"allow\",\"value\":true}},{\"name\":\"Default example #2\",\"params\":[{\"name\":\"listen\",\"value\":true}],\"result\":{\"name\":\"allow\",\"value\":false}}]},{\"name\":\"Privacy.onAllowCameraAnalyticsChanged\",\"tags\":[{\"name\":\"subscriber\",\"x-subscriber-for\":\"Privacy.allowCameraAnalytics\"},{\"name\":\"event\",\"x-alternative\":\"allowCameraAnalytics\"},{\"name\":\"capabilities\",\"x-uses\":[\"xrn:firebolt:capability:privacy:settings\"]}],\"summary\":\"Whether the user allows data from their camera to be used for Product Analytics\",\"params\":[{\"name\":\"listen\",\"required\":true,\"schema\":{\"type\":\"boolean\"}}],\"result\":{\"name\":\"allow\",\"schema\":{\"anyOf\":[{\"$ref\":\"#/x-schemas/Types/ListenResponse\"},{\"type\":\"boolean\"}]}},\"examples\":[{\"name\":\"Default example #1\",\"params\":[{\"name\":\"listen\",\"value\":true}],\"result\":{\"name\":\"allow\",\"value\":true}},{\"name\":\"Default example #2\",\"params\":[{\"name\":\"listen\",\"value\":true}],\"result\":{\"name\":\"allow\",\"value\":false}}]},{\"name\":\"Privacy.setAllowResumePoints\",\"tags\":[{\"name\":\"setter\",\"x-setter-for\":\"allowResumePoints\"},{\"name\":\"capabilities\",\"x-manages\":[\"xrn:firebolt:capability:privacy:settings\"]}],\"summary\":\"Whether the user allows resume points for content to show in the main experience\",\"params\":[{\"name\":\"value\",\"schema\":{\"type\":\"boolean\"},\"required\":true}],\"result\":{\"name\":\"result\",\"schema\":{\"type\":\"null\"}},\"examples\":[{\"name\":\"Default example #1\",\"params\":[{\"name\":\"value\",\"value\":true}],\"result\":{\"name\":\"allow\",\"value\":null}},{\"name\":\"Default example #2\",\"params\":[{\"name\":\"value\",\"value\":false}],\"result\":{\"name\":\"allow\",\"value\":null}}]},{\"name\":\"Privacy.setAllowUnentitledResumePoints\",\"tags\":[{\"name\":\"setter\",\"x-setter-for\":\"allowUnentitledResumePoints\"},{\"name\":\"capabilities\",\"x-manages\":[\"xrn:firebolt:capability:privacy:settings\"]}],\"summary\":\"Whether the user allows resume points for content from unentitled providers to show in the main experience\",\"params\":[{\"name\":\"value\",\"schema\":{\"type\":\"boolean\"},\"required\":true}],\"result\":{\"name\":\"result\",\"schema\":{\"type\":\"null\"}},\"examples\":[{\"name\":\"Default example #1\",\"params\":[{\"name\":\"value\",\"value\":true}],\"result\":{\"name\":\"allow\",\"value\":null}},{\"name\":\"Default example #2\",\"params\":[{\"name\":\"value\",\"value\":false}],\"result\":{\"name\":\"allow\",\"value\":null}}]},{\"name\":\"Privacy.setAllowWatchHistory\",\"tags\":[{\"name\":\"setter\",\"x-setter-for\":\"allowWatchHistory\"},{\"name\":\"capabilities\",\"x-manages\":[\"xrn:firebolt:capability:privacy:settings\"]}],\"summary\":\"Whether the user allows their watch history from all sources to show in the main experience\",\"params\":[{\"name\":\"value\",\"schema\":{\"type\":\"boolean\"},\"required\":true}],\"result\":{\"name\":\"result\",\"schema\":{\"type\":\"null\"}},\"examples\":[{\"name\":\"Default example #1\",\"params\":[{\"name\":\"value\",\"value\":true}],\"result\":{\"name\":\"allow\",\"value\":null}},{\"name\":\"Default example #2\",\"params\":[{\"name\":\"value\",\"value\":false}],\"result\":{\"name\":\"allow\",\"value\":null}}]},{\"name\":\"Privacy.setAllowProductAnalytics\",\"tags\":[{\"name\":\"setter\",\"x-setter-for\":\"allowProductAnalytics\"},{\"name\":\"capabilities\",\"x-manages\":[\"xrn:firebolt:capability:privacy:settings\"]}],\"summary\":\"Whether the user allows their usage data can be used for analytics about the product\",\"params\":[{\"name\":\"value\",\"schema\":{\"type\":\"boolean\"},\"required\":true}],\"result\":{\"name\":\"result\",\"schema\":{\"type\":\"null\"}},\"examples\":[{\"name\":\"Default example #1\",\"params\":[{\"name\":\"value\",\"value\":true}],\"result\":{\"name\":\"allow\",\"value\":null}},{\"name\":\"Default example #2\",\"params\":[{\"name\":\"value\",\"value\":false}],\"result\":{\"name\":\"allow\",\"value\":null}}]},{\"name\":\"Privacy.setAllowPersonalization\",\"tags\":[{\"name\":\"setter\",\"x-setter-for\":\"allowPersonalization\"},{\"name\":\"capabilities\",\"x-manages\":[\"xrn:firebolt:capability:privacy:settings\"]}],\"summary\":\"Whether the user allows their usage data to be used for personalization and recommendations\",\"params\":[{\"name\":\"value\",\"schema\":{\"type\":\"boolean\"},\"required\":true}],\"result\":{\"name\":\"result\",\"schema\":{\"type\":\"null\"}},\"examples\":[{\"name\":\"Default example #1\",\"params\":[{\"name\":\"value\",\"value\":true}],\"result\":{\"name\":\"allow\",\"value\":null}},{\"name\":\"Default example #2\",\"params\":[{\"name\":\"value\",\"value\":false}],\"result\":{\"name\":\"allow\",\"value\":null}}]},{\"name\":\"Privacy.setAllowUnentitledPersonalization\",\"tags\":[{\"name\":\"setter\",\"x-setter-for\":\"allowUnentitledPersonalization\"},{\"name\":\"capabilities\",\"x-manages\":[\"xrn:firebolt:capability:privacy:settings\"]}],\"summary\":\"Whether the user allows their usage data to be used for personalization and recommendations for unentitled content\",\"params\":[{\"name\":\"value\",\"schema\":{\"type\":\"boolean\"},\"required\":true}],\"result\":{\"name\":\"result\",\"schema\":{\"type\":\"null\"}},\"examples\":[{\"name\":\"Default example #1\",\"params\":[{\"name\":\"value\",\"value\":true}],\"result\":{\"name\":\"allow\",\"value\":null}},{\"name\":\"Default example #2\",\"params\":[{\"name\":\"value\",\"value\":false}],\"result\":{\"name\":\"allow\",\"value\":null}}]},{\"name\":\"Privacy.setAllowRemoteDiagnostics\",\"tags\":[{\"name\":\"setter\",\"x-setter-for\":\"allowRemoteDiagnostics\"},{\"name\":\"capabilities\",\"x-manages\":[\"xrn:firebolt:capability:privacy:settings\"]}],\"summary\":\"Whether the user allows their personal data to be included in diagnostic telemetry. This also allows whether device logs can be remotely accessed from the client device\",\"params\":[{\"name\":\"value\",\"schema\":{\"type\":\"boolean\"},\"required\":true}],\"result\":{\"name\":\"result\",\"schema\":{\"type\":\"null\"}},\"examples\":[{\"name\":\"Default example #1\",\"params\":[{\"name\":\"value\",\"value\":true}],\"result\":{\"name\":\"allow\",\"value\":null}},{\"name\":\"Default example #2\",\"params\":[{\"name\":\"value\",\"value\":false}],\"result\":{\"name\":\"allow\",\"value\":null}}]},{\"name\":\"Privacy.setAllowPrimaryContentAdTargeting\",\"tags\":[{\"name\":\"setter\",\"x-setter-for\":\"allowPrimaryContentAdTargeting\"},{\"name\":\"capabilities\",\"x-manages\":[\"xrn:firebolt:capability:privacy:settings\"]}],\"summary\":\"Whether the user allows ads to be targeted to the user while watching content in the primary experience\",\"params\":[{\"name\":\"value\",\"schema\":{\"type\":\"boolean\"},\"required\":true}],\"result\":{\"name\":\"result\",\"schema\":{\"type\":\"null\"}},\"examples\":[{\"name\":\"Default example #1\",\"params\":[{\"name\":\"value\",\"value\":true}],\"result\":{\"name\":\"allow\",\"value\":null}},{\"name\":\"Default example #2\",\"params\":[{\"name\":\"value\",\"value\":false}],\"result\":{\"name\":\"allow\",\"value\":null}}]},{\"name\":\"Privacy.setAllowPrimaryBrowseAdTargeting\",\"tags\":[{\"name\":\"setter\",\"x-setter-for\":\"allowPrimaryBrowseAdTargeting\"},{\"name\":\"capabilities\",\"x-manages\":[\"xrn:firebolt:capability:privacy:settings\"]}],\"summary\":\"Whether the user allows ads to be targeted to the user while browsing in the primary experience\",\"params\":[{\"name\":\"value\",\"schema\":{\"type\":\"boolean\"},\"required\":true}],\"result\":{\"name\":\"result\",\"schema\":{\"type\":\"null\"}},\"examples\":[{\"name\":\"Default example #1\",\"params\":[{\"name\":\"value\",\"value\":true}],\"result\":{\"name\":\"allow\",\"value\":null}},{\"name\":\"Default example #2\",\"params\":[{\"name\":\"value\",\"value\":false}],\"result\":{\"name\":\"allow\",\"value\":null}}]},{\"name\":\"Privacy.setAllowAppContentAdTargeting\",\"tags\":[{\"name\":\"setter\",\"x-setter-for\":\"allowAppContentAdTargeting\"},{\"name\":\"capabilities\",\"x-manages\":[\"xrn:firebolt:capability:privacy:settings\"]}],\"summary\":\"Whether the user allows ads to be targeted to the user while watching content in apps\",\"params\":[{\"name\":\"value\",\"schema\":{\"type\":\"boolean\"},\"required\":true}],\"result\":{\"name\":\"result\",\"schema\":{\"type\":\"null\"}},\"examples\":[{\"name\":\"Default example #1\",\"params\":[{\"name\":\"value\",\"value\":true}],\"result\":{\"name\":\"allow\",\"value\":null}},{\"name\":\"Default example #2\",\"params\":[{\"name\":\"value\",\"value\":false}],\"result\":{\"name\":\"allow\",\"value\":null}}]},{\"name\":\"Privacy.setAllowACRCollection\",\"tags\":[{\"name\":\"setter\",\"x-setter-for\":\"allowACRCollection\"},{\"name\":\"capabilities\",\"x-manages\":[\"xrn:firebolt:capability:privacy:settings\"]}],\"summary\":\"Whether the user allows their automatic content recognition data to be collected\",\"params\":[{\"name\":\"value\",\"schema\":{\"type\":\"boolean\"},\"required\":true}],\"result\":{\"name\":\"result\",\"schema\":{\"type\":\"null\"}},\"examples\":[{\"name\":\"Default example #1\",\"params\":[{\"name\":\"value\",\"value\":true}],\"result\":{\"name\":\"allow\",\"value\":null}},{\"name\":\"Default example #2\",\"params\":[{\"name\":\"value\",\"value\":false}],\"result\":{\"name\":\"allow\",\"value\":null}}]},{\"name\":\"Privacy.setAllowCameraAnalytics\",\"tags\":[{\"name\":\"setter\",\"x-setter-for\":\"allowCameraAnalytics\"},{\"name\":\"capabilities\",\"x-manages\":[\"xrn:firebolt:capability:privacy:settings\"]}],\"summary\":\"Whether the user allows data from their camera to be used for Product Analytics\",\"params\":[{\"name\":\"value\",\"schema\":{\"type\":\"boolean\"},\"required\":true}],\"result\":{\"name\":\"result\",\"schema\":{\"type\":\"null\"}},\"examples\":[{\"name\":\"Default example #1\",\"params\":[{\"name\":\"value\",\"value\":true}],\"result\":{\"name\":\"allow\",\"value\":null}},{\"name\":\"Default example #2\",\"params\":[{\"name\":\"value\",\"value\":false}],\"result\":{\"name\":\"allow\",\"value\":null}}]},{\"name\":\"Advertising.skipRestriction\",\"summary\":\"Set the value for AdPolicy.skipRestriction\",\"tags\":[{\"name\":\"property\"},{\"name\":\"capabilities\",\"x-manages\":[\"xrn:firebolt:capability:advertising:configuration\"]}],\"params\":[],\"result\":{\"name\":\"result\",\"schema\":{\"$ref\":\"#/x-schemas/Advertising/SkipRestriction\"}},\"examples\":[{\"name\":\"Default Example\",\"params\":[],\"result\":{\"name\":\"result\",\"value\":\"none\"}},{\"name\":\"Additional Example\",\"params\":[],\"result\":{\"name\":\"result\",\"value\":\"all\"}}]},{\"name\":\"Advertising.resetIdentifier\",\"summary\":\"Resets a user's identifier in the ad platform so that the advertising id that apps get will be a new value\",\"tags\":[{\"name\":\"capabilities\",\"x-manages\":[\"xrn:firebolt:capability:advertising:identifier\"]}],\"params\":[],\"result\":{\"name\":\"result\",\"schema\":{\"const\":null}},\"examples\":[{\"name\":\"Default Example\",\"params\":[],\"result\":{\"name\":\"defaultResult\",\"value\":null}}]},{\"name\":\"Advertising.onSkipRestrictionChanged\",\"summary\":\"Set the value for AdPolicy.skipRestriction\",\"tags\":[{\"name\":\"subscriber\",\"x-subscriber-for\":\"Advertising.skipRestriction\"},{\"name\":\"event\",\"x-alternative\":\"skipRestriction\"},{\"name\":\"capabilities\",\"x-manages\":[\"xrn:firebolt:capability:advertising:configuration\"]}],\"params\":[{\"name\":\"listen\",\"required\":true,\"schema\":{\"type\":\"boolean\"}}],\"result\":{\"name\":\"result\",\"schema\":{\"anyOf\":[{\"$ref\":\"#/x-schemas/Types/ListenResponse\"},{\"$ref\":\"#/x-schemas/Advertising/SkipRestriction\"}]}},\"examples\":[{\"name\":\"Default Example\",\"params\":[{\"name\":\"listen\",\"value\":true}],\"result\":{\"name\":\"result\",\"value\":\"none\"}},{\"name\":\"Additional Example\",\"params\":[{\"name\":\"listen\",\"value\":true}],\"result\":{\"name\":\"result\",\"value\":\"all\"}}]},{\"name\":\"Advertising.setSkipRestriction\",\"summary\":\"Set the value for AdPolicy.skipRestriction\",\"tags\":[{\"name\":\"setter\",\"x-setter-for\":\"skipRestriction\"},{\"name\":\"capabilities\",\"x-manages\":[\"xrn:firebolt:capability:advertising:configuration\"]}],\"params\":[{\"name\":\"value\",\"schema\":{\"$ref\":\"#/x-schemas/Advertising/SkipRestriction\"},\"required\":true}],\"result\":{\"name\":\"result\",\"schema\":{\"type\":\"null\"}},\"examples\":[{\"name\":\"Default Example\",\"params\":[{\"name\":\"value\",\"value\":\"none\"}],\"result\":{\"name\":\"result\",\"value\":null}},{\"name\":\"Additional Example\",\"params\":[{\"name\":\"value\",\"value\":\"all\"}],\"result\":{\"name\":\"result\",\"value\":null}}]},{\"name\":\"Account.session\",\"summary\":\"Used by a distributor to push Session token to firebolt.\",\"tags\":[{\"name\":\"capabilities\",\"x-manages\":[\"xrn:firebolt:capability:token:account\"]}],\"params\":[{\"name\":\"token\",\"required\":true,\"schema\":{\"$ref\":\"#/components/schemas/Token\"}},{\"name\":\"expiresIn\",\"required\":true,\"schema\":{\"$ref\":\"#/components/schemas/Expiry\"}}],\"result\":{\"name\":\"result\",\"schema\":{\"const\":null}},\"examples\":[{\"name\":\"Default Example\",\"params\":[{\"name\":\"token\",\"value\":\"RmlyZWJvbHQgTWFuYWdlIFNESyBSb2NrcyEhIQ==\"},{\"name\":\"expiresIn\",\"value\":84000}],\"result\":{\"name\":\"defaultResult\",\"value\":null}}]},{\"name\":\"Keyboard.onRequestStandard\",\"summary\":\"Registers as a provider for when the user should be shown a standard keyboard.\",\"params\":[{\"name\":\"listen\",\"required\":true,\"schema\":{\"type\":\"boolean\"}}],\"tags\":[{\"name\":\"rpc-only\"},{\"name\":\"event\",\"x-response\":{\"type\":\"string\",\"examples\":[\"username\"]},\"x-error\":{\"type\":\"object\",\"additionalProperties\":false,\"required\":[\"code\",\"message\"],\"properties\":{\"code\":{\"title\":\"errorObjectCode\",\"description\":\"A Number that indicates the error type that occurred. This MUST be an integer. The error codes from and including -32768 to -32000 are reserved for pre-defined errors. These pre-defined errors SHOULD be assumed to be returned from any JSON-RPC api.\",\"type\":\"integer\"},\"message\":{\"title\":\"errorObjectMessage\",\"description\":\"A String providing a short description of the error. The message SHOULD be limited to a concise single sentence.\",\"type\":\"string\"},\"data\":{\"title\":\"errorObjectData\",\"description\":\"A Primitive or Structured value that contains additional information about the error. This may be omitted. The value of this member is defined by the Server (e.g. detailed error information, nested errors etc.).\"}}}},{\"name\":\"capabilities\",\"x-provides\":\"xrn:firebolt:capability:input:keyboard\",\"x-allow-focus\":true}],\"result\":{\"name\":\"sessionRequest\",\"summary\":\"The request to start a keyboard session\",\"schema\":{\"anyOf\":[{\"$ref\":\"#/x-schemas/Types/ListenResponse\"},{\"$ref\":\"#/components/schemas/KeyboardProviderRequest\"}]}},\"examples\":[{\"name\":\"Default Example\",\"params\":[{\"name\":\"listen\",\"value\":true}],\"result\":{\"name\":\"Default Result\",\"value\":{\"correlationId\":\"abc\",\"parameters\":{\"message\":\"Enter your user name.\"}}}}]},{\"name\":\"Keyboard.onRequestPassword\",\"summary\":\"Registers as a provider for when the user should be shown a password keyboard, with dots for each character entered.\",\"params\":[{\"name\":\"listen\",\"required\":true,\"schema\":{\"type\":\"boolean\"}}],\"tags\":[{\"name\":\"rpc-only\"},{\"name\":\"event\",\"x-response\":{\"type\":\"string\",\"examples\":[\"password\"]},\"x-error\":{\"type\":\"object\",\"additionalProperties\":false,\"required\":[\"code\",\"message\"],\"properties\":{\"code\":{\"title\":\"errorObjectCode\",\"description\":\"A Number that indicates the error type that occurred. This MUST be an integer. The error codes from and including -32768 to -32000 are reserved for pre-defined errors. These pre-defined errors SHOULD be assumed to be returned from any JSON-RPC api.\",\"type\":\"integer\"},\"message\":{\"title\":\"errorObjectMessage\",\"description\":\"A String providing a short description of the error. The message SHOULD be limited to a concise single sentence.\",\"type\":\"string\"},\"data\":{\"title\":\"errorObjectData\",\"description\":\"A Primitive or Structured value that contains additional information about the error. This may be omitted. The value of this member is defined by the Server (e.g. detailed error information, nested errors etc.).\"}}}},{\"name\":\"capabilities\",\"x-provides\":\"xrn:firebolt:capability:input:keyboard\",\"x-allow-focus\":true}],\"result\":{\"name\":\"sessionRequest\",\"summary\":\"The request to start a keyboard session\",\"schema\":{\"anyOf\":[{\"$ref\":\"#/x-schemas/Types/ListenResponse\"},{\"$ref\":\"#/components/schemas/KeyboardProviderRequest\"}]}},\"examples\":[{\"name\":\"Default Example\",\"params\":[{\"name\":\"listen\",\"value\":true}],\"result\":{\"name\":\"Default Result\",\"value\":{\"correlationId\":\"abc\",\"parameters\":{\"message\":\"Enter your user name.\"}}}}]},{\"name\":\"Keyboard.onRequestEmail\",\"summary\":\"Registers as a provider for when the user should be shown a keyboard optimized for email address entry.\",\"params\":[{\"name\":\"listen\",\"required\":true,\"schema\":{\"type\":\"boolean\"}}],\"tags\":[{\"name\":\"rpc-only\"},{\"name\":\"event\",\"x-response\":{\"type\":\"string\",\"examples\":[\"email@address.com\"]},\"x-error\":{\"type\":\"object\",\"additionalProperties\":false,\"required\":[\"code\",\"message\"],\"properties\":{\"code\":{\"title\":\"errorObjectCode\",\"description\":\"A Number that indicates the error type that occurred. This MUST be an integer. The error codes from and including -32768 to -32000 are reserved for pre-defined errors. These pre-defined errors SHOULD be assumed to be returned from any JSON-RPC api.\",\"type\":\"integer\"},\"message\":{\"title\":\"errorObjectMessage\",\"description\":\"A String providing a short description of the error. The message SHOULD be limited to a concise single sentence.\",\"type\":\"string\"},\"data\":{\"title\":\"errorObjectData\",\"description\":\"A Primitive or Structured value that contains additional information about the error. This may be omitted. The value of this member is defined by the Server (e.g. detailed error information, nested errors etc.).\"}}}},{\"name\":\"capabilities\",\"x-provides\":\"xrn:firebolt:capability:input:keyboard\",\"x-allow-focus\":true}],\"result\":{\"name\":\"sessionRequest\",\"summary\":\"The request to start a keyboard session\",\"schema\":{\"anyOf\":[{\"$ref\":\"#/x-schemas/Types/ListenResponse\"},{\"$ref\":\"#/components/schemas/KeyboardProviderRequest\"}]}},\"examples\":[{\"name\":\"Default Example\",\"params\":[{\"name\":\"listen\",\"value\":true}],\"result\":{\"name\":\"Default Result\",\"value\":{\"correlationId\":\"abc\",\"parameters\":{\"message\":\"Enter your user name.\"}}}}]},{\"name\":\"Keyboard.standardFocus\",\"summary\":\"Internal API for Standard Provider to request focus for UX purposes.\",\"params\":[],\"tags\":[{\"name\":\"rpc-only\"},{\"name\":\"capabilities\",\"x-provides\":\"xrn:firebolt:capability:input:keyboard\",\"x-allow-focus\":true,\"x-allow-focus-for\":\"onRequestStandard\"}],\"result\":{\"name\":\"result\",\"schema\":{\"type\":\"null\"}},\"examples\":[{\"name\":\"Example\",\"params\":[],\"result\":{\"name\":\"result\",\"value\":null}}]},{\"name\":\"Keyboard.passwordFocus\",\"summary\":\"Internal API for Password Provider to request focus for UX purposes.\",\"params\":[],\"tags\":[{\"name\":\"rpc-only\"},{\"name\":\"capabilities\",\"x-provides\":\"xrn:firebolt:capability:input:keyboard\",\"x-allow-focus\":true,\"x-allow-focus-for\":\"onRequestPassword\"}],\"result\":{\"name\":\"result\",\"schema\":{\"type\":\"null\"}},\"examples\":[{\"name\":\"Example\",\"params\":[],\"result\":{\"name\":\"result\",\"value\":null}}]},{\"name\":\"Keyboard.emailFocus\",\"summary\":\"Internal API for Email Provider to request focus for UX purposes.\",\"params\":[],\"tags\":[{\"name\":\"rpc-only\"},{\"name\":\"capabilities\",\"x-provides\":\"xrn:firebolt:capability:input:keyboard\",\"x-allow-focus\":true,\"x-allow-focus-for\":\"onRequestEmail\"}],\"result\":{\"name\":\"result\",\"schema\":{\"type\":\"null\"}},\"examples\":[{\"name\":\"Example\",\"params\":[],\"result\":{\"name\":\"result\",\"value\":null}}]},{\"name\":\"Keyboard.standardResponse\",\"summary\":\"Internal API for Standard Provider to send back response.\",\"params\":[{\"name\":\"correlationId\",\"schema\":{\"type\":\"string\"},\"required\":true},{\"name\":\"result\",\"schema\":{\"type\":\"string\",\"examples\":[\"username\"]},\"required\":true}],\"tags\":[{\"name\":\"rpc-only\"},{\"name\":\"capabilities\",\"x-provides\":\"xrn:firebolt:capability:input:keyboard\",\"x-allow-focus\":true,\"x-response-for\":\"onRequestStandard\"}],\"result\":{\"name\":\"result\",\"schema\":{\"type\":\"null\"}},\"examples\":[{\"name\":\"Example\",\"params\":[{\"name\":\"correlationId\",\"value\":\"123\"},{\"name\":\"result\",\"value\":\"username\"}],\"result\":{\"name\":\"result\",\"value\":null}}]},{\"name\":\"Keyboard.standardError\",\"summary\":\"Internal API for Standard Provider to send back error.\",\"params\":[{\"name\":\"correlationId\",\"schema\":{\"type\":\"string\"},\"required\":true},{\"name\":\"error\",\"schema\":{\"type\":\"object\",\"additionalProperties\":false,\"required\":[\"code\",\"message\"],\"properties\":{\"code\":{\"title\":\"errorObjectCode\",\"description\":\"A Number that indicates the error type that occurred. This MUST be an integer. The error codes from and including -32768 to -32000 are reserved for pre-defined errors. These pre-defined errors SHOULD be assumed to be returned from any JSON-RPC api.\",\"type\":\"integer\"},\"message\":{\"title\":\"errorObjectMessage\",\"description\":\"A String providing a short description of the error. The message SHOULD be limited to a concise single sentence.\",\"type\":\"string\"},\"data\":{\"title\":\"errorObjectData\",\"description\":\"A Primitive or Structured value that contains additional information about the error. This may be omitted. The value of this member is defined by the Server (e.g. detailed error information, nested errors etc.).\"}}},\"required\":true}],\"tags\":[{\"name\":\"rpc-only\"},{\"name\":\"capabilities\",\"x-provides\":\"xrn:firebolt:capability:input:keyboard\",\"x-allow-focus\":true,\"x-error-for\":\"onRequestStandard\"}],\"result\":{\"name\":\"result\",\"schema\":{\"type\":\"null\"}},\"examples\":[{\"name\":\"Example 1\",\"params\":[{\"name\":\"correlationId\",\"value\":\"123\"},{\"name\":\"error\",\"value\":{\"code\":1,\"message\":\"Error\"}}],\"result\":{\"name\":\"result\",\"value\":null}}]},{\"name\":\"Keyboard.passwordResponse\",\"summary\":\"Internal API for Password Provider to send back response.\",\"params\":[{\"name\":\"correlationId\",\"schema\":{\"type\":\"string\"},\"required\":true},{\"name\":\"result\",\"schema\":{\"type\":\"string\",\"examples\":[\"password\"]},\"required\":true}],\"tags\":[{\"name\":\"rpc-only\"},{\"name\":\"capabilities\",\"x-provides\":\"xrn:firebolt:capability:input:keyboard\",\"x-allow-focus\":true,\"x-response-for\":\"onRequestPassword\"}],\"result\":{\"name\":\"result\",\"schema\":{\"type\":\"null\"}},\"examples\":[{\"name\":\"Example\",\"params\":[{\"name\":\"correlationId\",\"value\":\"123\"},{\"name\":\"result\",\"value\":\"password\"}],\"result\":{\"name\":\"result\",\"value\":null}}]},{\"name\":\"Keyboard.passwordError\",\"summary\":\"Internal API for Password Provider to send back error.\",\"params\":[{\"name\":\"correlationId\",\"schema\":{\"type\":\"string\"},\"required\":true},{\"name\":\"error\",\"schema\":{\"type\":\"object\",\"additionalProperties\":false,\"required\":[\"code\",\"message\"],\"properties\":{\"code\":{\"title\":\"errorObjectCode\",\"description\":\"A Number that indicates the error type that occurred. This MUST be an integer. The error codes from and including -32768 to -32000 are reserved for pre-defined errors. These pre-defined errors SHOULD be assumed to be returned from any JSON-RPC api.\",\"type\":\"integer\"},\"message\":{\"title\":\"errorObjectMessage\",\"description\":\"A String providing a short description of the error. The message SHOULD be limited to a concise single sentence.\",\"type\":\"string\"},\"data\":{\"title\":\"errorObjectData\",\"description\":\"A Primitive or Structured value that contains additional information about the error. This may be omitted. The value of this member is defined by the Server (e.g. detailed error information, nested errors etc.).\"}}},\"required\":true}],\"tags\":[{\"name\":\"rpc-only\"},{\"name\":\"capabilities\",\"x-provides\":\"xrn:firebolt:capability:input:keyboard\",\"x-allow-focus\":true,\"x-error-for\":\"onRequestPassword\"}],\"result\":{\"name\":\"result\",\"schema\":{\"type\":\"null\"}},\"examples\":[{\"name\":\"Example 1\",\"params\":[{\"name\":\"correlationId\",\"value\":\"123\"},{\"name\":\"error\",\"value\":{\"code\":1,\"message\":\"Error\"}}],\"result\":{\"name\":\"result\",\"value\":null}}]},{\"name\":\"Keyboard.emailResponse\",\"summary\":\"Internal API for Email Provider to send back response.\",\"params\":[{\"name\":\"correlationId\",\"schema\":{\"type\":\"string\"},\"required\":true},{\"name\":\"result\",\"schema\":{\"type\":\"string\",\"examples\":[\"email@address.com\"]},\"required\":true}],\"tags\":[{\"name\":\"rpc-only\"},{\"name\":\"capabilities\",\"x-provides\":\"xrn:firebolt:capability:input:keyboard\",\"x-allow-focus\":true,\"x-response-for\":\"onRequestEmail\"}],\"result\":{\"name\":\"result\",\"schema\":{\"type\":\"null\"}},\"examples\":[{\"name\":\"Example\",\"params\":[{\"name\":\"correlationId\",\"value\":\"123\"},{\"name\":\"result\",\"value\":\"email@address.com\"}],\"result\":{\"name\":\"result\",\"value\":null}}]},{\"name\":\"Keyboard.emailError\",\"summary\":\"Internal API for Email Provider to send back error.\",\"params\":[{\"name\":\"correlationId\",\"schema\":{\"type\":\"string\"},\"required\":true},{\"name\":\"error\",\"schema\":{\"type\":\"object\",\"additionalProperties\":false,\"required\":[\"code\",\"message\"],\"properties\":{\"code\":{\"title\":\"errorObjectCode\",\"description\":\"A Number that indicates the error type that occurred. This MUST be an integer. The error codes from and including -32768 to -32000 are reserved for pre-defined errors. These pre-defined errors SHOULD be assumed to be returned from any JSON-RPC api.\",\"type\":\"integer\"},\"message\":{\"title\":\"errorObjectMessage\",\"description\":\"A String providing a short description of the error. The message SHOULD be limited to a concise single sentence.\",\"type\":\"string\"},\"data\":{\"title\":\"errorObjectData\",\"description\":\"A Primitive or Structured value that contains additional information about the error. This may be omitted. The value of this member is defined by the Server (e.g. detailed error information, nested errors etc.).\"}}},\"required\":true}],\"tags\":[{\"name\":\"rpc-only\"},{\"name\":\"capabilities\",\"x-provides\":\"xrn:firebolt:capability:input:keyboard\",\"x-allow-focus\":true,\"x-error-for\":\"onRequestEmail\"}],\"result\":{\"name\":\"result\",\"schema\":{\"type\":\"null\"}},\"examples\":[{\"name\":\"Example 1\",\"params\":[{\"name\":\"correlationId\",\"value\":\"123\"},{\"name\":\"error\",\"value\":{\"code\":1,\"message\":\"Error\"}}],\"result\":{\"name\":\"result\",\"value\":null}}]},{\"name\":\"AcknowledgeChallenge.onRequestChallenge\",\"summary\":\"Registers as a provider for when the user should be challenged in order to confirm access to a capability\",\"params\":[{\"name\":\"listen\",\"required\":true,\"schema\":{\"type\":\"boolean\"}}],\"tags\":[{\"name\":\"rpc-only\"},{\"name\":\"event\",\"x-response\":{\"$ref\":\"#/components/schemas/GrantResult\"},\"x-error\":{\"type\":\"object\",\"additionalProperties\":false,\"required\":[\"code\",\"message\"],\"properties\":{\"code\":{\"title\":\"errorObjectCode\",\"description\":\"A Number that indicates the error type that occurred. This MUST be an integer. The error codes from and including -32768 to -32000 are reserved for pre-defined errors. These pre-defined errors SHOULD be assumed to be returned from any JSON-RPC api.\",\"type\":\"integer\"},\"message\":{\"title\":\"errorObjectMessage\",\"description\":\"A String providing a short description of the error. The message SHOULD be limited to a concise single sentence.\",\"type\":\"string\"},\"data\":{\"title\":\"errorObjectData\",\"description\":\"A Primitive or Structured value that contains additional information about the error. This may be omitted. The value of this member is defined by the Server (e.g. detailed error information, nested errors etc.).\"}}}},{\"name\":\"capabilities\",\"x-provides\":\"xrn:firebolt:capability:usergrant:acknowledgechallenge\",\"x-allow-focus\":true}],\"result\":{\"name\":\"challenge\",\"summary\":\"The request to challenge the user\",\"schema\":{\"anyOf\":[{\"$ref\":\"#/x-schemas/Types/ListenResponse\"},{\"$ref\":\"#/components/schemas/ChallengeProviderRequest\"}]}},\"examples\":[{\"name\":\"Default Example\",\"params\":[{\"name\":\"listen\",\"value\":true}],\"result\":{\"name\":\"Default Result\",\"value\":{\"correlationId\":\"abc\",\"parameters\":{\"capability\":\"xrn:firebolt:capability:localization::postal-code\",\"requestor\":{\"id\":\"ReferenceApp\",\"name\":\"Firebolt Reference App\"}}}}}]},{\"name\":\"AcknowledgeChallenge.challengeFocus\",\"summary\":\"Internal API for Challenge Provider to request focus for UX purposes.\",\"params\":[],\"tags\":[{\"name\":\"rpc-only\"},{\"name\":\"capabilities\",\"x-provides\":\"xrn:firebolt:capability:usergrant:acknowledgechallenge\",\"x-allow-focus\":true,\"x-allow-focus-for\":\"onRequestChallenge\"}],\"result\":{\"name\":\"result\",\"schema\":{\"type\":\"null\"}},\"examples\":[{\"name\":\"Example\",\"params\":[],\"result\":{\"name\":\"result\",\"value\":null}}]},{\"name\":\"AcknowledgeChallenge.challengeResponse\",\"summary\":\"Internal API for Challenge Provider to send back response.\",\"params\":[{\"name\":\"correlationId\",\"schema\":{\"type\":\"string\"},\"required\":true},{\"name\":\"result\",\"schema\":{\"$ref\":\"#/components/schemas/GrantResult\"},\"required\":true}],\"tags\":[{\"name\":\"rpc-only\"},{\"name\":\"capabilities\",\"x-provides\":\"xrn:firebolt:capability:usergrant:acknowledgechallenge\",\"x-allow-focus\":true,\"x-response-for\":\"onRequestChallenge\"}],\"result\":{\"name\":\"result\",\"schema\":{\"type\":\"null\"}},\"examples\":[{\"name\":\"Example #1\",\"params\":[{\"name\":\"correlationId\",\"value\":\"123\"},{\"name\":\"result\",\"value\":{\"granted\":true}}],\"result\":{\"name\":\"result\",\"value\":null}},{\"name\":\"Example #2\",\"params\":[{\"name\":\"correlationId\",\"value\":\"123\"},{\"name\":\"result\",\"value\":{\"granted\":false}}],\"result\":{\"name\":\"result\",\"value\":null}},{\"name\":\"Example #3\",\"params\":[{\"name\":\"correlationId\",\"value\":\"123\"},{\"name\":\"result\",\"value\":{\"granted\":null}}],\"result\":{\"name\":\"result\",\"value\":null}}]},{\"name\":\"AcknowledgeChallenge.challengeError\",\"summary\":\"Internal API for Challenge Provider to send back error.\",\"params\":[{\"name\":\"correlationId\",\"schema\":{\"type\":\"string\"},\"required\":true},{\"name\":\"error\",\"schema\":{\"type\":\"object\",\"additionalProperties\":false,\"required\":[\"code\",\"message\"],\"properties\":{\"code\":{\"title\":\"errorObjectCode\",\"description\":\"A Number that indicates the error type that occurred. This MUST be an integer. The error codes from and including -32768 to -32000 are reserved for pre-defined errors. These pre-defined errors SHOULD be assumed to be returned from any JSON-RPC api.\",\"type\":\"integer\"},\"message\":{\"title\":\"errorObjectMessage\",\"description\":\"A String providing a short description of the error. The message SHOULD be limited to a concise single sentence.\",\"type\":\"string\"},\"data\":{\"title\":\"errorObjectData\",\"description\":\"A Primitive or Structured value that contains additional information about the error. This may be omitted. The value of this member is defined by the Server (e.g. detailed error information, nested errors etc.).\"}}},\"required\":true}],\"tags\":[{\"name\":\"rpc-only\"},{\"name\":\"capabilities\",\"x-provides\":\"xrn:firebolt:capability:usergrant:acknowledgechallenge\",\"x-allow-focus\":true,\"x-error-for\":\"onRequestChallenge\"}],\"result\":{\"name\":\"result\",\"schema\":{\"type\":\"null\"}},\"examples\":[{\"name\":\"Example 1\",\"params\":[{\"name\":\"correlationId\",\"value\":\"123\"},{\"name\":\"error\",\"value\":{\"code\":1,\"message\":\"Error\"}}],\"result\":{\"name\":\"result\",\"value\":null}}]},{\"name\":\"PinChallenge.onRequestChallenge\",\"summary\":\"Registers as a provider for when the user should be challenged in order to confirm access to a capability through a pin prompt\",\"params\":[{\"name\":\"listen\",\"required\":true,\"schema\":{\"type\":\"boolean\"}}],\"tags\":[{\"name\":\"rpc-only\"},{\"name\":\"event\",\"x-response\":{\"$ref\":\"#/components/schemas/PinChallengeResult\",\"examples\":[{\"granted\":true,\"reason\":\"correctPin\"},{\"granted\":false,\"reason\":\"exceededPinFailures\"},{\"granted\":null,\"reason\":\"cancelled\"}]},\"x-error\":{\"type\":\"object\",\"additionalProperties\":false,\"required\":[\"code\",\"message\"],\"properties\":{\"code\":{\"title\":\"errorObjectCode\",\"description\":\"A Number that indicates the error type that occurred. This MUST be an integer. The error codes from and including -32768 to -32000 are reserved for pre-defined errors. These pre-defined errors SHOULD be assumed to be returned from any JSON-RPC api.\",\"type\":\"integer\"},\"message\":{\"title\":\"errorObjectMessage\",\"description\":\"A String providing a short description of the error. The message SHOULD be limited to a concise single sentence.\",\"type\":\"string\"},\"data\":{\"title\":\"errorObjectData\",\"description\":\"A Primitive or Structured value that contains additional information about the error. This may be omitted. The value of this member is defined by the Server (e.g. detailed error information, nested errors etc.).\"}}}},{\"name\":\"capabilities\",\"x-provides\":\"xrn:firebolt:capability:usergrant:pinchallenge\",\"x-allow-focus\":true}],\"result\":{\"name\":\"challenge\",\"summary\":\"The request to challenge the user\",\"schema\":{\"anyOf\":[{\"$ref\":\"#/x-schemas/Types/ListenResponse\"},{\"$ref\":\"#/components/schemas/PinChallengeProviderRequest\"}]}},\"examples\":[{\"name\":\"Default Example\",\"params\":[{\"name\":\"listen\",\"value\":true}],\"result\":{\"name\":\"Default Result\",\"value\":{\"correlationId\":\"abc\",\"parameters\":{\"capability\":\"xrn:firebolt:capability:commerce::purchase\",\"requestor\":{\"id\":\"ReferenceApp\",\"name\":\"Firebolt Reference App\"},\"pinSpace\":\"purchase\"}}}}]},{\"name\":\"PinChallenge.challengeFocus\",\"summary\":\"Internal API for Challenge Provider to request focus for UX purposes.\",\"params\":[],\"tags\":[{\"name\":\"rpc-only\"},{\"name\":\"capabilities\",\"x-provides\":\"xrn:firebolt:capability:usergrant:pinchallenge\",\"x-allow-focus\":true,\"x-allow-focus-for\":\"onRequestChallenge\"}],\"result\":{\"name\":\"result\",\"schema\":{\"type\":\"null\"}},\"examples\":[{\"name\":\"Example\",\"params\":[],\"result\":{\"name\":\"result\",\"value\":null}}]},{\"name\":\"PinChallenge.challengeResponse\",\"summary\":\"Internal API for Challenge Provider to send back response.\",\"params\":[{\"name\":\"correlationId\",\"schema\":{\"type\":\"string\"},\"required\":true},{\"name\":\"result\",\"schema\":{\"$ref\":\"#/components/schemas/PinChallengeResult\",\"examples\":[{\"granted\":true,\"reason\":\"correctPin\"},{\"granted\":false,\"reason\":\"exceededPinFailures\"},{\"granted\":null,\"reason\":\"cancelled\"}]},\"required\":true}],\"tags\":[{\"name\":\"rpc-only\"},{\"name\":\"capabilities\",\"x-provides\":\"xrn:firebolt:capability:usergrant:pinchallenge\",\"x-allow-focus\":true,\"x-response-for\":\"onRequestChallenge\"}],\"result\":{\"name\":\"result\",\"schema\":{\"type\":\"null\"}},\"examples\":[{\"name\":\"Example #1\",\"params\":[{\"name\":\"correlationId\",\"value\":\"123\"},{\"name\":\"result\",\"value\":{\"granted\":true,\"reason\":\"correctPin\"}}],\"result\":{\"name\":\"result\",\"value\":null}},{\"name\":\"Example #2\",\"params\":[{\"name\":\"correlationId\",\"value\":\"123\"},{\"name\":\"result\",\"value\":{\"granted\":false,\"reason\":\"exceededPinFailures\"}}],\"result\":{\"name\":\"result\",\"value\":null}},{\"name\":\"Example #3\",\"params\":[{\"name\":\"correlationId\",\"value\":\"123\"},{\"name\":\"result\",\"value\":{\"granted\":null,\"reason\":\"cancelled\"}}],\"result\":{\"name\":\"result\",\"value\":null}}]},{\"name\":\"PinChallenge.challengeError\",\"summary\":\"Internal API for Challenge Provider to send back error.\",\"params\":[{\"name\":\"correlationId\",\"schema\":{\"type\":\"string\"},\"required\":true},{\"name\":\"error\",\"schema\":{\"type\":\"object\",\"additionalProperties\":false,\"required\":[\"code\",\"message\"],\"properties\":{\"code\":{\"title\":\"errorObjectCode\",\"description\":\"A Number that indicates the error type that occurred. This MUST be an integer. The error codes from and including -32768 to -32000 are reserved for pre-defined errors. These pre-defined errors SHOULD be assumed to be returned from any JSON-RPC api.\",\"type\":\"integer\"},\"message\":{\"title\":\"errorObjectMessage\",\"description\":\"A String providing a short description of the error. The message SHOULD be limited to a concise single sentence.\",\"type\":\"string\"},\"data\":{\"title\":\"errorObjectData\",\"description\":\"A Primitive or Structured value that contains additional information about the error. This may be omitted. The value of this member is defined by the Server (e.g. detailed error information, nested errors etc.).\"}}},\"required\":true}],\"tags\":[{\"name\":\"rpc-only\"},{\"name\":\"capabilities\",\"x-provides\":\"xrn:firebolt:capability:usergrant:pinchallenge\",\"x-allow-focus\":true,\"x-error-for\":\"onRequestChallenge\"}],\"result\":{\"name\":\"result\",\"schema\":{\"type\":\"null\"}},\"examples\":[{\"name\":\"Example 1\",\"params\":[{\"name\":\"correlationId\",\"value\":\"123\"},{\"name\":\"error\",\"value\":{\"code\":1,\"message\":\"Error\"}}],\"result\":{\"name\":\"result\",\"value\":null}}]},{\"name\":\"SecureStorage.setForApp\",\"summary\":\"Set or update a secure data value for a specific app.\",\"tags\":[{\"name\":\"capabilities\",\"x-manages\":[\"xrn:firebolt:capability:storage:secure\"]}],\"params\":[{\"name\":\"appId\",\"summary\":\"appId for which value is being set\",\"schema\":{\"type\":\"string\"},\"required\":true},{\"name\":\"scope\",\"summary\":\"The scope of the data key\",\"schema\":{\"$ref\":\"#/components/schemas/StorageScope\"},\"required\":true},{\"name\":\"key\",\"summary\":\"Key to set\",\"schema\":{\"type\":\"string\"},\"required\":true},{\"name\":\"value\",\"summary\":\"Value to set\",\"schema\":{\"type\":\"string\"},\"required\":true},{\"name\":\"options\",\"summary\":\"Optional parameters to set\",\"schema\":{\"$ref\":\"#/components/schemas/StorageOptions\"},\"required\":false}],\"result\":{\"name\":\"success\",\"schema\":{\"const\":null}},\"examples\":[{\"name\":\"Set a refresh token with name authRefreshToken with optional parameter for appId foo\",\"params\":[{\"name\":\"appId\",\"value\":\"foo\"},{\"name\":\"scope\",\"value\":\"device\"},{\"name\":\"key\",\"value\":\"authRefreshToken\"},{\"name\":\"value\",\"value\":\"VGhpcyBub3QgYSByZWFsIHRva2VuLgo=\"},{\"name\":\"options\",\"value\":{\"ttl\":600}}],\"result\":{\"name\":\"defaultResult\",\"value\":null}},{\"name\":\"Set a refresh token with name authRefreshToken without optional parameter for appId foo\",\"params\":[{\"name\":\"appId\",\"value\":\"foo\"},{\"name\":\"scope\",\"value\":\"account\"},{\"name\":\"key\",\"value\":\"authRefreshToken\"},{\"name\":\"value\",\"value\":\"VGhpcyBub3QgYSByZWFsIHRva2VuLgo=\"}],\"result\":{\"name\":\"defaultResult\",\"value\":null}}]},{\"name\":\"SecureStorage.removeForApp\",\"summary\":\"Removes single data value for a specific app.\",\"tags\":[{\"name\":\"capabilities\",\"x-manages\":[\"xrn:firebolt:capability:storage:secure\"]}],\"params\":[{\"name\":\"appId\",\"summary\":\"appId for which values are removed\",\"schema\":{\"type\":\"string\"},\"required\":true},{\"name\":\"scope\",\"summary\":\"The scope of the key/value\",\"schema\":{\"$ref\":\"#/components/schemas/StorageScope\"},\"required\":true},{\"name\":\"key\",\"summary\":\"Key to remove\",\"schema\":{\"type\":\"string\"},\"required\":true}],\"result\":{\"name\":\"success\",\"summary\":\"\",\"schema\":{\"const\":null}},\"examples\":[{\"name\":\"Removes authRefreshToken for appId foo\",\"params\":[{\"name\":\"appId\",\"value\":\"foo\"},{\"name\":\"scope\",\"value\":\"account\"},{\"name\":\"key\",\"value\":\"authRefreshToken\"}],\"result\":{\"name\":\"defaultResult\",\"value\":null}}]},{\"name\":\"SecureStorage.clearForApp\",\"summary\":\"Clears all the secure data values for a specific app\",\"tags\":[{\"name\":\"capabilities\",\"x-manages\":[\"xrn:firebolt:capability:storage:secure\"]}],\"params\":[{\"name\":\"appId\",\"summary\":\"appId for which values are removed\",\"schema\":{\"type\":\"string\"},\"required\":true},{\"name\":\"scope\",\"summary\":\"The scope of the key/value\",\"schema\":{\"$ref\":\"#/components/schemas/StorageScope\"},\"required\":true}],\"result\":{\"name\":\"success\",\"summary\":\"\",\"schema\":{\"const\":null}},\"examples\":[{\"name\":\"Clears all the secure data values for appId foo\",\"params\":[{\"name\":\"appId\",\"value\":\"foo\"},{\"name\":\"scope\",\"value\":\"account\"}],\"result\":{\"name\":\"defaultResult\",\"value\":null}}]},{\"name\":\"Discovery.onSignIn\",\"tags\":[{\"name\":\"event\"},{\"name\":\"capabilities\",\"x-manages\":[\"xrn:firebolt:capability:discovery:sign-in-status\"]}],\"summary\":\"Listen to events from all apps that call Discovery.signIn\",\"params\":[{\"name\":\"listen\",\"required\":true,\"schema\":{\"type\":\"boolean\"}}],\"result\":{\"name\":\"event\",\"schema\":{\"anyOf\":[{\"$ref\":\"#/x-schemas/Types/ListenResponse\"},{\"type\":\"object\",\"properties\":{\"appId\":{\"type\":\"string\"}},\"required\":[\"appId\"]}]}},\"examples\":[{\"name\":\"Default Example\",\"params\":[{\"name\":\"listen\",\"value\":true}],\"result\":{\"name\":\"Default Event\",\"value\":{\"appId\":\"firecert\"}}}]},{\"name\":\"Discovery.onSignOut\",\"tags\":[{\"name\":\"event\"},{\"name\":\"capabilities\",\"x-manages\":[\"xrn:firebolt:capability:discovery:sign-in-status\"]}],\"summary\":\"Listen to events from all apps that call Discovery.signOut\",\"params\":[{\"name\":\"listen\",\"required\":true,\"schema\":{\"type\":\"boolean\"}}],\"result\":{\"name\":\"event\",\"schema\":{\"anyOf\":[{\"$ref\":\"#/x-schemas/Types/ListenResponse\"},{\"type\":\"object\",\"properties\":{\"appId\":{\"type\":\"string\"}},\"required\":[\"appId\"]}]}},\"examples\":[{\"name\":\"Default Example\",\"params\":[{\"name\":\"listen\",\"value\":true}],\"result\":{\"name\":\"Default Event\",\"value\":{\"appId\":\"firecert\"}}}]},{\"name\":\"HDMIInput.ports\",\"tags\":[{\"name\":\"capabilities\",\"x-uses\":[\"xrn:firebolt:capability:inputs:hdmi\"]}],\"summary\":\"Retrieve a list of HDMI input ports.\",\"params\":[],\"result\":{\"name\":\"ports\",\"schema\":{\"type\":\"array\",\"items\":{\"$ref\":\"#/components/schemas/HDMIInputPort\"}}},\"examples\":[{\"name\":\"Default Example\",\"params\":[],\"result\":{\"name\":\"ports\",\"value\":[{\"port\":\"HDMI1\",\"connected\":true,\"signal\":\"stable\",\"arcCapable\":true,\"arcConnected\":true,\"edidVersion\":\"2.0\",\"autoLowLatencyModeCapable\":true,\"autoLowLatencyModeSignalled\":true}]}}]},{\"name\":\"HDMIInput.port\",\"tags\":[{\"name\":\"capabilities\",\"x-uses\":[\"xrn:firebolt:capability:inputs:hdmi\"]}],\"summary\":\"Retrieve a specific HDMI input port.\",\"params\":[{\"name\":\"portId\",\"schema\":{\"$ref\":\"#/components/schemas/HDMIPortId\"},\"required\":true}],\"result\":{\"name\":\"port\",\"schema\":{\"$ref\":\"#/components/schemas/HDMIInputPort\"}},\"examples\":[{\"name\":\"Default Example\",\"params\":[{\"name\":\"portId\",\"value\":\"HDMI1\"}],\"result\":{\"name\":\"ports\",\"value\":{\"port\":\"HDMI1\",\"connected\":true,\"signal\":\"stable\",\"arcCapable\":true,\"arcConnected\":true,\"edidVersion\":\"2.0\",\"autoLowLatencyModeCapable\":true,\"autoLowLatencyModeSignalled\":true}}}]},{\"name\":\"HDMIInput.open\",\"tags\":[{\"name\":\"capabilities\",\"x-manages\":[\"xrn:firebolt:capability:inputs:hdmi\"]}],\"summary\":\"Opens the HDMI Port allowing it to be the active source device. Incase there is a different HDMI portId already set as the active source, this call would stop the older portId before opening the given portId.\",\"params\":[{\"name\":\"portId\",\"schema\":{\"$ref\":\"#/components/schemas/HDMIPortId\"},\"required\":true}],\"result\":{\"name\":\"port\",\"schema\":{\"const\":null}},\"examples\":[{\"name\":\"Default Example for open\",\"params\":[{\"name\":\"portId\",\"value\":\"HDMI1\"}],\"result\":{\"name\":\"port\",\"value\":null}}]},{\"name\":\"HDMIInput.close\",\"tags\":[{\"name\":\"capabilities\",\"x-manages\":[\"xrn:firebolt:capability:inputs:hdmi\"]}],\"summary\":\"Closes the given HDMI Port if it is the current active source for HDMI Input. If there was no active source, then there would no action taken on the device.\",\"params\":[],\"result\":{\"name\":\"port\",\"schema\":{\"const\":null}},\"examples\":[{\"name\":\"Default Example for stop\",\"params\":[],\"result\":{\"name\":\"port\",\"value\":null}}]},{\"name\":\"HDMIInput.onConnectionChanged\",\"tags\":[{\"name\":\"event\"},{\"name\":\"capabilities\",\"x-uses\":[\"xrn:firebolt:capability:inputs:hdmi\"]}],\"summary\":\"Notification for when any HDMI port has a connection physically engaged or disengaged.\",\"params\":[{\"name\":\"listen\",\"required\":true,\"schema\":{\"type\":\"boolean\"}}],\"result\":{\"name\":\"info\",\"schema\":{\"anyOf\":[{\"$ref\":\"#/x-schemas/Types/ListenResponse\"},{\"$ref\":\"#/components/schemas/ConnectionChangedInfo\"}]}},\"examples\":[{\"name\":\"Default Example\",\"params\":[{\"name\":\"listen\",\"value\":true}],\"result\":{\"name\":\"info\",\"value\":{\"port\":\"HDMI1\",\"connected\":true}}}]},{\"name\":\"HDMIInput.onSignalChanged\",\"tags\":[{\"name\":\"event\"},{\"name\":\"capabilities\",\"x-uses\":[\"xrn:firebolt:capability:inputs:hdmi\"]}],\"summary\":\"Notification for when any HDMI port has it's signal status changed.\",\"params\":[{\"name\":\"listen\",\"required\":true,\"schema\":{\"type\":\"boolean\"}}],\"result\":{\"name\":\"info\",\"schema\":{\"anyOf\":[{\"$ref\":\"#/x-schemas/Types/ListenResponse\"},{\"$ref\":\"#/components/schemas/SignalChangedInfo\"}]}},\"examples\":[{\"name\":\"Default Example\",\"params\":[{\"name\":\"listen\",\"value\":true}],\"result\":{\"name\":\"info\",\"value\":{\"port\":\"HDMI1\",\"signal\":\"stable\"}}}]},{\"name\":\"HDMIInput.lowLatencyMode\",\"summary\":\"Property for the low latency mode setting.\",\"tags\":[{\"name\":\"capabilities\",\"x-uses\":[\"xrn:firebolt:capability:inputs:hdmi\"]},{\"name\":\"property\"}],\"params\":[],\"result\":{\"name\":\"enabled\",\"schema\":{\"type\":\"boolean\"}},\"examples\":[{\"name\":\"Default Example\",\"params\":[],\"result\":{\"name\":\"enabled\",\"value\":true}},{\"name\":\"Default Example #2\",\"params\":[],\"result\":{\"name\":\"enabled\",\"value\":false}}]},{\"name\":\"HDMIInput.onAutoLowLatencyModeSignalChanged\",\"summary\":\"Notification for changes to ALLM status of any input device.\",\"tags\":[{\"name\":\"capabilities\",\"x-uses\":[\"xrn:firebolt:capability:inputs:hdmi\"]},{\"name\":\"event\"}],\"params\":[{\"name\":\"listen\",\"required\":true,\"schema\":{\"type\":\"boolean\"}}],\"result\":{\"name\":\"info\",\"schema\":{\"anyOf\":[{\"$ref\":\"#/x-schemas/Types/ListenResponse\"},{\"$ref\":\"#/components/schemas/AutoLowLatencyModeSignalChangedInfo\"}]}},\"examples\":[{\"name\":\"Default Example\",\"params\":[{\"name\":\"listen\",\"value\":true}],\"result\":{\"name\":\"info\",\"value\":{\"port\":\"HDMI1\",\"autoLowLatencyModeSignalled\":true}}}]},{\"name\":\"HDMIInput.autoLowLatencyModeCapable\",\"summary\":\"Property for each port auto low latency mode setting.\",\"tags\":[{\"name\":\"capabilities\",\"x-uses\":[\"xrn:firebolt:capability:inputs:hdmi\"]},{\"name\":\"property\",\"x-subscriber-type\":\"global\"}],\"params\":[{\"name\":\"port\",\"required\":true,\"schema\":{\"$ref\":\"#/components/schemas/HDMIPortId\"}}],\"result\":{\"name\":\"enabled\",\"schema\":{\"type\":\"boolean\"}},\"examples\":[{\"name\":\"Default Example\",\"params\":[{\"name\":\"port\",\"value\":\"HDMI1\"}],\"result\":{\"name\":\"enabled\",\"value\":true}},{\"name\":\"Default Example #2\",\"params\":[{\"name\":\"port\",\"value\":\"HDMI1\"}],\"result\":{\"name\":\"enabled\",\"value\":false}}]},{\"name\":\"HDMIInput.edidVersion\",\"summary\":\"Property for each port's active EDID version.\",\"tags\":[{\"name\":\"capabilities\",\"x-uses\":[\"xrn:firebolt:capability:inputs:hdmi\"]},{\"name\":\"property\"}],\"params\":[{\"name\":\"port\",\"required\":true,\"schema\":{\"$ref\":\"#/components/schemas/HDMIPortId\"}}],\"result\":{\"name\":\"edidVersion\",\"schema\":{\"$ref\":\"#/components/schemas/EDIDVersion\"}},\"examples\":[{\"name\":\"Default Example\",\"params\":[{\"name\":\"port\",\"value\":\"HDMI1\"}],\"result\":{\"name\":\"edidVersion\",\"value\":\"2.0\"}},{\"name\":\"Default Example #2\",\"params\":[{\"name\":\"port\",\"value\":\"HDMI1\"}],\"result\":{\"name\":\"edidVersion\",\"value\":\"1.4\"}}]},{\"name\":\"HDMIInput.onLowLatencyModeChanged\",\"summary\":\"Property for the low latency mode setting.\",\"tags\":[{\"name\":\"subscriber\",\"x-subscriber-for\":\"HDMIInput.lowLatencyMode\"},{\"name\":\"event\",\"x-alternative\":\"lowLatencyMode\"},{\"name\":\"capabilities\",\"x-uses\":[\"xrn:firebolt:capability:inputs:hdmi\"]}],\"params\":[{\"name\":\"listen\",\"required\":true,\"schema\":{\"type\":\"boolean\"}}],\"result\":{\"name\":\"enabled\",\"schema\":{\"anyOf\":[{\"$ref\":\"#/x-schemas/Types/ListenResponse\"},{\"type\":\"boolean\"}]}},\"examples\":[{\"name\":\"Default Example\",\"params\":[{\"name\":\"listen\",\"value\":true}],\"result\":{\"name\":\"enabled\",\"value\":true}},{\"name\":\"Default Example #2\",\"params\":[{\"name\":\"listen\",\"value\":true}],\"result\":{\"name\":\"enabled\",\"value\":false}}]},{\"name\":\"HDMIInput.onAutoLowLatencyModeCapableChanged\",\"summary\":\"Property for each port auto low latency mode setting.\",\"tags\":[{\"name\":\"subscriber\",\"x-subscriber-for\":\"HDMIInput.autoLowLatencyModeCapable\"},{\"name\":\"event\",\"x-alternative\":\"autoLowLatencyModeCapable\"},{\"name\":\"capabilities\",\"x-uses\":[\"xrn:firebolt:capability:inputs:hdmi\"]}],\"params\":[{\"name\":\"listen\",\"required\":true,\"schema\":{\"type\":\"boolean\"}}],\"result\":{\"name\":\"data\",\"schema\":{\"anyOf\":[{\"$ref\":\"#/x-schemas/Types/ListenResponse\"},{\"$ref\":\"#/components/schemas/AutoLowLatencyModeCapableChangedInfo\"}]}},\"examples\":[{\"name\":\"Default Example\",\"params\":[{\"name\":\"listen\",\"value\":true}],\"result\":{\"name\":\"data\",\"value\":{\"port\":\"HDMI1\",\"enabled\":true}}},{\"name\":\"Default Example #2\",\"params\":[{\"name\":\"listen\",\"value\":true}],\"result\":{\"name\":\"data\",\"value\":{\"port\":\"HDMI1\",\"enabled\":false}}}]},{\"name\":\"HDMIInput.onEdidVersionChanged\",\"summary\":\"Property for each port's active EDID version.\",\"tags\":[{\"name\":\"subscriber\",\"x-subscriber-for\":\"HDMIInput.edidVersion\"},{\"name\":\"event\",\"x-alternative\":\"edidVersion\"},{\"name\":\"capabilities\",\"x-uses\":[\"xrn:firebolt:capability:inputs:hdmi\"]}],\"params\":[{\"name\":\"port\",\"required\":true,\"schema\":{\"$ref\":\"#/components/schemas/HDMIPortId\"}},{\"name\":\"listen\",\"required\":true,\"schema\":{\"type\":\"boolean\"}}],\"result\":{\"name\":\"edidVersion\",\"schema\":{\"anyOf\":[{\"$ref\":\"#/x-schemas/Types/ListenResponse\"},{\"$ref\":\"#/components/schemas/EDIDVersion\"}]}},\"examples\":[{\"name\":\"Default Example\",\"params\":[{\"name\":\"port\",\"value\":\"HDMI1\"},{\"name\":\"listen\",\"value\":true}],\"result\":{\"name\":\"edidVersion\",\"value\":\"2.0\"}},{\"name\":\"Default Example #2\",\"params\":[{\"name\":\"port\",\"value\":\"HDMI1\"},{\"name\":\"listen\",\"value\":true}],\"result\":{\"name\":\"edidVersion\",\"value\":\"1.4\"}}]},{\"name\":\"HDMIInput.setLowLatencyMode\",\"summary\":\"Property for the low latency mode setting.\",\"tags\":[{\"name\":\"setter\",\"x-setter-for\":\"lowLatencyMode\"},{\"name\":\"capabilities\",\"x-manages\":[\"xrn:firebolt:capability:inputs:hdmi\"]}],\"params\":[{\"name\":\"value\",\"schema\":{\"type\":\"boolean\"},\"required\":true}],\"result\":{\"name\":\"result\",\"schema\":{\"type\":\"null\"}},\"examples\":[{\"name\":\"Default Example\",\"params\":[{\"name\":\"value\",\"value\":true}],\"result\":{\"name\":\"enabled\",\"value\":null}},{\"name\":\"Default Example #2\",\"params\":[{\"name\":\"value\",\"value\":false}],\"result\":{\"name\":\"enabled\",\"value\":null}}]},{\"name\":\"HDMIInput.setAutoLowLatencyModeCapable\",\"summary\":\"Property for each port auto low latency mode setting.\",\"tags\":[{\"name\":\"setter\",\"x-setter-for\":\"autoLowLatencyModeCapable\"},{\"name\":\"capabilities\",\"x-manages\":[\"xrn:firebolt:capability:inputs:hdmi\"]}],\"params\":[{\"name\":\"port\",\"required\":true,\"schema\":{\"$ref\":\"#/components/schemas/HDMIPortId\"}},{\"name\":\"value\",\"schema\":{\"type\":\"boolean\"},\"required\":true}],\"result\":{\"name\":\"result\",\"schema\":{\"type\":\"null\"}},\"examples\":[{\"name\":\"Default Example\",\"params\":[{\"name\":\"port\",\"value\":\"HDMI1\"},{\"name\":\"value\",\"value\":true}],\"result\":{\"name\":\"enabled\",\"value\":null}},{\"name\":\"Default Example #2\",\"params\":[{\"name\":\"port\",\"value\":\"HDMI1\"},{\"name\":\"value\",\"value\":false}],\"result\":{\"name\":\"enabled\",\"value\":null}}]},{\"name\":\"HDMIInput.setEdidVersion\",\"summary\":\"Property for each port's active EDID version.\",\"tags\":[{\"name\":\"setter\",\"x-setter-for\":\"edidVersion\"},{\"name\":\"capabilities\",\"x-manages\":[\"xrn:firebolt:capability:inputs:hdmi\"]}],\"params\":[{\"name\":\"port\",\"required\":true,\"schema\":{\"$ref\":\"#/components/schemas/HDMIPortId\"}},{\"name\":\"value\",\"schema\":{\"$ref\":\"#/components/schemas/EDIDVersion\"},\"required\":true}],\"result\":{\"name\":\"result\",\"schema\":{\"type\":\"null\"}},\"examples\":[{\"name\":\"Default Example\",\"params\":[{\"name\":\"port\",\"value\":\"HDMI1\"},{\"name\":\"value\",\"value\":\"2.0\"}],\"result\":{\"name\":\"edidVersion\",\"value\":null}},{\"name\":\"Default Example #2\",\"params\":[{\"name\":\"port\",\"value\":\"HDMI1\"},{\"name\":\"value\",\"value\":\"1.4\"}],\"result\":{\"name\":\"edidVersion\",\"value\":null}}]}],\"components\":{\"schemas\":{\"Token\":{\"type\":\"string\",\"description\":\"Encoded token provided by the Distributor for Device Authentication.\"},\"Expiry\":{\"type\":\"integer\",\"description\":\"Number of secs before the token expires\",\"minimum\":1},\"ChallengeRequestor\":{\"title\":\"ChallengeRequestor\",\"type\":\"object\",\"required\":[\"id\",\"name\"],\"properties\":{\"id\":{\"type\":\"string\",\"description\":\"The id of the app that requested the challenge\"},\"name\":{\"type\":\"string\",\"description\":\"The name of the app that requested the challenge\"}}},\"Challenge\":{\"title\":\"Challenge\",\"type\":\"object\",\"required\":[\"capability\",\"requestor\"],\"properties\":{\"capability\":{\"type\":\"string\",\"description\":\"The capability that is being requested by the user to approve\"},\"requestor\":{\"description\":\"The identity of which app is requesting access to this capability\",\"$ref\":\"#/components/schemas/ChallengeRequestor\"}}},\"ChallengeProviderRequest\":{\"title\":\"ChallengeProviderRequest\",\"allOf\":[{\"$ref\":\"#/x-schemas/Types/ProviderRequest\"},{\"type\":\"object\",\"required\":[\"parameters\"],\"properties\":{\"parameters\":{\"description\":\"The request to challenge the user\",\"$ref\":\"#/components/schemas/Challenge\"}}}]},\"GrantResult\":{\"title\":\"GrantResult\",\"type\":\"object\",\"required\":[\"granted\"],\"properties\":{\"granted\":{\"oneOf\":[{\"type\":\"boolean\",\"description\":\"Whether the user approved or denied the challenge\"},{\"const\":null}]}},\"examples\":[{\"granted\":true},{\"granted\":false},{\"granted\":null}]},\"NetworkType\":{\"title\":\"NetworkType\",\"type\":\"string\",\"enum\":[\"wifi\",\"ethernet\",\"hybrid\"],\"description\":\"The type of network that is currently active\"},\"NetworkState\":{\"title\":\"NetworkState\",\"type\":\"string\",\"enum\":[\"connected\",\"disconnected\"],\"description\":\"The type of network that is currently active\"},\"FederatedRequest\":{\"title\":\"FederatedRequest\",\"type\":\"object\",\"properties\":{\"correlationId\":{\"type\":\"string\"}},\"required\":[\"correlationId\"],\"propertyNames\":{\"enum\":[\"correlationId\",\"parameters\"]},\"examples\":[{\"correlationId\":\"xyz\"}]},\"FederatedResponse\":{\"title\":\"FederatedResponse\",\"type\":\"object\",\"properties\":{\"correlationId\":{\"type\":\"string\"}},\"required\":[\"correlationId\",\"result\"],\"propertyNames\":{\"enum\":[\"correlationId\",\"result\"]},\"examples\":[{\"correlationId\":\"xyz\"}]},\"EntityInfoParameters\":{\"title\":\"EntityInfoParameters\",\"type\":\"object\",\"properties\":{\"entityId\":{\"type\":\"string\"},\"assetId\":{\"type\":\"string\"}},\"required\":[\"entityId\"],\"additionalProperties\":false,\"examples\":[{\"entityId\":\"345\"}]},\"PurchasedContentParameters\":{\"title\":\"PurchasedContentParameters\",\"type\":\"object\",\"properties\":{\"limit\":{\"type\":\"integer\",\"minimum\":-1},\"offeringType\":{\"$ref\":\"#/x-schemas/Entertainment/OfferingType\"},\"programType\":{\"$ref\":\"#/x-schemas/Entertainment/ProgramType\"}},\"required\":[\"limit\"],\"additionalProperties\":false,\"examples\":[{\"limit\":100}]},\"Availability\":{\"title\":\"Availability\",\"type\":\"object\",\"properties\":{\"type\":{\"type\":\"string\",\"enum\":[\"channel-lineup\",\"program-lineup\"]},\"id\":{\"type\":\"string\"},\"catalogId\":{\"type\":\"string\"},\"startTime\":{\"type\":\"string\",\"format\":\"date-time\"},\"endTime\":{\"type\":\"string\",\"format\":\"date-time\"}},\"required\":[\"type\",\"id\"]},\"HDMIPortId\":{\"type\":\"string\",\"pattern\":\"^HDMI[0-9]+$\"},\"EDIDVersion\":{\"title\":\"EDIDVersion\",\"type\":\"string\",\"enum\":[\"1.4\",\"2.0\",\"unknown\"]},\"HDMIInputPort\":{\"title\":\"HDMIInputPort\",\"type\":\"object\",\"additionalProperties\":false,\"properties\":{\"port\":{\"$ref\":\"#/components/schemas/HDMIPortId\"},\"connected\":{\"type\":\"boolean\"},\"signal\":{\"$ref\":\"#/components/schemas/HDMISignalStatus\"},\"arcCapable\":{\"type\":\"boolean\"},\"arcConnected\":{\"type\":\"boolean\"},\"edidVersion\":{\"$ref\":\"#/components/schemas/EDIDVersion\"},\"autoLowLatencyModeCapable\":{\"type\":\"boolean\"},\"autoLowLatencyModeSignalled\":{\"type\":\"boolean\"}},\"if\":{\"properties\":{\"edidVersion\":{\"type\":\"string\",\"enum\":[\"1.4\",\"unknown\"]}}},\"then\":{\"properties\":{\"autoLowLatencyModeCapable\":{\"const\":false},\"autoLowLatencyModeSignalled\":{\"const\":false}}},\"required\":[\"port\",\"connected\",\"signal\",\"arcCapable\",\"arcConnected\",\"edidVersion\",\"autoLowLatencyModeCapable\",\"autoLowLatencyModeSignalled\"]},\"HDMISignalStatus\":{\"type\":\"string\",\"enum\":[\"none\",\"stable\",\"unstable\",\"unsupported\",\"unknown\"]},\"SignalChangedInfo\":{\"title\":\"SignalChangedInfo\",\"type\":\"object\",\"properties\":{\"port\":{\"$ref\":\"#/components/schemas/HDMIPortId\"},\"signal\":{\"$ref\":\"#/components/schemas/HDMISignalStatus\"}},\"required\":[\"port\",\"signal\"]},\"ConnectionChangedInfo\":{\"title\":\"ConnectionChangedInfo\",\"type\":\"object\",\"properties\":{\"port\":{\"$ref\":\"#/components/schemas/HDMIPortId\"},\"connected\":{\"type\":\"boolean\"}}},\"AutoLowLatencyModeSignalChangedInfo\":{\"title\":\"AutoLowLatencyModeSignalChangedInfo\",\"type\":\"object\",\"properties\":{\"port\":{\"$ref\":\"#/components/schemas/HDMIPortId\"},\"autoLowLatencyModeSignalled\":{\"type\":\"boolean\"}}},\"AutoLowLatencyModeCapableChangedInfo\":{\"title\":\"AutoLowLatencyModeCapableChangedInfo\",\"type\":\"object\",\"properties\":{\"port\":{\"$ref\":\"#/components/schemas/HDMIPortId\"},\"enabled\":{\"type\":\"boolean\"}},\"required\":[\"port\",\"enabled\"]},\"KeyboardParameters\":{\"title\":\"KeyboardParameters\",\"type\":\"object\",\"required\":[\"message\"],\"properties\":{\"message\":{\"description\":\"The message to display to the user so the user knows what they are entering\",\"type\":\"string\"}},\"examples\":[{\"type\":\"standard\",\"message\":\"Enter your user name.\"}]},\"KeyboardProviderRequest\":{\"title\":\"KeyboardProviderRequest\",\"type\":\"object\",\"required\":[\"correlationId\",\"parameters\"],\"properties\":{\"correlationId\":{\"type\":\"string\",\"description\":\"An id to correlate the provider response with this request\"},\"parameters\":{\"description\":\"The request to start a keyboard session\",\"$ref\":\"#/components/schemas/KeyboardParameters\"}}},\"EventObjectPrimitives\":{\"title\":\"EventObjectPrimitives\",\"anyOf\":[{\"type\":\"string\",\"maxLength\":256},{\"type\":\"number\"},{\"type\":\"integer\"},{\"type\":\"boolean\"},{\"type\":\"null\"}]},\"EventObject\":{\"title\":\"EventObject\",\"type\":\"object\",\"maxProperties\":256,\"additionalProperties\":{\"anyOf\":[{\"$ref\":\"#/components/schemas/EventObjectPrimitives\"},{\"type\":\"array\",\"maxItems\":256,\"items\":{\"anyOf\":[{\"$ref\":\"#/components/schemas/EventObjectPrimitives\"},{\"$ref\":\"#/components/schemas/EventObject\"}]}},{\"$ref\":\"#/components/schemas/EventObject\"}]}},\"PinChallenge\":{\"title\":\"PinChallenge\",\"type\":\"object\",\"required\":[\"requestor\",\"pinSpace\"],\"properties\":{\"pinSpace\":{\"type\":\"string\",\"description\":\"The pin space that this challenge is for\",\"enum\":[\"purchase\",\"content\"]},\"capability\":{\"type\":\"string\",\"description\":\"The capability that is gated by a pin challenge\"},\"requestor\":{\"description\":\"The identity of which app is requesting access to this capability\",\"$ref\":\"#/components/schemas/ChallengeRequestor\"}}},\"PinChallengeProviderRequest\":{\"title\":\"PinChallengeProviderRequest\",\"allOf\":[{\"$ref\":\"#/x-schemas/Types/ProviderRequest\"},{\"type\":\"object\",\"required\":[\"parameters\"],\"properties\":{\"parameters\":{\"description\":\"The request to challenge the user\",\"$ref\":\"#/components/schemas/PinChallenge\"}}}]},\"ResultReason\":{\"title\":\"ResultReason\",\"type\":\"string\",\"description\":\"The reason for the result of challenging the user\",\"enum\":[\"noPinRequired\",\"noPinRequiredWindow\",\"exceededPinFailures\",\"correctPin\",\"cancelled\"]},\"PinChallengeResult\":{\"title\":\"PinChallengeResult\",\"type\":\"object\",\"required\":[\"granted\",\"reason\"],\"properties\":{\"granted\":{\"oneOf\":[{\"type\":\"boolean\",\"description\":\"Whether the user succeeded in the pin challenge\"},{\"const\":null}]},\"reason\":{\"$ref\":\"#/components/schemas/ResultReason\",\"description\":\"The reason for the result \"}}},\"PrivacySettings\":{\"title\":\"PrivacySettings\",\"type\":\"object\",\"required\":[\"allowACRCollection\",\"allowResumePoints\",\"allowAppContentAdTargeting\",\"allowCameraAnalytics\",\"allowPersonalization\",\"allowPrimaryBrowseAdTargeting\",\"allowPrimaryContentAdTargeting\",\"allowProductAnalytics\",\"allowRemoteDiagnostics\",\"allowUnentitledPersonalization\",\"allowUnentitledResumePoints\",\"allowWatchHistory\"],\"properties\":{\"allowACRCollection\":{\"description\":\"\",\"type\":\"boolean\"},\"allowResumePoints\":{\"description\":\"\",\"type\":\"boolean\"},\"allowAppContentAdTargeting\":{\"description\":\"\",\"type\":\"boolean\"},\"allowCameraAnalytics\":{\"description\":\"\",\"type\":\"boolean\"},\"allowPersonalization\":{\"description\":\"\",\"type\":\"boolean\"},\"allowPrimaryBrowseAdTargeting\":{\"description\":\"\",\"type\":\"boolean\"},\"allowPrimaryContentAdTargeting\":{\"description\":\"\",\"type\":\"boolean\"},\"allowProductAnalytics\":{\"description\":\"\",\"type\":\"boolean\"},\"allowRemoteDiagnostics\":{\"description\":\"\",\"type\":\"boolean\"},\"allowUnentitledPersonalization\":{\"description\":\"\",\"type\":\"boolean\"},\"allowUnentitledResumePoints\":{\"description\":\"\",\"type\":\"boolean\"},\"allowWatchHistory\":{\"description\":\"\",\"type\":\"boolean\"}},\"examples\":[{\"allowACRCollection\":true,\"allowResumePoints\":false,\"allowAppContentAdTargeting\":false,\"allowCameraAnalytics\":true,\"allowPersonalization\":true,\"allowPrimaryBrowseAdTargeting\":false,\"allowPrimaryContentAdTargeting\":false,\"allowProductAnalytics\":true,\"allowRemoteDiagnostics\":true,\"allowUnentitledPersonalization\":true,\"allowUnentitledResumePoints\":false,\"allowWatchHistory\":true}]},\"StorageScope\":{\"title\":\"StorageScope\",\"type\":\"string\",\"enum\":[\"device\",\"account\"],\"description\":\"The scope of the data\"},\"StorageOptions\":{\"title\":\"StorageOptions\",\"type\":\"object\",\"required\":[\"ttl\"],\"properties\":{\"ttl\":{\"type\":\"number\",\"description\":\"Seconds from set time before the data expires and is removed\"}}},\"GrantInfo\":{\"description\":\"Information about a grant given by a user\",\"type\":\"object\",\"properties\":{\"app\":{\"$ref\":\"#/components/schemas/AppInfo\"},\"state\":{\"$ref\":\"#/components/schemas/GrantState\"},\"capability\":{\"$ref\":\"#/x-schemas/Capabilities/Capability\"},\"role\":{\"$ref\":\"#/x-schemas/Capabilities/Role\"},\"lifespan\":{\"type\":\"string\",\"enum\":[\"once\",\"forever\",\"appActive\",\"powerActive\",\"seconds\"]},\"expires\":{\"type\":\"string\",\"format\":\"date-time\"}},\"additionalProperties\":false,\"required\":[\"state\",\"capability\",\"role\",\"lifespan\"],\"examples\":[{\"app\":{\"id\":\"certapp\",\"title\":\"Firebolt Certification\"},\"state\":\"granted\",\"capability\":\"xrn:firebolt:capability:data:app-usage\",\"role\":\"use\",\"lifespan\":\"seconds\",\"expires\":\"2022-12-14T20:20:39+00:00\"}]},\"AppInfo\":{\"description\":\"Information about an app that a grant was for\",\"type\":\"object\",\"properties\":{\"id\":{\"type\":\"string\"},\"title\":{\"type\":\"string\"}},\"additionalProperties\":false,\"required\":[\"id\"]},\"GrantState\":{\"description\":\"The state the grant is in\",\"type\":\"string\",\"enum\":[\"granted\",\"denied\"]},\"GrantModificationOptions\":{\"description\":\"Options when modifying any grant\",\"type\":\"object\",\"properties\":{\"appId\":{\"type\":\"string\"}},\"additionalProperties\":false,\"required\":[]},\"RequestOptions\":{\"title\":\"RequestOptions\",\"type\":\"object\",\"properties\":{\"force\":{\"type\":\"boolean\",\"description\":\"Whether to force for user grant even if the previous decision stored\"}}},\"AccessPointList\":{\"title\":\"AccessPointList\",\"type\":\"object\",\"description\":\"List of scanned Wifi networks available near the device.\",\"properties\":{\"list\":{\"type\":\"array\",\"items\":{\"$ref\":\"#/components/schemas/AccessPoint\"}}}},\"WifiSecurityMode\":{\"title\":\"WifiSecurityMode\",\"description\":\"Security Mode supported for Wifi\",\"type\":\"string\",\"enum\":[\"none\",\"wep64\",\"wep128\",\"wpaPskTkip\",\"wpaPskAes\",\"wpa2PskTkip\",\"wpa2PskAes\",\"wpaEnterpriseTkip\",\"wpaEnterpriseAes\",\"wpa2EnterpriseTkip\",\"wpa2EnterpriseAes\",\"wpa2Psk\",\"wpa2Enterprise\",\"wpa3PskAes\",\"wpa3Sae\"]},\"WifiSignalStrength\":{\"title\":\"WifiSignalStrength\",\"description\":\"Strength of Wifi signal, value is negative based on RSSI specification.\",\"type\":\"integer\",\"default\":-255,\"minimum\":-255,\"maximum\":0},\"WifiFrequency\":{\"title\":\"WifiFrequency\",\"description\":\"Wifi Frequency in Ghz, example 2.4Ghz and 5Ghz.\",\"type\":\"number\",\"default\":0,\"minimum\":0},\"AccessPoint\":{\"title\":\"AccessPoint\",\"description\":\"Properties of a scanned wifi list item.\",\"type\":\"object\",\"properties\":{\"ssid\":{\"type\":\"string\",\"description\":\"Name of the wifi.\"},\"securityMode\":{\"$ref\":\"#/components/schemas/WifiSecurityMode\"},\"signalStrength\":{\"$ref\":\"#/components/schemas/WifiSignalStrength\"},\"frequency\":{\"$ref\":\"#/components/schemas/WifiFrequency\"}}},\"WPSSecurityPin\":{\"title\":\"WPSSecurityPin\",\"description\":\"Security pin type for WPS(Wifi Protected Setup).\",\"type\":\"string\",\"enum\":[\"pushButton\",\"pin\",\"manufacturerPin\"]}}},\"x-schemas\":{\"Types\":{\"uri\":\"https://meta.comcast.com/firebolt/types\",\"SemanticVersion\":{\"title\":\"SemanticVersion\",\"type\":\"object\",\"properties\":{\"major\":{\"type\":\"integer\",\"minimum\":0},\"minor\":{\"type\":\"integer\",\"minimum\":0},\"patch\":{\"type\":\"integer\",\"minimum\":0},\"readable\":{\"type\":\"string\"}},\"required\":[\"major\",\"minor\",\"patch\",\"readable\"],\"additionalProperties\":false},\"ListenResponse\":{\"title\":\"ListenResponse\",\"type\":\"object\",\"required\":[\"event\",\"listening\"],\"properties\":{\"event\":{\"type\":\"string\",\"pattern\":\"[a-zA-Z]+\\\\.on[A-Z][a-zA-Z]+\"},\"listening\":{\"type\":\"boolean\"}},\"additionalProperties\":false},\"ProviderRequest\":{\"title\":\"ProviderRequest\",\"type\":\"object\",\"required\":[\"correlationId\"],\"additionalProperties\":false,\"properties\":{\"correlationId\":{\"type\":\"string\",\"description\":\"The id that was passed in to the event that triggered a provider method to be called\"},\"parameters\":{\"description\":\"The result of the provider response.\",\"type\":[\"object\",\"null\"]}}},\"AudioProfile\":{\"title\":\"AudioProfile\",\"type\":\"string\",\"enum\":[\"stereo\",\"dolbyDigital5.1\",\"dolbyDigital5.1+\",\"dolbyAtmos\"]},\"LocalizedString\":{\"title\":\"LocalizedString\",\"description\":\"Localized string supports either a simple `string` or a Map of language codes to strings. When using a simple `string`, the current preferred langauge from `Localization.langauge()` is assumed.\",\"oneOf\":[{\"type\":\"string\"},{\"type\":\"object\",\"additionalProperties\":{\"type\":\"string\"}}],\"examples\":[\"A simple string, with no language code\",{\"en\":\"This is english\",\"es\":\"esto es español\"}]},\"FlatMap\":{\"type\":\"object\",\"additionalProperties\":{\"oneOf\":[{\"type\":\"string\"},{\"type\":\"number\"},{\"type\":\"boolean\"}]}},\"BooleanMap\":{\"title\":\"BooleanMap\",\"type\":\"object\",\"additionalProperties\":{\"type\":\"boolean\"}},\"Timeout\":{\"title\":\"Timeout\",\"description\":\"Defines the timeout in seconds. If the threshold for timeout is passed for any operation without a result it will throw an error.\",\"type\":\"integer\",\"default\":0,\"minimum\":0,\"maximum\":9999}},\"Accessibility\":{\"uri\":\"https://meta.comcast.com/firebolt/accessibility\",\"ClosedCaptionsSettings\":{\"title\":\"ClosedCaptionsSettings\",\"type\":\"object\",\"required\":[\"enabled\"],\"properties\":{\"enabled\":{\"type\":\"boolean\",\"description\":\"Whether or not closed-captions should be enabled by default\"},\"styles\":{\"$ref\":\"#/x-schemas/Accessibility/ClosedCaptionsStyles\"},\"preferredLanguages\":{\"type\":\"array\",\"items\":{\"$ref\":\"#/x-schemas/Localization/ISO639_2Language\"}}},\"examples\":[{\"enabled\":true,\"styles\":{\"fontFamily\":\"monospaced_serif\",\"fontSize\":1,\"fontColor\":\"#ffffff\",\"fontEdge\":\"none\",\"fontEdgeColor\":\"#7F7F7F\",\"fontOpacity\":100,\"backgroundColor\":\"#000000\",\"backgroundOpacity\":100,\"textAlign\":\"center\",\"textAlignVertical\":\"middle\",\"windowColor\":\"white\",\"windowOpacity\":50},\"preferredLanguages\":[\"eng\",\"spa\"]}]},\"VoiceGuidanceSettings\":{\"title\":\"VoiceGuidanceSettings\",\"type\":\"object\",\"required\":[\"enabled\"],\"properties\":{\"enabled\":{\"type\":\"boolean\",\"description\":\"Whether or not voice guidance should be enabled by default\"},\"speed\":{\"$ref\":\"#/x-schemas/Accessibility/VoiceSpeed\",\"description\":\"The speed at which voice guidance speech will be read back to the user\"}},\"examples\":[{\"enabled\":true,\"speed\":2}]},\"VoiceSpeed\":{\"title\":\"VoiceSpeed\",\"type\":\"number\",\"minimum\":0.5,\"maximum\":2},\"ClosedCaptionsStyles\":{\"title\":\"ClosedCaptionsStyles\",\"type\":\"object\",\"description\":\"The default styles to use when displaying closed-captions\",\"properties\":{\"fontFamily\":{\"$ref\":\"#/x-schemas/Accessibility/FontFamily\"},\"fontSize\":{\"$ref\":\"#/x-schemas/Accessibility/FontSize\"},\"fontColor\":{\"$ref\":\"#/x-schemas/Accessibility/Color\"},\"fontEdge\":{\"$ref\":\"#/x-schemas/Accessibility/FontEdge\"},\"fontEdgeColor\":{\"$ref\":\"#/x-schemas/Accessibility/Color\"},\"fontOpacity\":{\"$ref\":\"#/x-schemas/Accessibility/Opacity\"},\"backgroundColor\":{\"$ref\":\"#/x-schemas/Accessibility/Color\"},\"backgroundOpacity\":{\"$ref\":\"#/x-schemas/Accessibility/Opacity\"},\"textAlign\":{\"$ref\":\"#/x-schemas/Accessibility/HorizontalAlignment\"},\"textAlignVertical\":{\"$ref\":\"#/x-schemas/Accessibility/VerticalAlignment\"},\"windowColor\":{\"$ref\":\"#/x-schemas/Accessibility/Color\"},\"windowOpacity\":{\"$ref\":\"#/x-schemas/Accessibility/Opacity\"}}},\"FontFamily\":{\"type\":[\"string\",\"null\"],\"enum\":[\"monospaced_serif\",\"proportional_serif\",\"monospaced_sanserif\",\"proportional_sanserif\",\"smallcaps\",\"cursive\",\"casual\",null]},\"FontSize\":{\"type\":[\"number\",\"null\"],\"minimum\":0},\"Color\":{\"type\":[\"string\",\"null\"]},\"FontEdge\":{\"type\":[\"string\",\"null\"],\"enum\":[\"none\",\"raised\",\"depressed\",\"uniform\",\"drop_shadow_left\",\"drop_shadow_right\",null]},\"Opacity\":{\"type\":[\"number\",\"null\"],\"minimum\":0,\"maximum\":100},\"HorizontalAlignment\":{\"type\":[\"string\",\"null\"]},\"VerticalAlignment\":{\"type\":[\"string\",\"null\"]}},\"Localization\":{\"uri\":\"https://meta.comcast.com/firebolt/localization\",\"ISO639_2Language\":{\"type\":\"string\",\"pattern\":\"^[a-z]{3}$\"},\"Locality\":{\"type\":\"string\"},\"CountryCode\":{\"type\":\"string\",\"pattern\":\"^[A-Z]{2}$\"},\"Language\":{\"type\":\"string\",\"pattern\":\"^[A-Za-z]{2}$\"},\"Locale\":{\"type\":\"string\",\"pattern\":\"^[a-zA-Z]+([a-zA-Z0-9\\\\-]*)$\"},\"TimeZone\":{\"type\":\"string\",\"pattern\":\"^[-+_/ A-Za-z 0-9]*$\"}},\"Advertising\":{\"uri\":\"https://meta.comcast.com/firebolt/advertising\",\"SkipRestriction\":{\"title\":\"SkipRestriction\",\"$comment\":\"xrn:advertising:policy:skipRestriction:\",\"type\":\"string\",\"enum\":[\"none\",\"adsUnwatched\",\"adsAll\",\"all\"],\"description\":\"The advertisement skip restriction.\\n\\nApplies to fast-forward/rewind (e.g. trick mode), seeking over an entire opportunity (e.g. jump), seeking out of what's currently playing, and \\\"Skip this ad...\\\" features. Seeking over multiple ad opportunities only requires playback of the _last_ opportunity, not all opportunities, preceding the seek destination.\\n\\n| Value | Description |\\n|--------------|--------------------------------------------------------------------------------|\\n| none |No fast-forward, jump, or skip restrictions |\\n| adsUnwatched | Restrict fast-forward, jump, and skip for unwatched ad opportunities only. |\\n| adsAll | Restrict fast-forward, jump, and skip for all ad opportunities |\\n| all | Restrict fast-forward, jump, and skip for all ad opportunities and all content |\\n\\nNamespace: `xrn:advertising:policy:skipRestriction:`\\n\\n\"}},\"Capabilities\":{\"uri\":\"https://meta.comcast.com/firebolt/capabilities\",\"Capability\":{\"title\":\"Capability\",\"type\":\"string\",\"description\":\"A Capability is a discrete unit of functionality that a Firebolt device might be able to perform.\",\"pattern\":\"^xrn:firebolt:capability:([a-z0-9\\\\-]+)((:[a-z0-9\\\\-]+)?)$\"},\"CapabilityInfo\":{\"title\":\"CapabilityInfo\",\"type\":\"object\",\"required\":[\"supported\",\"available\",\"use\",\"manage\",\"provide\"],\"properties\":{\"capability\":{\"$ref\":\"#/x-schemas/Capabilities/Capability\"},\"supported\":{\"type\":\"boolean\",\"description\":\"Provides info whether the capability is supported\"},\"available\":{\"type\":\"boolean\",\"description\":\"Provides info whether the capability is available\"},\"use\":{\"$ref\":\"#/x-schemas/Capabilities/CapPermissionStatus\"},\"manage\":{\"$ref\":\"#/x-schemas/Capabilities/CapPermissionStatus\"},\"provide\":{\"$ref\":\"#/x-schemas/Capabilities/CapPermissionStatus\"},\"details\":{\"type\":\"array\",\"items\":{\"$ref\":\"#/x-schemas/Capabilities/DenyReason\"},\"minItems\":1,\"maxItems\":6}},\"additionalProperties\":false,\"examples\":[{\"capability\":\"xrn:firebolt:capability:keyboard\",\"supported\":true,\"available\":true,\"use\":{\"permitted\":true,\"granted\":true},\"manage\":{\"permitted\":true,\"granted\":true},\"provide\":{\"permitted\":true,\"granted\":true}}]},\"Permission\":{\"title\":\"Permission\",\"description\":\"A capability combined with a Role, which an app may be permitted (by a distributor) or granted (by an end user).\",\"type\":\"object\",\"required\":[\"capability\"],\"properties\":{\"role\":{\"$ref\":\"#/x-schemas/Capabilities/Role\"},\"capability\":{\"$ref\":\"#/x-schemas/Capabilities/Capability\"}},\"additionalProperties\":false},\"Role\":{\"title\":\"Role\",\"description\":\"Role provides access level for the app for a given capability.\",\"type\":\"string\",\"enum\":[\"use\",\"manage\",\"provide\"]},\"CapPermissionStatus\":{\"type\":\"object\",\"properties\":{\"permitted\":{\"type\":\"boolean\",\"description\":\"Provides info whether the capability is permitted\"},\"granted\":{\"oneOf\":[{\"type\":\"boolean\",\"description\":\"Provides info whether the capability is granted\"},{\"const\":null}]}},\"additionalProperties\":false},\"DenyReason\":{\"title\":\"DenyReason\",\"description\":\"Reasons why a Capability might not be invokable\",\"type\":\"string\",\"enum\":[\"unpermitted\",\"unsupported\",\"disabled\",\"unavailable\",\"grantDenied\",\"ungranted\"]}},\"Discovery\":{\"uri\":\"https://meta.comcast.com/firebolt/discovery\",\"InterestType\":{\"title\":\"InterestType\",\"type\":\"string\",\"enum\":[\"interest\",\"disinterest\"]},\"InterestReason\":{\"title\":\"InterestReason\",\"type\":\"string\",\"enum\":[\"playlist\",\"reaction\",\"recording\"]},\"EntityInfoResult\":{\"title\":\"EntityInfoResult\",\"description\":\"The result for an `entityInfo()` push or pull.\",\"type\":\"object\",\"properties\":{\"expires\":{\"type\":\"string\",\"format\":\"date-time\"},\"entity\":{\"$ref\":\"#/x-schemas/Entertainment/EntityInfo\"},\"related\":{\"type\":\"array\",\"items\":{\"$ref\":\"#/x-schemas/Entertainment/EntityInfo\"}}},\"required\":[\"expires\",\"entity\"],\"additionalProperties\":false},\"PurchasedContentResult\":{\"title\":\"PurchasedContentResult\",\"type\":\"object\",\"properties\":{\"expires\":{\"type\":\"string\",\"format\":\"date-time\"},\"totalCount\":{\"type\":\"integer\",\"minimum\":0},\"entries\":{\"type\":\"array\",\"items\":{\"$ref\":\"#/x-schemas/Entertainment/EntityInfo\"}}},\"required\":[\"expires\",\"totalCount\",\"entries\"],\"additionalProperties\":false}},\"Entity\":{\"uri\":\"https://meta.comcast.com/firebolt/entity\",\"EntityDetails\":{\"title\":\"EntityDetails\",\"type\":\"object\",\"required\":[\"identifiers\"],\"properties\":{\"identifiers\":{\"$ref\":\"#/x-schemas/Entity/Entity\"},\"info\":{\"$ref\":\"#/x-schemas/Entity/Metadata\"},\"waysToWatch\":{\"type\":\"array\",\"items\":{\"$ref\":\"#/x-schemas/Entertainment/WayToWatch\"},\"description\":\"An array of ways a user is might watch this entity, regardless of entitlements.\"}}},\"Entity\":{\"oneOf\":[{\"$ref\":\"#/x-schemas/Entity/ProgramEntity\"},{\"$ref\":\"#/x-schemas/Entity/MusicEntity\"},{\"$ref\":\"#/x-schemas/Entity/ChannelEntity\"},{\"$ref\":\"#/x-schemas/Entity/UntypedEntity\"},{\"$ref\":\"#/x-schemas/Entity/PlaylistEntity\"}]},\"Metadata\":{\"title\":\"Metadata\",\"type\":\"object\",\"properties\":{\"title\":{\"type\":\"string\",\"description\":\"Title of the entity.\"},\"synopsis\":{\"type\":\"string\",\"description\":\"Short description of the entity.\"},\"seasonNumber\":{\"type\":\"number\",\"description\":\"For TV seasons, the season number. For TV episodes, the season that the episode belongs to.\"},\"seasonCount\":{\"type\":\"number\",\"description\":\"For TV series, seasons, and episodes, the total number of seasons.\"},\"episodeNumber\":{\"type\":\"number\",\"description\":\"For TV episodes, the episode number.\"},\"episodeCount\":{\"type\":\"number\",\"description\":\"For TV seasons and episodes, the total number of episodes in the current season.\"},\"releaseDate\":{\"type\":\"string\",\"format\":\"date-time\",\"description\":\"The date that the program or entity was released or first aired.\"},\"contentRatings\":{\"type\":\"array\",\"items\":{\"$ref\":\"#/x-schemas/Entertainment/ContentRating\"},\"description\":\"A list of ContentRating objects, describing the entity's ratings in various rating schemes.\"}}},\"ProgramEntity\":{\"title\":\"ProgramEntity\",\"oneOf\":[{\"$ref\":\"#/x-schemas/Entity/MovieEntity\"},{\"$ref\":\"#/x-schemas/Entity/TVEpisodeEntity\"},{\"$ref\":\"#/x-schemas/Entity/TVSeasonEntity\"},{\"$ref\":\"#/x-schemas/Entity/TVSeriesEntity\"},{\"$ref\":\"#/x-schemas/Entity/AdditionalEntity\"}]},\"MusicEntity\":{\"title\":\"MusicEntity\",\"type\":\"object\",\"properties\":{\"entityType\":{\"const\":\"music\"},\"musicType\":{\"$ref\":\"#/x-schemas/Entertainment/MusicType\"},\"entityId\":{\"type\":\"string\"}},\"required\":[\"entityType\",\"musicType\",\"entityId\"]},\"ChannelEntity\":{\"title\":\"ChannelEntity\",\"type\":\"object\",\"properties\":{\"entityType\":{\"const\":\"channel\"},\"channelType\":{\"type\":\"string\",\"enum\":[\"streaming\",\"overTheAir\"]},\"entityId\":{\"type\":\"string\",\"description\":\"ID of the channel, in the target App's scope.\"},\"appContentData\":{\"type\":\"string\",\"maxLength\":256}},\"required\":[\"entityType\",\"channelType\",\"entityId\"],\"additionalProperties\":false},\"UntypedEntity\":{\"title\":\"UntypedEntity\",\"allOf\":[{\"description\":\"A Firebolt compliant representation of the remaining entity types.\",\"type\":\"object\",\"required\":[\"entityId\"],\"properties\":{\"entityId\":{\"type\":\"string\"},\"assetId\":{\"type\":\"string\"},\"appContentData\":{\"type\":\"string\",\"maxLength\":256}},\"additionalProperties\":false}],\"examples\":[{\"entityId\":\"an-entity\"}]},\"PlaylistEntity\":{\"title\":\"PlaylistEntity\",\"description\":\"A Firebolt compliant representation of a Playlist entity.\",\"type\":\"object\",\"required\":[\"entityType\",\"entityId\"],\"properties\":{\"entityType\":{\"const\":\"playlist\"},\"entityId\":{\"type\":\"string\"},\"assetId\":{\"type\":\"string\"},\"appContentData\":{\"type\":\"string\",\"maxLength\":256}},\"additionalProperties\":false,\"examples\":[{\"entityType\":\"playlist\",\"entityId\":\"playlist/xyz\"}]},\"MovieEntity\":{\"title\":\"MovieEntity\",\"description\":\"A Firebolt compliant representation of a Movie entity.\",\"type\":\"object\",\"required\":[\"entityType\",\"programType\",\"entityId\"],\"properties\":{\"entityType\":{\"const\":\"program\"},\"programType\":{\"const\":\"movie\"},\"entityId\":{\"type\":\"string\"},\"assetId\":{\"type\":\"string\"},\"appContentData\":{\"type\":\"string\",\"maxLength\":256}},\"additionalProperties\":false,\"examples\":[{\"entityType\":\"program\",\"programType\":\"movie\",\"entityId\":\"el-camino\"}]},\"TVEpisodeEntity\":{\"title\":\"TVEpisodeEntity\",\"description\":\"A Firebolt compliant representation of a TV Episode entity.\",\"type\":\"object\",\"required\":[\"entityType\",\"programType\",\"entityId\",\"seriesId\",\"seasonId\"],\"properties\":{\"entityType\":{\"const\":\"program\"},\"programType\":{\"const\":\"episode\"},\"entityId\":{\"type\":\"string\"},\"seriesId\":{\"type\":\"string\"},\"seasonId\":{\"type\":\"string\"},\"assetId\":{\"type\":\"string\"},\"appContentData\":{\"type\":\"string\",\"maxLength\":256}},\"additionalProperties\":false,\"examples\":[{\"entityType\":\"program\",\"programType\":\"episode\",\"entityId\":\"breaking-bad-pilot\",\"seriesId\":\"breaking-bad\",\"seasonId\":\"breaking-bad-season-1\"}]},\"TVSeasonEntity\":{\"title\":\"TVSeasonEntity\",\"description\":\"A Firebolt compliant representation of a TV Season entity.\",\"type\":\"object\",\"required\":[\"entityType\",\"programType\",\"entityId\",\"seriesId\"],\"properties\":{\"entityType\":{\"const\":\"program\"},\"programType\":{\"const\":\"season\"},\"entityId\":{\"type\":\"string\"},\"seriesId\":{\"type\":\"string\"},\"assetId\":{\"type\":\"string\"},\"appContentData\":{\"type\":\"string\",\"maxLength\":256}},\"additionalProperties\":false,\"examples\":[{\"entityType\":\"program\",\"programType\":\"season\",\"entityId\":\"breaking-bad-season-1\",\"seriesId\":\"breaking-bad\"}]},\"TVSeriesEntity\":{\"title\":\"TVSeriesEntity\",\"description\":\"A Firebolt compliant representation of a TV Series entity.\",\"type\":\"object\",\"required\":[\"entityType\",\"programType\",\"entityId\"],\"properties\":{\"entityType\":{\"const\":\"program\"},\"programType\":{\"const\":\"series\"},\"entityId\":{\"type\":\"string\"},\"assetId\":{\"type\":\"string\"},\"appContentData\":{\"type\":\"string\",\"maxLength\":256}},\"additionalProperties\":false,\"examples\":[{\"entityType\":\"program\",\"programType\":\"series\",\"entityId\":\"breaking-bad\"}]},\"AdditionalEntity\":{\"title\":\"AdditionalEntity\",\"description\":\"A Firebolt compliant representation of the remaining program entity types.\",\"type\":\"object\",\"required\":[\"entityType\",\"programType\",\"entityId\"],\"properties\":{\"entityType\":{\"const\":\"program\"},\"programType\":{\"type\":\"string\",\"enum\":[\"concert\",\"sportingEvent\",\"preview\",\"other\",\"advertisement\",\"musicVideo\",\"minisode\",\"extra\"]},\"entityId\":{\"type\":\"string\"},\"assetId\":{\"type\":\"string\"},\"appContentData\":{\"type\":\"string\",\"maxLength\":256}},\"additionalProperties\":false,\"examples\":[{\"entityType\":\"program\",\"programType\":\"concert\",\"entityId\":\"live-aid\"}]},\"PlayableEntity\":{\"title\":\"PlayableEntity\",\"anyOf\":[{\"$ref\":\"#/x-schemas/Entity/MovieEntity\"},{\"$ref\":\"#/x-schemas/Entity/TVEpisodeEntity\"},{\"$ref\":\"#/x-schemas/Entity/PlaylistEntity\"},{\"$ref\":\"#/x-schemas/Entity/MusicEntity\"},{\"$ref\":\"#/x-schemas/Entity/AdditionalEntity\"}]}},\"Entertainment\":{\"uri\":\"https://meta.comcast.com/firebolt/entertainment\",\"WayToWatch\":{\"title\":\"WayToWatch\",\"type\":\"object\",\"required\":[\"identifiers\",\"audioProfile\"],\"properties\":{\"identifiers\":{\"$ref\":\"#/x-schemas/Entertainment/ContentIdentifiers\"},\"expires\":{\"type\":\"string\",\"format\":\"date-time\",\"description\":\"Time when the WayToWatch is no longer available.\"},\"entitled\":{\"type\":\"boolean\",\"description\":\"Specify if the user is entitled to watch the entity.\"},\"entitledExpires\":{\"type\":\"string\",\"format\":\"date-time\",\"description\":\"Time when the entity is no longer entitled.\"},\"offeringType\":{\"$ref\":\"#/x-schemas/Entertainment/OfferingType\"},\"hasAds\":{\"type\":\"boolean\",\"description\":\"True if the streamable asset contains ads.\"},\"price\":{\"type\":\"number\",\"description\":\"For \\\"buy\\\" and \\\"rent\\\" WayToWatch, the price to buy or rent in the user's preferred currency.\"},\"videoQuality\":{\"type\":\"array\",\"items\":{\"type\":\"string\",\"enum\":[\"SD\",\"HD\",\"UHD\"]},\"description\":\"List of the video qualities available via the WayToWatch.\"},\"audioProfile\":{\"type\":\"array\",\"items\":{\"$ref\":\"#/x-schemas/Types/AudioProfile\"},\"description\":\"List of the audio types available via the WayToWatch.\"},\"audioLanguages\":{\"type\":\"array\",\"items\":{\"type\":\"string\"},\"description\":\"List of audio track languages available on the WayToWatch. The first is considered the primary language. Languages are expressed as ISO 639 1/2 codes.\"},\"closedCaptions\":{\"type\":\"array\",\"items\":{\"type\":\"string\"},\"description\":\"List of languages for which closed captions are available on the WayToWatch. Languages are expressed as ISO 639 1/2 codes.\"},\"subtitles\":{\"type\":\"array\",\"items\":{\"type\":\"string\"},\"description\":\"List of languages for which subtitles are available on the WayToWatch. Languages are expressed as ISO 639 1/2 codes.\"},\"audioDescriptions\":{\"type\":\"array\",\"items\":{\"type\":\"string\"},\"description\":\"List of languages for which audio descriptions (DVD) as available on the WayToWatch. Languages are expressed as ISO 639 1/2 codes.\"}},\"description\":\"A WayToWatch describes a way to watch a video program. It may describe a single\\nstreamable asset or a set of streamable assets. For example, an app provider may\\ndescribe HD, SD, and UHD assets as individual WayToWatch objects or rolled into\\na single WayToWatch.\\n\\nIf the WayToWatch represents a single streamable asset, the provided\\nContentIdentifiers must be sufficient to play back the specific asset when sent\\nvia a playback intent or deep link. If the WayToWatch represents multiple\\nstreamable assets, the provided ContentIdentifiers must be sufficient to\\nplayback one of the assets represented with no user action. In this scenario,\\nthe app SHOULD choose the best asset for the user based on their device and\\nsettings. The ContentIdentifiers MUST also be sufficient for navigating the user\\nto the appropriate entity or detail screen via an entity intent.\\n\\nThe app should set the `entitled` property to indicate if the user can watch, or\\nnot watch, the asset without making a purchase. If the entitlement is known to\\nexpire at a certain time (e.g., a rental), the app should also provide the\\n`entitledExpires` property. If the entitlement is not expired, the UI will use\\nthe `entitled` property to display watchable assets to the user, adjust how\\nassets are presented to the user, and how intents into the app are generated.\\nFor example, the the Aggregated Experience could render a \\\"Watch\\\" button for an\\nentitled asset versus a \\\"Subscribe\\\" button for an non-entitled asset.\\n\\nThe app should set the `offeringType` to define how the content may be\\nauthorized. The UI will use this to adjust how content is presented to the user.\\n\\nA single WayToWatch cannot represent streamable assets available via multiple\\npurchase paths. If, for example, an asset has both Buy, Rent and Subscription\\navailability, the three different entitlement paths MUST be represented as\\nmultiple WayToWatch objects.\\n\\n`price` should be populated for WayToWatch objects with `buy` or `rent`\\n`offeringType`. If the WayToWatch represents a set of assets with various price\\npoints, the `price` provided must be the lowest available price.\"},\"OfferingType\":{\"title\":\"OfferingType\",\"type\":\"string\",\"enum\":[\"free\",\"subscribe\",\"buy\",\"rent\"],\"description\":\"The offering type of the WayToWatch.\"},\"ContentIdentifiers\":{\"title\":\"ContentIdentifiers\",\"type\":\"object\",\"properties\":{\"assetId\":{\"type\":\"string\",\"description\":\"Identifies a particular playable asset. For example, the HD version of a particular movie separate from the UHD version.\"},\"entityId\":{\"type\":\"string\",\"description\":\"Identifies an entity, such as a Movie, TV Series or TV Episode.\"},\"seasonId\":{\"type\":\"string\",\"description\":\"The TV Season for a TV Episode.\"},\"seriesId\":{\"type\":\"string\",\"description\":\"The TV Series for a TV Episode or TV Season.\"},\"appContentData\":{\"type\":\"string\",\"description\":\"App-specific content identifiers.\",\"maxLength\":1024}},\"description\":\"The ContentIdentifiers object is how the app identifies an entity or asset to\\nthe Firebolt platform. These ids are used to look up metadata and deep link into\\nthe app.\\n\\nApps do not need to provide all ids. They only need to provide the minimum\\nrequired to target a playable stream or an entity detail screen via a deep link.\\nIf an id isn't needed to get to those pages, it doesn't need to be included.\"},\"ContentRating\":{\"title\":\"ContentRating\",\"type\":\"object\",\"required\":[\"scheme\",\"rating\"],\"properties\":{\"scheme\":{\"type\":\"string\",\"enum\":[\"CA-Movie\",\"CA-TV\",\"CA-Movie-Fr\",\"CA-TV-Fr\",\"US-Movie\",\"US-TV\"],\"description\":\"The rating scheme.\"},\"rating\":{\"type\":\"string\",\"description\":\"The content rating.\"},\"advisories\":{\"type\":\"array\",\"items\":{\"type\":\"string\"},\"description\":\"Optional list of subratings or content advisories.\"}},\"description\":\"A ContentRating represents an age or content based of an entity. Supported rating schemes and associated types are below.\\n\\n## United States\\n\\n`US-Movie` (MPAA):\\n\\nRatings: `NR`, `G`, `PG`, `PG13`, `R`, `NC17`\\n\\nAdvisories: `AT`, `BN`, `SL`, `SS`, `N`, `V`\\n\\n`US-TV` (Vchip):\\n\\nRatings: `TVY`, `TVY7`, `TVG`, `TVPG`, `TV14`, `TVMA`\\n\\nAdvisories: `FV`, `D`, `L`, `S`, `V`\\n\\n## Canada\\n\\n`CA-Movie` (OFRB):\\n\\nRatings: `G`, `PG`, `14A`, `18A`, `R`, `E`\\n\\n`CA-TV` (AGVOT)\\n\\nRatings: `E`, `C`, `C8`, `G`, `PG`, `14+`, `18+`\\n\\nAdvisories: `C`, `C8`, `G`, `PG`, `14+`, `18+`\\n\\n`CA-Movie-Fr` (Canadian French language movies):\\n\\nRatings: `G`, `8+`, `13+`, `16+`, `18+`\\n\\n`CA-TV-Fr` (Canadian French language TV):\\n\\nRatings: `G`, `8+`, `13+`, `16+`, `18+`\\n\"},\"MusicType\":{\"title\":\"MusicType\",\"type\":\"string\",\"description\":\"In the case of a music `entityType`, specifies the type of music entity.\",\"enum\":[\"song\",\"album\"]},\"Entitlement\":{\"title\":\"Entitlement\",\"type\":\"object\",\"properties\":{\"entitlementId\":{\"type\":\"string\"},\"startTime\":{\"type\":\"string\",\"format\":\"date-time\"},\"endTime\":{\"type\":\"string\",\"format\":\"date-time\"}},\"required\":[\"entitlementId\"]},\"EntityInfo\":{\"title\":\"EntityInfo\",\"description\":\"An EntityInfo object represents an \\\"entity\\\" on the platform. Currently, only entities of type `program` are supported. `programType` must be supplied to identify the program type.\\n\\nAdditionally, EntityInfo objects must specify a properly formed\\nContentIdentifiers object, `entityType`, and `title`. The app should provide\\nthe `synopsis` property for a good user experience if the content\\nmetadata is not available another way.\\n\\nThe ContentIdentifiers must be sufficient for navigating the user to the\\nappropriate entity or detail screen via a `detail` intent or deep link.\\n\\nEntityInfo objects must provide at least one WayToWatch object when returned as\\npart of an `entityInfo` method and a streamable asset is available to the user.\\nIt is optional for the `purchasedContent` method, but recommended because the UI\\nmay use those data.\",\"type\":\"object\",\"required\":[\"identifiers\",\"entityType\",\"title\"],\"properties\":{\"identifiers\":{\"$ref\":\"#/x-schemas/Entertainment/ContentIdentifiers\"},\"title\":{\"type\":\"string\",\"description\":\"Title of the entity.\"},\"entityType\":{\"type\":\"string\",\"enum\":[\"program\",\"music\"],\"description\":\"The type of the entity, e.g. `program` or `music`.\"},\"programType\":{\"$ref\":\"#/x-schemas/Entertainment/ProgramType\"},\"musicType\":{\"$ref\":\"#/x-schemas/Entertainment/MusicType\"},\"synopsis\":{\"type\":\"string\",\"description\":\"Short description of the entity.\"},\"seasonNumber\":{\"type\":\"number\",\"description\":\"For TV seasons, the season number. For TV episodes, the season that the episode belongs to.\"},\"seasonCount\":{\"type\":\"number\",\"description\":\"For TV series, seasons, and episodes, the total number of seasons.\"},\"episodeNumber\":{\"type\":\"number\",\"description\":\"For TV episodes, the episode number.\"},\"episodeCount\":{\"type\":\"number\",\"description\":\"For TV seasons and episodes, the total number of episodes in the current season.\"},\"releaseDate\":{\"type\":\"string\",\"format\":\"date-time\",\"description\":\"The date that the program or entity was released or first aired.\"},\"contentRatings\":{\"type\":\"array\",\"items\":{\"$ref\":\"#/x-schemas/Entertainment/ContentRating\"},\"description\":\"A list of ContentRating objects, describing the entity's ratings in various rating schemes.\"},\"waysToWatch\":{\"type\":\"array\",\"items\":{\"$ref\":\"#/x-schemas/Entertainment/WayToWatch\"},\"description\":\"An array of ways a user is might watch this entity, regardless of entitlements.\"}},\"if\":{\"properties\":{\"entityType\":{\"const\":\"program\"}}},\"then\":{\"required\":[\"programType\"],\"not\":{\"required\":[\"musicType\"]}},\"else\":{\"required\":[\"musicType\"],\"not\":{\"required\":[\"programType\"]}}},\"ProgramType\":{\"title\":\"ProgramType\",\"type\":\"string\",\"description\":\"In the case of a program `entityType`, specifies the program type.\",\"enum\":[\"movie\",\"episode\",\"season\",\"series\",\"other\",\"preview\",\"extra\",\"concert\",\"sportingEvent\",\"advertisement\",\"musicVideo\",\"minisode\"]}},\"Intents\":{\"uri\":\"https://meta.comcast.com/firebolt/intents\",\"NavigationIntent\":{\"title\":\"NavigationIntent\",\"description\":\"A Firebolt compliant representation of a user intention to navigate to a specific place in an app.\",\"anyOf\":[{\"$ref\":\"#/x-schemas/Intents/HomeIntent\"},{\"$ref\":\"#/x-schemas/Intents/LaunchIntent\"},{\"$ref\":\"#/x-schemas/Intents/EntityIntent\"},{\"$ref\":\"#/x-schemas/Intents/PlaybackIntent\"},{\"$ref\":\"#/x-schemas/Intents/SearchIntent\"},{\"$ref\":\"#/x-schemas/Intents/SectionIntent\"},{\"$ref\":\"#/x-schemas/Intents/TuneIntent\"},{\"$ref\":\"#/x-schemas/Intents/PlayEntityIntent\"},{\"$ref\":\"#/x-schemas/Intents/PlayQueryIntent\"}]},\"HomeIntent\":{\"description\":\"A Firebolt compliant representation of a user intention to navigate an app to it's home screen, and bring that app to the foreground if needed.\",\"title\":\"HomeIntent\",\"allOf\":[{\"title\":\"HomeIntent\",\"$ref\":\"#/x-schemas/Intents/Intent\"},{\"title\":\"HomeIntent\",\"$ref\":\"#/x-schemas/Intents/IntentProperties\"},{\"title\":\"HomeIntent\",\"type\":\"object\",\"properties\":{\"action\":{\"const\":\"home\"}},\"not\":{\"required\":[\"data\"]}}],\"examples\":[{\"action\":\"home\",\"context\":{\"source\":\"voice\"}}]},\"LaunchIntent\":{\"description\":\"A Firebolt compliant representation of a user intention to launch an app.\",\"title\":\"LaunchIntent\",\"allOf\":[{\"$ref\":\"#/x-schemas/Intents/Intent\"},{\"$ref\":\"#/x-schemas/Intents/IntentProperties\"},{\"type\":\"object\",\"properties\":{\"action\":{\"const\":\"launch\"}},\"not\":{\"required\":[\"data\"]}}],\"examples\":[{\"action\":\"launch\",\"context\":{\"source\":\"voice\"}}]},\"EntityIntent\":{\"description\":\"A Firebolt compliant representation of a user intention to navigate an app to a specific entity page, and bring that app to the foreground if needed.\",\"title\":\"EntityIntent\",\"allOf\":[{\"$ref\":\"#/x-schemas/Intents/Intent\"},{\"$ref\":\"#/x-schemas/Intents/IntentProperties\"},{\"type\":\"object\",\"required\":[\"data\"],\"properties\":{\"action\":{\"const\":\"entity\"},\"data\":{\"$ref\":\"#/x-schemas/Entity/Entity\"}}}],\"examples\":[{\"action\":\"entity\",\"context\":{\"source\":\"voice\"},\"data\":{\"entityType\":\"program\",\"programType\":\"movie\",\"entityId\":\"el-camino\"}}]},\"PlaybackIntent\":{\"description\":\"A Firebolt compliant representation of a user intention to navigate an app to a the video player for a specific, playable entity, and bring that app to the foreground if needed.\",\"title\":\"PlaybackIntent\",\"allOf\":[{\"$ref\":\"#/x-schemas/Intents/Intent\"},{\"$ref\":\"#/x-schemas/Intents/IntentProperties\"},{\"type\":\"object\",\"required\":[\"data\"],\"properties\":{\"action\":{\"const\":\"playback\"},\"data\":{\"$ref\":\"#/x-schemas/Entity/PlayableEntity\"}}}],\"examples\":[{\"action\":\"playback\",\"data\":{\"entityType\":\"program\",\"programType\":\"episode\",\"entityId\":\"breaking-bad-pilot\",\"seriesId\":\"breaking-bad\",\"seasonId\":\"breaking-bad-season-1\"},\"context\":{\"source\":\"voice\"}}]},\"SearchIntent\":{\"description\":\"A Firebolt compliant representation of a user intention to navigate an app to it's search UI with a search term populated, and bring that app to the foreground if needed.\",\"title\":\"SearchIntent\",\"allOf\":[{\"$ref\":\"#/x-schemas/Intents/Intent\"},{\"$ref\":\"#/x-schemas/Intents/IntentProperties\"},{\"type\":\"object\",\"properties\":{\"action\":{\"const\":\"search\"},\"data\":{\"type\":\"object\",\"required\":[\"query\"],\"properties\":{\"query\":{\"type\":\"string\"},\"suggestions\":{\"type\":\"array\",\"items\":{\"$ref\":\"#/x-schemas/Entity/Entity\"}}},\"additionalProperties\":false}}}],\"examples\":[{\"action\":\"search\",\"data\":{\"query\":\"walter white\"},\"context\":{\"source\":\"voice\"}}]},\"SectionIntent\":{\"description\":\"A Firebolt compliant representation of a user intention to navigate an app to a section not covered by `home`, `entity`, `player`, or `search`, and bring that app to the foreground if needed.\",\"title\":\"SectionIntent\",\"allOf\":[{\"$ref\":\"#/x-schemas/Intents/Intent\"},{\"$ref\":\"#/x-schemas/Intents/IntentProperties\"},{\"type\":\"object\",\"properties\":{\"action\":{\"const\":\"section\"},\"data\":{\"type\":\"object\",\"required\":[\"sectionName\"],\"properties\":{\"sectionName\":{\"type\":\"string\"}},\"additionalProperties\":false}},\"required\":[\"data\"]}],\"examples\":[{\"action\":\"section\",\"data\":{\"sectionName\":\"settings\"},\"context\":{\"source\":\"voice\"}}]},\"TuneIntent\":{\"description\":\"A Firebolt compliant representation of a user intention to 'tune' to a traditional over-the-air broadcast, or an OTT Stream from an OTT or vMVPD App.\",\"title\":\"TuneIntent\",\"allOf\":[{\"$ref\":\"#/x-schemas/Intents/Intent\"},{\"$ref\":\"#/x-schemas/Intents/IntentProperties\"},{\"type\":\"object\",\"required\":[\"data\"],\"properties\":{\"action\":{\"const\":\"tune\"},\"data\":{\"type\":\"object\",\"required\":[\"entity\"],\"additionalProperties\":false,\"properties\":{\"entity\":{\"$ref\":\"#/x-schemas/Entity/ChannelEntity\"},\"options\":{\"description\":\"The options property of the data property MUST have only one of the following fields.\",\"type\":\"object\",\"required\":[],\"additionalProperties\":false,\"minProperties\":1,\"maxProperties\":1,\"properties\":{\"assetId\":{\"type\":\"string\",\"description\":\"The ID of a specific 'listing', as scoped by the target App's ID-space, which the App should begin playback from.\"},\"restartCurrentProgram\":{\"type\":\"boolean\",\"description\":\"Denotes that the App should start playback at the most recent program boundary, rather than 'live.'\"},\"time\":{\"type\":\"string\",\"format\":\"date-time\",\"description\":\"ISO 8601 Date/Time where the App should begin playback from.\"}}}}}}}],\"examples\":[{\"action\":\"tune\",\"data\":{\"entity\":{\"entityType\":\"channel\",\"channelType\":\"streaming\",\"entityId\":\"an-ott-channel\"},\"options\":{\"restartCurrentProgram\":true}},\"context\":{\"source\":\"voice\"}}]},\"PlayEntityIntent\":{\"description\":\"A Firebolt compliant representation of a user intention to navigate an app to a the video player for a specific, playable entity, and bring that app to the foreground if needed.\",\"title\":\"PlayEntityIntent\",\"allOf\":[{\"$ref\":\"#/x-schemas/Intents/Intent\"},{\"$ref\":\"#/x-schemas/Intents/IntentProperties\"},{\"type\":\"object\",\"required\":[\"data\"],\"properties\":{\"action\":{\"const\":\"play-entity\"},\"data\":{\"type\":\"object\",\"properties\":{\"entity\":{\"$ref\":\"#/x-schemas/Entity/PlayableEntity\"},\"options\":{\"type\":\"object\",\"properties\":{\"playFirstId\":{\"type\":\"string\"},\"playFirstTrack\":{\"type\":\"integer\",\"minimum\":1}},\"additionalProperties\":false}},\"required\":[\"entity\"],\"propertyNames\":{\"enum\":[\"entity\",\"options\"]},\"if\":{\"properties\":{\"entity\":{\"type\":\"object\",\"required\":[\"entityType\"],\"properties\":{\"entityType\":{\"const\":\"playlist\"}}}}},\"then\":{\"type\":\"object\",\"properties\":{\"options\":{\"type\":\"object\",\"maxProperties\":1}}},\"else\":{\"type\":\"object\",\"properties\":{\"options\":{\"type\":\"object\",\"maxProperties\":0}}}}}}],\"examples\":[{\"action\":\"play-entity\",\"data\":{\"entity\":{\"entityType\":\"playlist\",\"entityId\":\"playlist/xyz\"},\"options\":{\"playFirstId\":\"song/xyz\"}},\"context\":{\"source\":\"voice\"}},{\"action\":\"play-entity\",\"data\":{\"entity\":{\"entityType\":\"playlist\",\"entityId\":\"playlist/xyz\"},\"options\":{\"playFirstTrack\":3}},\"context\":{\"source\":\"voice\"}}]},\"PlayQueryIntent\":{\"description\":\"A Firebolt compliant representation of a user intention to navigate an app to a the video player for an abstract query to be searched for and played by the app.\",\"title\":\"PlayQueryIntent\",\"allOf\":[{\"$ref\":\"#/x-schemas/Intents/Intent\"},{\"$ref\":\"#/x-schemas/Intents/IntentProperties\"},{\"type\":\"object\",\"required\":[\"data\"],\"properties\":{\"action\":{\"const\":\"play-query\"},\"data\":{\"type\":\"object\",\"properties\":{\"query\":{\"type\":\"string\"},\"options\":{\"type\":\"object\",\"properties\":{\"programTypes\":{\"type\":\"array\",\"items\":{\"$ref\":\"#/x-schemas/Entertainment/ProgramType\"}},\"musicTypes\":{\"type\":\"array\",\"items\":{\"$ref\":\"#/x-schemas/Entertainment/MusicType\"}}},\"additionalProperties\":false}},\"required\":[\"query\"],\"propertyNames\":{\"enum\":[\"query\",\"options\"]}}}}],\"examples\":[{\"action\":\"play-query\",\"data\":{\"query\":\"Ed Sheeran\"},\"context\":{\"source\":\"voice\"}},{\"action\":\"play-query\",\"data\":{\"query\":\"Ed Sheeran\",\"options\":{\"programTypes\":[\"movie\"]}},\"context\":{\"source\":\"voice\"}},{\"action\":\"play-query\",\"data\":{\"query\":\"Ed Sheeran\",\"options\":{\"programTypes\":[\"movie\"],\"musicTypes\":[\"song\"]}},\"context\":{\"source\":\"voice\"}}]},\"Intent\":{\"description\":\"A Firebolt compliant representation of a user intention.\",\"type\":\"object\",\"required\":[\"action\",\"context\"],\"properties\":{\"action\":{\"type\":\"string\"},\"context\":{\"type\":\"object\",\"required\":[\"source\"],\"properties\":{\"source\":{\"type\":\"string\"}}}}},\"IntentProperties\":{\"type\":\"object\",\"propertyNames\":{\"enum\":[\"action\",\"data\",\"context\"]}}},\"Lifecycle\":{\"uri\":\"https://meta.comcast.com/firebolt/lifecycle\",\"CloseReason\":{\"title\":\"CloseReason\",\"description\":\"The application close reason\",\"type\":\"string\",\"enum\":[\"remoteButton\",\"userExit\",\"done\",\"error\"]},\"LifecycleState\":{\"title\":\"LifecycleState\",\"description\":\"The application lifecycle state\",\"type\":\"string\",\"enum\":[\"initializing\",\"inactive\",\"foreground\",\"background\",\"unloading\",\"suspended\"]}},\"SecondScreen\":{\"uri\":\"https://meta.comcast.com/firebolt/secondscreen\",\"SecondScreenEvent\":{\"title\":\"SecondScreenEvent\",\"description\":\"An a message notification from a second screen device\",\"type\":\"object\",\"required\":[\"type\"],\"properties\":{\"type\":{\"type\":\"string\",\"enum\":[\"dial\"]},\"version\":{\"type\":\"string\"},\"data\":{\"type\":\"string\"}}}}}}"); + +/***/ }), + +/***/ "./node_modules/@firebolt-js/manage-sdk/dist/lib/Account/defaults.mjs": +/*!****************************************************************************!*\ + !*** ./node_modules/@firebolt-js/manage-sdk/dist/lib/Account/defaults.mjs ***! + \****************************************************************************/ +/*! exports provided: default */ +/***/ (function(__webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var _Prop_MockProps_mjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Prop/MockProps.mjs */ "./node_modules/@firebolt-js/manage-sdk/dist/lib/Prop/MockProps.mjs"); +/* + * Copyright 2021 Comcast Cable Communications Management, LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + */ + + +/* harmony default export */ __webpack_exports__["default"] = ({ + session: null, +}); + + +/***/ }), + +/***/ "./node_modules/@firebolt-js/manage-sdk/dist/lib/Account/index.mjs": +/*!*************************************************************************!*\ + !*** ./node_modules/@firebolt-js/manage-sdk/dist/lib/Account/index.mjs ***! + \*************************************************************************/ +/*! exports provided: default */ +/***/ (function(__webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var _Transport_index_mjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Transport/index.mjs */ "./node_modules/@firebolt-js/manage-sdk/dist/lib/Transport/index.mjs"); +/* + * Copyright 2021 Comcast Cable Communications Management, LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + */ + + + +// Methods + +function session(token, expiresIn) { + const transforms = null + + return _Transport_index_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].send('Account', 'session', { token, expiresIn }, transforms) +} + +/* harmony default export */ __webpack_exports__["default"] = ({ + session, +}); + + +/***/ }), + +/***/ "./node_modules/@firebolt-js/manage-sdk/dist/lib/AcknowledgeChallenge/defaults.mjs": +/*!*****************************************************************************************!*\ + !*** ./node_modules/@firebolt-js/manage-sdk/dist/lib/AcknowledgeChallenge/defaults.mjs ***! + \*****************************************************************************************/ +/*! exports provided: default */ +/***/ (function(__webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var _Prop_MockProps_mjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Prop/MockProps.mjs */ "./node_modules/@firebolt-js/manage-sdk/dist/lib/Prop/MockProps.mjs"); +/* + * Copyright 2021 Comcast Cable Communications Management, LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + */ + + +/* harmony default export */ __webpack_exports__["default"] = ({ + challengeFocus: null, + challengeResponse: null, + challengeError: null, +}); + + +/***/ }), + +/***/ "./node_modules/@firebolt-js/manage-sdk/dist/lib/AcknowledgeChallenge/index.mjs": +/*!**************************************************************************************!*\ + !*** ./node_modules/@firebolt-js/manage-sdk/dist/lib/AcknowledgeChallenge/index.mjs ***! + \**************************************************************************************/ +/*! exports provided: default */ +/***/ (function(__webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var _Transport_index_mjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Transport/index.mjs */ "./node_modules/@firebolt-js/manage-sdk/dist/lib/Transport/index.mjs"); +/* harmony import */ var _ProvideManager_index_mjs__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../ProvideManager/index.mjs */ "./node_modules/@firebolt-js/manage-sdk/dist/lib/ProvideManager/index.mjs"); +/* + * Copyright 2021 Comcast Cable Communications Management, LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + */ + + + + + +Object(_ProvideManager_index_mjs__WEBPACK_IMPORTED_MODULE_1__["registerProviderInterface"])( + 'xrn:firebolt:capability:usergrant:acknowledgechallenge', + 'AcknowledgeChallenge', + [{ name: 'challenge', focus: true, response: true, parameters: true }], +) + +// Methods +function provide(capability, provider) { + return _ProvideManager_index_mjs__WEBPACK_IMPORTED_MODULE_1__["default"].provide(capability, provider) +} + +/* harmony default export */ __webpack_exports__["default"] = ({ + provide, +}); + + +/***/ }), + +/***/ "./node_modules/@firebolt-js/manage-sdk/dist/lib/Advertising/defaults.mjs": +/*!********************************************************************************!*\ + !*** ./node_modules/@firebolt-js/manage-sdk/dist/lib/Advertising/defaults.mjs ***! + \********************************************************************************/ +/*! exports provided: default */ +/***/ (function(__webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var _Prop_MockProps_mjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Prop/MockProps.mjs */ "./node_modules/@firebolt-js/manage-sdk/dist/lib/Prop/MockProps.mjs"); +/* + * Copyright 2021 Comcast Cable Communications Management, LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + */ + + +/* harmony default export */ __webpack_exports__["default"] = ({ + skipRestriction: function (params) { + return _Prop_MockProps_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].mock( + 'Advertising', + 'skipRestriction', + params, + undefined, + 0, + 'none', + ) + }, + resetIdentifier: null, + setSkipRestriction: function (params) { + const callbackOrValue = params.value + delete params.value + return _Prop_MockProps_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].mock( + 'Advertising', + 'skipRestriction', + params, + callbackOrValue, + 0, + null, + ) + }, +}); + + +/***/ }), + +/***/ "./node_modules/@firebolt-js/manage-sdk/dist/lib/Advertising/index.mjs": +/*!*****************************************************************************!*\ + !*** ./node_modules/@firebolt-js/manage-sdk/dist/lib/Advertising/index.mjs ***! + \*****************************************************************************/ +/*! exports provided: default */ +/***/ (function(__webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var _Transport_index_mjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Transport/index.mjs */ "./node_modules/@firebolt-js/manage-sdk/dist/lib/Transport/index.mjs"); +/* harmony import */ var _Events_index_mjs__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Events/index.mjs */ "./node_modules/@firebolt-js/manage-sdk/dist/lib/Events/index.mjs"); +/* harmony import */ var _Prop_index_mjs__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Prop/index.mjs */ "./node_modules/@firebolt-js/manage-sdk/dist/lib/Prop/index.mjs"); +/* + * Copyright 2021 Comcast Cable Communications Management, LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + */ + + + + + + +Object(_Events_index_mjs__WEBPACK_IMPORTED_MODULE_1__["registerEvents"])('Advertising', ['skipRestrictionChanged']) + +// onSkipRestrictionChanged is accessed via listen('skipRestrictionChanged, ...) + +// Methods +function clear(...args) { + return _Events_index_mjs__WEBPACK_IMPORTED_MODULE_1__["default"].clear('Advertising', ...args) +} + +function listen(...args) { + return _Events_index_mjs__WEBPACK_IMPORTED_MODULE_1__["default"].listen('Advertising', ...args) +} + +function once(...args) { + return _Events_index_mjs__WEBPACK_IMPORTED_MODULE_1__["default"].once('Advertising', ...args) +} + +function resetIdentifier() { + const transforms = null + + return _Transport_index_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].send('Advertising', 'resetIdentifier', {}, transforms) +} +function skipRestriction() { + let callbackOrValue = arguments[0] + let params = {} + + // x-subscriber-type: global + if (arguments.length === 1 && typeof arguments[0] === 'function') { + callbackOrValue = arguments[0] + params = {} + } + + return _Prop_index_mjs__WEBPACK_IMPORTED_MODULE_2__["default"].prop( + 'Advertising', + 'skipRestriction', + params, + callbackOrValue, + false, + false, + 0, + ) +} + +/* harmony default export */ __webpack_exports__["default"] = ({ + Events: { + SKIP_RESTRICTION_CHANGED: 'skipRestrictionChanged', + }, + + /** + * The advertisement skip restriction. + +Applies to fast-forward/rewind (e.g. trick mode), seeking over an entire opportunity (e.g. jump), seeking out of what's currently playing, and "Skip this ad..." features. Seeking over multiple ad opportunities only requires playback of the _last_ opportunity, not all opportunities, preceding the seek destination. + +| Value | Description | +|--------------|--------------------------------------------------------------------------------| +| none |No fast-forward, jump, or skip restrictions | +| adsUnwatched | Restrict fast-forward, jump, and skip for unwatched ad opportunities only. | +| adsAll | Restrict fast-forward, jump, and skip for all ad opportunities | +| all | Restrict fast-forward, jump, and skip for all ad opportunities and all content | + +Namespace: `xrn:advertising:policy:skipRestriction:` + + + */ + SkipRestriction: { + NONE: 'none', + ADS_UNWATCHED: 'adsUnwatched', + ADS_ALL: 'adsAll', + ALL: 'all', + }, + + clear, + listen, + once, + resetIdentifier, + skipRestriction, +}); + + +/***/ }), + +/***/ "./node_modules/@firebolt-js/manage-sdk/dist/lib/AudioDescriptions/defaults.mjs": +/*!**************************************************************************************!*\ + !*** ./node_modules/@firebolt-js/manage-sdk/dist/lib/AudioDescriptions/defaults.mjs ***! + \**************************************************************************************/ +/*! exports provided: default */ +/***/ (function(__webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var _Prop_MockProps_mjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Prop/MockProps.mjs */ "./node_modules/@firebolt-js/manage-sdk/dist/lib/Prop/MockProps.mjs"); +/* + * Copyright 2021 Comcast Cable Communications Management, LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + */ + + +/* harmony default export */ __webpack_exports__["default"] = ({ + enabled: function (params) { + return _Prop_MockProps_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].mock( + 'AudioDescriptions', + 'enabled', + params, + undefined, + 0, + true, + ) + }, + setEnabled: function (params) { + const callbackOrValue = params.value + delete params.value + return _Prop_MockProps_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].mock( + 'AudioDescriptions', + 'enabled', + params, + callbackOrValue, + 0, + null, + ) + }, +}); + + +/***/ }), + +/***/ "./node_modules/@firebolt-js/manage-sdk/dist/lib/AudioDescriptions/index.mjs": +/*!***********************************************************************************!*\ + !*** ./node_modules/@firebolt-js/manage-sdk/dist/lib/AudioDescriptions/index.mjs ***! + \***********************************************************************************/ +/*! exports provided: default */ +/***/ (function(__webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var _Transport_index_mjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Transport/index.mjs */ "./node_modules/@firebolt-js/manage-sdk/dist/lib/Transport/index.mjs"); +/* harmony import */ var _Events_index_mjs__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Events/index.mjs */ "./node_modules/@firebolt-js/manage-sdk/dist/lib/Events/index.mjs"); +/* harmony import */ var _Prop_index_mjs__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Prop/index.mjs */ "./node_modules/@firebolt-js/manage-sdk/dist/lib/Prop/index.mjs"); +/* + * Copyright 2021 Comcast Cable Communications Management, LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + */ + + + + + + +Object(_Events_index_mjs__WEBPACK_IMPORTED_MODULE_1__["registerEvents"])('AudioDescriptions', ['enabledChanged']) + +// onEnabledChanged is accessed via listen('enabledChanged, ...) + +// Methods +function clear(...args) { + return _Events_index_mjs__WEBPACK_IMPORTED_MODULE_1__["default"].clear('AudioDescriptions', ...args) +} + +function enabled() { + let callbackOrValue = arguments[0] + let params = {} + + // x-subscriber-type: global + if (arguments.length === 1 && typeof arguments[0] === 'function') { + callbackOrValue = arguments[0] + params = {} + } + + return _Prop_index_mjs__WEBPACK_IMPORTED_MODULE_2__["default"].prop( + 'AudioDescriptions', + 'enabled', + params, + callbackOrValue, + false, + false, + 0, + ) +} +function listen(...args) { + return _Events_index_mjs__WEBPACK_IMPORTED_MODULE_1__["default"].listen('AudioDescriptions', ...args) +} + +function once(...args) { + return _Events_index_mjs__WEBPACK_IMPORTED_MODULE_1__["default"].once('AudioDescriptions', ...args) +} + +/* harmony default export */ __webpack_exports__["default"] = ({ + Events: { + ENABLED_CHANGED: 'enabledChanged', + }, + + clear, + enabled, + listen, + once, +}); + + +/***/ }), + +/***/ "./node_modules/@firebolt-js/manage-sdk/dist/lib/ClosedCaptions/defaults.mjs": +/*!***********************************************************************************!*\ + !*** ./node_modules/@firebolt-js/manage-sdk/dist/lib/ClosedCaptions/defaults.mjs ***! + \***********************************************************************************/ +/*! exports provided: default */ +/***/ (function(__webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var _Prop_MockProps_mjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Prop/MockProps.mjs */ "./node_modules/@firebolt-js/manage-sdk/dist/lib/Prop/MockProps.mjs"); +/* + * Copyright 2021 Comcast Cable Communications Management, LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + */ + + +/* harmony default export */ __webpack_exports__["default"] = ({ + enabled: function (params) { + return _Prop_MockProps_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].mock( + 'ClosedCaptions', + 'enabled', + params, + undefined, + 0, + true, + ) + }, + fontFamily: function (params) { + return _Prop_MockProps_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].mock( + 'ClosedCaptions', + 'fontFamily', + params, + undefined, + 0, + 'monospaced_sanserif', + ) + }, + fontSize: function (params) { + return _Prop_MockProps_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].mock('ClosedCaptions', 'fontSize', params, undefined, 0, 1) + }, + fontColor: function (params) { + return _Prop_MockProps_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].mock( + 'ClosedCaptions', + 'fontColor', + params, + undefined, + 0, + '#ffffff', + ) + }, + fontEdge: function (params) { + return _Prop_MockProps_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].mock( + 'ClosedCaptions', + 'fontEdge', + params, + undefined, + 0, + 'none', + ) + }, + fontEdgeColor: function (params) { + return _Prop_MockProps_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].mock( + 'ClosedCaptions', + 'fontEdgeColor', + params, + undefined, + 0, + '#000000', + ) + }, + fontOpacity: function (params) { + return _Prop_MockProps_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].mock( + 'ClosedCaptions', + 'fontOpacity', + params, + undefined, + 0, + 99, + ) + }, + backgroundColor: function (params) { + return _Prop_MockProps_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].mock( + 'ClosedCaptions', + 'backgroundColor', + params, + undefined, + 0, + '#000000', + ) + }, + backgroundOpacity: function (params) { + return _Prop_MockProps_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].mock( + 'ClosedCaptions', + 'backgroundOpacity', + params, + undefined, + 0, + 99, + ) + }, + textAlign: function (params) { + return _Prop_MockProps_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].mock( + 'ClosedCaptions', + 'textAlign', + params, + undefined, + 0, + 'center', + ) + }, + textAlignVertical: function (params) { + return _Prop_MockProps_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].mock( + 'ClosedCaptions', + 'textAlignVertical', + params, + undefined, + 0, + 'middle', + ) + }, + windowColor: function (params) { + return _Prop_MockProps_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].mock( + 'ClosedCaptions', + 'windowColor', + params, + undefined, + 0, + '#000000', + ) + }, + windowOpacity: function (params) { + return _Prop_MockProps_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].mock( + 'ClosedCaptions', + 'windowOpacity', + params, + undefined, + 0, + 99, + ) + }, + preferredLanguages: function (params) { + return _Prop_MockProps_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].mock( + 'ClosedCaptions', + 'preferredLanguages', + params, + undefined, + 0, + ['spa', 'eng'], + ) + }, + setEnabled: function (params) { + const callbackOrValue = params.value + delete params.value + return _Prop_MockProps_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].mock( + 'ClosedCaptions', + 'enabled', + params, + callbackOrValue, + 0, + null, + ) + }, + setFontFamily: function (params) { + const callbackOrValue = params.value + delete params.value + return _Prop_MockProps_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].mock( + 'ClosedCaptions', + 'fontFamily', + params, + callbackOrValue, + 0, + null, + ) + }, + setFontSize: function (params) { + const callbackOrValue = params.value + delete params.value + return _Prop_MockProps_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].mock( + 'ClosedCaptions', + 'fontSize', + params, + callbackOrValue, + 0, + null, + ) + }, + setFontColor: function (params) { + const callbackOrValue = params.value + delete params.value + return _Prop_MockProps_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].mock( + 'ClosedCaptions', + 'fontColor', + params, + callbackOrValue, + 0, + null, + ) + }, + setFontEdge: function (params) { + const callbackOrValue = params.value + delete params.value + return _Prop_MockProps_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].mock( + 'ClosedCaptions', + 'fontEdge', + params, + callbackOrValue, + 0, + null, + ) + }, + setFontEdgeColor: function (params) { + const callbackOrValue = params.value + delete params.value + return _Prop_MockProps_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].mock( + 'ClosedCaptions', + 'fontEdgeColor', + params, + callbackOrValue, + 0, + null, + ) + }, + setFontOpacity: function (params) { + const callbackOrValue = params.value + delete params.value + return _Prop_MockProps_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].mock( + 'ClosedCaptions', + 'fontOpacity', + params, + callbackOrValue, + 0, + null, + ) + }, + setBackgroundColor: function (params) { + const callbackOrValue = params.value + delete params.value + return _Prop_MockProps_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].mock( + 'ClosedCaptions', + 'backgroundColor', + params, + callbackOrValue, + 0, + null, + ) + }, + setBackgroundOpacity: function (params) { + const callbackOrValue = params.value + delete params.value + return _Prop_MockProps_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].mock( + 'ClosedCaptions', + 'backgroundOpacity', + params, + callbackOrValue, + 0, + null, + ) + }, + setTextAlign: function (params) { + const callbackOrValue = params.value + delete params.value + return _Prop_MockProps_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].mock( + 'ClosedCaptions', + 'textAlign', + params, + callbackOrValue, + 0, + null, + ) + }, + setTextAlignVertical: function (params) { + const callbackOrValue = params.value + delete params.value + return _Prop_MockProps_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].mock( + 'ClosedCaptions', + 'textAlignVertical', + params, + callbackOrValue, + 0, + null, + ) + }, + setWindowColor: function (params) { + const callbackOrValue = params.value + delete params.value + return _Prop_MockProps_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].mock( + 'ClosedCaptions', + 'windowColor', + params, + callbackOrValue, + 0, + null, + ) + }, + setWindowOpacity: function (params) { + const callbackOrValue = params.value + delete params.value + return _Prop_MockProps_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].mock( + 'ClosedCaptions', + 'windowOpacity', + params, + callbackOrValue, + 0, + null, + ) + }, + setPreferredLanguages: function (params) { + const callbackOrValue = params.value + delete params.value + return _Prop_MockProps_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].mock( + 'ClosedCaptions', + 'preferredLanguages', + params, + callbackOrValue, + 0, + null, + ) + }, +}); + + +/***/ }), + +/***/ "./node_modules/@firebolt-js/manage-sdk/dist/lib/ClosedCaptions/index.mjs": +/*!********************************************************************************!*\ + !*** ./node_modules/@firebolt-js/manage-sdk/dist/lib/ClosedCaptions/index.mjs ***! + \********************************************************************************/ +/*! exports provided: default */ +/***/ (function(__webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var _Transport_index_mjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Transport/index.mjs */ "./node_modules/@firebolt-js/manage-sdk/dist/lib/Transport/index.mjs"); +/* harmony import */ var _Events_index_mjs__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Events/index.mjs */ "./node_modules/@firebolt-js/manage-sdk/dist/lib/Events/index.mjs"); +/* harmony import */ var _Prop_index_mjs__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Prop/index.mjs */ "./node_modules/@firebolt-js/manage-sdk/dist/lib/Prop/index.mjs"); +/* + * Copyright 2021 Comcast Cable Communications Management, LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + */ + + + + + + +Object(_Events_index_mjs__WEBPACK_IMPORTED_MODULE_1__["registerEvents"])('ClosedCaptions', [ + 'backgroundColorChanged', + 'backgroundOpacityChanged', + 'enabledChanged', + 'fontColorChanged', + 'fontEdgeChanged', + 'fontEdgeColorChanged', + 'fontFamilyChanged', + 'fontOpacityChanged', + 'fontSizeChanged', + 'preferredLanguagesChanged', + 'textAlignChanged', + 'textAlignVerticalChanged', + 'windowColorChanged', + 'windowOpacityChanged', +]) + +// onBackgroundColorChanged is accessed via listen('backgroundColorChanged, ...) + +// onBackgroundOpacityChanged is accessed via listen('backgroundOpacityChanged, ...) + +// onEnabledChanged is accessed via listen('enabledChanged, ...) + +// onFontColorChanged is accessed via listen('fontColorChanged, ...) + +// onFontEdgeChanged is accessed via listen('fontEdgeChanged, ...) + +// onFontEdgeColorChanged is accessed via listen('fontEdgeColorChanged, ...) + +// onFontFamilyChanged is accessed via listen('fontFamilyChanged, ...) + +// onFontOpacityChanged is accessed via listen('fontOpacityChanged, ...) + +// onFontSizeChanged is accessed via listen('fontSizeChanged, ...) + +// onPreferredLanguagesChanged is accessed via listen('preferredLanguagesChanged, ...) + +// onTextAlignChanged is accessed via listen('textAlignChanged, ...) + +// onTextAlignVerticalChanged is accessed via listen('textAlignVerticalChanged, ...) + +// onWindowColorChanged is accessed via listen('windowColorChanged, ...) + +// onWindowOpacityChanged is accessed via listen('windowOpacityChanged, ...) + +// Methods +function backgroundColor() { + let callbackOrValue = arguments[0] + let params = {} + + // x-subscriber-type: global + if (arguments.length === 1 && typeof arguments[0] === 'function') { + callbackOrValue = arguments[0] + params = {} + } + + return _Prop_index_mjs__WEBPACK_IMPORTED_MODULE_2__["default"].prop( + 'ClosedCaptions', + 'backgroundColor', + params, + callbackOrValue, + false, + false, + 0, + ) +} +function backgroundOpacity() { + let callbackOrValue = arguments[0] + let params = {} + + // x-subscriber-type: global + if (arguments.length === 1 && typeof arguments[0] === 'function') { + callbackOrValue = arguments[0] + params = {} + } + + return _Prop_index_mjs__WEBPACK_IMPORTED_MODULE_2__["default"].prop( + 'ClosedCaptions', + 'backgroundOpacity', + params, + callbackOrValue, + false, + false, + 0, + ) +} +function clear(...args) { + return _Events_index_mjs__WEBPACK_IMPORTED_MODULE_1__["default"].clear('ClosedCaptions', ...args) +} + +function enabled() { + let callbackOrValue = arguments[0] + let params = {} + + // x-subscriber-type: global + if (arguments.length === 1 && typeof arguments[0] === 'function') { + callbackOrValue = arguments[0] + params = {} + } + + return _Prop_index_mjs__WEBPACK_IMPORTED_MODULE_2__["default"].prop( + 'ClosedCaptions', + 'enabled', + params, + callbackOrValue, + false, + false, + 0, + ) +} +function fontColor() { + let callbackOrValue = arguments[0] + let params = {} + + // x-subscriber-type: global + if (arguments.length === 1 && typeof arguments[0] === 'function') { + callbackOrValue = arguments[0] + params = {} + } + + return _Prop_index_mjs__WEBPACK_IMPORTED_MODULE_2__["default"].prop( + 'ClosedCaptions', + 'fontColor', + params, + callbackOrValue, + false, + false, + 0, + ) +} +function fontEdge() { + let callbackOrValue = arguments[0] + let params = {} + + // x-subscriber-type: global + if (arguments.length === 1 && typeof arguments[0] === 'function') { + callbackOrValue = arguments[0] + params = {} + } + + return _Prop_index_mjs__WEBPACK_IMPORTED_MODULE_2__["default"].prop( + 'ClosedCaptions', + 'fontEdge', + params, + callbackOrValue, + false, + false, + 0, + ) +} +function fontEdgeColor() { + let callbackOrValue = arguments[0] + let params = {} + + // x-subscriber-type: global + if (arguments.length === 1 && typeof arguments[0] === 'function') { + callbackOrValue = arguments[0] + params = {} + } + + return _Prop_index_mjs__WEBPACK_IMPORTED_MODULE_2__["default"].prop( + 'ClosedCaptions', + 'fontEdgeColor', + params, + callbackOrValue, + false, + false, + 0, + ) +} +function fontFamily() { + let callbackOrValue = arguments[0] + let params = {} + + // x-subscriber-type: global + if (arguments.length === 1 && typeof arguments[0] === 'function') { + callbackOrValue = arguments[0] + params = {} + } + + return _Prop_index_mjs__WEBPACK_IMPORTED_MODULE_2__["default"].prop( + 'ClosedCaptions', + 'fontFamily', + params, + callbackOrValue, + false, + false, + 0, + ) +} +function fontOpacity() { + let callbackOrValue = arguments[0] + let params = {} + + // x-subscriber-type: global + if (arguments.length === 1 && typeof arguments[0] === 'function') { + callbackOrValue = arguments[0] + params = {} + } + + return _Prop_index_mjs__WEBPACK_IMPORTED_MODULE_2__["default"].prop( + 'ClosedCaptions', + 'fontOpacity', + params, + callbackOrValue, + false, + false, + 0, + ) +} +function fontSize() { + let callbackOrValue = arguments[0] + let params = {} + + // x-subscriber-type: global + if (arguments.length === 1 && typeof arguments[0] === 'function') { + callbackOrValue = arguments[0] + params = {} + } + + return _Prop_index_mjs__WEBPACK_IMPORTED_MODULE_2__["default"].prop( + 'ClosedCaptions', + 'fontSize', + params, + callbackOrValue, + false, + false, + 0, + ) +} +function listen(...args) { + return _Events_index_mjs__WEBPACK_IMPORTED_MODULE_1__["default"].listen('ClosedCaptions', ...args) +} + +function once(...args) { + return _Events_index_mjs__WEBPACK_IMPORTED_MODULE_1__["default"].once('ClosedCaptions', ...args) +} + +function preferredLanguages() { + let callbackOrValue = arguments[0] + let params = {} + + // x-subscriber-type: global + if (arguments.length === 1 && typeof arguments[0] === 'function') { + callbackOrValue = arguments[0] + params = {} + } + + return _Prop_index_mjs__WEBPACK_IMPORTED_MODULE_2__["default"].prop( + 'ClosedCaptions', + 'preferredLanguages', + params, + callbackOrValue, + false, + false, + 0, + ) +} +function textAlign() { + let callbackOrValue = arguments[0] + let params = {} + + // x-subscriber-type: global + if (arguments.length === 1 && typeof arguments[0] === 'function') { + callbackOrValue = arguments[0] + params = {} + } + + return _Prop_index_mjs__WEBPACK_IMPORTED_MODULE_2__["default"].prop( + 'ClosedCaptions', + 'textAlign', + params, + callbackOrValue, + false, + false, + 0, + ) +} +function textAlignVertical() { + let callbackOrValue = arguments[0] + let params = {} + + // x-subscriber-type: global + if (arguments.length === 1 && typeof arguments[0] === 'function') { + callbackOrValue = arguments[0] + params = {} + } + + return _Prop_index_mjs__WEBPACK_IMPORTED_MODULE_2__["default"].prop( + 'ClosedCaptions', + 'textAlignVertical', + params, + callbackOrValue, + false, + false, + 0, + ) +} +function windowColor() { + let callbackOrValue = arguments[0] + let params = {} + + // x-subscriber-type: global + if (arguments.length === 1 && typeof arguments[0] === 'function') { + callbackOrValue = arguments[0] + params = {} + } + + return _Prop_index_mjs__WEBPACK_IMPORTED_MODULE_2__["default"].prop( + 'ClosedCaptions', + 'windowColor', + params, + callbackOrValue, + false, + false, + 0, + ) +} +function windowOpacity() { + let callbackOrValue = arguments[0] + let params = {} + + // x-subscriber-type: global + if (arguments.length === 1 && typeof arguments[0] === 'function') { + callbackOrValue = arguments[0] + params = {} + } + + return _Prop_index_mjs__WEBPACK_IMPORTED_MODULE_2__["default"].prop( + 'ClosedCaptions', + 'windowOpacity', + params, + callbackOrValue, + false, + false, + 0, + ) +} + +/* harmony default export */ __webpack_exports__["default"] = ({ + Events: { + ENABLED_CHANGED: 'enabledChanged', + FONT_FAMILY_CHANGED: 'fontFamilyChanged', + FONT_SIZE_CHANGED: 'fontSizeChanged', + FONT_COLOR_CHANGED: 'fontColorChanged', + FONT_EDGE_CHANGED: 'fontEdgeChanged', + FONT_EDGE_COLOR_CHANGED: 'fontEdgeColorChanged', + FONT_OPACITY_CHANGED: 'fontOpacityChanged', + BACKGROUND_COLOR_CHANGED: 'backgroundColorChanged', + BACKGROUND_OPACITY_CHANGED: 'backgroundOpacityChanged', + TEXT_ALIGN_CHANGED: 'textAlignChanged', + TEXT_ALIGN_VERTICAL_CHANGED: 'textAlignVerticalChanged', + WINDOW_COLOR_CHANGED: 'windowColorChanged', + WINDOW_OPACITY_CHANGED: 'windowOpacityChanged', + PREFERRED_LANGUAGES_CHANGED: 'preferredLanguagesChanged', + }, + + /** + * + */ + FontFamily: { + MONOSPACED_SERIF: 'monospaced_serif', + PROPORTIONAL_SERIF: 'proportional_serif', + MONOSPACED_SANSERIF: 'monospaced_sanserif', + PROPORTIONAL_SANSERIF: 'proportional_sanserif', + SMALLCAPS: 'smallcaps', + CURSIVE: 'cursive', + CASUAL: 'casual', + }, + + /** + * + */ + FontEdge: { + NONE: 'none', + RAISED: 'raised', + DEPRESSED: 'depressed', + UNIFORM: 'uniform', + DROP_SHADOW_LEFT: 'drop_shadow_left', + DROP_SHADOW_RIGHT: 'drop_shadow_right', + }, + + backgroundColor, + backgroundOpacity, + clear, + enabled, + fontColor, + fontEdge, + fontEdgeColor, + fontFamily, + fontOpacity, + fontSize, + listen, + once, + preferredLanguages, + textAlign, + textAlignVertical, + windowColor, + windowOpacity, +}); + + +/***/ }), + +/***/ "./node_modules/@firebolt-js/manage-sdk/dist/lib/Device/defaults.mjs": +/*!***************************************************************************!*\ + !*** ./node_modules/@firebolt-js/manage-sdk/dist/lib/Device/defaults.mjs ***! + \***************************************************************************/ +/*! exports provided: default */ +/***/ (function(__webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var _Prop_MockProps_mjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Prop/MockProps.mjs */ "./node_modules/@firebolt-js/manage-sdk/dist/lib/Prop/MockProps.mjs"); +/* + * Copyright 2021 Comcast Cable Communications Management, LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + */ + + +/* harmony default export */ __webpack_exports__["default"] = ({ + name: function (params) { + return _Prop_MockProps_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].mock('Device', 'name', params, undefined, 0, 'Living Room') + }, + provision: null, + setName: function (params) { + const callbackOrValue = params.value + delete params.value + return _Prop_MockProps_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].mock('Device', 'name', params, callbackOrValue, 0, null) + }, +}); + + +/***/ }), + +/***/ "./node_modules/@firebolt-js/manage-sdk/dist/lib/Device/index.mjs": +/*!************************************************************************!*\ + !*** ./node_modules/@firebolt-js/manage-sdk/dist/lib/Device/index.mjs ***! + \************************************************************************/ +/*! exports provided: default */ +/***/ (function(__webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var _Transport_index_mjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Transport/index.mjs */ "./node_modules/@firebolt-js/manage-sdk/dist/lib/Transport/index.mjs"); +/* harmony import */ var _Events_index_mjs__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Events/index.mjs */ "./node_modules/@firebolt-js/manage-sdk/dist/lib/Events/index.mjs"); +/* harmony import */ var _Prop_index_mjs__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Prop/index.mjs */ "./node_modules/@firebolt-js/manage-sdk/dist/lib/Prop/index.mjs"); +/* + * Copyright 2021 Comcast Cable Communications Management, LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + */ + + + + + + +Object(_Events_index_mjs__WEBPACK_IMPORTED_MODULE_1__["registerEvents"])('Device', ['deviceNameChanged', 'nameChanged']) + +_Transport_index_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].registerDeprecatedMethod( + 'Device', + 'onDeviceNameChanged', + 'Use Device.name() instead.', +) + +// onDeviceNameChanged is accessed via listen('deviceNameChanged, ...) + +// onNameChanged is accessed via listen('nameChanged, ...) + +// Methods +function clear(...args) { + return _Events_index_mjs__WEBPACK_IMPORTED_MODULE_1__["default"].clear('Device', ...args) +} + +function listen(...args) { + return _Events_index_mjs__WEBPACK_IMPORTED_MODULE_1__["default"].listen('Device', ...args) +} + +function name() { + let callbackOrValue = arguments[0] + let params = {} + + // x-subscriber-type: global + if (arguments.length === 1 && typeof arguments[0] === 'function') { + callbackOrValue = arguments[0] + params = {} + } + + return _Prop_index_mjs__WEBPACK_IMPORTED_MODULE_2__["default"].prop('Device', 'name', params, callbackOrValue, false, false, 0) +} +function once(...args) { + return _Events_index_mjs__WEBPACK_IMPORTED_MODULE_1__["default"].once('Device', ...args) +} + +function provision(accountId, deviceId, distributorId) { + const transforms = null + + return _Transport_index_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].send( + 'Device', + 'provision', + { accountId, deviceId, distributorId }, + transforms, + ) +} + +/* harmony default export */ __webpack_exports__["default"] = ({ + Events: { + DEVICE_NAME_CHANGED: 'deviceNameChanged', + NAME_CHANGED: 'nameChanged', + }, + + clear, + listen, + name, + once, + provision, +}); + + +/***/ }), + +/***/ "./node_modules/@firebolt-js/manage-sdk/dist/lib/Discovery/defaults.mjs": +/*!******************************************************************************!*\ + !*** ./node_modules/@firebolt-js/manage-sdk/dist/lib/Discovery/defaults.mjs ***! + \******************************************************************************/ +/*! exports provided: default */ +/***/ (function(__webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var _Prop_MockProps_mjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Prop/MockProps.mjs */ "./node_modules/@firebolt-js/manage-sdk/dist/lib/Prop/MockProps.mjs"); +/* + * Copyright 2021 Comcast Cable Communications Management, LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + */ + + +/* harmony default export */ __webpack_exports__["default"] = ({}); + + +/***/ }), + +/***/ "./node_modules/@firebolt-js/manage-sdk/dist/lib/Discovery/index.mjs": +/*!***************************************************************************!*\ + !*** ./node_modules/@firebolt-js/manage-sdk/dist/lib/Discovery/index.mjs ***! + \***************************************************************************/ +/*! exports provided: default */ +/***/ (function(__webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var _Transport_index_mjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Transport/index.mjs */ "./node_modules/@firebolt-js/manage-sdk/dist/lib/Transport/index.mjs"); +/* harmony import */ var _Events_index_mjs__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Events/index.mjs */ "./node_modules/@firebolt-js/manage-sdk/dist/lib/Events/index.mjs"); +/* + * Copyright 2021 Comcast Cable Communications Management, LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + */ + + + + + +Object(_Events_index_mjs__WEBPACK_IMPORTED_MODULE_1__["registerEvents"])('Discovery', ['signIn', 'signOut']) + +// onSignIn is accessed via listen('signIn, ...) + +// onSignOut is accessed via listen('signOut, ...) + +// Methods +function clear(...args) { + return _Events_index_mjs__WEBPACK_IMPORTED_MODULE_1__["default"].clear('Discovery', ...args) +} + +function listen(...args) { + return _Events_index_mjs__WEBPACK_IMPORTED_MODULE_1__["default"].listen('Discovery', ...args) +} + +function once(...args) { + return _Events_index_mjs__WEBPACK_IMPORTED_MODULE_1__["default"].once('Discovery', ...args) +} + +/* harmony default export */ __webpack_exports__["default"] = ({ + Events: { + SIGN_IN: 'signIn', + SIGN_OUT: 'signOut', + }, + + clear, + listen, + once, +}); + + +/***/ }), + +/***/ "./node_modules/@firebolt-js/manage-sdk/dist/lib/Events/index.mjs": +/*!************************************************************************!*\ + !*** ./node_modules/@firebolt-js/manage-sdk/dist/lib/Events/index.mjs ***! + \************************************************************************/ +/*! exports provided: emit, registerEvents, registerEventContext, prioritize, default */ +/***/ (function(__webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "emit", function() { return emit; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "registerEvents", function() { return registerEvents; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "registerEventContext", function() { return registerEventContext; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "prioritize", function() { return prioritize; }); +/* harmony import */ var _Transport_index_mjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Transport/index.mjs */ "./node_modules/@firebolt-js/manage-sdk/dist/lib/Transport/index.mjs"); +/* harmony import */ var _Transport_MockTransport_mjs__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Transport/MockTransport.mjs */ "./node_modules/@firebolt-js/manage-sdk/dist/lib/Transport/MockTransport.mjs"); +/* + * Copyright 2021 Comcast Cable Communications Management, LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + */ + + + + +let listenerId = 0 + +// holds two maps of ${module}.${event} => listenerId, e.g. callback method id +// note that one callback can listen to multiple events, e.g. 'discovery.*' +// internal is only available via a private export that we use to ensure our modules know about +// events before the apps using the SDK (otherwise state errors can happen) +const listeners = { + internal: {}, + external: {}, + + // Several convenience functions below for checking both internal & external lists w/ one operation + + // gets a merge list of ids for a single event key + get: (key) => { + return Object.assign( + Object.assign({}, listeners.internal[key]), + listeners.external[key], + ) + }, + // adds a callback/id to a key on the external list only + set: (key, id, value) => { + listeners.external[key] = listeners.external[key] || {} + listeners.external[key][id] = value + }, + // adds a callback/id to a key on the internal list only + setInternal: (key, id, value) => { + listeners.internal[key] = listeners.internal[key] || {} + listeners.internal[key][id] = value + }, + // finds the key for an id in either list (it can only be in one) + find: (id) => { + let key + ;[listeners.internal, listeners.external].find((group) => { + key = Object.keys(group).find((key) => group[key][id]) + if (key) return true + }) + return key + }, + // removes an id from either list + remove: (id) => { + ;[listeners.internal, listeners.external].forEach((group) => { + Object.keys(group).forEach((key) => { + if (group[key] && group[key][id]) { + delete group[key][id] + if (Object.values(group[key]).length === 0) { + delete group[key] + } + } + }) + }) + }, + // removes a key from both lists if _internal is true, otherwise only the external list + removeKey: (key, _internal = false) => { + _internal && listeners.internal[key] && delete listeners.internal[key] + listeners.external[key] && delete listeners.external[key] + }, + // gives a list of all keys + keys: () => { + return Array.from( + new Set( + Object.keys(listeners.internal).concat(Object.keys(listeners.external)), + ), + ) + }, + // counts how many listeners are in a key across both lists + count: (key) => { + return Object.values(listeners.get(key)).length + }, +} + +// holds a map of RPC Ids => Context Key, e.g. the RPC id of an onEvent call mapped to the corresponding context parameters key for that RPC call +const keys = {} + +// holds a map of ${module}.${event} => Transport.send calls (only called once per event) +// note that the keys here MUST NOT contain wild cards +const oncers = [] +const validEvents = {} +const validContext = {} + +let transportInitialized = false + +const emit = (id, value) => { + callCallbacks(listeners.internal[keys[id]], [value]) + callCallbacks(listeners.external[keys[id]], [value]) +} + +const registerEvents = (module, events) => { + validEvents[module.toLowerCase()] = events.concat() +} + +const registerEventContext = (module, event, context) => { + validContext[module.toLowerCase()] = validContext[module.toLowerCase()] || {} + validContext[module.toLowerCase()][event] = context.concat() +} + +const callCallbacks = (cbs, args) => { + cbs && + Object.keys(cbs).forEach((listenerId) => { + let callback = cbs[listenerId] + if (oncers.indexOf(parseInt(listenerId)) >= 0) { + oncers.splice(oncers.indexOf(parseInt(listenerId)), 1) + delete cbs[listenerId] + } + callback.apply(null, args) + }) +} + +const doListen = function ( + module, + event, + callback, + context, + once, + internal = false, +) { + init() + + if (typeof callback !== 'function') { + return Promise.reject('No valid callback function provided.') + } else { + if (module === '*') { + return Promise.reject('No valid module name provided') + } + + const wildcard = event === '*' + const events = wildcard ? validEvents[module] : [event] // explodes wildcards into an array + const promises = [] + const hasContext = Object.values(context).length > 0 + const contextKey = Object.keys(context) + .sort() + .map((key) => key + '=' + JSON.stringify(context[key])) + .join('&') + + listenerId++ + + if (once) { + oncers.push(listenerId) + } + + events.forEach((event) => { + const key = module + '.' + event + (hasContext ? `.${contextKey}` : '') + + if (Object.values(listeners.get(key)).length === 0) { + const args = Object.assign({ listen: true }, context) + const { id, promise } = _Transport_index_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].listen( + module, + 'on' + event[0].toUpperCase() + event.substring(1), + args, + ) + keys[id] = key + promises.push(promise) + } + + const setter = internal ? listeners.setInternal : listeners.set + + if (wildcard) { + setter(key, '' + listenerId, (value) => callback(event, value)) + } else { + setter(key, '' + listenerId, callback) + } + }) + + let resolve, reject + let p = new Promise((res, rej) => { + resolve = res + reject = rej + }) + + if (promises.length) { + Promise.all(promises) + .then((responses) => { + resolve(listenerId) + }) + .catch((error) => { + // Promise.all rejects if at least one promise rejects... we don't want that behavior here + // TODO: Do something better than fail silently + if (event === '*') { + resolve(listenerId) + } else { + reject(error) + } + }) + } else { + resolve(listenerId) + } + return p + } +} + +const getListenArgs = function (...args) { + const callback = args.pop() + const [module, event, context] = getClearArgs(...args) + + return [module, event, callback, context] +} + +const getClearArgs = function (...args) { + const module = (args.shift() || '*').toLowerCase() + const event = args.shift() || '*' + const context = {} + + for (let i = 0; args.length; i++) { + context[validContext[module][event][i]] = args.shift() + } + + return [module, event, context] +} + +const once = function (...args) { + const [module, event, callback, context] = getListenArgs(...args) + return doListen(module, event, callback, context, true) +} + +const listen = function (...args) { + const [module, event, callback, context] = getListenArgs(...args) + return doListen(module, event, callback, context, false) +} + +const clear = function (...args) { + if (args && args.length && typeof args[0] === 'number') { + return doClear(args[0]) + } else if (args && args.length && typeof args[1] === 'number') { + return doClear(args[1]) + } else { + const [moduleOrId, event, context] = getClearArgs(...args) + return doClear(moduleOrId, event, context) + } +} + +// calls doListen with a priority flag for internal listeners to get priority +const prioritize = function (...args) { + const [module, event, callback, context] = getListenArgs(...args) + return doListen(module, event, callback, context, false, true) +} + +const unsubscribe = (key, context) => { + const [module, event] = key.split('.').slice(0, 2) + const args = Object.assign({ listen: false }, context) + _Transport_index_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].send(module, 'on' + event[0].toUpperCase() + event.substr(1), args) +} + +// TODO: clear needs to go through Transport Layer +const doClear = function (moduleOrId = false, event = false, context) { + if (event === '*') { + event = false + } + + if (typeof moduleOrId === 'number') { + const searchId = moduleOrId.toString() + const key = listeners.find(searchId) + + if (key) { + listeners.remove(searchId) + if (listeners.count(key) === 0) { + unsubscribe(key) + } + return true + } + return false + } else { + if (!moduleOrId && !event) { + listeners.keys().forEach((key) => { + listeners.removeKey(key) + unsubscribe(key) + }) + } else if (!event) { + listeners.keys().forEach((key) => { + if (key.indexOf(moduleOrId.toLowerCase()) === 0) { + listeners.removeKey(key) + unsubscribe(key) + } + }) + } else { + const hasContext = Object.values(context).length > 0 + const contextKey = Object.keys(context) + .sort() + .map((key) => key + '=' + JSON.stringify(context[key])) + .join('&') + const key = + moduleOrId + '.' + event + (hasContext ? `.${contextKey}` : '') + + listeners.removeKey(key) + unsubscribe(key, context) + } + } +} + +const init = () => { + if (!transportInitialized) { + _Transport_index_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].addEventEmitter(emit) + Object(_Transport_MockTransport_mjs__WEBPACK_IMPORTED_MODULE_1__["setMockListener"])(listen) + transportInitialized = true + } +} + +/* harmony default export */ __webpack_exports__["default"] = ({ + listen: listen, + once: once, + clear: clear, + broadcast(event, value) { + emit(Object.entries(keys).find(([k, v]) => v === 'app.' + event)[0], value) + }, +}); + + +/***/ }), + +/***/ "./node_modules/@firebolt-js/manage-sdk/dist/lib/HDMIInput/defaults.mjs": +/*!******************************************************************************!*\ + !*** ./node_modules/@firebolt-js/manage-sdk/dist/lib/HDMIInput/defaults.mjs ***! + \******************************************************************************/ +/*! exports provided: default */ +/***/ (function(__webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var _Prop_MockProps_mjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Prop/MockProps.mjs */ "./node_modules/@firebolt-js/manage-sdk/dist/lib/Prop/MockProps.mjs"); +/* + * Copyright 2021 Comcast Cable Communications Management, LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + */ + + +/* harmony default export */ __webpack_exports__["default"] = ({ + ports: [ + { + port: 'HDMI1', + connected: true, + signal: 'stable', + arcCapable: true, + arcConnected: true, + edidVersion: '2.0', + autoLowLatencyModeCapable: true, + autoLowLatencyModeSignalled: true, + }, + ], + port: { + port: 'HDMI1', + connected: true, + signal: 'stable', + arcCapable: true, + arcConnected: true, + edidVersion: '2.0', + autoLowLatencyModeCapable: true, + autoLowLatencyModeSignalled: true, + }, + open: null, + close: null, + lowLatencyMode: function (params) { + return _Prop_MockProps_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].mock( + 'HDMIInput', + 'lowLatencyMode', + params, + undefined, + 0, + true, + ) + }, + autoLowLatencyModeCapable: function (params) { + return _Prop_MockProps_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].mock( + 'HDMIInput', + 'autoLowLatencyModeCapable', + params, + undefined, + 1, + true, + ) + }, + edidVersion: function (params) { + return _Prop_MockProps_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].mock( + 'HDMIInput', + 'edidVersion', + params, + undefined, + 1, + '2.0', + ) + }, + setLowLatencyMode: function (params) { + const callbackOrValue = params.value + delete params.value + return _Prop_MockProps_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].mock( + 'HDMIInput', + 'lowLatencyMode', + params, + callbackOrValue, + 0, + null, + ) + }, + setAutoLowLatencyModeCapable: function (params) { + const callbackOrValue = params.value + delete params.value + return _Prop_MockProps_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].mock( + 'HDMIInput', + 'autoLowLatencyModeCapable', + params, + callbackOrValue, + 0, + null, + ) + }, + setEdidVersion: function (params) { + const callbackOrValue = params.value + delete params.value + return _Prop_MockProps_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].mock( + 'HDMIInput', + 'edidVersion', + params, + callbackOrValue, + 0, + null, + ) + }, +}); + + +/***/ }), + +/***/ "./node_modules/@firebolt-js/manage-sdk/dist/lib/HDMIInput/index.mjs": +/*!***************************************************************************!*\ + !*** ./node_modules/@firebolt-js/manage-sdk/dist/lib/HDMIInput/index.mjs ***! + \***************************************************************************/ +/*! exports provided: default */ +/***/ (function(__webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var _Transport_index_mjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Transport/index.mjs */ "./node_modules/@firebolt-js/manage-sdk/dist/lib/Transport/index.mjs"); +/* harmony import */ var _Events_index_mjs__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Events/index.mjs */ "./node_modules/@firebolt-js/manage-sdk/dist/lib/Events/index.mjs"); +/* harmony import */ var _Prop_index_mjs__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Prop/index.mjs */ "./node_modules/@firebolt-js/manage-sdk/dist/lib/Prop/index.mjs"); +/* + * Copyright 2021 Comcast Cable Communications Management, LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + */ + + + + + + + +Object(_Events_index_mjs__WEBPACK_IMPORTED_MODULE_1__["registerEvents"])('HDMIInput', [ + 'autoLowLatencyModeCapableChanged', + 'autoLowLatencyModeSignalChanged', + 'connectionChanged', + 'edidVersionChanged', + 'lowLatencyModeChanged', + 'signalChanged', +]) + +// onAutoLowLatencyModeCapableChanged is accessed via listen('autoLowLatencyModeCapableChanged, ...) + +// onAutoLowLatencyModeSignalChanged is accessed via listen('autoLowLatencyModeSignalChanged, ...) + +// onConnectionChanged is accessed via listen('connectionChanged, ...) + +// onEdidVersionChanged is accessed via listen('edidVersionChanged, ...) + +Object(_Events_index_mjs__WEBPACK_IMPORTED_MODULE_1__["registerEventContext"])('HDMIInput', 'edidVersionChanged', ['port']) +// onLowLatencyModeChanged is accessed via listen('lowLatencyModeChanged, ...) + +// onSignalChanged is accessed via listen('signalChanged, ...) + +// Methods +function autoLowLatencyModeCapable(port) { + let callbackOrValue = arguments[1] + let params = { port } + + // x-subscriber-type: global + if (arguments.length === 1 && typeof arguments[0] === 'function') { + callbackOrValue = arguments[0] + params = {} + } + + return _Prop_index_mjs__WEBPACK_IMPORTED_MODULE_2__["default"].prop( + 'HDMIInput', + 'autoLowLatencyModeCapable', + params, + callbackOrValue, + false, + false, + 1, + ) +} +function clear(...args) { + return _Events_index_mjs__WEBPACK_IMPORTED_MODULE_1__["default"].clear('HDMIInput', ...args) +} + +function close() { + const transforms = null + + return _Transport_index_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].send('HDMIInput', 'close', {}, transforms) +} +function edidVersion(port) { + let callbackOrValue = arguments[1] + let params = { port } + + // x-subscriber-type: global + if (arguments.length === 1 && typeof arguments[0] === 'function') { + callbackOrValue = arguments[0] + params = {} + } + + return _Prop_index_mjs__WEBPACK_IMPORTED_MODULE_2__["default"].prop( + 'HDMIInput', + 'edidVersion', + params, + callbackOrValue, + false, + false, + 1, + ) +} +function listen(...args) { + return _Events_index_mjs__WEBPACK_IMPORTED_MODULE_1__["default"].listen('HDMIInput', ...args) +} + +function lowLatencyMode() { + let callbackOrValue = arguments[0] + let params = {} + + // x-subscriber-type: global + if (arguments.length === 1 && typeof arguments[0] === 'function') { + callbackOrValue = arguments[0] + params = {} + } + + return _Prop_index_mjs__WEBPACK_IMPORTED_MODULE_2__["default"].prop( + 'HDMIInput', + 'lowLatencyMode', + params, + callbackOrValue, + false, + false, + 0, + ) +} +function once(...args) { + return _Events_index_mjs__WEBPACK_IMPORTED_MODULE_1__["default"].once('HDMIInput', ...args) +} + +function open(portId) { + const transforms = null + + return _Transport_index_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].send('HDMIInput', 'open', { portId }, transforms) +} + +function port(portId) { + const transforms = null + + return _Transport_index_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].send('HDMIInput', 'port', { portId }, transforms) +} + +function ports() { + const transforms = null + + return _Transport_index_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].send('HDMIInput', 'ports', {}, transforms) +} + +/* harmony default export */ __webpack_exports__["default"] = ({ + Events: { + CONNECTION_CHANGED: 'connectionChanged', + SIGNAL_CHANGED: 'signalChanged', + AUTO_LOW_LATENCY_MODE_SIGNAL_CHANGED: 'autoLowLatencyModeSignalChanged', + LOW_LATENCY_MODE_CHANGED: 'lowLatencyModeChanged', + AUTO_LOW_LATENCY_MODE_CAPABLE_CHANGED: 'autoLowLatencyModeCapableChanged', + EDID_VERSION_CHANGED: 'edidVersionChanged', + }, + + /** + * + */ + EDIDVersion: { + V1_4: '1.4', + V2_0: '2.0', + UNKNOWN: 'unknown', + }, + + /** + * + */ + HDMISignalStatus: { + NONE: 'none', + STABLE: 'stable', + UNSTABLE: 'unstable', + UNSUPPORTED: 'unsupported', + UNKNOWN: 'unknown', + }, + + autoLowLatencyModeCapable, + clear, + close, + edidVersion, + listen, + lowLatencyMode, + once, + open, + port, + ports, +}); + + +/***/ }), + +/***/ "./node_modules/@firebolt-js/manage-sdk/dist/lib/Keyboard/defaults.mjs": +/*!*****************************************************************************!*\ + !*** ./node_modules/@firebolt-js/manage-sdk/dist/lib/Keyboard/defaults.mjs ***! + \*****************************************************************************/ +/*! exports provided: default */ +/***/ (function(__webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var _Prop_MockProps_mjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Prop/MockProps.mjs */ "./node_modules/@firebolt-js/manage-sdk/dist/lib/Prop/MockProps.mjs"); +/* + * Copyright 2021 Comcast Cable Communications Management, LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + */ + + +/* harmony default export */ __webpack_exports__["default"] = ({ + standardFocus: null, + passwordFocus: null, + emailFocus: null, + standardResponse: null, + standardError: null, + passwordResponse: null, + passwordError: null, + emailResponse: null, + emailError: null, +}); + + +/***/ }), + +/***/ "./node_modules/@firebolt-js/manage-sdk/dist/lib/Keyboard/index.mjs": +/*!**************************************************************************!*\ + !*** ./node_modules/@firebolt-js/manage-sdk/dist/lib/Keyboard/index.mjs ***! + \**************************************************************************/ +/*! exports provided: default */ +/***/ (function(__webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var _Transport_index_mjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Transport/index.mjs */ "./node_modules/@firebolt-js/manage-sdk/dist/lib/Transport/index.mjs"); +/* harmony import */ var _ProvideManager_index_mjs__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../ProvideManager/index.mjs */ "./node_modules/@firebolt-js/manage-sdk/dist/lib/ProvideManager/index.mjs"); +/* + * Copyright 2021 Comcast Cable Communications Management, LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + */ + + + + + +Object(_ProvideManager_index_mjs__WEBPACK_IMPORTED_MODULE_1__["registerProviderInterface"])( + 'xrn:firebolt:capability:input:keyboard', + 'Keyboard', + [ + { name: 'standard', focus: true, response: true, parameters: true }, + { name: 'password', focus: true, response: true, parameters: true }, + { name: 'email', focus: true, response: true, parameters: true }, + ], +) + +// Methods +function provide(capability, provider) { + return _ProvideManager_index_mjs__WEBPACK_IMPORTED_MODULE_1__["default"].provide(capability, provider) +} + +/* harmony default export */ __webpack_exports__["default"] = ({ + provide, +}); + + +/***/ }), + +/***/ "./node_modules/@firebolt-js/manage-sdk/dist/lib/Localization/defaults.mjs": +/*!*********************************************************************************!*\ + !*** ./node_modules/@firebolt-js/manage-sdk/dist/lib/Localization/defaults.mjs ***! + \*********************************************************************************/ +/*! exports provided: default */ +/***/ (function(__webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var _Prop_MockProps_mjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Prop/MockProps.mjs */ "./node_modules/@firebolt-js/manage-sdk/dist/lib/Prop/MockProps.mjs"); +/* + * Copyright 2021 Comcast Cable Communications Management, LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + */ + + +/* harmony default export */ __webpack_exports__["default"] = ({ + locality: function (params) { + return _Prop_MockProps_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].mock( + 'Localization', + 'locality', + params, + undefined, + 0, + 'Philadelphia', + ) + }, + postalCode: function (params) { + return _Prop_MockProps_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].mock( + 'Localization', + 'postalCode', + params, + undefined, + 0, + '19103', + ) + }, + countryCode: function (params) { + return _Prop_MockProps_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].mock( + 'Localization', + 'countryCode', + params, + undefined, + 0, + 'US', + ) + }, + language: function (params) { + return _Prop_MockProps_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].mock( + 'Localization', + 'language', + params, + undefined, + 0, + 'en', + ) + }, + preferredAudioLanguages: function (params) { + return _Prop_MockProps_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].mock( + 'Localization', + 'preferredAudioLanguages', + params, + undefined, + 0, + ['spa', 'eng'], + ) + }, + locale: function (params) { + return _Prop_MockProps_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].mock( + 'Localization', + 'locale', + params, + undefined, + 0, + 'en-US', + ) + }, + additionalInfo: {}, + addAdditionalInfo: null, + removeAdditionalInfo: null, + timeZone: function (params) { + return _Prop_MockProps_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].mock( + 'Localization', + 'timeZone', + params, + undefined, + 0, + 'America/New_York', + ) + }, + setLocality: function (params) { + const callbackOrValue = params.value + delete params.value + return _Prop_MockProps_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].mock( + 'Localization', + 'locality', + params, + callbackOrValue, + 0, + null, + ) + }, + setPostalCode: function (params) { + const callbackOrValue = params.value + delete params.value + return _Prop_MockProps_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].mock( + 'Localization', + 'postalCode', + params, + callbackOrValue, + 0, + null, + ) + }, + setCountryCode: function (params) { + const callbackOrValue = params.value + delete params.value + return _Prop_MockProps_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].mock( + 'Localization', + 'countryCode', + params, + callbackOrValue, + 0, + null, + ) + }, + setLanguage: function (params) { + const callbackOrValue = params.value + delete params.value + return _Prop_MockProps_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].mock( + 'Localization', + 'language', + params, + callbackOrValue, + 0, + null, + ) + }, + setPreferredAudioLanguages: function (params) { + const callbackOrValue = params.value + delete params.value + return _Prop_MockProps_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].mock( + 'Localization', + 'preferredAudioLanguages', + params, + callbackOrValue, + 0, + null, + ) + }, + setLocale: function (params) { + const callbackOrValue = params.value + delete params.value + return _Prop_MockProps_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].mock( + 'Localization', + 'locale', + params, + callbackOrValue, + 0, + null, + ) + }, + setTimeZone: function (params) { + const callbackOrValue = params.value + delete params.value + return _Prop_MockProps_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].mock( + 'Localization', + 'timeZone', + params, + callbackOrValue, + 0, + null, + ) + }, +}); + + +/***/ }), + +/***/ "./node_modules/@firebolt-js/manage-sdk/dist/lib/Localization/index.mjs": +/*!******************************************************************************!*\ + !*** ./node_modules/@firebolt-js/manage-sdk/dist/lib/Localization/index.mjs ***! + \******************************************************************************/ +/*! exports provided: default */ +/***/ (function(__webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var _Transport_index_mjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Transport/index.mjs */ "./node_modules/@firebolt-js/manage-sdk/dist/lib/Transport/index.mjs"); +/* harmony import */ var _Events_index_mjs__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Events/index.mjs */ "./node_modules/@firebolt-js/manage-sdk/dist/lib/Events/index.mjs"); +/* harmony import */ var _Prop_index_mjs__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Prop/index.mjs */ "./node_modules/@firebolt-js/manage-sdk/dist/lib/Prop/index.mjs"); +/* + * Copyright 2021 Comcast Cable Communications Management, LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + */ + + + + + + +Object(_Events_index_mjs__WEBPACK_IMPORTED_MODULE_1__["registerEvents"])('Localization', [ + 'countryCodeChanged', + 'languageChanged', + 'localeChanged', + 'localityChanged', + 'postalCodeChanged', + 'preferredAudioLanguagesChanged', + 'timeZoneChanged', +]) + +_Transport_index_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].registerDeprecatedMethod( + 'Localization', + 'language', + 'Use Localization.locale instead.', +) +_Transport_index_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].registerDeprecatedMethod( + 'Localization', + 'onLanguageChanged', + 'Use language instead.', +) +_Transport_index_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].registerDeprecatedMethod( + 'Localization', + 'setLanguage', + 'Use Localization.locale instead.', +) + +// onCountryCodeChanged is accessed via listen('countryCodeChanged, ...) + +// onLanguageChanged is accessed via listen('languageChanged, ...) + +// onLocaleChanged is accessed via listen('localeChanged, ...) + +// onLocalityChanged is accessed via listen('localityChanged, ...) + +// onPostalCodeChanged is accessed via listen('postalCodeChanged, ...) + +// onPreferredAudioLanguagesChanged is accessed via listen('preferredAudioLanguagesChanged, ...) + +// onTimeZoneChanged is accessed via listen('timeZoneChanged, ...) + +// Methods + +function addAdditionalInfo(key, value) { + const transforms = null + + return _Transport_index_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].send( + 'Localization', + 'addAdditionalInfo', + { key, value }, + transforms, + ) +} + +function additionalInfo() { + const transforms = null + + return _Transport_index_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].send('Localization', 'additionalInfo', {}, transforms) +} +function clear(...args) { + return _Events_index_mjs__WEBPACK_IMPORTED_MODULE_1__["default"].clear('Localization', ...args) +} + +function countryCode() { + let callbackOrValue = arguments[0] + let params = {} + + // x-subscriber-type: global + if (arguments.length === 1 && typeof arguments[0] === 'function') { + callbackOrValue = arguments[0] + params = {} + } + + return _Prop_index_mjs__WEBPACK_IMPORTED_MODULE_2__["default"].prop( + 'Localization', + 'countryCode', + params, + callbackOrValue, + false, + false, + 0, + ) +} +function language() { + let callbackOrValue = arguments[0] + let params = {} + + // x-subscriber-type: global + if (arguments.length === 1 && typeof arguments[0] === 'function') { + callbackOrValue = arguments[0] + params = {} + } + + return _Prop_index_mjs__WEBPACK_IMPORTED_MODULE_2__["default"].prop( + 'Localization', + 'language', + params, + callbackOrValue, + false, + false, + 0, + ) +} +function listen(...args) { + return _Events_index_mjs__WEBPACK_IMPORTED_MODULE_1__["default"].listen('Localization', ...args) +} + +function locale() { + let callbackOrValue = arguments[0] + let params = {} + + // x-subscriber-type: global + if (arguments.length === 1 && typeof arguments[0] === 'function') { + callbackOrValue = arguments[0] + params = {} + } + + return _Prop_index_mjs__WEBPACK_IMPORTED_MODULE_2__["default"].prop( + 'Localization', + 'locale', + params, + callbackOrValue, + false, + false, + 0, + ) +} +function locality() { + let callbackOrValue = arguments[0] + let params = {} + + // x-subscriber-type: global + if (arguments.length === 1 && typeof arguments[0] === 'function') { + callbackOrValue = arguments[0] + params = {} + } + + return _Prop_index_mjs__WEBPACK_IMPORTED_MODULE_2__["default"].prop( + 'Localization', + 'locality', + params, + callbackOrValue, + false, + false, + 0, + ) +} +function once(...args) { + return _Events_index_mjs__WEBPACK_IMPORTED_MODULE_1__["default"].once('Localization', ...args) +} + +function postalCode() { + let callbackOrValue = arguments[0] + let params = {} + + // x-subscriber-type: global + if (arguments.length === 1 && typeof arguments[0] === 'function') { + callbackOrValue = arguments[0] + params = {} + } + + return _Prop_index_mjs__WEBPACK_IMPORTED_MODULE_2__["default"].prop( + 'Localization', + 'postalCode', + params, + callbackOrValue, + false, + false, + 0, + ) +} +function preferredAudioLanguages() { + let callbackOrValue = arguments[0] + let params = {} + + // x-subscriber-type: global + if (arguments.length === 1 && typeof arguments[0] === 'function') { + callbackOrValue = arguments[0] + params = {} + } + + return _Prop_index_mjs__WEBPACK_IMPORTED_MODULE_2__["default"].prop( + 'Localization', + 'preferredAudioLanguages', + params, + callbackOrValue, + false, + false, + 0, + ) +} + +function removeAdditionalInfo(key) { + const transforms = null + + return _Transport_index_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].send( + 'Localization', + 'removeAdditionalInfo', + { key }, + transforms, + ) +} +function timeZone() { + let callbackOrValue = arguments[0] + let params = {} + + // x-subscriber-type: global + if (arguments.length === 1 && typeof arguments[0] === 'function') { + callbackOrValue = arguments[0] + params = {} + } + + return _Prop_index_mjs__WEBPACK_IMPORTED_MODULE_2__["default"].prop( + 'Localization', + 'timeZone', + params, + callbackOrValue, + false, + false, + 0, + ) +} + +/* harmony default export */ __webpack_exports__["default"] = ({ + Events: { + LOCALITY_CHANGED: 'localityChanged', + POSTAL_CODE_CHANGED: 'postalCodeChanged', + COUNTRY_CODE_CHANGED: 'countryCodeChanged', + LANGUAGE_CHANGED: 'languageChanged', + PREFERRED_AUDIO_LANGUAGES_CHANGED: 'preferredAudioLanguagesChanged', + LOCALE_CHANGED: 'localeChanged', + TIME_ZONE_CHANGED: 'timeZoneChanged', + }, + + addAdditionalInfo, + additionalInfo, + clear, + countryCode, + language, + listen, + locale, + locality, + once, + postalCode, + preferredAudioLanguages, + removeAdditionalInfo, + timeZone, +}); + + +/***/ }), + +/***/ "./node_modules/@firebolt-js/manage-sdk/dist/lib/Log/index.mjs": +/*!*********************************************************************!*\ + !*** ./node_modules/@firebolt-js/manage-sdk/dist/lib/Log/index.mjs ***! + \*********************************************************************/ +/*! exports provided: default */ +/***/ (function(__webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var _Settings_index_mjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Settings/index.mjs */ "./node_modules/@firebolt-js/manage-sdk/dist/lib/Settings/index.mjs"); +/* + * Copyright 2021 Comcast Cable Communications Management, LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + */ + + + +const prepLog = (type, args) => { + const colors = { + Info: 'green', + Debug: 'gray', + Warn: 'orange', + Error: 'red', + } + + args = Array.from(args) + return [ + '%c' + + (args.length > 1 && typeof args[0] === 'string' ? args.shift() : type), + 'background-color: ' + + colors[type] + + '; color: white; padding: 2px 4px; border-radius: 2px', + args, + ] +} + +/* harmony default export */ __webpack_exports__["default"] = ({ + info() { + _Settings_index_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].get('platform', 'log') && + console.log.apply(console, prepLog('Info', arguments)) + }, + debug() { + _Settings_index_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].get('platform', 'log') && + console.debug.apply(console, prepLog('Debug', arguments)) + }, + error() { + _Settings_index_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].get('platform', 'log') && + console.error.apply(console, prepLog('Error', arguments)) + }, + warn() { + _Settings_index_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].get('platform', 'log') && + console.warn.apply(console, prepLog('Warn', arguments)) + }, +}); + + +/***/ }), + +/***/ "./node_modules/@firebolt-js/manage-sdk/dist/lib/Metrics/defaults.mjs": +/*!****************************************************************************!*\ + !*** ./node_modules/@firebolt-js/manage-sdk/dist/lib/Metrics/defaults.mjs ***! + \****************************************************************************/ +/*! exports provided: default */ +/***/ (function(__webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var _Prop_MockProps_mjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Prop/MockProps.mjs */ "./node_modules/@firebolt-js/manage-sdk/dist/lib/Prop/MockProps.mjs"); +/* + * Copyright 2021 Comcast Cable Communications Management, LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + */ + + +/* harmony default export */ __webpack_exports__["default"] = ({ + event: null, +}); + + +/***/ }), + +/***/ "./node_modules/@firebolt-js/manage-sdk/dist/lib/Metrics/index.mjs": +/*!*************************************************************************!*\ + !*** ./node_modules/@firebolt-js/manage-sdk/dist/lib/Metrics/index.mjs ***! + \*************************************************************************/ +/*! exports provided: default */ +/***/ (function(__webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var _Transport_index_mjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Transport/index.mjs */ "./node_modules/@firebolt-js/manage-sdk/dist/lib/Transport/index.mjs"); +/* + * Copyright 2021 Comcast Cable Communications Management, LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + */ + + + +// Methods + +function event(schema, data) { + const transforms = null + + return _Transport_index_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].send('Metrics', 'event', { schema, data }, transforms) +} + +/* harmony default export */ __webpack_exports__["default"] = ({ + event, +}); + + +/***/ }), + +/***/ "./node_modules/@firebolt-js/manage-sdk/dist/lib/PinChallenge/defaults.mjs": +/*!*********************************************************************************!*\ + !*** ./node_modules/@firebolt-js/manage-sdk/dist/lib/PinChallenge/defaults.mjs ***! + \*********************************************************************************/ +/*! exports provided: default */ +/***/ (function(__webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var _Prop_MockProps_mjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Prop/MockProps.mjs */ "./node_modules/@firebolt-js/manage-sdk/dist/lib/Prop/MockProps.mjs"); +/* + * Copyright 2021 Comcast Cable Communications Management, LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + */ + + +/* harmony default export */ __webpack_exports__["default"] = ({ + challengeFocus: null, + challengeResponse: null, + challengeError: null, +}); + + +/***/ }), + +/***/ "./node_modules/@firebolt-js/manage-sdk/dist/lib/PinChallenge/index.mjs": +/*!******************************************************************************!*\ + !*** ./node_modules/@firebolt-js/manage-sdk/dist/lib/PinChallenge/index.mjs ***! + \******************************************************************************/ +/*! exports provided: default */ +/***/ (function(__webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var _Transport_index_mjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Transport/index.mjs */ "./node_modules/@firebolt-js/manage-sdk/dist/lib/Transport/index.mjs"); +/* harmony import */ var _ProvideManager_index_mjs__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../ProvideManager/index.mjs */ "./node_modules/@firebolt-js/manage-sdk/dist/lib/ProvideManager/index.mjs"); +/* + * Copyright 2021 Comcast Cable Communications Management, LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + */ + + + + + +Object(_ProvideManager_index_mjs__WEBPACK_IMPORTED_MODULE_1__["registerProviderInterface"])( + 'xrn:firebolt:capability:usergrant:pinchallenge', + 'PinChallenge', + [{ name: 'challenge', focus: true, response: true, parameters: true }], +) + +// Methods +function provide(capability, provider) { + return _ProvideManager_index_mjs__WEBPACK_IMPORTED_MODULE_1__["default"].provide(capability, provider) +} + +/* harmony default export */ __webpack_exports__["default"] = ({ + /** + * The reason for the result of challenging the user + */ + ResultReason: { + NO_PIN_REQUIRED: 'noPinRequired', + NO_PIN_REQUIRED_WINDOW: 'noPinRequiredWindow', + EXCEEDED_PIN_FAILURES: 'exceededPinFailures', + CORRECT_PIN: 'correctPin', + CANCELLED: 'cancelled', + }, + + provide, +}); + + +/***/ }), + +/***/ "./node_modules/@firebolt-js/manage-sdk/dist/lib/Privacy/defaults.mjs": +/*!****************************************************************************!*\ + !*** ./node_modules/@firebolt-js/manage-sdk/dist/lib/Privacy/defaults.mjs ***! + \****************************************************************************/ +/*! exports provided: default */ +/***/ (function(__webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var _Prop_MockProps_mjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Prop/MockProps.mjs */ "./node_modules/@firebolt-js/manage-sdk/dist/lib/Prop/MockProps.mjs"); +/* + * Copyright 2021 Comcast Cable Communications Management, LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + */ + + +/* harmony default export */ __webpack_exports__["default"] = ({ + allowResumePoints: function (params) { + return _Prop_MockProps_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].mock( + 'Privacy', + 'allowResumePoints', + params, + undefined, + 0, + true, + ) + }, + allowUnentitledResumePoints: function (params) { + return _Prop_MockProps_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].mock( + 'Privacy', + 'allowUnentitledResumePoints', + params, + undefined, + 0, + true, + ) + }, + allowWatchHistory: function (params) { + return _Prop_MockProps_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].mock( + 'Privacy', + 'allowWatchHistory', + params, + undefined, + 0, + true, + ) + }, + allowProductAnalytics: function (params) { + return _Prop_MockProps_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].mock( + 'Privacy', + 'allowProductAnalytics', + params, + undefined, + 0, + true, + ) + }, + allowPersonalization: function (params) { + return _Prop_MockProps_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].mock( + 'Privacy', + 'allowPersonalization', + params, + undefined, + 0, + true, + ) + }, + allowUnentitledPersonalization: function (params) { + return _Prop_MockProps_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].mock( + 'Privacy', + 'allowUnentitledPersonalization', + params, + undefined, + 0, + true, + ) + }, + allowRemoteDiagnostics: function (params) { + return _Prop_MockProps_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].mock( + 'Privacy', + 'allowRemoteDiagnostics', + params, + undefined, + 0, + true, + ) + }, + allowPrimaryContentAdTargeting: function (params) { + return _Prop_MockProps_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].mock( + 'Privacy', + 'allowPrimaryContentAdTargeting', + params, + undefined, + 0, + true, + ) + }, + allowPrimaryBrowseAdTargeting: function (params) { + return _Prop_MockProps_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].mock( + 'Privacy', + 'allowPrimaryBrowseAdTargeting', + params, + undefined, + 0, + true, + ) + }, + allowAppContentAdTargeting: function (params) { + return _Prop_MockProps_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].mock( + 'Privacy', + 'allowAppContentAdTargeting', + params, + undefined, + 0, + true, + ) + }, + allowACRCollection: function (params) { + return _Prop_MockProps_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].mock( + 'Privacy', + 'allowACRCollection', + params, + undefined, + 0, + true, + ) + }, + allowCameraAnalytics: function (params) { + return _Prop_MockProps_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].mock( + 'Privacy', + 'allowCameraAnalytics', + params, + undefined, + 0, + true, + ) + }, + settings: { + allowACRCollection: true, + allowResumePoints: false, + allowAppContentAdTargeting: false, + allowCameraAnalytics: true, + allowPersonalization: true, + allowPrimaryBrowseAdTargeting: false, + allowPrimaryContentAdTargeting: false, + allowProductAnalytics: true, + allowRemoteDiagnostics: true, + allowUnentitledPersonalization: true, + allowUnentitledResumePoints: false, + allowWatchHistory: true, + }, + setAllowResumePoints: function (params) { + const callbackOrValue = params.value + delete params.value + return _Prop_MockProps_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].mock( + 'Privacy', + 'allowResumePoints', + params, + callbackOrValue, + 0, + null, + ) + }, + setAllowUnentitledResumePoints: function (params) { + const callbackOrValue = params.value + delete params.value + return _Prop_MockProps_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].mock( + 'Privacy', + 'allowUnentitledResumePoints', + params, + callbackOrValue, + 0, + null, + ) + }, + setAllowWatchHistory: function (params) { + const callbackOrValue = params.value + delete params.value + return _Prop_MockProps_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].mock( + 'Privacy', + 'allowWatchHistory', + params, + callbackOrValue, + 0, + null, + ) + }, + setAllowProductAnalytics: function (params) { + const callbackOrValue = params.value + delete params.value + return _Prop_MockProps_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].mock( + 'Privacy', + 'allowProductAnalytics', + params, + callbackOrValue, + 0, + null, + ) + }, + setAllowPersonalization: function (params) { + const callbackOrValue = params.value + delete params.value + return _Prop_MockProps_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].mock( + 'Privacy', + 'allowPersonalization', + params, + callbackOrValue, + 0, + null, + ) + }, + setAllowUnentitledPersonalization: function (params) { + const callbackOrValue = params.value + delete params.value + return _Prop_MockProps_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].mock( + 'Privacy', + 'allowUnentitledPersonalization', + params, + callbackOrValue, + 0, + null, + ) + }, + setAllowRemoteDiagnostics: function (params) { + const callbackOrValue = params.value + delete params.value + return _Prop_MockProps_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].mock( + 'Privacy', + 'allowRemoteDiagnostics', + params, + callbackOrValue, + 0, + null, + ) + }, + setAllowPrimaryContentAdTargeting: function (params) { + const callbackOrValue = params.value + delete params.value + return _Prop_MockProps_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].mock( + 'Privacy', + 'allowPrimaryContentAdTargeting', + params, + callbackOrValue, + 0, + null, + ) + }, + setAllowPrimaryBrowseAdTargeting: function (params) { + const callbackOrValue = params.value + delete params.value + return _Prop_MockProps_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].mock( + 'Privacy', + 'allowPrimaryBrowseAdTargeting', + params, + callbackOrValue, + 0, + null, + ) + }, + setAllowAppContentAdTargeting: function (params) { + const callbackOrValue = params.value + delete params.value + return _Prop_MockProps_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].mock( + 'Privacy', + 'allowAppContentAdTargeting', + params, + callbackOrValue, + 0, + null, + ) + }, + setAllowACRCollection: function (params) { + const callbackOrValue = params.value + delete params.value + return _Prop_MockProps_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].mock( + 'Privacy', + 'allowACRCollection', + params, + callbackOrValue, + 0, + null, + ) + }, + setAllowCameraAnalytics: function (params) { + const callbackOrValue = params.value + delete params.value + return _Prop_MockProps_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].mock( + 'Privacy', + 'allowCameraAnalytics', + params, + callbackOrValue, + 0, + null, + ) + }, +}); + + +/***/ }), + +/***/ "./node_modules/@firebolt-js/manage-sdk/dist/lib/Privacy/index.mjs": +/*!*************************************************************************!*\ + !*** ./node_modules/@firebolt-js/manage-sdk/dist/lib/Privacy/index.mjs ***! + \*************************************************************************/ +/*! exports provided: default */ +/***/ (function(__webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var _Transport_index_mjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Transport/index.mjs */ "./node_modules/@firebolt-js/manage-sdk/dist/lib/Transport/index.mjs"); +/* harmony import */ var _Events_index_mjs__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Events/index.mjs */ "./node_modules/@firebolt-js/manage-sdk/dist/lib/Events/index.mjs"); +/* harmony import */ var _Prop_index_mjs__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Prop/index.mjs */ "./node_modules/@firebolt-js/manage-sdk/dist/lib/Prop/index.mjs"); +/* + * Copyright 2021 Comcast Cable Communications Management, LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + */ + + + + + + +Object(_Events_index_mjs__WEBPACK_IMPORTED_MODULE_1__["registerEvents"])('Privacy', [ + 'allowACRCollectionChanged', + 'allowAppContentAdTargetingChanged', + 'allowCameraAnalyticsChanged', + 'allowPersonalizationChanged', + 'allowPrimaryBrowseAdTargetingChanged', + 'allowPrimaryContentAdTargetingChanged', + 'allowProductAnalyticsChanged', + 'allowRemoteDiagnosticsChanged', + 'allowResumePointsChanged', + 'allowUnentitledPersonalizationChanged', + 'allowUnentitledResumePointsChanged', + 'allowWatchHistoryChanged', +]) + +// onAllowACRCollectionChanged is accessed via listen('allowACRCollectionChanged, ...) + +// onAllowAppContentAdTargetingChanged is accessed via listen('allowAppContentAdTargetingChanged, ...) + +// onAllowCameraAnalyticsChanged is accessed via listen('allowCameraAnalyticsChanged, ...) + +// onAllowPersonalizationChanged is accessed via listen('allowPersonalizationChanged, ...) + +// onAllowPrimaryBrowseAdTargetingChanged is accessed via listen('allowPrimaryBrowseAdTargetingChanged, ...) + +// onAllowPrimaryContentAdTargetingChanged is accessed via listen('allowPrimaryContentAdTargetingChanged, ...) + +// onAllowProductAnalyticsChanged is accessed via listen('allowProductAnalyticsChanged, ...) + +// onAllowRemoteDiagnosticsChanged is accessed via listen('allowRemoteDiagnosticsChanged, ...) + +// onAllowResumePointsChanged is accessed via listen('allowResumePointsChanged, ...) + +// onAllowUnentitledPersonalizationChanged is accessed via listen('allowUnentitledPersonalizationChanged, ...) + +// onAllowUnentitledResumePointsChanged is accessed via listen('allowUnentitledResumePointsChanged, ...) + +// onAllowWatchHistoryChanged is accessed via listen('allowWatchHistoryChanged, ...) + +// Methods +function allowACRCollection() { + let callbackOrValue = arguments[0] + let params = {} + + // x-subscriber-type: global + if (arguments.length === 1 && typeof arguments[0] === 'function') { + callbackOrValue = arguments[0] + params = {} + } + + return _Prop_index_mjs__WEBPACK_IMPORTED_MODULE_2__["default"].prop( + 'Privacy', + 'allowACRCollection', + params, + callbackOrValue, + false, + false, + 0, + ) +} +function allowAppContentAdTargeting() { + let callbackOrValue = arguments[0] + let params = {} + + // x-subscriber-type: global + if (arguments.length === 1 && typeof arguments[0] === 'function') { + callbackOrValue = arguments[0] + params = {} + } + + return _Prop_index_mjs__WEBPACK_IMPORTED_MODULE_2__["default"].prop( + 'Privacy', + 'allowAppContentAdTargeting', + params, + callbackOrValue, + false, + false, + 0, + ) +} +function allowCameraAnalytics() { + let callbackOrValue = arguments[0] + let params = {} + + // x-subscriber-type: global + if (arguments.length === 1 && typeof arguments[0] === 'function') { + callbackOrValue = arguments[0] + params = {} + } + + return _Prop_index_mjs__WEBPACK_IMPORTED_MODULE_2__["default"].prop( + 'Privacy', + 'allowCameraAnalytics', + params, + callbackOrValue, + false, + false, + 0, + ) +} +function allowPersonalization() { + let callbackOrValue = arguments[0] + let params = {} + + // x-subscriber-type: global + if (arguments.length === 1 && typeof arguments[0] === 'function') { + callbackOrValue = arguments[0] + params = {} + } + + return _Prop_index_mjs__WEBPACK_IMPORTED_MODULE_2__["default"].prop( + 'Privacy', + 'allowPersonalization', + params, + callbackOrValue, + false, + false, + 0, + ) +} +function allowPrimaryBrowseAdTargeting() { + let callbackOrValue = arguments[0] + let params = {} + + // x-subscriber-type: global + if (arguments.length === 1 && typeof arguments[0] === 'function') { + callbackOrValue = arguments[0] + params = {} + } + + return _Prop_index_mjs__WEBPACK_IMPORTED_MODULE_2__["default"].prop( + 'Privacy', + 'allowPrimaryBrowseAdTargeting', + params, + callbackOrValue, + false, + false, + 0, + ) +} +function allowPrimaryContentAdTargeting() { + let callbackOrValue = arguments[0] + let params = {} + + // x-subscriber-type: global + if (arguments.length === 1 && typeof arguments[0] === 'function') { + callbackOrValue = arguments[0] + params = {} + } + + return _Prop_index_mjs__WEBPACK_IMPORTED_MODULE_2__["default"].prop( + 'Privacy', + 'allowPrimaryContentAdTargeting', + params, + callbackOrValue, + false, + false, + 0, + ) +} +function allowProductAnalytics() { + let callbackOrValue = arguments[0] + let params = {} + + // x-subscriber-type: global + if (arguments.length === 1 && typeof arguments[0] === 'function') { + callbackOrValue = arguments[0] + params = {} + } + + return _Prop_index_mjs__WEBPACK_IMPORTED_MODULE_2__["default"].prop( + 'Privacy', + 'allowProductAnalytics', + params, + callbackOrValue, + false, + false, + 0, + ) +} +function allowRemoteDiagnostics() { + let callbackOrValue = arguments[0] + let params = {} + + // x-subscriber-type: global + if (arguments.length === 1 && typeof arguments[0] === 'function') { + callbackOrValue = arguments[0] + params = {} + } + + return _Prop_index_mjs__WEBPACK_IMPORTED_MODULE_2__["default"].prop( + 'Privacy', + 'allowRemoteDiagnostics', + params, + callbackOrValue, + false, + false, + 0, + ) +} +function allowResumePoints() { + let callbackOrValue = arguments[0] + let params = {} + + // x-subscriber-type: global + if (arguments.length === 1 && typeof arguments[0] === 'function') { + callbackOrValue = arguments[0] + params = {} + } + + return _Prop_index_mjs__WEBPACK_IMPORTED_MODULE_2__["default"].prop( + 'Privacy', + 'allowResumePoints', + params, + callbackOrValue, + false, + false, + 0, + ) +} +function allowUnentitledPersonalization() { + let callbackOrValue = arguments[0] + let params = {} + + // x-subscriber-type: global + if (arguments.length === 1 && typeof arguments[0] === 'function') { + callbackOrValue = arguments[0] + params = {} + } + + return _Prop_index_mjs__WEBPACK_IMPORTED_MODULE_2__["default"].prop( + 'Privacy', + 'allowUnentitledPersonalization', + params, + callbackOrValue, + false, + false, + 0, + ) +} +function allowUnentitledResumePoints() { + let callbackOrValue = arguments[0] + let params = {} + + // x-subscriber-type: global + if (arguments.length === 1 && typeof arguments[0] === 'function') { + callbackOrValue = arguments[0] + params = {} + } + + return _Prop_index_mjs__WEBPACK_IMPORTED_MODULE_2__["default"].prop( + 'Privacy', + 'allowUnentitledResumePoints', + params, + callbackOrValue, + false, + false, + 0, + ) +} +function allowWatchHistory() { + let callbackOrValue = arguments[0] + let params = {} + + // x-subscriber-type: global + if (arguments.length === 1 && typeof arguments[0] === 'function') { + callbackOrValue = arguments[0] + params = {} + } + + return _Prop_index_mjs__WEBPACK_IMPORTED_MODULE_2__["default"].prop( + 'Privacy', + 'allowWatchHistory', + params, + callbackOrValue, + false, + false, + 0, + ) +} +function clear(...args) { + return _Events_index_mjs__WEBPACK_IMPORTED_MODULE_1__["default"].clear('Privacy', ...args) +} + +function listen(...args) { + return _Events_index_mjs__WEBPACK_IMPORTED_MODULE_1__["default"].listen('Privacy', ...args) +} + +function once(...args) { + return _Events_index_mjs__WEBPACK_IMPORTED_MODULE_1__["default"].once('Privacy', ...args) +} + +function settings() { + const transforms = null + + return _Transport_index_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].send('Privacy', 'settings', {}, transforms) +} + +/* harmony default export */ __webpack_exports__["default"] = ({ + Events: { + ALLOW_RESUME_POINTS_CHANGED: 'allowResumePointsChanged', + ALLOW_UNENTITLED_RESUME_POINTS_CHANGED: + 'allowUnentitledResumePointsChanged', + ALLOW_WATCH_HISTORY_CHANGED: 'allowWatchHistoryChanged', + ALLOW_PRODUCT_ANALYTICS_CHANGED: 'allowProductAnalyticsChanged', + ALLOW_PERSONALIZATION_CHANGED: 'allowPersonalizationChanged', + ALLOW_UNENTITLED_PERSONALIZATION_CHANGED: + 'allowUnentitledPersonalizationChanged', + ALLOW_REMOTE_DIAGNOSTICS_CHANGED: 'allowRemoteDiagnosticsChanged', + ALLOW_PRIMARY_CONTENT_AD_TARGETING_CHANGED: + 'allowPrimaryContentAdTargetingChanged', + ALLOW_PRIMARY_BROWSE_AD_TARGETING_CHANGED: + 'allowPrimaryBrowseAdTargetingChanged', + ALLOW_APP_CONTENT_AD_TARGETING_CHANGED: 'allowAppContentAdTargetingChanged', + ALLOW_ACRCOLLECTION_CHANGED: 'allowACRCollectionChanged', + ALLOW_CAMERA_ANALYTICS_CHANGED: 'allowCameraAnalyticsChanged', + }, + + allowACRCollection, + allowAppContentAdTargeting, + allowCameraAnalytics, + allowPersonalization, + allowPrimaryBrowseAdTargeting, + allowPrimaryContentAdTargeting, + allowProductAnalytics, + allowRemoteDiagnostics, + allowResumePoints, + allowUnentitledPersonalization, + allowUnentitledResumePoints, + allowWatchHistory, + clear, + listen, + once, + settings, +}); + + +/***/ }), + +/***/ "./node_modules/@firebolt-js/manage-sdk/dist/lib/Prop/MockProps.mjs": +/*!**************************************************************************!*\ + !*** ./node_modules/@firebolt-js/manage-sdk/dist/lib/Prop/MockProps.mjs ***! + \**************************************************************************/ +/*! exports provided: default */ +/***/ (function(__webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var _Transport_MockTransport_mjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Transport/MockTransport.mjs */ "./node_modules/@firebolt-js/manage-sdk/dist/lib/Transport/MockTransport.mjs"); +/* harmony import */ var _Router_mjs__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./Router.mjs */ "./node_modules/@firebolt-js/manage-sdk/dist/lib/Prop/Router.mjs"); + + + +const mocks = {} + +function mock(module, method, params, value, contextParameterCount, def) { + const type = Object(_Router_mjs__WEBPACK_IMPORTED_MODULE_1__["default"])(params, value, contextParameterCount) + const hash = contextParameterCount + ? '.' + + Object.keys(params) + .filter((key) => key !== 'value') + .map((key) => params[key]) + .join('.') + : '' + const key = `${module}.${method}${hash}` + + if (type === 'getter') { + const value = mocks.hasOwnProperty(key) ? mocks[key] : def + return value + } else if (type === 'subscriber') { + } else if (type === 'setter') { + mocks[key] = value + _Transport_MockTransport_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].event(module, `${method}Changed`, { value }) + return null + } +} + +/* harmony default export */ __webpack_exports__["default"] = ({ + mock: mock, +}); + + +/***/ }), + +/***/ "./node_modules/@firebolt-js/manage-sdk/dist/lib/Prop/Router.mjs": +/*!***********************************************************************!*\ + !*** ./node_modules/@firebolt-js/manage-sdk/dist/lib/Prop/Router.mjs ***! + \***********************************************************************/ +/*! exports provided: default */ +/***/ (function(__webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony default export */ __webpack_exports__["default"] = (function (params, callbackOrValue, contextParameterCount) { + const numArgs = params ? Object.values(params).length : 0 + + if (numArgs === contextParameterCount && callbackOrValue === undefined) { + // getter + return 'getter' + } else if ( + numArgs === contextParameterCount && + typeof callbackOrValue === 'function' + ) { + // subscribe + return 'subscriber' + } else if (numArgs === 0 && typeof callbackOrValue === 'function') { + // for x-subscriber-type: global + return 'subscriber' + } else if ( + numArgs === contextParameterCount && + callbackOrValue !== undefined + ) { + // setter + return 'setter' + } + + return null +}); + + +/***/ }), + +/***/ "./node_modules/@firebolt-js/manage-sdk/dist/lib/Prop/index.mjs": +/*!**********************************************************************!*\ + !*** ./node_modules/@firebolt-js/manage-sdk/dist/lib/Prop/index.mjs ***! + \**********************************************************************/ +/*! exports provided: default */ +/***/ (function(__webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var _Transport_index_mjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Transport/index.mjs */ "./node_modules/@firebolt-js/manage-sdk/dist/lib/Transport/index.mjs"); +/* harmony import */ var _Events_index_mjs__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Events/index.mjs */ "./node_modules/@firebolt-js/manage-sdk/dist/lib/Events/index.mjs"); +/* harmony import */ var _Router_mjs__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./Router.mjs */ "./node_modules/@firebolt-js/manage-sdk/dist/lib/Prop/Router.mjs"); + + + + +function prop( + moduleName, + key, + params, + callbackOrValue = undefined, + immutable, + readonly, + contextParameterCount, +) { + const numArgs = Object.values(params).length + const type = Object(_Router_mjs__WEBPACK_IMPORTED_MODULE_2__["default"])(params, callbackOrValue, contextParameterCount) + + if (type === 'getter') { + return _Transport_index_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].send(moduleName, key, params) + } else if (type === 'subscriber') { + // subscriber + if (immutable) { + throw new Error('Cannot subscribe to an immutable property') + } + return _Events_index_mjs__WEBPACK_IMPORTED_MODULE_1__["default"].listen( + moduleName, + key + 'Changed', + ...Object.values(params), + callbackOrValue, + ) + } else if (type === 'setter') { + // setter + if (immutable) { + throw new Error('Cannot set a value to an immutable property') + } + if (readonly) { + throw new Error('Cannot set a value to a readonly property') + } + return _Transport_index_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].send( + moduleName, + 'set' + key[0].toUpperCase() + key.substring(1), + Object.assign( + { + value: callbackOrValue, + }, + params, + ), + ) + } else if (numArgs < contextParameterCount) { + throw new Error( + 'Cannot get a value without all required context parameters.', + ) + } else { + throw new Error('Property accessed with unexpected number of parameters.') + } +} + +/* harmony default export */ __webpack_exports__["default"] = ({ + prop: prop, +}); + + +/***/ }), + +/***/ "./node_modules/@firebolt-js/manage-sdk/dist/lib/ProvideManager/index.mjs": +/*!********************************************************************************!*\ + !*** ./node_modules/@firebolt-js/manage-sdk/dist/lib/ProvideManager/index.mjs ***! + \********************************************************************************/ +/*! exports provided: registerProviderInterface, default */ +/***/ (function(__webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "registerProviderInterface", function() { return registerProviderInterface; }); +/* harmony import */ var _Transport_index_mjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Transport/index.mjs */ "./node_modules/@firebolt-js/manage-sdk/dist/lib/Transport/index.mjs"); +/* harmony import */ var _Events_index_mjs__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Events/index.mjs */ "./node_modules/@firebolt-js/manage-sdk/dist/lib/Events/index.mjs"); +/* + * Copyright 2021 Comcast Cable Communications Management, LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + */ + + + + +const providerInterfaces = {} + +const registerProviderInterface = (capability, module, methods) => { + if (providerInterfaces[capability]) { + throw `Capability ${capability} has multiple provider interfaces registered.` + } + + methods.forEach((m) => (m.name = `${module}.${m.name}`)) + providerInterfaces[capability] = methods.concat() +} + +const provide = function (capability, provider) { + const methods = [] + const iface = providerInterfaces[capability] + + if (provider.constructor.name !== 'Object') { + methods.push( + ...Object.getOwnPropertyNames(Object.getPrototypeOf(provider)).filter( + (item) => + typeof provider[item] === 'function' && item !== 'constructor', + ), + ) + } else { + methods.push( + ...Object.getOwnPropertyNames(provider).filter( + (item) => typeof provider[item] === 'function', + ), + ) + } + + if (!iface) { + throw 'Ignoring unknown provider capability.' + } + + // make sure every interfaced method exists in the providers methods list + const valid = iface.every((method) => + methods.find((m) => m === method.name.split('.').pop()), + ) + + if (!valid) { + throw `Provider that does not fully implement ${capability}:\n\t${iface + .map((m) => m.name.split('.').pop()) + .join('\n\t')}` + } + + iface.forEach((imethod) => { + const parts = imethod.name.split('.') + const method = parts.pop() + const module = parts.pop().toLowerCase() + const defined = !!methods.find((m) => m === method) + + if (!defined) { + return // returns from this cycle of iface.forEach + } + + _Events_index_mjs__WEBPACK_IMPORTED_MODULE_1__["default"].listen( + module, + `request${method.charAt(0).toUpperCase() + method.substr(1)}`, + function (request) { + const providerCallArgs = [] + + // only pass in parameters object if schema exists + if (imethod.parameters) { + providerCallArgs.push(request.parameters) + } else { + providerCallArgs.push(null) + } + + const session = { + correlationId: () => { + return request.correlationId + }, + } + + // only pass in the focus handshake if needed + if (imethod.focus) { + session.focus = () => { + _Transport_index_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].send(module, `${method}Focus`, { + correlationId: request.correlationId, + }) + } + } + + providerCallArgs.push(session) + + const response = { + correlationId: request.correlationId, + } + let handleError = (error) => { + response.error = { + code: error.code || 1000, // todo: should be some reserved code for "Unknown" + message: + error.message || + `An error occured while calling provided ${method} method.`, + } + + if (error.data) { + response.error.data = JSON.parse(JSON.stringify(error.data)) + } + + _Transport_index_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].send(module, `${method}Error`, response) + } + + try { + const result = provider[method].apply(provider, providerCallArgs) + + if (!(result instanceof Promise)) { + throw `Provider method ${method} did not return a Promise.` + } + + result + .then((result) => { + if (imethod.response) { + // void results should be null in the JSONRPC message + response.result = result == null ? null : result + } + + _Transport_index_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].send(module, `${method}Response`, response) + }) + .catch((err) => handleError(err)) + } catch (error) { + handleError(error) + } + }, + ) + }) +} + +/* harmony default export */ __webpack_exports__["default"] = ({ + provide, +}); + + +/***/ }), + +/***/ "./node_modules/@firebolt-js/manage-sdk/dist/lib/Results/index.mjs": +/*!*************************************************************************!*\ + !*** ./node_modules/@firebolt-js/manage-sdk/dist/lib/Results/index.mjs ***! + \*************************************************************************/ +/*! exports provided: default */ +/***/ (function(__webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var _Transport_index_mjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Transport/index.mjs */ "./node_modules/@firebolt-js/manage-sdk/dist/lib/Transport/index.mjs"); + + +/* +methods = Map +*/ + +function transform(result, transforms) { + if (!transforms || !transforms.methods) { + return result + } + + const { methods } = transforms + const transformed = JSON.parse(JSON.stringify(result)) + + Object.keys(methods).forEach((key) => { + const method_info = methods[key] + const rpc_method = method_info['x-method'] + const [module, method] = rpc_method.split('.') + const params = {} + params[method_info['x-this-param']] = transformed + transformed[key] = (...args) => { + // copy the args into the correct RPC param names + for (var i = 0; i < args.length; i++) { + params[method_info['x-additional-params'][i]] = args[i] + } + return _Transport_index_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].send(module.toLowerCase(), method, params) + } + }) + return transformed +} + +/* harmony default export */ __webpack_exports__["default"] = ({ + transform, +}); + + +/***/ }), + +/***/ "./node_modules/@firebolt-js/manage-sdk/dist/lib/SecureStorage/defaults.mjs": +/*!**********************************************************************************!*\ + !*** ./node_modules/@firebolt-js/manage-sdk/dist/lib/SecureStorage/defaults.mjs ***! + \**********************************************************************************/ +/*! exports provided: default */ +/***/ (function(__webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var _Prop_MockProps_mjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Prop/MockProps.mjs */ "./node_modules/@firebolt-js/manage-sdk/dist/lib/Prop/MockProps.mjs"); +/* + * Copyright 2021 Comcast Cable Communications Management, LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + */ + + +/* harmony default export */ __webpack_exports__["default"] = ({ + setForApp: null, + removeForApp: null, + clearForApp: null, +}); + + +/***/ }), + +/***/ "./node_modules/@firebolt-js/manage-sdk/dist/lib/SecureStorage/index.mjs": +/*!*******************************************************************************!*\ + !*** ./node_modules/@firebolt-js/manage-sdk/dist/lib/SecureStorage/index.mjs ***! + \*******************************************************************************/ +/*! exports provided: default */ +/***/ (function(__webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var _Transport_index_mjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Transport/index.mjs */ "./node_modules/@firebolt-js/manage-sdk/dist/lib/Transport/index.mjs"); +/* + * Copyright 2021 Comcast Cable Communications Management, LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + */ + + + +// Methods + +function clearForApp(appId, scope) { + const transforms = null + + return _Transport_index_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].send( + 'SecureStorage', + 'clearForApp', + { appId, scope }, + transforms, + ) +} + +function removeForApp(appId, scope, key) { + const transforms = null + + return _Transport_index_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].send( + 'SecureStorage', + 'removeForApp', + { appId, scope, key }, + transforms, + ) +} + +function setForApp(appId, scope, key, value, options) { + const transforms = null + + return _Transport_index_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].send( + 'SecureStorage', + 'setForApp', + { appId, scope, key, value, options }, + transforms, + ) +} + +/* harmony default export */ __webpack_exports__["default"] = ({ + /** + * The scope of the data + */ + StorageScope: { + DEVICE: 'device', + ACCOUNT: 'account', + }, + + clearForApp, + removeForApp, + setForApp, +}); + + +/***/ }), + +/***/ "./node_modules/@firebolt-js/manage-sdk/dist/lib/Settings/index.mjs": +/*!**************************************************************************!*\ + !*** ./node_modules/@firebolt-js/manage-sdk/dist/lib/Settings/index.mjs ***! + \**************************************************************************/ +/*! exports provided: initSettings, default */ +/***/ (function(__webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "initSettings", function() { return initSettings; }); +/* + * Copyright 2021 Comcast Cable Communications Management, LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + */ + +const settings = {} +const subscribers = {} + +const initSettings = (appSettings, platformSettings) => { + settings['app'] = appSettings + settings['platform'] = { + logLevel: 'WARN', + ...platformSettings, + } + settings['user'] = {} +} + +const publish = (key, value) => { + subscribers[key] && + subscribers[key].forEach((subscriber) => subscriber(value)) +} + +const dotGrab = (obj = {}, key) => { + const keys = key.split('.') + for (let i = 0; i < keys.length; i++) { + obj = obj[keys[i]] = obj[keys[i]] !== undefined ? obj[keys[i]] : {} + } + return typeof obj === 'object' + ? Object.keys(obj).length + ? obj + : undefined + : obj +} + +/* harmony default export */ __webpack_exports__["default"] = ({ + get(type, key, fallback = undefined) { + const val = dotGrab(settings[type], key) + return val !== undefined ? val : fallback + }, + has(type, key) { + return !!this.get(type, key) + }, + set(key, value) { + settings['user'][key] = value + publish(key, value) + }, + subscribe(key, callback) { + subscribers[key] = subscribers[key] || [] + subscribers[key].push(callback) + }, + unsubscribe(key, callback) { + if (callback) { + const index = + subscribers[key] && subscribers[key].findIndex((cb) => cb === callback) + index > -1 && subscribers[key].splice(index, 1) + } else { + if (key in subscribers) { + subscribers[key] = [] + } + } + }, + clearSubscribers() { + for (const key of Object.getOwnPropertyNames(subscribers)) { + delete subscribers[key] + } + }, + setLogLevel(logLevel) { + settings.platform.logLevel = logLevel + }, + getLogLevel() { + return settings.platform.logLevel + }, +}); + + +/***/ }), + +/***/ "./node_modules/@firebolt-js/manage-sdk/dist/lib/Transport/LegacyTransport.mjs": +/*!*************************************************************************************!*\ + !*** ./node_modules/@firebolt-js/manage-sdk/dist/lib/Transport/LegacyTransport.mjs ***! + \*************************************************************************************/ +/*! exports provided: default */ +/***/ (function(__webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return LegacyTransport; }); +/* + * Copyright 2021 Comcast Cable Communications Management, LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + */ + +const win = typeof window !== 'undefined' ? window : {} + +class LegacyTransport { + constructor(bridge) { + this.bridge = bridge + } + + send(msg) { + this.bridge.JSMessageChanged(msg, () => {}) + } + + receive(callback) { + win.$badger = win.$badger || {} + /** Hold on to real $badger callback and event methods so they can be called for non-jsonrpc messages */ + const badgerCallback = win.$badger.callback + ? win.$badger.callback.bind(win.$badger) + : null + const badgerEvent = win.$badger.event + ? win.$badger.event.bind(win.$badger) + : null + win.$badger.callback = (pid, success, json) => { + if (json.jsonrpc) { + callback(JSON.stringify(json)) + } else if (badgerCallback) { + badgerCallback(pid, success, json) + } + } + win.$badger.event = (handlerId, json) => { + if (json.jsonrpc) { + callback(JSON.stringify(json)) + } else if (badgerEvent) { + badgerEvent(handlerId, json) + } + } + } + + static isLegacy(transport) { + return ( + LegacyTransport.isXREProxy(transport) || + (transport.send === undefined && transport.JSMessageChanged) + ) + } + + static isXREProxy(transport) { + /** Set top boxes running XRE has a "Proxy" transport + * native object that intercepts ALL method calls, so we + * cannot test for transport.send existence because it will return true + * even though it actually is not supported. Check if some obscure method + * name like "proxyObjectTest" is defined. If it is then we know we are using a + * Proxy object and thus is legacy transport. + */ + return transport.proxyObjectTest !== undefined + } +} + + +/***/ }), + +/***/ "./node_modules/@firebolt-js/manage-sdk/dist/lib/Transport/MockTransport.mjs": +/*!***********************************************************************************!*\ + !*** ./node_modules/@firebolt-js/manage-sdk/dist/lib/Transport/MockTransport.mjs ***! + \***********************************************************************************/ +/*! exports provided: setMockListener, setMockResponses, default */ +/***/ (function(__webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "setMockListener", function() { return setMockListener; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "setMockResponses", function() { return setMockResponses; }); +/* + * Copyright 2021 Comcast Cable Communications Management, LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + */ + +const win = typeof window !== 'undefined' ? window : {} + +let listener +const setMockListener = (func) => { + listener = func +} + +let mock +const pending = [] +const eventMap = {} + +let callback +let testHarness + +if (win.__firebolt && win.__firebolt.testHarness) { + testHarness = win.__firebolt.testHarness +} + +function send(message) { + console.debug('Sending message to transport: ' + message) + let json = JSON.parse(message) + + // handle bulk sends + if (Array.isArray(json)) { + json.forEach((j) => send(JSON.stringify(j))) + return + } + + let [module, method] = json.method.split('.') + + if (testHarness && testHarness.onSend) { + testHarness.onSend(module, method, json.params, json.id) + } + + // store the ID of the first listen for each event + if (method.match(/^on[A-Z]/)) { + if (json.params.listen) { + eventMap[json.id] = + module.toLowerCase() + '.' + method[2].toLowerCase() + method.substr(3) + } else { + Object.keys(eventMap).forEach((key) => { + if ( + eventMap[key] === + module.toLowerCase() + + '.' + + method[2].toLowerCase() + + method.substr(3) + ) { + delete eventMap[key] + } + }) + } + } + + if (mock) handle(json) + else pending.push(json) +} + +function handle(json) { + let result + try { + result = getResult(json.method, json.params) + } catch (error) { + setTimeout(() => + callback( + JSON.stringify({ + jsonrpc: '2.0', + error: { + code: -32602, + message: + 'Invalid params (this is a mock error from the mock transport layer)', + }, + id: json.id, + }), + ), + ) + } + + setTimeout(() => + callback( + JSON.stringify({ + jsonrpc: '2.0', + result: result, + id: json.id, + }), + ), + ) +} + +function receive(_callback) { + callback = _callback + + if (testHarness && typeof testHarness.initialize === 'function') { + testHarness.initialize({ + emit: event, + listen: function (...args) { + listener(...args) + }, + }) + } +} + +function event(module, event, value) { + const listener = Object.entries(eventMap).find( + ([k, v]) => + v.toLowerCase() === module.toLowerCase() + '.' + event.toLowerCase(), + ) + if (listener) { + let message = JSON.stringify({ + jsonrpc: '2.0', + id: parseInt(listener[0]), + result: value, + }) + callback(message) + } +} + +function dotGrab(obj = {}, key) { + const keys = key.split('.') + let ref = obj + for (let i = 0; i < keys.length; i++) { + ref = (Object.entries(ref).find( + ([k, v]) => k.toLowerCase() === keys[i].toLowerCase(), + ) || [null, {}])[1] + } + return ref +} + +function getResult(method, params) { + let api = dotGrab(mock, method) + + if (method.match(/^[a-zA-Z]+\.on[A-Za-z]+$/)) { + api = { + event: method, + listening: true, + } + } + + if (typeof api === 'function') { + return params == null ? api() : api(params) + } else return api +} + +function setMockResponses(m) { + mock = m + + pending.forEach((json) => handle(json)) + pending.length = 0 +} + +/* harmony default export */ __webpack_exports__["default"] = ({ + send: send, + receive: receive, + event: event, +}); + + +/***/ }), + +/***/ "./node_modules/@firebolt-js/manage-sdk/dist/lib/Transport/WebsocketTransport.mjs": +/*!****************************************************************************************!*\ + !*** ./node_modules/@firebolt-js/manage-sdk/dist/lib/Transport/WebsocketTransport.mjs ***! + \****************************************************************************************/ +/*! exports provided: default */ +/***/ (function(__webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return WebsocketTransport; }); +const MAX_QUEUED_MESSAGES = 100 + +class WebsocketTransport { + constructor(endpoint) { + this._endpoint = endpoint + this._ws = null + this._connected = false + this._queue = [] + this._callbacks = [] + } + + send(msg) { + this._connect() + + if (this._connected) { + this._ws.send(msg) + } else { + if (this._queue.length < MAX_QUEUED_MESSAGES) { + this._queue.push(msg) + } + } + } + + receive(callback) { + if (!callback) return + this._connect() + this._callbacks.push(callback) + } + + _notifyCallbacks(message) { + for (let i = 0; i < this._callbacks.length; i++) { + setTimeout(() => this._callbacks[i](message), 1) + } + } + + _connect() { + if (this._ws) return + this._ws = new WebSocket(this._endpoint, ['jsonrpc']) + this._ws.addEventListener('message', (message) => { + this._notifyCallbacks(message.data) + }) + this._ws.addEventListener('error', (message) => {}) + this._ws.addEventListener('close', (message) => { + this._ws = null + this._connected = false + }) + this._ws.addEventListener('open', (message) => { + this._connected = true + for (let i = 0; i < this._queue.length; i++) { + this._ws.send(this._queue[i]) + } + this._queue = [] + }) + } +} + + +/***/ }), + +/***/ "./node_modules/@firebolt-js/manage-sdk/dist/lib/Transport/index.mjs": +/*!***************************************************************************!*\ + !*** ./node_modules/@firebolt-js/manage-sdk/dist/lib/Transport/index.mjs ***! + \***************************************************************************/ +/*! exports provided: default */ +/***/ (function(__webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return Transport; }); +/* harmony import */ var _MockTransport_mjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./MockTransport.mjs */ "./node_modules/@firebolt-js/manage-sdk/dist/lib/Transport/MockTransport.mjs"); +/* harmony import */ var _queue_mjs__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./queue.mjs */ "./node_modules/@firebolt-js/manage-sdk/dist/lib/Transport/queue.mjs"); +/* harmony import */ var _Settings_index_mjs__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Settings/index.mjs */ "./node_modules/@firebolt-js/manage-sdk/dist/lib/Settings/index.mjs"); +/* harmony import */ var _LegacyTransport_mjs__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./LegacyTransport.mjs */ "./node_modules/@firebolt-js/manage-sdk/dist/lib/Transport/LegacyTransport.mjs"); +/* harmony import */ var _WebsocketTransport_mjs__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./WebsocketTransport.mjs */ "./node_modules/@firebolt-js/manage-sdk/dist/lib/Transport/WebsocketTransport.mjs"); +/* harmony import */ var _Results_index_mjs__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../Results/index.mjs */ "./node_modules/@firebolt-js/manage-sdk/dist/lib/Results/index.mjs"); +/* + * Copyright 2021 Comcast Cable Communications Management, LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + */ + + + + + + + + +const LEGACY_TRANSPORT_SERVICE_NAME = 'com.comcast.BridgeObject_1' +let moduleInstance = null + +const isEventSuccess = (x) => + x && typeof x.event === 'string' && typeof x.listening === 'boolean' + +const win = typeof window !== 'undefined' ? window : {} + +class Transport { + constructor() { + this._promises = [] + this._transport = null + this._id = 1 + this._eventEmitters = [] + this._eventIds = [] + this._queue = new _queue_mjs__WEBPACK_IMPORTED_MODULE_1__["default"]() + this._deprecated = {} + this.isMock = false + } + + static addEventEmitter(emitter) { + Transport.get()._eventEmitters.push(emitter) + } + + static registerDeprecatedMethod(module, method, alternative) { + Transport.get()._deprecated[ + module.toLowerCase() + '.' + method.toLowerCase() + ] = { + alternative: alternative || '', + } + } + + _endpoint() { + if (win.__firebolt && win.__firebolt.endpoint) { + return win.__firebolt.endpoint + } + return null + } + + constructTransportLayer() { + let transport + const endpoint = this._endpoint() + if ( + endpoint && + (endpoint.startsWith('ws://') || endpoint.startsWith('wss://')) + ) { + transport = new _WebsocketTransport_mjs__WEBPACK_IMPORTED_MODULE_4__["default"](endpoint) + transport.receive(this.receiveHandler.bind(this)) + } else if ( + typeof win.ServiceManager !== 'undefined' && + win.ServiceManager && + win.ServiceManager.version + ) { + // Wire up the queue + transport = this._queue + // get the default bridge service, and flush the queue + win.ServiceManager.getServiceForJavaScript( + LEGACY_TRANSPORT_SERVICE_NAME, + (service) => { + if (_LegacyTransport_mjs__WEBPACK_IMPORTED_MODULE_3__["default"].isLegacy(service)) { + transport = new _LegacyTransport_mjs__WEBPACK_IMPORTED_MODULE_3__["default"](service) + } else { + transport = service + } + this.setTransportLayer(transport) + }, + ) + } else { + this.isMock = true + transport = _MockTransport_mjs__WEBPACK_IMPORTED_MODULE_0__["default"] + transport.receive(this.receiveHandler.bind(this)) + } + return transport + } + + setTransportLayer(tl) { + this._transport = tl + this._queue.flush(tl) + } + + static send(module, method, params, transforms) { + /** Transport singleton across all SDKs to keep single id map */ + return Transport.get()._send(module, method, params, transforms) + } + + static listen(module, method, params, transforms) { + return Transport.get()._sendAndGetId(module, method, params, transforms) + } + + _send(module, method, params, transforms) { + if (Array.isArray(module) && !method && !params) { + return this._batch(module) + } else { + return this._sendAndGetId(module, method, params, transforms).promise + } + } + + _sendAndGetId(module, method, params, transforms) { + const { promise, json, id } = this._processRequest( + module, + method, + params, + transforms, + ) + const msg = JSON.stringify(json) + if (_Settings_index_mjs__WEBPACK_IMPORTED_MODULE_2__["default"].getLogLevel() === 'DEBUG') { + console.debug('Sending message to transport: ' + msg) + } + this._transport.send(msg) + + return { id, promise } + } + + _batch(requests) { + const results = [] + const json = [] + + requests.forEach(({ module, method, params, transforms }) => { + const result = this._processRequest(module, method, params, transforms) + results.push({ + promise: result.promise, + id: result.id, + }) + json.push(result.json) + }) + + const msg = JSON.stringify(json) + if (_Settings_index_mjs__WEBPACK_IMPORTED_MODULE_2__["default"].getLogLevel() === 'DEBUG') { + console.debug('Sending message to transport: ' + msg) + } + this._transport.send(msg) + + return results + } + + _processRequest(module, method, params, transforms) { + const p = this._addPromiseToQueue(module, method, params, transforms) + const json = this._createRequestJSON(module, method, params) + + const result = { + promise: p, + json: json, + id: this._id, + } + + this._id++ + + return result + } + + _createRequestJSON(module, method, params) { + return { + jsonrpc: '2.0', + method: module.toLowerCase() + '.' + method, + params: params, + id: this._id, + } + } + + _addPromiseToQueue(module, method, params, transforms) { + return new Promise((resolve, reject) => { + this._promises[this._id] = {} + this._promises[this._id].promise = this + this._promises[this._id].resolve = resolve + this._promises[this._id].reject = reject + this._promises[this._id].transforms = transforms + + const deprecated = + this._deprecated[module.toLowerCase() + '.' + method.toLowerCase()] + if (deprecated) { + console.warn( + `WARNING: ${module}.${method}() is deprecated. ` + + deprecated.alternative, + ) + } + + // store the ID of the first listen for each event + // TODO: what about wild cards? + if (method.match(/^on[A-Z]/)) { + if (params.listen) { + this._eventIds.push(this._id) + } else { + this._eventIds = this._eventIds.filter((id) => id !== this._id) + } + } + }) + } + + /** + * If we have a global transport, use that. Otherwise, use the module-scoped transport instance. + * @returns {Transport} + */ + static get() { + /** Set up singleton and initialize it */ + win.__firebolt = win.__firebolt || {} + if (win.__firebolt.transport == null && moduleInstance == null) { + const transport = new Transport() + transport.init() + if (transport.isMock) { + /** We should use the mock transport built with the SDK, not a global */ + moduleInstance = transport + } else { + win.__firebolt = win.__firebolt || {} + win.__firebolt.transport = transport + } + win.__firebolt.setTransportLayer = + transport.setTransportLayer.bind(transport) + } + return win.__firebolt.transport ? win.__firebolt.transport : moduleInstance + } + + receiveHandler(message) { + if (_Settings_index_mjs__WEBPACK_IMPORTED_MODULE_2__["default"].getLogLevel() === 'DEBUG') { + console.debug('Received message from transport: ' + message) + } + const json = JSON.parse(message) + const p = this._promises[json.id] + + if (p) { + if (json.error) p.reject(json.error) + else { + // Do any module-specific transforms on the result + let result = json.result + + if (p.transforms) { + if (Array.isArray(json.result)) { + result = result.map((x) => _Results_index_mjs__WEBPACK_IMPORTED_MODULE_5__["default"].transform(x, p.transforms)) + } else { + result = _Results_index_mjs__WEBPACK_IMPORTED_MODULE_5__["default"].transform(result, p.transforms) + } + } + + p.resolve(result) + } + delete this._promises[json.id] + } + + // event responses need to be emitted, even after the listen call is resolved + if (this._eventIds.includes(json.id) && !isEventSuccess(json.result)) { + this._eventEmitters.forEach((emit) => { + emit(json.id, json.result) + }) + } + } + + init() { + Object(_Settings_index_mjs__WEBPACK_IMPORTED_MODULE_2__["initSettings"])({}, { log: true }) + this._queue.receive(this.receiveHandler.bind(this)) + if (win.__firebolt) { + if (win.__firebolt.mockTransportLayer === true) { + this.isMock = true + this.setTransportLayer(_MockTransport_mjs__WEBPACK_IMPORTED_MODULE_0__["default"]) + } else if (win.__firebolt.getTransportLayer) { + this.setTransportLayer(win.__firebolt.getTransportLayer()) + } + } + if (this._transport == null) { + this._transport = this.constructTransportLayer() + } + } +} +win.__firebolt = win.__firebolt || {} +win.__firebolt.setTransportLayer = (transport) => { + Transport.get().setTransportLayer(transport) +} + + +/***/ }), + +/***/ "./node_modules/@firebolt-js/manage-sdk/dist/lib/Transport/queue.mjs": +/*!***************************************************************************!*\ + !*** ./node_modules/@firebolt-js/manage-sdk/dist/lib/Transport/queue.mjs ***! + \***************************************************************************/ +/*! exports provided: default */ +/***/ (function(__webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return Queue; }); +/* + * Copyright 2021 Comcast Cable Communications Management, LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + */ + +class Queue { + constructor() { + this._callback = null + this._queue = [] + } + + send(json) { + this._queue.push(json) + } + + receive(_callback) { + this._callback = _callback + } + + flush(transport) { + transport.receive(this._callback) + this._queue.forEach((item) => transport.send(item)) + } +} + + +/***/ }), + +/***/ "./node_modules/@firebolt-js/manage-sdk/dist/lib/UserGrants/defaults.mjs": +/*!*******************************************************************************!*\ + !*** ./node_modules/@firebolt-js/manage-sdk/dist/lib/UserGrants/defaults.mjs ***! + \*******************************************************************************/ +/*! exports provided: default */ +/***/ (function(__webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var _Prop_MockProps_mjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Prop/MockProps.mjs */ "./node_modules/@firebolt-js/manage-sdk/dist/lib/Prop/MockProps.mjs"); +/* + * Copyright 2021 Comcast Cable Communications Management, LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + */ + + +/* harmony default export */ __webpack_exports__["default"] = ({ + app: [ + { + app: { id: 'certapp', title: 'Firebolt Certification' }, + state: 'granted', + capability: 'xrn:firebolt:capability:data:app-usage', + role: 'use', + lifespan: 'seconds', + expires: '2022-12-14T20:20:39+00:00', + }, + { + app: { id: 'certapp', title: 'Firebolt Certification' }, + state: 'denied', + capability: 'xrn:firebolt:capability:localization:postal-code', + role: 'use', + lifespan: 'appActive', + }, + ], + device: [ + { + state: 'granted', + capability: 'xrn:firebolt:capability:localization:postal-code', + role: 'use', + lifespan: 'powerActive', + }, + ], + capability: [ + { + state: 'granted', + capability: 'xrn:firebolt:capability:localization:postal-code', + role: 'use', + lifespan: 'powerActive', + }, + ], + grant: null, + deny: null, + clear: null, + request: [ + { + app: { id: 'certapp', title: 'Certification App' }, + state: 'granted', + capability: 'xrn:firebolt:capability:localization:postal-code', + role: 'use', + lifespan: 'powerActive', + }, + ], +}); + + +/***/ }), + +/***/ "./node_modules/@firebolt-js/manage-sdk/dist/lib/UserGrants/index.mjs": +/*!****************************************************************************!*\ + !*** ./node_modules/@firebolt-js/manage-sdk/dist/lib/UserGrants/index.mjs ***! + \****************************************************************************/ +/*! exports provided: default */ +/***/ (function(__webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var _Transport_index_mjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Transport/index.mjs */ "./node_modules/@firebolt-js/manage-sdk/dist/lib/Transport/index.mjs"); +/* + * Copyright 2021 Comcast Cable Communications Management, LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + */ + + + +// Methods + +function app(appId) { + const transforms = null + + return _Transport_index_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].send('UserGrants', 'app', { appId }, transforms) +} + +function capability(capability) { + const transforms = null + + return _Transport_index_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].send('UserGrants', 'capability', { capability }, transforms) +} + +function clear(role, capability, options) { + const transforms = null + + return _Transport_index_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].send( + 'UserGrants', + 'clear', + { role, capability, options }, + transforms, + ) +} + +function deny(role, capability, options) { + const transforms = null + + return _Transport_index_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].send( + 'UserGrants', + 'deny', + { role, capability, options }, + transforms, + ) +} + +function device() { + const transforms = null + + return _Transport_index_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].send('UserGrants', 'device', {}, transforms) +} + +function grant(role, capability, options) { + const transforms = null + + return _Transport_index_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].send( + 'UserGrants', + 'grant', + { role, capability, options }, + transforms, + ) +} + +function request(appId, permissions, options) { + const transforms = null + + return _Transport_index_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].send( + 'UserGrants', + 'request', + { appId, permissions, options }, + transforms, + ) +} + +/* harmony default export */ __webpack_exports__["default"] = ({ + /** + * Role provides access level for the app for a given capability. + */ + Role: { + USE: 'use', + MANAGE: 'manage', + PROVIDE: 'provide', + }, + + /** + * The state the grant is in + */ + GrantState: { + GRANTED: 'granted', + DENIED: 'denied', + }, + + app, + capability, + clear, + deny, + device, + grant, + request, +}); + + +/***/ }), + +/***/ "./node_modules/@firebolt-js/manage-sdk/dist/lib/VoiceGuidance/defaults.mjs": +/*!**********************************************************************************!*\ + !*** ./node_modules/@firebolt-js/manage-sdk/dist/lib/VoiceGuidance/defaults.mjs ***! + \**********************************************************************************/ +/*! exports provided: default */ +/***/ (function(__webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var _Prop_MockProps_mjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Prop/MockProps.mjs */ "./node_modules/@firebolt-js/manage-sdk/dist/lib/Prop/MockProps.mjs"); +/* + * Copyright 2021 Comcast Cable Communications Management, LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + */ + + +/* harmony default export */ __webpack_exports__["default"] = ({ + enabled: function (params) { + return _Prop_MockProps_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].mock( + 'VoiceGuidance', + 'enabled', + params, + undefined, + 0, + true, + ) + }, + speed: function (params) { + return _Prop_MockProps_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].mock('VoiceGuidance', 'speed', params, undefined, 0, 1) + }, + setEnabled: function (params) { + const callbackOrValue = params.value + delete params.value + return _Prop_MockProps_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].mock( + 'VoiceGuidance', + 'enabled', + params, + callbackOrValue, + 0, + null, + ) + }, + setSpeed: function (params) { + const callbackOrValue = params.value + delete params.value + return _Prop_MockProps_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].mock( + 'VoiceGuidance', + 'speed', + params, + callbackOrValue, + 0, + null, + ) + }, +}); + + +/***/ }), + +/***/ "./node_modules/@firebolt-js/manage-sdk/dist/lib/VoiceGuidance/index.mjs": +/*!*******************************************************************************!*\ + !*** ./node_modules/@firebolt-js/manage-sdk/dist/lib/VoiceGuidance/index.mjs ***! + \*******************************************************************************/ +/*! exports provided: default */ +/***/ (function(__webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var _Transport_index_mjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Transport/index.mjs */ "./node_modules/@firebolt-js/manage-sdk/dist/lib/Transport/index.mjs"); +/* harmony import */ var _Events_index_mjs__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Events/index.mjs */ "./node_modules/@firebolt-js/manage-sdk/dist/lib/Events/index.mjs"); +/* harmony import */ var _Prop_index_mjs__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Prop/index.mjs */ "./node_modules/@firebolt-js/manage-sdk/dist/lib/Prop/index.mjs"); +/* + * Copyright 2021 Comcast Cable Communications Management, LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + */ + + + + + + +Object(_Events_index_mjs__WEBPACK_IMPORTED_MODULE_1__["registerEvents"])('VoiceGuidance', ['enabledChanged', 'speedChanged']) + +// onEnabledChanged is accessed via listen('enabledChanged, ...) + +// onSpeedChanged is accessed via listen('speedChanged, ...) + +// Methods +function clear(...args) { + return _Events_index_mjs__WEBPACK_IMPORTED_MODULE_1__["default"].clear('VoiceGuidance', ...args) +} + +function enabled() { + let callbackOrValue = arguments[0] + let params = {} + + // x-subscriber-type: global + if (arguments.length === 1 && typeof arguments[0] === 'function') { + callbackOrValue = arguments[0] + params = {} + } + + return _Prop_index_mjs__WEBPACK_IMPORTED_MODULE_2__["default"].prop( + 'VoiceGuidance', + 'enabled', + params, + callbackOrValue, + false, + false, + 0, + ) +} +function listen(...args) { + return _Events_index_mjs__WEBPACK_IMPORTED_MODULE_1__["default"].listen('VoiceGuidance', ...args) +} + +function once(...args) { + return _Events_index_mjs__WEBPACK_IMPORTED_MODULE_1__["default"].once('VoiceGuidance', ...args) +} + +function speed() { + let callbackOrValue = arguments[0] + let params = {} + + // x-subscriber-type: global + if (arguments.length === 1 && typeof arguments[0] === 'function') { + callbackOrValue = arguments[0] + params = {} + } + + return _Prop_index_mjs__WEBPACK_IMPORTED_MODULE_2__["default"].prop( + 'VoiceGuidance', + 'speed', + params, + callbackOrValue, + false, + false, + 0, + ) +} + +/* harmony default export */ __webpack_exports__["default"] = ({ + Events: { + ENABLED_CHANGED: 'enabledChanged', + SPEED_CHANGED: 'speedChanged', + }, + + clear, + enabled, + listen, + once, + speed, +}); + + +/***/ }), + +/***/ "./node_modules/@firebolt-js/manage-sdk/dist/lib/Wifi/defaults.mjs": +/*!*************************************************************************!*\ + !*** ./node_modules/@firebolt-js/manage-sdk/dist/lib/Wifi/defaults.mjs ***! + \*************************************************************************/ +/*! exports provided: default */ +/***/ (function(__webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var _Prop_MockProps_mjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Prop/MockProps.mjs */ "./node_modules/@firebolt-js/manage-sdk/dist/lib/Prop/MockProps.mjs"); +/* + * Copyright 2021 Comcast Cable Communications Management, LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + */ + + +/* harmony default export */ __webpack_exports__["default"] = ({ + scan: { + list: [ + { ssid: 'DND', security: 'wpa2Psk', signalStrength: -70, frequency: 2.4 }, + { + ssid: 'Fortnite', + security: 'WPA2_ENTERPRISE_AES', + signalStrength: -70, + frequency: 5, + }, + { + ssid: 'Guardian', + security: 'none', + signalStrength: -70, + frequency: 2.4, + }, + ], + }, + connect: { + ssid: 'DND', + security: 'wpa2Psk', + signalStrength: -70, + frequency: 2.4, + }, + disconnect: null, + wps: { + ssid: 'DND', + security: 'wpa2Psk', + signalStrength: -70, + frequency: 2.4, + }, +}); + + +/***/ }), + +/***/ "./node_modules/@firebolt-js/manage-sdk/dist/lib/Wifi/index.mjs": +/*!**********************************************************************!*\ + !*** ./node_modules/@firebolt-js/manage-sdk/dist/lib/Wifi/index.mjs ***! + \**********************************************************************/ +/*! exports provided: default */ +/***/ (function(__webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var _Transport_index_mjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Transport/index.mjs */ "./node_modules/@firebolt-js/manage-sdk/dist/lib/Transport/index.mjs"); +/* + * Copyright 2021 Comcast Cable Communications Management, LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + */ + + + +// Methods + +function connect(ssid, passphrase, security) { + const transforms = null + + return _Transport_index_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].send( + 'Wifi', + 'connect', + { ssid, passphrase, security }, + transforms, + ) +} + +function disconnect() { + const transforms = null + + return _Transport_index_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].send('Wifi', 'disconnect', {}, transforms) +} + +function scan(timeout) { + const transforms = null + + return _Transport_index_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].send('Wifi', 'scan', { timeout }, transforms) +} + +function wps(security) { + const transforms = null + + return _Transport_index_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].send('Wifi', 'wps', { security }, transforms) +} + +/* harmony default export */ __webpack_exports__["default"] = ({ + /** + * Security Mode supported for Wifi + */ + WifiSecurityMode: { + NONE: 'none', + WEP_64: 'wep64', + WEP_128: 'wep128', + WPA_PSK_TKIP: 'wpaPskTkip', + WPA_PSK_AES: 'wpaPskAes', + WPA_2PSK_TKIP: 'wpa2PskTkip', + WPA_2PSK_AES: 'wpa2PskAes', + WPA_ENTERPRISE_TKIP: 'wpaEnterpriseTkip', + WPA_ENTERPRISE_AES: 'wpaEnterpriseAes', + WPA_2ENTERPRISE_TKIP: 'wpa2EnterpriseTkip', + WPA_2ENTERPRISE_AES: 'wpa2EnterpriseAes', + WPA_2PSK: 'wpa2Psk', + WPA_2ENTERPRISE: 'wpa2Enterprise', + WPA_3PSK_AES: 'wpa3PskAes', + WPA_3SAE: 'wpa3Sae', + }, + + /** + * Security pin type for WPS(Wifi Protected Setup). + */ + WPSSecurityPin: { + PUSH_BUTTON: 'pushButton', + PIN: 'pin', + MANUFACTURER_PIN: 'manufacturerPin', + }, + + connect, + disconnect, + scan, + wps, +}); + + +/***/ }), + +/***/ "./node_modules/@firebolt-js/manage-sdk/dist/lib/firebolt-manage.mjs": +/*!***************************************************************************!*\ + !*** ./node_modules/@firebolt-js/manage-sdk/dist/lib/firebolt-manage.mjs ***! + \***************************************************************************/ +/*! exports provided: Localization, Metrics, Wifi, ClosedCaptions, AudioDescriptions, VoiceGuidance, Device, UserGrants, Privacy, Advertising, Account, Keyboard, AcknowledgeChallenge, PinChallenge, SecureStorage, Discovery, HDMIInput, Log, Events, Settings */ +/***/ (function(__webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var _Transport_MockTransport_mjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./Transport/MockTransport.mjs */ "./node_modules/@firebolt-js/manage-sdk/dist/lib/Transport/MockTransport.mjs"); +/* harmony import */ var _Localization_defaults_mjs__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./Localization/defaults.mjs */ "./node_modules/@firebolt-js/manage-sdk/dist/lib/Localization/defaults.mjs"); +/* harmony import */ var _Metrics_defaults_mjs__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./Metrics/defaults.mjs */ "./node_modules/@firebolt-js/manage-sdk/dist/lib/Metrics/defaults.mjs"); +/* harmony import */ var _Wifi_defaults_mjs__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./Wifi/defaults.mjs */ "./node_modules/@firebolt-js/manage-sdk/dist/lib/Wifi/defaults.mjs"); +/* harmony import */ var _ClosedCaptions_defaults_mjs__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./ClosedCaptions/defaults.mjs */ "./node_modules/@firebolt-js/manage-sdk/dist/lib/ClosedCaptions/defaults.mjs"); +/* harmony import */ var _AudioDescriptions_defaults_mjs__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./AudioDescriptions/defaults.mjs */ "./node_modules/@firebolt-js/manage-sdk/dist/lib/AudioDescriptions/defaults.mjs"); +/* harmony import */ var _VoiceGuidance_defaults_mjs__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./VoiceGuidance/defaults.mjs */ "./node_modules/@firebolt-js/manage-sdk/dist/lib/VoiceGuidance/defaults.mjs"); +/* harmony import */ var _Device_defaults_mjs__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./Device/defaults.mjs */ "./node_modules/@firebolt-js/manage-sdk/dist/lib/Device/defaults.mjs"); +/* harmony import */ var _UserGrants_defaults_mjs__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./UserGrants/defaults.mjs */ "./node_modules/@firebolt-js/manage-sdk/dist/lib/UserGrants/defaults.mjs"); +/* harmony import */ var _Privacy_defaults_mjs__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./Privacy/defaults.mjs */ "./node_modules/@firebolt-js/manage-sdk/dist/lib/Privacy/defaults.mjs"); +/* harmony import */ var _Advertising_defaults_mjs__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./Advertising/defaults.mjs */ "./node_modules/@firebolt-js/manage-sdk/dist/lib/Advertising/defaults.mjs"); +/* harmony import */ var _Account_defaults_mjs__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ./Account/defaults.mjs */ "./node_modules/@firebolt-js/manage-sdk/dist/lib/Account/defaults.mjs"); +/* harmony import */ var _Keyboard_defaults_mjs__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ./Keyboard/defaults.mjs */ "./node_modules/@firebolt-js/manage-sdk/dist/lib/Keyboard/defaults.mjs"); +/* harmony import */ var _AcknowledgeChallenge_defaults_mjs__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ./AcknowledgeChallenge/defaults.mjs */ "./node_modules/@firebolt-js/manage-sdk/dist/lib/AcknowledgeChallenge/defaults.mjs"); +/* harmony import */ var _PinChallenge_defaults_mjs__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ./PinChallenge/defaults.mjs */ "./node_modules/@firebolt-js/manage-sdk/dist/lib/PinChallenge/defaults.mjs"); +/* harmony import */ var _SecureStorage_defaults_mjs__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ./SecureStorage/defaults.mjs */ "./node_modules/@firebolt-js/manage-sdk/dist/lib/SecureStorage/defaults.mjs"); +/* harmony import */ var _Discovery_defaults_mjs__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(/*! ./Discovery/defaults.mjs */ "./node_modules/@firebolt-js/manage-sdk/dist/lib/Discovery/defaults.mjs"); +/* harmony import */ var _HDMIInput_defaults_mjs__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(/*! ./HDMIInput/defaults.mjs */ "./node_modules/@firebolt-js/manage-sdk/dist/lib/HDMIInput/defaults.mjs"); +/* harmony import */ var _Localization_index_mjs__WEBPACK_IMPORTED_MODULE_18__ = __webpack_require__(/*! ./Localization/index.mjs */ "./node_modules/@firebolt-js/manage-sdk/dist/lib/Localization/index.mjs"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Localization", function() { return _Localization_index_mjs__WEBPACK_IMPORTED_MODULE_18__["default"]; }); + +/* harmony import */ var _Metrics_index_mjs__WEBPACK_IMPORTED_MODULE_19__ = __webpack_require__(/*! ./Metrics/index.mjs */ "./node_modules/@firebolt-js/manage-sdk/dist/lib/Metrics/index.mjs"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Metrics", function() { return _Metrics_index_mjs__WEBPACK_IMPORTED_MODULE_19__["default"]; }); + +/* harmony import */ var _Wifi_index_mjs__WEBPACK_IMPORTED_MODULE_20__ = __webpack_require__(/*! ./Wifi/index.mjs */ "./node_modules/@firebolt-js/manage-sdk/dist/lib/Wifi/index.mjs"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Wifi", function() { return _Wifi_index_mjs__WEBPACK_IMPORTED_MODULE_20__["default"]; }); + +/* harmony import */ var _ClosedCaptions_index_mjs__WEBPACK_IMPORTED_MODULE_21__ = __webpack_require__(/*! ./ClosedCaptions/index.mjs */ "./node_modules/@firebolt-js/manage-sdk/dist/lib/ClosedCaptions/index.mjs"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ClosedCaptions", function() { return _ClosedCaptions_index_mjs__WEBPACK_IMPORTED_MODULE_21__["default"]; }); + +/* harmony import */ var _AudioDescriptions_index_mjs__WEBPACK_IMPORTED_MODULE_22__ = __webpack_require__(/*! ./AudioDescriptions/index.mjs */ "./node_modules/@firebolt-js/manage-sdk/dist/lib/AudioDescriptions/index.mjs"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AudioDescriptions", function() { return _AudioDescriptions_index_mjs__WEBPACK_IMPORTED_MODULE_22__["default"]; }); + +/* harmony import */ var _VoiceGuidance_index_mjs__WEBPACK_IMPORTED_MODULE_23__ = __webpack_require__(/*! ./VoiceGuidance/index.mjs */ "./node_modules/@firebolt-js/manage-sdk/dist/lib/VoiceGuidance/index.mjs"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "VoiceGuidance", function() { return _VoiceGuidance_index_mjs__WEBPACK_IMPORTED_MODULE_23__["default"]; }); + +/* harmony import */ var _Device_index_mjs__WEBPACK_IMPORTED_MODULE_24__ = __webpack_require__(/*! ./Device/index.mjs */ "./node_modules/@firebolt-js/manage-sdk/dist/lib/Device/index.mjs"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Device", function() { return _Device_index_mjs__WEBPACK_IMPORTED_MODULE_24__["default"]; }); + +/* harmony import */ var _UserGrants_index_mjs__WEBPACK_IMPORTED_MODULE_25__ = __webpack_require__(/*! ./UserGrants/index.mjs */ "./node_modules/@firebolt-js/manage-sdk/dist/lib/UserGrants/index.mjs"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "UserGrants", function() { return _UserGrants_index_mjs__WEBPACK_IMPORTED_MODULE_25__["default"]; }); + +/* harmony import */ var _Privacy_index_mjs__WEBPACK_IMPORTED_MODULE_26__ = __webpack_require__(/*! ./Privacy/index.mjs */ "./node_modules/@firebolt-js/manage-sdk/dist/lib/Privacy/index.mjs"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Privacy", function() { return _Privacy_index_mjs__WEBPACK_IMPORTED_MODULE_26__["default"]; }); + +/* harmony import */ var _Advertising_index_mjs__WEBPACK_IMPORTED_MODULE_27__ = __webpack_require__(/*! ./Advertising/index.mjs */ "./node_modules/@firebolt-js/manage-sdk/dist/lib/Advertising/index.mjs"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Advertising", function() { return _Advertising_index_mjs__WEBPACK_IMPORTED_MODULE_27__["default"]; }); + +/* harmony import */ var _Account_index_mjs__WEBPACK_IMPORTED_MODULE_28__ = __webpack_require__(/*! ./Account/index.mjs */ "./node_modules/@firebolt-js/manage-sdk/dist/lib/Account/index.mjs"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Account", function() { return _Account_index_mjs__WEBPACK_IMPORTED_MODULE_28__["default"]; }); + +/* harmony import */ var _Keyboard_index_mjs__WEBPACK_IMPORTED_MODULE_29__ = __webpack_require__(/*! ./Keyboard/index.mjs */ "./node_modules/@firebolt-js/manage-sdk/dist/lib/Keyboard/index.mjs"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Keyboard", function() { return _Keyboard_index_mjs__WEBPACK_IMPORTED_MODULE_29__["default"]; }); + +/* harmony import */ var _AcknowledgeChallenge_index_mjs__WEBPACK_IMPORTED_MODULE_30__ = __webpack_require__(/*! ./AcknowledgeChallenge/index.mjs */ "./node_modules/@firebolt-js/manage-sdk/dist/lib/AcknowledgeChallenge/index.mjs"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AcknowledgeChallenge", function() { return _AcknowledgeChallenge_index_mjs__WEBPACK_IMPORTED_MODULE_30__["default"]; }); + +/* harmony import */ var _PinChallenge_index_mjs__WEBPACK_IMPORTED_MODULE_31__ = __webpack_require__(/*! ./PinChallenge/index.mjs */ "./node_modules/@firebolt-js/manage-sdk/dist/lib/PinChallenge/index.mjs"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PinChallenge", function() { return _PinChallenge_index_mjs__WEBPACK_IMPORTED_MODULE_31__["default"]; }); + +/* harmony import */ var _SecureStorage_index_mjs__WEBPACK_IMPORTED_MODULE_32__ = __webpack_require__(/*! ./SecureStorage/index.mjs */ "./node_modules/@firebolt-js/manage-sdk/dist/lib/SecureStorage/index.mjs"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SecureStorage", function() { return _SecureStorage_index_mjs__WEBPACK_IMPORTED_MODULE_32__["default"]; }); + +/* harmony import */ var _Discovery_index_mjs__WEBPACK_IMPORTED_MODULE_33__ = __webpack_require__(/*! ./Discovery/index.mjs */ "./node_modules/@firebolt-js/manage-sdk/dist/lib/Discovery/index.mjs"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Discovery", function() { return _Discovery_index_mjs__WEBPACK_IMPORTED_MODULE_33__["default"]; }); + +/* harmony import */ var _HDMIInput_index_mjs__WEBPACK_IMPORTED_MODULE_34__ = __webpack_require__(/*! ./HDMIInput/index.mjs */ "./node_modules/@firebolt-js/manage-sdk/dist/lib/HDMIInput/index.mjs"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "HDMIInput", function() { return _HDMIInput_index_mjs__WEBPACK_IMPORTED_MODULE_34__["default"]; }); + +/* harmony import */ var _Log_index_mjs__WEBPACK_IMPORTED_MODULE_35__ = __webpack_require__(/*! ./Log/index.mjs */ "./node_modules/@firebolt-js/manage-sdk/dist/lib/Log/index.mjs"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Log", function() { return _Log_index_mjs__WEBPACK_IMPORTED_MODULE_35__["default"]; }); + +/* harmony import */ var _Events_index_mjs__WEBPACK_IMPORTED_MODULE_36__ = __webpack_require__(/*! ./Events/index.mjs */ "./node_modules/@firebolt-js/manage-sdk/dist/lib/Events/index.mjs"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Events", function() { return _Events_index_mjs__WEBPACK_IMPORTED_MODULE_36__["default"]; }); + +/* harmony import */ var _Settings_index_mjs__WEBPACK_IMPORTED_MODULE_37__ = __webpack_require__(/*! ./Settings/index.mjs */ "./node_modules/@firebolt-js/manage-sdk/dist/lib/Settings/index.mjs"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Settings", function() { return _Settings_index_mjs__WEBPACK_IMPORTED_MODULE_37__["default"]; }); + +/* + * Copyright 2021 Comcast Cable Communications Management, LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + */ + + + + + + + + + + + + + + + + + + + + + +Object(_Transport_MockTransport_mjs__WEBPACK_IMPORTED_MODULE_0__["setMockResponses"])({ + Localization: _Localization_defaults_mjs__WEBPACK_IMPORTED_MODULE_1__["default"], + Metrics: _Metrics_defaults_mjs__WEBPACK_IMPORTED_MODULE_2__["default"], + Wifi: _Wifi_defaults_mjs__WEBPACK_IMPORTED_MODULE_3__["default"], + ClosedCaptions: _ClosedCaptions_defaults_mjs__WEBPACK_IMPORTED_MODULE_4__["default"], + AudioDescriptions: _AudioDescriptions_defaults_mjs__WEBPACK_IMPORTED_MODULE_5__["default"], + VoiceGuidance: _VoiceGuidance_defaults_mjs__WEBPACK_IMPORTED_MODULE_6__["default"], + Device: _Device_defaults_mjs__WEBPACK_IMPORTED_MODULE_7__["default"], + UserGrants: _UserGrants_defaults_mjs__WEBPACK_IMPORTED_MODULE_8__["default"], + Privacy: _Privacy_defaults_mjs__WEBPACK_IMPORTED_MODULE_9__["default"], + Advertising: _Advertising_defaults_mjs__WEBPACK_IMPORTED_MODULE_10__["default"], + Account: _Account_defaults_mjs__WEBPACK_IMPORTED_MODULE_11__["default"], + Keyboard: _Keyboard_defaults_mjs__WEBPACK_IMPORTED_MODULE_12__["default"], + AcknowledgeChallenge: _AcknowledgeChallenge_defaults_mjs__WEBPACK_IMPORTED_MODULE_13__["default"], + PinChallenge: _PinChallenge_defaults_mjs__WEBPACK_IMPORTED_MODULE_14__["default"], + SecureStorage: _SecureStorage_defaults_mjs__WEBPACK_IMPORTED_MODULE_15__["default"], + Discovery: _Discovery_defaults_mjs__WEBPACK_IMPORTED_MODULE_16__["default"], + HDMIInput: _HDMIInput_defaults_mjs__WEBPACK_IMPORTED_MODULE_17__["default"], +}) + + + + + + + + + + + + + + + + + + + + + + + +/***/ }), + +/***/ "./node_modules/@firebolt-js/sdk/dist/firebolt-core-open-rpc.json": +/*!************************************************************************!*\ + !*** ./node_modules/@firebolt-js/sdk/dist/firebolt-core-open-rpc.json ***! + \************************************************************************/ +/*! exports provided: openrpc, info, methods, components, x-schemas, default */ +/***/ (function(module) { + +module.exports = JSON.parse("{\"openrpc\":\"1.2.4\",\"info\":{\"title\":\"Firebolt Core SDK\",\"version\":\"1.4.1\",\"x-module-descriptions\":{\"Internal\":\"Internal methods for SDK / FEE integration\",\"Accessibility\":\"The `Accessibility` module provides access to the user/device settings for closed captioning and voice guidance.\\n\\nApps **SHOULD** attempt o respect these settings, rather than manage and persist seprate settings, which would be different per-app.\",\"Account\":\"A module for querying about the device account.\",\"Advertising\":\"A module for platform provided advertising settings and functionality.\",\"Authentication\":\"A module for acquiring authentication tokens.\",\"Capabilities\":\"The Capabilities module provides information about which discreet unit of functionality is enabled for the apps.\",\"Device\":\"A module for querying about the device and it's capabilities.\",\"Discovery\":\"Your App likely wants to integrate with the Platform's discovery capabilities. For example to add a \\\"Watch Next\\\" tile that links to your app from the platform's home screen.\\n\\nGetting access to this information requires to connect to lower level APIs made available by the platform. Since implementations differ between operators and platforms, the Firebolt SDK offers a Discovery module, that exposes a generic, agnostic interface to the developer.\\n\\nUnder the hood, an underlaying transport layer will then take care of calling the right APIs for the actual platform implementation that your App is running on.\\n\\nThe Discovery plugin is used to _send_ information to the Platform.\\n\\n### Localization\\nApps should provide all user-facing strings in the device's language, as specified by the Firebolt `Localization.language` property.\\n\\nApps should provide prices in the same currency presented in the app. If multiple currencies are supported in the app, the app should provide prices in the user's current default currency.\",\"Keyboard\":\"Methods for prompting users to enter text with task-oriented UX\",\"Lifecycle\":\"Methods and events for responding to lifecycle changes in your app\",\"Localization\":\"Methods for accessessing location and language preferences\",\"Metrics\":\"Methods for sending metrics\",\"Parameters\":\"Methods for getting initialization parameters for an app cold launch.\",\"Profile\":\"Methods for getting information about the current user/account profile\",\"SecondScreen\":\"Methods for communicating with second screen devices\",\"SecureStorage\":\"A module for storing and retrieving secure data owned by the app\"}},\"methods\":[{\"name\":\"Accessibility.closedCaptions\",\"summary\":\"Get the user's preferred closed-captions settings\",\"params\":[],\"tags\":[{\"name\":\"deprecated\",\"x-alternative\":\"Accessibility.closedCaptionsSettings()\",\"x-since\":\"0.6.0\"},{\"name\":\"capabilities\",\"x-uses\":[\"xrn:firebolt:capability:accessibility:closedcaptions\"]}],\"result\":{\"name\":\"closedCaptionsSettings\",\"summary\":\"the closed captions settings\",\"schema\":{\"$ref\":\"#/x-schemas/Accessibility/ClosedCaptionsSettings\"}},\"examples\":[{\"name\":\"Getting the closed captions settings\",\"params\":[],\"result\":{\"name\":\"settings\",\"value\":{\"enabled\":true,\"styles\":{\"fontFamily\":\"monospaced_sanserif\",\"fontSize\":1,\"fontColor\":\"#ffffff\",\"fontEdge\":\"none\",\"fontEdgeColor\":\"#7F7F7F\",\"fontOpacity\":100,\"backgroundColor\":\"#000000\",\"backgroundOpacity\":100,\"textAlign\":\"center\",\"textAlignVertical\":\"middle\",\"windowColor\":\"white\",\"windowOpacity\":50},\"preferredLanguages\":[\"eng\",\"spa\"]}}}]},{\"name\":\"Accessibility.closedCaptionsSettings\",\"summary\":\"Get the user's preferred closed-captions settings\",\"params\":[],\"tags\":[{\"name\":\"property:readonly\"},{\"name\":\"capabilities\",\"x-uses\":[\"xrn:firebolt:capability:accessibility:closedcaptions\"]}],\"result\":{\"name\":\"closedCaptionsSettings\",\"summary\":\"the closed captions settings\",\"schema\":{\"$ref\":\"#/x-schemas/Accessibility/ClosedCaptionsSettings\"}},\"examples\":[{\"name\":\"Getting the closed captions settings\",\"params\":[],\"result\":{\"name\":\"settings\",\"value\":{\"enabled\":true,\"styles\":{\"fontFamily\":\"monospaced_sanserif\",\"fontSize\":1,\"fontColor\":\"#ffffff\",\"fontEdge\":\"none\",\"fontEdgeColor\":\"#7F7F7F\",\"fontOpacity\":100,\"backgroundColor\":\"#000000\",\"backgroundOpacity\":100,\"textAlign\":\"center\",\"textAlignVertical\":\"middle\",\"windowColor\":\"white\",\"windowOpacity\":50},\"preferredLanguages\":[\"eng\",\"spa\"]}}}]},{\"name\":\"Accessibility.voiceGuidance\",\"summary\":\"Get the user's preferred voice guidance settings\",\"params\":[],\"tags\":[{\"name\":\"deprecated\",\"x-alternative\":\"Accessibility.voiceGuidanceSettings()\",\"x-since\":\"0.6.0\"},{\"name\":\"capabilities\",\"x-uses\":[\"xrn:firebolt:capability:accessibility:voiceguidance\"]}],\"result\":{\"name\":\"settings\",\"summary\":\"the voice guidance settings\",\"schema\":{\"$ref\":\"#/x-schemas/Accessibility/VoiceGuidanceSettings\"}},\"examples\":[{\"name\":\"Getting the voice guidance settings\",\"params\":[],\"result\":{\"name\":\"Default Result\",\"value\":{\"enabled\":true,\"speed\":2}}}]},{\"name\":\"Accessibility.voiceGuidanceSettings\",\"summary\":\"Get the user's preferred voice guidance settings\",\"params\":[],\"tags\":[{\"name\":\"property:readonly\"},{\"name\":\"capabilities\",\"x-uses\":[\"xrn:firebolt:capability:accessibility:voiceguidance\"]}],\"result\":{\"name\":\"settings\",\"summary\":\"the voice guidance settings\",\"schema\":{\"$ref\":\"#/x-schemas/Accessibility/VoiceGuidanceSettings\"}},\"examples\":[{\"name\":\"Getting the voice guidance settings\",\"params\":[],\"result\":{\"name\":\"Default Result\",\"value\":{\"enabled\":true,\"speed\":2}}}]},{\"name\":\"Accessibility.audioDescriptionSettings\",\"summary\":\"Get the user's preferred audio description settings\",\"params\":[],\"tags\":[{\"name\":\"property:readonly\"},{\"name\":\"capabilities\",\"x-uses\":[\"xrn:firebolt:capability:accessibility:audiodescriptions\"]}],\"result\":{\"name\":\"settings\",\"summary\":\"the audio description settings\",\"schema\":{\"$ref\":\"#/components/schemas/AudioDescriptionSettings\"}},\"examples\":[{\"name\":\"Getting the audio description settings\",\"params\":[],\"result\":{\"name\":\"Default Result\",\"value\":{\"enabled\":true}}}]},{\"name\":\"Accessibility.onClosedCaptionsSettingsChanged\",\"summary\":\"Get the user's preferred closed-captions settings\",\"params\":[{\"name\":\"listen\",\"required\":true,\"schema\":{\"type\":\"boolean\"}}],\"tags\":[{\"name\":\"subscriber\",\"x-subscriber-for\":\"Accessibility.closedCaptionsSettings\"},{\"name\":\"event\",\"x-alternative\":\"closedCaptionsSettings\"},{\"name\":\"capabilities\",\"x-uses\":[\"xrn:firebolt:capability:accessibility:closedcaptions\"]}],\"result\":{\"name\":\"closedCaptionsSettings\",\"summary\":\"the closed captions settings\",\"schema\":{\"anyOf\":[{\"$ref\":\"#/x-schemas/Types/ListenResponse\"},{\"$ref\":\"#/x-schemas/Accessibility/ClosedCaptionsSettings\"}]}},\"examples\":[{\"name\":\"Getting the closed captions settings\",\"params\":[{\"name\":\"listen\",\"value\":true}],\"result\":{\"name\":\"settings\",\"value\":{\"enabled\":true,\"styles\":{\"fontFamily\":\"monospaced_sanserif\",\"fontSize\":1,\"fontColor\":\"#ffffff\",\"fontEdge\":\"none\",\"fontEdgeColor\":\"#7F7F7F\",\"fontOpacity\":100,\"backgroundColor\":\"#000000\",\"backgroundOpacity\":100,\"textAlign\":\"center\",\"textAlignVertical\":\"middle\",\"windowColor\":\"white\",\"windowOpacity\":50},\"preferredLanguages\":[\"eng\",\"spa\"]}}}]},{\"name\":\"Accessibility.onVoiceGuidanceSettingsChanged\",\"summary\":\"Get the user's preferred voice guidance settings\",\"params\":[{\"name\":\"listen\",\"required\":true,\"schema\":{\"type\":\"boolean\"}}],\"tags\":[{\"name\":\"subscriber\",\"x-subscriber-for\":\"Accessibility.voiceGuidanceSettings\"},{\"name\":\"event\",\"x-alternative\":\"voiceGuidanceSettings\"},{\"name\":\"capabilities\",\"x-uses\":[\"xrn:firebolt:capability:accessibility:voiceguidance\"]}],\"result\":{\"name\":\"settings\",\"summary\":\"the voice guidance settings\",\"schema\":{\"anyOf\":[{\"$ref\":\"#/x-schemas/Types/ListenResponse\"},{\"$ref\":\"#/x-schemas/Accessibility/VoiceGuidanceSettings\"}]}},\"examples\":[{\"name\":\"Getting the voice guidance settings\",\"params\":[{\"name\":\"listen\",\"value\":true}],\"result\":{\"name\":\"Default Result\",\"value\":{\"enabled\":true,\"speed\":2}}}]},{\"name\":\"Accessibility.onAudioDescriptionSettingsChanged\",\"summary\":\"Get the user's preferred audio description settings\",\"params\":[{\"name\":\"listen\",\"required\":true,\"schema\":{\"type\":\"boolean\"}}],\"tags\":[{\"name\":\"subscriber\",\"x-subscriber-for\":\"Accessibility.audioDescriptionSettings\"},{\"name\":\"event\",\"x-alternative\":\"audioDescriptionSettings\"},{\"name\":\"capabilities\",\"x-uses\":[\"xrn:firebolt:capability:accessibility:audiodescriptions\"]}],\"result\":{\"name\":\"settings\",\"summary\":\"the audio description settings\",\"schema\":{\"anyOf\":[{\"$ref\":\"#/x-schemas/Types/ListenResponse\"},{\"$ref\":\"#/components/schemas/AudioDescriptionSettings\"}]}},\"examples\":[{\"name\":\"Getting the audio description settings\",\"params\":[{\"name\":\"listen\",\"value\":true}],\"result\":{\"name\":\"Default Result\",\"value\":{\"enabled\":true}}}]},{\"name\":\"Account.id\",\"summary\":\"Get the platform back-office account identifier\",\"params\":[],\"tags\":[{\"name\":\"property:immutable\"},{\"name\":\"capabilities\",\"x-uses\":[\"xrn:firebolt:capability:account:id\"]}],\"result\":{\"name\":\"id\",\"summary\":\"the id\",\"schema\":{\"type\":\"string\"}},\"examples\":[{\"name\":\"Default Example\",\"params\":[],\"result\":{\"name\":\"Default Result\",\"value\":\"123\"}}]},{\"name\":\"Account.uid\",\"summary\":\"Gets a unique id for the current app & account\",\"params\":[],\"tags\":[{\"name\":\"property:immutable\"},{\"name\":\"capabilities\",\"x-uses\":[\"xrn:firebolt:capability:account:uid\"]}],\"result\":{\"name\":\"uniqueId\",\"summary\":\"a unique ID\",\"schema\":{\"type\":\"string\"}},\"examples\":[{\"name\":\"Getting the unique ID\",\"params\":[],\"result\":{\"name\":\"Default Result\",\"value\":\"ee6723b8-7ab3-462c-8d93-dbf61227998e\"}}]},{\"name\":\"Advertising.config\",\"summary\":\"Build configuration object for Ad Framework initialization\",\"tags\":[{\"name\":\"capabilities\",\"x-uses\":[\"xrn:firebolt:capability:advertising:configuration\"]}],\"params\":[{\"name\":\"options\",\"summary\":\"Configuration options\",\"required\":true,\"schema\":{\"$ref\":\"#/components/schemas/AdConfigurationOptions\"}}],\"result\":{\"name\":\"adFrameworkConfig\",\"summary\":\"the ad framework config\",\"schema\":{\"type\":\"object\",\"description\":\"An opaque object represneting the AdConfiguration\"}},\"examples\":[{\"name\":\"Initializing the Ad Framework\",\"params\":[{\"name\":\"options\",\"value\":{\"environment\":\"prod\",\"authenticationEntity\":\"MVPD\"}}],\"result\":{\"name\":\"Default Result\",\"value\":{\"adServerUrl\":\"https://demo.v.fwmrm.net/ad/p/1\",\"adServerUrlTemplate\":\"https://demo.v.fwmrm.net/ad/p/1?flag=+sltp+exvt+slcb+emcr+amcb+aeti&prof=12345:caf_allinone_profile &nw=12345&mode=live&vdur=123&caid=a110523018&asnw=372464&csid=gmott_ios_tablet_watch_live_ESPNU&ssnw=372464&vip=198.205.92.1&resp=vmap1&metr=1031&pvrn=12345&vprn=12345&vcid=1X0Ce7L3xRWlTeNhc7br8Q%3D%3D\",\"adNetworkId\":\"519178\",\"adProfileId\":\"12345:caf_allinone_profile\",\"adSiteSectionId\":\"caf_allinone_profile_section\",\"adOptOut\":true,\"privacyData\":\"ew0KICAicGR0IjogImdkcDp2MSIsDQogICJ1c19wcml2YWN5IjogIjEtTi0iLA0KICAibG10IjogIjEiIA0KfQ0K\",\"ifaValue\":\"01234567-89AB-CDEF-GH01-23456789ABCD\",\"ifa\":\"ewogICJ2YWx1ZSI6ICIwMTIzNDU2Ny04OUFCLUNERUYtR0gwMS0yMzQ1Njc4OUFCQ0QiLAogICJpZmFfdHlwZSI6ICJzc3BpZCIsCiAgImxtdCI6ICIwIgp9Cg==\",\"appName\":\"FutureToday\",\"appBundleId\":\"FutureToday.comcast\",\"distributorAppId\":\"1001\",\"deviceAdAttributes\":\"ewogICJib0F0dHJpYnV0ZXNGb3JSZXZTaGFyZUlkIjogIjEyMzQiCn0=\",\"coppa\":0,\"authenticationEntity\":\"60f72475281cfba3852413bd53e957f6\"}}}]},{\"name\":\"Advertising.policy\",\"summary\":\"Get the advertising privacy and playback policy\",\"params\":[],\"tags\":[{\"name\":\"property:readonly\"},{\"name\":\"capabilities\",\"x-uses\":[\"xrn:firebolt:capability:advertising:policy\"]}],\"result\":{\"name\":\"adPolicy\",\"summary\":\"the ad policy\",\"schema\":{\"$ref\":\"#/components/schemas/AdPolicy\"}},\"examples\":[{\"name\":\"Getting the advertising policy settings\",\"params\":[],\"result\":{\"name\":\"Default Result\",\"value\":{\"skipRestriction\":\"adsUnwatched\",\"limitAdTracking\":false}}}]},{\"name\":\"Advertising.advertisingId\",\"tags\":[{\"name\":\"capabilities\",\"x-uses\":[\"xrn:firebolt:capability:advertising:identifier\"]}],\"summary\":\"Get the IAB compliant identifier for advertising (IFA). It is recommended to use the IFA to manage advertising related activities while respecting the user's privacy settings.\",\"params\":[{\"name\":\"options\",\"summary\":\"AdvertisingId options\",\"required\":false,\"schema\":{\"$ref\":\"#/components/schemas/AdvertisingIdOptions\"}}],\"result\":{\"name\":\"advertisingId\",\"summary\":\"the advertising ID\",\"schema\":{\"$ref\":\"#/components/schemas/AdvertisingIdResult\"}},\"examples\":[{\"name\":\"Getting the advertising ID\",\"params\":[],\"result\":{\"name\":\"Default Result\",\"value\":{\"ifa\":\"01234567-89AB-CDEF-GH01-23456789ABCD\",\"ifa_type\":\"sspid\",\"lmt\":\"0\"}}},{\"name\":\"Getting the advertising ID with scope browse\",\"params\":[{\"name\":\"options\",\"value\":{\"scope\":{\"type\":\"browse\",\"id\":\"paidPlacement\"}}}],\"result\":{\"name\":\"Default Result\",\"value\":{\"ifa\":\"01234567-89AB-CDEF-GH01-23456789ABCD\",\"ifa_type\":\"sspid\",\"lmt\":\"0\"}}},{\"name\":\"Getting the advertising ID with scope content\",\"params\":[{\"name\":\"options\",\"value\":{\"scope\":{\"type\":\"content\",\"id\":\"metadata:linear:station:123\"}}}],\"result\":{\"name\":\"Default Result\",\"value\":{\"ifa\":\"01234567-89AB-CDEF-GH01-23456789ABCD\",\"ifa_type\":\"idfa\",\"lmt\":\"0\"}}}]},{\"name\":\"Advertising.deviceAttributes\",\"tags\":[{\"name\":\"capabilities\",\"x-uses\":[\"xrn:firebolt:capability:advertising:configuration\"]}],\"summary\":\"Get the device advertising device attributes\",\"params\":[],\"result\":{\"name\":\"deviceAttributes\",\"summary\":\"the device attributes\",\"schema\":{\"type\":\"object\"}},\"examples\":[{\"name\":\"Getting the device attributes\",\"params\":[],\"result\":{\"name\":\"Default Result\",\"value\":{}}}]},{\"name\":\"Advertising.appBundleId\",\"tags\":[{\"name\":\"capabilities\",\"x-uses\":[\"xrn:firebolt:capability:advertising:configuration\"]}],\"summary\":\"Get the App's Bundle ID\",\"params\":[],\"result\":{\"name\":\"appBundleId\",\"summary\":\"the app bundle ID\",\"schema\":{\"type\":\"string\"}},\"examples\":[{\"name\":\"Default Example\",\"params\":[],\"result\":{\"name\":\"Default Result\",\"value\":\"app.operator\"}}]},{\"name\":\"Advertising.onPolicyChanged\",\"summary\":\"Get the advertising privacy and playback policy\",\"params\":[{\"name\":\"listen\",\"required\":true,\"schema\":{\"type\":\"boolean\"}}],\"tags\":[{\"name\":\"subscriber\",\"x-subscriber-for\":\"Advertising.policy\"},{\"name\":\"event\",\"x-alternative\":\"policy\"},{\"name\":\"capabilities\",\"x-uses\":[\"xrn:firebolt:capability:advertising:policy\"]}],\"result\":{\"name\":\"adPolicy\",\"summary\":\"the ad policy\",\"schema\":{\"anyOf\":[{\"$ref\":\"#/x-schemas/Types/ListenResponse\"},{\"$ref\":\"#/components/schemas/AdPolicy\"}]}},\"examples\":[{\"name\":\"Getting the advertising policy settings\",\"params\":[{\"name\":\"listen\",\"value\":true}],\"result\":{\"name\":\"Default Result\",\"value\":{\"skipRestriction\":\"adsUnwatched\",\"limitAdTracking\":false}}}]},{\"name\":\"Authentication.token\",\"summary\":\"Get a specific `type` of authentication token\",\"tags\":[{\"name\":\"deprecated\",\"x-alternative\":\"Authentication module has individual methods for each token type.\",\"x-since\":\"0.9.0\"},{\"name\":\"capabilities\",\"x-uses\":[\"xrn:firebolt:capability:token:platform\"]}],\"params\":[{\"name\":\"type\",\"summary\":\"What type of token to get\",\"schema\":{\"$ref\":\"#/components/schemas/TokenType\"},\"required\":true},{\"name\":\"options\",\"summary\":\"Additional options for acquiring the token.\",\"schema\":{\"type\":\"object\"},\"required\":false}],\"result\":{\"name\":\"token\",\"summary\":\"the token value, type, and expiration\",\"schema\":{\"$ref\":\"#/components/schemas/AuthenticationTokenResult\"}},\"examples\":[{\"name\":\"Acquire a Firebolt platform token\",\"params\":[{\"name\":\"type\",\"value\":\"platform\"}],\"result\":{\"name\":\"token\",\"value\":{\"value\":\"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c\",\"expires\":\"2022-04-23T18:25:43.511Z\",\"type\":\"platform\"}}},{\"name\":\"Acquire a Firebolt device identity token\",\"params\":[{\"name\":\"type\",\"value\":\"device\"}],\"result\":{\"name\":\"token\",\"value\":{\"value\":\"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c\",\"expires\":\"2022-04-23T18:25:43.511Z\",\"type\":\"device\"}}},{\"name\":\"Acquire a Firebolt distributor token\",\"params\":[{\"name\":\"type\",\"value\":\"distributor\"},{\"name\":\"options\",\"value\":{\"clientId\":\"xyz\"}}],\"result\":{\"name\":\"token\",\"value\":{\"value\":\"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c\",\"expires\":\"2022-04-23T18:25:43.511Z\",\"type\":\"distributor\",\"data\":{\"tid\":\"EB00E9230AB2A35F57DB4EFDDC4908F6446D38F08F4FF0BD57FE6A61E21EEFD9\",\"scope\":\"scope\"}}}}]},{\"name\":\"Authentication.device\",\"summary\":\"Get a device token scoped to the current app.\",\"tags\":[{\"name\":\"capabilities\",\"x-uses\":[\"xrn:firebolt:capability:token:device\"]}],\"params\":[],\"result\":{\"name\":\"token\",\"summary\":\"the token value and expiration\",\"schema\":{\"type\":\"string\"}},\"examples\":[{\"name\":\"Acquire a Firebolt device identity token\",\"params\":[],\"result\":{\"name\":\"token\",\"value\":\"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c\"}}]},{\"name\":\"Authentication.session\",\"summary\":\"Get a destributor session token.\",\"tags\":[{\"name\":\"capabilities\",\"x-uses\":[\"xrn:firebolt:capability:token:session\"]}],\"params\":[],\"result\":{\"name\":\"token\",\"summary\":\"the token value\",\"schema\":{\"type\":\"string\"}},\"examples\":[{\"name\":\"Acquire a distributor session token\",\"params\":[],\"result\":{\"name\":\"token\",\"value\":\"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c\"}}]},{\"name\":\"Authentication.root\",\"summary\":\"Get a root device token.\",\"tags\":[{\"name\":\"capabilities\",\"x-uses\":[\"xrn:firebolt:capability:token:root\"]}],\"params\":[],\"result\":{\"name\":\"token\",\"summary\":\"the token value\",\"schema\":{\"type\":\"string\"}},\"examples\":[{\"name\":\"Acquire a Firebolt root device identity token\",\"params\":[],\"result\":{\"name\":\"token\",\"value\":\"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c\"}}]},{\"name\":\"Capabilities.supported\",\"summary\":\"Returns whether the platform supports the passed capability.\",\"tags\":[{\"name\":\"capabilities\",\"x-uses\":[\"xrn:firebolt:capability:capabilities:info\"]}],\"params\":[{\"name\":\"capability\",\"required\":true,\"schema\":{\"$ref\":\"#/x-schemas/Capabilities/Capability\"}}],\"result\":{\"name\":\"supported\",\"summary\":\"Whether or not capability is supported in device.\",\"schema\":{\"type\":\"boolean\"}},\"examples\":[{\"name\":\"Wifi scan supported capability\",\"params\":[{\"name\":\"capability\",\"value\":\"xrn:firebolt:capability:wifi:scan\"}],\"result\":{\"name\":\"Default Result\",\"value\":true}},{\"name\":\"BLE protocol unsupported capability\",\"params\":[{\"name\":\"capability\",\"value\":\"xrn:firebolt:capability:protocol:bluetoothle\"}],\"result\":{\"name\":\"Default Result\",\"value\":false}}]},{\"name\":\"Capabilities.available\",\"summary\":\"Returns whether a capability is available now.\",\"tags\":[{\"name\":\"capabilities\",\"x-uses\":[\"xrn:firebolt:capability:capabilities:info\"]}],\"params\":[{\"name\":\"capability\",\"required\":true,\"schema\":{\"$ref\":\"#/x-schemas/Capabilities/Capability\"}}],\"result\":{\"name\":\"available\",\"summary\":\"Whether or not capability is available now.\",\"schema\":{\"type\":\"boolean\"}},\"examples\":[{\"name\":\"Device Token.\",\"params\":[{\"name\":\"capability\",\"value\":\"xrn:firebolt:capability:token:device\"}],\"result\":{\"name\":\"Default Result\",\"value\":true}},{\"name\":\"Unavailable Platform token.\",\"params\":[{\"name\":\"capability\",\"value\":\"xrn:firebolt:capability:token:platform\"}],\"result\":{\"name\":\"Default Result\",\"value\":false}}]},{\"name\":\"Capabilities.permitted\",\"summary\":\"Returns whether the current App has permission to the passed capability and role.\",\"tags\":[{\"name\":\"capabilities\",\"x-uses\":[\"xrn:firebolt:capability:capabilities:info\"]}],\"params\":[{\"name\":\"capability\",\"required\":true,\"schema\":{\"$ref\":\"#/x-schemas/Capabilities/Capability\"}},{\"name\":\"options\",\"summary\":\"Capability options\",\"schema\":{\"$ref\":\"#/components/schemas/CapabilityOption\"}}],\"result\":{\"name\":\"permitted\",\"summary\":\"Whether or not app is permitted for the given capability and the role\",\"schema\":{\"type\":\"boolean\"}},\"examples\":[{\"name\":\"Keyboard\",\"params\":[{\"name\":\"capability\",\"value\":\"xrn:firebolt:capability:input:keyboard\"}],\"result\":{\"name\":\"Default Result\",\"value\":true}},{\"name\":\"Keyboard incorrect manage role capability\",\"params\":[{\"name\":\"capability\",\"value\":\"xrn:firebolt:capability:input:keyboard\"},{\"name\":\"options\",\"value\":{\"role\":\"manage\"}}],\"result\":{\"name\":\"Default Result\",\"value\":false}},{\"name\":\"Wifi scan not permitted capability\",\"params\":[{\"name\":\"capability\",\"value\":\"xrn:firebolt:capability:wifi:scan\"}],\"result\":{\"name\":\"Default Result\",\"value\":false}}]},{\"name\":\"Capabilities.granted\",\"summary\":\"Returns whether the current App has a user grant for passed capability and role.\",\"tags\":[{\"name\":\"capabilities\",\"x-uses\":[\"xrn:firebolt:capability:capabilities:info\"]}],\"params\":[{\"name\":\"capability\",\"required\":true,\"schema\":{\"$ref\":\"#/x-schemas/Capabilities/Capability\"}},{\"name\":\"options\",\"summary\":\"Capability options\",\"schema\":{\"$ref\":\"#/components/schemas/CapabilityOption\"}}],\"result\":{\"name\":\"granted\",\"summary\":\"Whether or not app is granted to use the given capability and the role\",\"schema\":{\"oneOf\":[{\"type\":\"boolean\"},{\"const\":null}]}},\"examples\":[{\"name\":\"Default capabilities without grants.\",\"params\":[{\"name\":\"capability\",\"value\":\"xrn:firebolt:capability:input:keyboard\"}],\"result\":{\"name\":\"Default Result\",\"value\":true}},{\"name\":\"Get Postal code without grants.\",\"params\":[{\"name\":\"capability\",\"value\":\"xrn:firebolt:capability:localization:postal-code\"}],\"result\":{\"name\":\"Default Result\",\"value\":false}},{\"name\":\"Get Postal code with grants.\",\"params\":[{\"name\":\"capability\",\"value\":\"xrn:firebolt:capability:localization:postal-code\"}],\"result\":{\"name\":\"Default Result\",\"value\":null}}]},{\"name\":\"Capabilities.info\",\"summary\":\"Returns an array of CapabilityInfo objects for the passed in capabilities.\",\"tags\":[{\"name\":\"capabilities\",\"x-uses\":[\"xrn:firebolt:capability:capabilities:info\"]}],\"params\":[{\"name\":\"capabilities\",\"required\":true,\"schema\":{\"type\":\"array\",\"items\":{\"$ref\":\"#/x-schemas/Capabilities/Capability\"},\"minItems\":1}}],\"result\":{\"name\":\"info\",\"summary\":\"Returns an array of CapabilityInfo objects for the passed in capabilities.\",\"schema\":{\"type\":\"array\",\"items\":{\"$ref\":\"#/x-schemas/Capabilities/CapabilityInfo\"},\"minItems\":1}},\"examples\":[{\"name\":\"Default result\",\"params\":[{\"name\":\"capabilities\",\"value\":[\"xrn:firebolt:capability:device:model\",\"xrn:firebolt:capability:input:keyboard\",\"xrn:firebolt:capability:protocol:bluetoothle\",\"xrn:firebolt:capability:token:device\",\"xrn:firebolt:capability:token:platform\",\"xrn:firebolt:capability:protocol:moca\",\"xrn:firebolt:capability:wifi:scan\",\"xrn:firebolt:capability:localization:postal-code\",\"xrn:firebolt:capability:localization:locality\"]}],\"result\":{\"name\":\"Default Result\",\"value\":[{\"capability\":\"xrn:firebolt:capability:device:model\",\"supported\":true,\"available\":true,\"use\":{\"permitted\":true,\"granted\":true},\"manage\":{\"permitted\":true,\"granted\":true},\"provide\":{\"permitted\":true,\"granted\":true}},{\"capability\":\"xrn:firebolt:capability:input:keyboard\",\"supported\":true,\"available\":true,\"use\":{\"permitted\":true,\"granted\":true},\"manage\":{\"permitted\":true,\"granted\":true},\"provide\":{\"permitted\":true,\"granted\":true}},{\"capability\":\"xrn:firebolt:capability:protocol:bluetoothle\",\"supported\":false,\"available\":false,\"use\":{\"permitted\":true,\"granted\":true},\"manage\":{\"permitted\":true,\"granted\":true},\"provide\":{\"permitted\":true,\"granted\":true},\"details\":[\"unsupported\"]},{\"capability\":\"xrn:firebolt:capability:token:device\",\"supported\":true,\"available\":true,\"use\":{\"permitted\":true,\"granted\":true},\"manage\":{\"permitted\":true,\"granted\":true},\"provide\":{\"permitted\":true,\"granted\":true}},{\"capability\":\"xrn:firebolt:capability:token:platform\",\"supported\":true,\"available\":false,\"use\":{\"permitted\":true,\"granted\":true},\"manage\":{\"permitted\":true,\"granted\":true},\"provide\":{\"permitted\":true,\"granted\":true},\"details\":[\"unavailable\"]},{\"capability\":\"xrn:firebolt:capability:protocol:moca\",\"supported\":true,\"available\":false,\"use\":{\"permitted\":true,\"granted\":true},\"manage\":{\"permitted\":true,\"granted\":true},\"provide\":{\"permitted\":true,\"granted\":true},\"details\":[\"disabled\",\"unavailable\"]},{\"capability\":\"xrn:firebolt:capability:wifi:scan\",\"supported\":true,\"available\":true,\"use\":{\"permitted\":true,\"granted\":true},\"manage\":{\"permitted\":true,\"granted\":true},\"provide\":{\"permitted\":true,\"granted\":true},\"details\":[\"unpermitted\"]},{\"capability\":\"xrn:firebolt:capability:localization:postal-code\",\"supported\":true,\"available\":true,\"use\":{\"permitted\":true,\"granted\":null},\"manage\":{\"permitted\":true,\"granted\":true},\"provide\":{\"permitted\":true,\"granted\":true},\"details\":[\"ungranted\"]},{\"capability\":\"xrn:firebolt:capability:localization:postal-code\",\"supported\":true,\"available\":true,\"use\":{\"permitted\":true,\"granted\":true},\"manage\":{\"permitted\":true,\"granted\":true},\"provide\":{\"permitted\":true,\"granted\":true},\"details\":[\"ungranted\"]},{\"capability\":\"xrn:firebolt:capability:localization:locality\",\"supported\":true,\"available\":true,\"use\":{\"permitted\":true,\"granted\":true},\"manage\":{\"permitted\":true,\"granted\":true},\"provide\":{\"permitted\":true,\"granted\":true},\"details\":[\"grantDenied\",\"ungranted\"]}]}}]},{\"name\":\"Capabilities.request\",\"summary\":\"Requests grants for all capability/role combinations in the roles array.\",\"tags\":[{\"name\":\"capabilities\",\"x-uses\":[\"xrn:firebolt:capability:capabilities:request\"]}],\"params\":[{\"name\":\"grants\",\"required\":true,\"schema\":{\"type\":\"array\",\"items\":{\"$ref\":\"#/x-schemas/Capabilities/Permission\"},\"minItems\":1}}],\"result\":{\"name\":\"request\",\"summary\":\"Returns an array of CapabilityInfo objects for the passed in capabilities.\",\"schema\":{\"type\":\"array\",\"items\":{\"$ref\":\"#/x-schemas/Capabilities/CapabilityInfo\"},\"minItems\":1}},\"examples\":[{\"name\":\"Default result\",\"params\":[{\"name\":\"grants\",\"value\":[{\"role\":\"use\",\"capability\":\"xrn:firebolt:capability:commerce:purchase\"}]}],\"result\":{\"name\":\"Default Result\",\"value\":[{\"capability\":\"xrn:firebolt:capability:commerce:purchase\",\"supported\":true,\"available\":true,\"use\":{\"permitted\":true,\"granted\":true},\"manage\":{\"permitted\":true,\"granted\":true},\"provide\":{\"permitted\":true,\"granted\":true}}]}}]},{\"name\":\"Capabilities.onAvailable\",\"tags\":[{\"name\":\"event\"},{\"name\":\"capabilities\",\"x-uses\":[\"xrn:firebolt:capability:capabilities:info\"]}],\"summary\":\"Listens for all App permitted capabilities to become available.\",\"params\":[{\"name\":\"capability\",\"required\":true,\"schema\":{\"$ref\":\"#/x-schemas/Capabilities/Capability\"}},{\"name\":\"listen\",\"required\":true,\"schema\":{\"type\":\"boolean\"}}],\"result\":{\"name\":\"value\",\"summary\":\"Provides the capability info.\",\"schema\":{\"anyOf\":[{\"$ref\":\"#/x-schemas/Types/ListenResponse\"},{\"$ref\":\"#/x-schemas/Capabilities/CapabilityInfo\"}]}},\"examples\":[{\"name\":\"Platform token is available\",\"params\":[{\"name\":\"capability\",\"value\":\"xrn:firebolt:capability:token:platform\"},{\"name\":\"listen\",\"value\":true}],\"result\":{\"name\":\"Default result\",\"value\":{\"capability\":\"xrn:firebolt:capability:token:platform\",\"supported\":true,\"available\":true,\"use\":{\"permitted\":true,\"granted\":true},\"manage\":{\"permitted\":true,\"granted\":true},\"provide\":{\"permitted\":true,\"granted\":true},\"details\":[\"unpermitted\"]}}}]},{\"name\":\"Capabilities.onUnavailable\",\"tags\":[{\"name\":\"event\"},{\"name\":\"capabilities\",\"x-uses\":[\"xrn:firebolt:capability:capabilities:info\"]}],\"summary\":\"Listens for all App permitted capabilities to become unavailable.\",\"params\":[{\"name\":\"capability\",\"required\":true,\"schema\":{\"$ref\":\"#/x-schemas/Capabilities/Capability\"}},{\"name\":\"listen\",\"required\":true,\"schema\":{\"type\":\"boolean\"}}],\"result\":{\"name\":\"value\",\"summary\":\"Provides the capability info.\",\"schema\":{\"anyOf\":[{\"$ref\":\"#/x-schemas/Types/ListenResponse\"},{\"$ref\":\"#/x-schemas/Capabilities/CapabilityInfo\"}]}},\"examples\":[{\"name\":\"Platform token is unavailable.\",\"params\":[{\"name\":\"capability\",\"value\":\"xrn:firebolt:capability:token:platform\"},{\"name\":\"listen\",\"value\":true}],\"result\":{\"name\":\"Default Result\",\"value\":{\"capability\":\"xrn:firebolt:capability:token:platform\",\"supported\":true,\"available\":false,\"use\":{\"permitted\":true,\"granted\":true},\"manage\":{\"permitted\":true,\"granted\":true},\"provide\":{\"permitted\":true,\"granted\":true},\"details\":[\"unavailable\"]}}}]},{\"name\":\"Capabilities.onGranted\",\"tags\":[{\"name\":\"event\"},{\"name\":\"capabilities\",\"x-uses\":[\"xrn:firebolt:capability:capabilities:info\"]}],\"summary\":\"Listens for all App permitted capabilities to become granted.\",\"params\":[{\"name\":\"role\",\"required\":true,\"schema\":{\"$ref\":\"#/x-schemas/Capabilities/Role\"}},{\"name\":\"capability\",\"required\":true,\"schema\":{\"$ref\":\"#/x-schemas/Capabilities/Capability\"}},{\"name\":\"listen\",\"required\":true,\"schema\":{\"type\":\"boolean\"}}],\"result\":{\"name\":\"value\",\"summary\":\"Provides the capability info.\",\"schema\":{\"anyOf\":[{\"$ref\":\"#/x-schemas/Types/ListenResponse\"},{\"$ref\":\"#/x-schemas/Capabilities/CapabilityInfo\"}]}},\"examples\":[{\"name\":\"Postal code granted\",\"params\":[{\"name\":\"role\",\"value\":\"use\"},{\"name\":\"capability\",\"value\":\"xrn:firebolt:capability:localization:postal-code\"},{\"name\":\"listen\",\"value\":true}],\"result\":{\"name\":\"Default Result\",\"value\":{\"capability\":\"xrn:firebolt:capability:localization:postal-code\",\"supported\":true,\"available\":true,\"use\":{\"permitted\":true,\"granted\":true},\"manage\":{\"permitted\":true,\"granted\":true},\"provide\":{\"permitted\":true,\"granted\":true}}}}]},{\"name\":\"Capabilities.onRevoked\",\"tags\":[{\"name\":\"event\"},{\"name\":\"capabilities\",\"x-uses\":[\"xrn:firebolt:capability:capabilities:info\"]}],\"summary\":\"Listens for all App permitted capabilities to become revoked.\",\"params\":[{\"name\":\"role\",\"required\":true,\"schema\":{\"$ref\":\"#/x-schemas/Capabilities/Role\"}},{\"name\":\"capability\",\"required\":true,\"schema\":{\"$ref\":\"#/x-schemas/Capabilities/Capability\"}},{\"name\":\"listen\",\"required\":true,\"schema\":{\"type\":\"boolean\"}}],\"result\":{\"name\":\"value\",\"summary\":\"Provides the capability info.\",\"schema\":{\"anyOf\":[{\"$ref\":\"#/x-schemas/Types/ListenResponse\"},{\"$ref\":\"#/x-schemas/Capabilities/CapabilityInfo\"}]}},\"examples\":[{\"name\":\"Postal code revoked\",\"params\":[{\"name\":\"role\",\"value\":\"use\"},{\"name\":\"capability\",\"value\":\"xrn:firebolt:capability:localization:postal-code\"},{\"name\":\"listen\",\"value\":true}],\"result\":{\"name\":\"Default Result\",\"value\":{\"capability\":\"xrn:firebolt:capability:localization:postal-code\",\"supported\":true,\"available\":true,\"use\":{\"permitted\":true,\"granted\":true},\"manage\":{\"permitted\":true,\"granted\":true},\"provide\":{\"permitted\":true,\"granted\":true},\"details\":[\"grantDenied\"]}}}]},{\"name\":\"Device.id\",\"summary\":\"Get the platform back-office device identifier\",\"params\":[],\"tags\":[{\"name\":\"property:immutable\"},{\"name\":\"capabilities\",\"x-uses\":[\"xrn:firebolt:capability:device:id\"]}],\"result\":{\"name\":\"id\",\"summary\":\"the id\",\"schema\":{\"type\":\"string\"}},\"examples\":[{\"name\":\"Default Example\",\"params\":[],\"result\":{\"name\":\"Default Result\",\"value\":\"123\"}}]},{\"name\":\"Device.distributor\",\"summary\":\"Get the name of the entity which is distributing the current device. There can be multiple distributors which distribute the same device model.\",\"params\":[],\"tags\":[{\"name\":\"property:immutable\"},{\"name\":\"capabilities\",\"x-uses\":[\"xrn:firebolt:capability:device:distributor\"]}],\"result\":{\"name\":\"distributorId\",\"summary\":\"the distributor ID\",\"schema\":{\"type\":\"string\"}},\"examples\":[{\"name\":\"Getting the distributor ID\",\"params\":[],\"result\":{\"name\":\"Default Result\",\"value\":\"Company\"}}]},{\"name\":\"Device.platform\",\"summary\":\"Get a platform identifier for the device. This API should be used to correlate metrics on the device only and cannot be guaranteed to have consistent responses across platforms.\",\"params\":[],\"tags\":[{\"name\":\"property:immutable\"},{\"name\":\"capabilities\",\"x-uses\":[\"xrn:firebolt:capability:device:info\"]}],\"result\":{\"name\":\"platformId\",\"summary\":\"the platform ID\",\"schema\":{\"type\":\"string\"}},\"examples\":[{\"name\":\"Getting the platform ID\",\"params\":[],\"result\":{\"name\":\"Default Result\",\"value\":\"WPE\"}}]},{\"name\":\"Device.uid\",\"summary\":\"Gets a unique id for the current app & device\",\"params\":[],\"tags\":[{\"name\":\"property:immutable\"},{\"name\":\"capabilities\",\"x-uses\":[\"xrn:firebolt:capability:device:uid\"]}],\"result\":{\"name\":\"uniqueId\",\"summary\":\"a unique ID\",\"schema\":{\"type\":\"string\"}},\"examples\":[{\"name\":\"Getting the unique ID\",\"params\":[],\"result\":{\"name\":\"Default Result\",\"value\":\"ee6723b8-7ab3-462c-8d93-dbf61227998e\"}}]},{\"name\":\"Device.type\",\"summary\":\"Get the device type\",\"params\":[],\"tags\":[{\"name\":\"property:immutable\"},{\"name\":\"capabilities\",\"x-uses\":[\"xrn:firebolt:capability:device:info\"]}],\"result\":{\"name\":\"deviceType\",\"summary\":\"the device type\",\"schema\":{\"type\":\"string\"}},\"examples\":[{\"name\":\"Getting the device type\",\"params\":[],\"result\":{\"name\":\"Default Result\",\"value\":\"STB\"}}]},{\"name\":\"Device.model\",\"summary\":\"Get the manufacturer designated model of the device\",\"params\":[],\"tags\":[{\"name\":\"property:immutable\"},{\"name\":\"capabilities\",\"x-uses\":[\"xrn:firebolt:capability:device:model\"]}],\"result\":{\"name\":\"model\",\"summary\":\"the device model\",\"schema\":{\"type\":\"string\"}},\"examples\":[{\"name\":\"Getting the device model\",\"params\":[],\"result\":{\"name\":\"Default Result\",\"value\":\"xi6\"}}]},{\"name\":\"Device.sku\",\"summary\":\"Get the device sku\",\"params\":[],\"tags\":[{\"name\":\"property:immutable\"},{\"name\":\"capabilities\",\"x-uses\":[\"xrn:firebolt:capability:device:sku\"]}],\"result\":{\"name\":\"sku\",\"summary\":\"the device sku\",\"schema\":{\"type\":\"string\"}},\"examples\":[{\"name\":\"Getting the device sku\",\"params\":[],\"result\":{\"name\":\"Default Result\",\"value\":\"AX061AEI\"}}]},{\"name\":\"Device.make\",\"summary\":\"Get the manufacturer of the device model\",\"params\":[],\"tags\":[{\"name\":\"property:immutable\"},{\"name\":\"capabilities\",\"x-uses\":[\"xrn:firebolt:capability:device:make\"]}],\"result\":{\"name\":\"make\",\"summary\":\"the device make\",\"schema\":{\"type\":\"string\"}},\"examples\":[{\"name\":\"Getting the device make\",\"params\":[],\"result\":{\"name\":\"Default Result\",\"value\":\"Arris\"}}]},{\"name\":\"Device.version\",\"summary\":\"Get the SDK, OS and other version info\",\"params\":[],\"tags\":[{\"name\":\"exclude-from-sdk\"},{\"name\":\"property:immutable\"},{\"name\":\"capabilities\",\"x-uses\":[\"xrn:firebolt:capability:device:info\"]}],\"result\":{\"name\":\"versions\",\"summary\":\"the versions\",\"schema\":{\"$ref\":\"#/components/schemas/DeviceVersion\"}},\"examples\":[{\"name\":\"Getting the os and sdk versions\",\"params\":[],\"result\":{\"name\":\"Default Result\",\"value\":{\"sdk\":{\"major\":0,\"minor\":8,\"patch\":0,\"readable\":\"Firebolt JS SDK v0.8.0\"},\"api\":{\"major\":0,\"minor\":8,\"patch\":0,\"readable\":\"Firebolt API v0.8.0\"},\"firmware\":{\"major\":1,\"minor\":2,\"patch\":3,\"readable\":\"Device Firmware v1.2.3\"},\"os\":{\"major\":0,\"minor\":1,\"patch\":0,\"readable\":\"Firebolt OS v0.1.0\"},\"debug\":\"Non-parsable build info for error logging only.\"}}}]},{\"name\":\"Device.hdcp\",\"summary\":\"Get the negotiated HDCP profiles for a connected device. \\n\\n For devices that do not require additional connections (e.g. panels), `true` will be returned for all profiles.\",\"params\":[],\"tags\":[{\"name\":\"property:readonly\"},{\"name\":\"capabilities\",\"x-uses\":[\"xrn:firebolt:capability:device:info\"]}],\"result\":{\"name\":\"negotiatedHdcpVersions\",\"summary\":\"the negotiated HDCP versions\",\"schema\":{\"$ref\":\"#/components/schemas/HDCPVersionMap\"}},\"examples\":[{\"name\":\"Getting the negotiated HDCP versions\",\"params\":[],\"result\":{\"name\":\"Default Result\",\"value\":{\"hdcp1.4\":true,\"hdcp2.2\":true}}}]},{\"name\":\"Device.hdr\",\"summary\":\"Get the negotiated HDR formats for the connected display and device\",\"params\":[],\"tags\":[{\"name\":\"property:readonly\"},{\"name\":\"capabilities\",\"x-uses\":[\"xrn:firebolt:capability:device:info\"]}],\"result\":{\"name\":\"negotiatedHdrFormats\",\"summary\":\"the negotiated HDR formats\",\"schema\":{\"$ref\":\"#/components/schemas/HDRFormatMap\"}},\"examples\":[{\"name\":\"Getting the negotiated HDR formats\",\"params\":[],\"result\":{\"name\":\"Default Result\",\"value\":{\"hdr10\":true,\"hdr10Plus\":true,\"dolbyVision\":true,\"hlg\":true}}}]},{\"name\":\"Device.audio\",\"summary\":\"Get the supported audio profiles for the connected devices. \\n\\n It is not recommended to use this API for visual badging on content within your app since this does not reflect the settings of the user.\",\"params\":[],\"tags\":[{\"name\":\"property:readonly\"},{\"name\":\"capabilities\",\"x-uses\":[\"xrn:firebolt:capability:device:info\"]}],\"result\":{\"name\":\"supportedAudioProfiles\",\"summary\":\"the supported audio profiles\",\"schema\":{\"$ref\":\"#/components/schemas/AudioProfiles\"}},\"examples\":[{\"name\":\"Getting the supported audio profiles\",\"params\":[],\"result\":{\"name\":\"Default Result\",\"value\":{\"stereo\":true,\"dolbyDigital5.1\":true,\"dolbyDigital5.1+\":true,\"dolbyAtmos\":true}}}]},{\"name\":\"Device.screenResolution\",\"summary\":\"Get the resolution for the graphical surface of the app. \\n\\nThe pairs returned will be of a [width, height] format and will correspond to the following values: \\n\\nNTSC Standard Definition (SD): [720, 480] \\n\\nPAL Standard Definition (SD): [720, 576] \\n\\nHigh Definition (HD): [1280, 720] \\n\\nFull HD (FHD): [1920, 1080]\\n\\n4K Ultra High Definition (UHD): [3840, 2160] \\n\\n**Deprecated:** Use non-Firebolt APIs specific to your platform, e.g. W3C APIs\",\"params\":[],\"tags\":[{\"name\":\"property:readonly\"},{\"name\":\"capabilities\",\"x-uses\":[\"xrn:firebolt:capability:device:info\"]},{\"name\":\"deprecated\",\"x-alternative\":\"Use non-Firebolt APIs specific to your platform, e.g. W3C APIs\",\"x-since\":\"1.4.0\"}],\"result\":{\"name\":\"screenResolution\",\"summary\":\"the resolution\",\"schema\":{\"$ref\":\"#/components/schemas/Resolution\"}},\"examples\":[{\"name\":\"Getting the screen resolution\",\"params\":[],\"result\":{\"name\":\"Default Result\",\"value\":[1920,1080]}}]},{\"name\":\"Device.videoResolution\",\"summary\":\"Get the maximum supported video resolution of the currently connected device and display. \\n\\nThe pairs returned will be of a [width, height] format and will correspond to the following values: \\n\\nNTSC Standard Definition (SD): [720, 480] \\n\\nPAL Standard Definition (SD): [720, 576] \\n\\nHigh Definition (HD): [1280, 720] \\n\\nFull HD (FHD): [1920, 1080]\\n\\n4K Ultra High Definition (UHD): [3840, 2160]\",\"params\":[],\"tags\":[{\"name\":\"property:readonly\"},{\"name\":\"capabilities\",\"x-uses\":[\"xrn:firebolt:capability:device:info\"]}],\"result\":{\"name\":\"videoResolution\",\"summary\":\"the resolution\",\"schema\":{\"$ref\":\"#/components/schemas/Resolution\"}},\"examples\":[{\"name\":\"Getting the video resolution\",\"params\":[],\"result\":{\"name\":\"Default Result\",\"value\":[1920,1080]}}]},{\"name\":\"Device.name\",\"summary\":\"The human readable name of the device\",\"params\":[],\"tags\":[{\"name\":\"property\"},{\"name\":\"capabilities\",\"x-uses\":[\"xrn:firebolt:capability:device:name\"]}],\"result\":{\"name\":\"value\",\"summary\":\"the device friendly-name\",\"schema\":{\"type\":\"string\"}},\"examples\":[{\"name\":\"Default example #1\",\"params\":[],\"result\":{\"name\":\"Default Result\",\"value\":\"Living Room\"}},{\"name\":\"Default example #2\",\"params\":[],\"result\":{\"name\":\"Default Result\",\"value\":\"Kitchen\"}}]},{\"name\":\"Device.onDeviceNameChanged\",\"tags\":[{\"name\":\"event\"},{\"name\":\"deprecated\",\"x-since\":\"0.6.0\",\"x-alternative\":\"Device.name()\"},{\"name\":\"capabilities\",\"x-uses\":[\"xrn:firebolt:capability:device:name\"]}],\"summary\":\"Get the human readable name of the device\",\"params\":[{\"name\":\"listen\",\"required\":true,\"schema\":{\"type\":\"boolean\"}}],\"result\":{\"name\":\"value\",\"summary\":\"the device friendly-name\",\"schema\":{\"anyOf\":[{\"$ref\":\"#/x-schemas/Types/ListenResponse\"},{\"type\":\"string\"}]}},\"examples\":[{\"name\":\"Getting the device name\",\"params\":[{\"name\":\"listen\",\"value\":true}],\"result\":{\"name\":\"Default Result\",\"value\":\"Living Room\"}}]},{\"name\":\"Device.network\",\"summary\":\"Get the current network status and type\",\"params\":[],\"tags\":[{\"name\":\"property:readonly\"},{\"name\":\"capabilities\",\"x-uses\":[\"xrn:firebolt:capability:network:status\"]}],\"result\":{\"name\":\"networkInfo\",\"summary\":\"the status and type\",\"schema\":{\"$ref\":\"#/components/schemas/NetworkInfoResult\"}},\"examples\":[{\"name\":\"Getting the network info\",\"params\":[],\"result\":{\"name\":\"Default Result\",\"value\":{\"state\":\"connected\",\"type\":\"wifi\"}}}]},{\"name\":\"Device.onNameChanged\",\"summary\":\"The human readable name of the device\",\"params\":[{\"name\":\"listen\",\"required\":true,\"schema\":{\"type\":\"boolean\"}}],\"tags\":[{\"name\":\"subscriber\",\"x-subscriber-for\":\"Device.name\"},{\"name\":\"event\",\"x-alternative\":\"name\"},{\"name\":\"capabilities\",\"x-uses\":[\"xrn:firebolt:capability:device:name\"]}],\"result\":{\"name\":\"value\",\"summary\":\"the device friendly-name\",\"schema\":{\"anyOf\":[{\"$ref\":\"#/x-schemas/Types/ListenResponse\"},{\"type\":\"string\"}]}},\"examples\":[{\"name\":\"Default example #1\",\"params\":[{\"name\":\"listen\",\"value\":true}],\"result\":{\"name\":\"Default Result\",\"value\":\"Living Room\"}},{\"name\":\"Default example #2\",\"params\":[{\"name\":\"listen\",\"value\":true}],\"result\":{\"name\":\"Default Result\",\"value\":\"Kitchen\"}}]},{\"name\":\"Device.onHdcpChanged\",\"summary\":\"Get the negotiated HDCP profiles for a connected device. \\n\\n For devices that do not require additional connections (e.g. panels), `true` will be returned for all profiles.\",\"params\":[{\"name\":\"listen\",\"required\":true,\"schema\":{\"type\":\"boolean\"}}],\"tags\":[{\"name\":\"subscriber\",\"x-subscriber-for\":\"Device.hdcp\"},{\"name\":\"event\",\"x-alternative\":\"hdcp\"},{\"name\":\"capabilities\",\"x-uses\":[\"xrn:firebolt:capability:device:info\"]}],\"result\":{\"name\":\"negotiatedHdcpVersions\",\"summary\":\"the negotiated HDCP versions\",\"schema\":{\"anyOf\":[{\"$ref\":\"#/x-schemas/Types/ListenResponse\"},{\"$ref\":\"#/components/schemas/HDCPVersionMap\"}]}},\"examples\":[{\"name\":\"Getting the negotiated HDCP versions\",\"params\":[{\"name\":\"listen\",\"value\":true}],\"result\":{\"name\":\"Default Result\",\"value\":{\"hdcp1.4\":true,\"hdcp2.2\":true}}}]},{\"name\":\"Device.onHdrChanged\",\"summary\":\"Get the negotiated HDR formats for the connected display and device\",\"params\":[{\"name\":\"listen\",\"required\":true,\"schema\":{\"type\":\"boolean\"}}],\"tags\":[{\"name\":\"subscriber\",\"x-subscriber-for\":\"Device.hdr\"},{\"name\":\"event\",\"x-alternative\":\"hdr\"},{\"name\":\"capabilities\",\"x-uses\":[\"xrn:firebolt:capability:device:info\"]}],\"result\":{\"name\":\"negotiatedHdrFormats\",\"summary\":\"the negotiated HDR formats\",\"schema\":{\"anyOf\":[{\"$ref\":\"#/x-schemas/Types/ListenResponse\"},{\"$ref\":\"#/components/schemas/HDRFormatMap\"}]}},\"examples\":[{\"name\":\"Getting the negotiated HDR formats\",\"params\":[{\"name\":\"listen\",\"value\":true}],\"result\":{\"name\":\"Default Result\",\"value\":{\"hdr10\":true,\"hdr10Plus\":true,\"dolbyVision\":true,\"hlg\":true}}}]},{\"name\":\"Device.onAudioChanged\",\"summary\":\"Get the supported audio profiles for the connected devices. \\n\\n It is not recommended to use this API for visual badging on content within your app since this does not reflect the settings of the user.\",\"params\":[{\"name\":\"listen\",\"required\":true,\"schema\":{\"type\":\"boolean\"}}],\"tags\":[{\"name\":\"subscriber\",\"x-subscriber-for\":\"Device.audio\"},{\"name\":\"event\",\"x-alternative\":\"audio\"},{\"name\":\"capabilities\",\"x-uses\":[\"xrn:firebolt:capability:device:info\"]}],\"result\":{\"name\":\"supportedAudioProfiles\",\"summary\":\"the supported audio profiles\",\"schema\":{\"anyOf\":[{\"$ref\":\"#/x-schemas/Types/ListenResponse\"},{\"$ref\":\"#/components/schemas/AudioProfiles\"}]}},\"examples\":[{\"name\":\"Getting the supported audio profiles\",\"params\":[{\"name\":\"listen\",\"value\":true}],\"result\":{\"name\":\"Default Result\",\"value\":{\"stereo\":true,\"dolbyDigital5.1\":true,\"dolbyDigital5.1+\":true,\"dolbyAtmos\":true}}}]},{\"name\":\"Device.onScreenResolutionChanged\",\"summary\":\"Get the resolution for the graphical surface of the app. \\n\\nThe pairs returned will be of a [width, height] format and will correspond to the following values: \\n\\nNTSC Standard Definition (SD): [720, 480] \\n\\nPAL Standard Definition (SD): [720, 576] \\n\\nHigh Definition (HD): [1280, 720] \\n\\nFull HD (FHD): [1920, 1080]\\n\\n4K Ultra High Definition (UHD): [3840, 2160] \\n\\n**Deprecated:** Use non-Firebolt APIs specific to your platform, e.g. W3C APIs\",\"params\":[{\"name\":\"listen\",\"required\":true,\"schema\":{\"type\":\"boolean\"}}],\"tags\":[{\"name\":\"subscriber\",\"x-subscriber-for\":\"Device.screenResolution\"},{\"name\":\"event\",\"x-alternative\":\"screenResolution\"},{\"name\":\"capabilities\",\"x-uses\":[\"xrn:firebolt:capability:device:info\"]},{\"name\":\"deprecated\",\"x-alternative\":\"Use non-Firebolt APIs specific to your platform, e.g. W3C APIs\",\"x-since\":\"1.4.0\"}],\"result\":{\"name\":\"screenResolution\",\"summary\":\"the resolution\",\"schema\":{\"anyOf\":[{\"$ref\":\"#/x-schemas/Types/ListenResponse\"},{\"$ref\":\"#/components/schemas/Resolution\"}]}},\"examples\":[{\"name\":\"Getting the screen resolution\",\"params\":[{\"name\":\"listen\",\"value\":true}],\"result\":{\"name\":\"Default Result\",\"value\":[1920,1080]}}]},{\"name\":\"Device.onVideoResolutionChanged\",\"summary\":\"Get the maximum supported video resolution of the currently connected device and display. \\n\\nThe pairs returned will be of a [width, height] format and will correspond to the following values: \\n\\nNTSC Standard Definition (SD): [720, 480] \\n\\nPAL Standard Definition (SD): [720, 576] \\n\\nHigh Definition (HD): [1280, 720] \\n\\nFull HD (FHD): [1920, 1080]\\n\\n4K Ultra High Definition (UHD): [3840, 2160]\",\"params\":[{\"name\":\"listen\",\"required\":true,\"schema\":{\"type\":\"boolean\"}}],\"tags\":[{\"name\":\"subscriber\",\"x-subscriber-for\":\"Device.videoResolution\"},{\"name\":\"event\",\"x-alternative\":\"videoResolution\"},{\"name\":\"capabilities\",\"x-uses\":[\"xrn:firebolt:capability:device:info\"]}],\"result\":{\"name\":\"videoResolution\",\"summary\":\"the resolution\",\"schema\":{\"anyOf\":[{\"$ref\":\"#/x-schemas/Types/ListenResponse\"},{\"$ref\":\"#/components/schemas/Resolution\"}]}},\"examples\":[{\"name\":\"Getting the video resolution\",\"params\":[{\"name\":\"listen\",\"value\":true}],\"result\":{\"name\":\"Default Result\",\"value\":[1920,1080]}}]},{\"name\":\"Device.onNetworkChanged\",\"summary\":\"Get the current network status and type\",\"params\":[{\"name\":\"listen\",\"required\":true,\"schema\":{\"type\":\"boolean\"}}],\"tags\":[{\"name\":\"subscriber\",\"x-subscriber-for\":\"Device.network\"},{\"name\":\"event\",\"x-alternative\":\"network\"},{\"name\":\"capabilities\",\"x-uses\":[\"xrn:firebolt:capability:network:status\"]}],\"result\":{\"name\":\"networkInfo\",\"summary\":\"the status and type\",\"schema\":{\"anyOf\":[{\"$ref\":\"#/x-schemas/Types/ListenResponse\"},{\"$ref\":\"#/components/schemas/NetworkInfoResult\"}]}},\"examples\":[{\"name\":\"Getting the network info\",\"params\":[{\"name\":\"listen\",\"value\":true}],\"result\":{\"name\":\"Default Result\",\"value\":{\"state\":\"connected\",\"type\":\"wifi\"}}}]},{\"name\":\"Discovery.policy\",\"summary\":\"get the discovery policy\",\"params\":[],\"tags\":[{\"name\":\"property:readonly\"},{\"name\":\"capabilities\",\"x-uses\":[\"xrn:firebolt:capability:discovery:policy\"]}],\"result\":{\"name\":\"policy\",\"summary\":\"discovery policy opt-in/outs\",\"schema\":{\"$ref\":\"#/components/schemas/DiscoveryPolicy\"}},\"examples\":[{\"name\":\"Getting the discovery policy\",\"params\":[],\"result\":{\"name\":\"Default Result\",\"value\":{\"enableRecommendations\":true,\"shareWatchHistory\":true,\"rememberWatchedPrograms\":true}}}]},{\"name\":\"Discovery.entityInfo\",\"tags\":[{\"name\":\"polymorphic-pull\"},{\"name\":\"capabilities\",\"x-provides\":\"xrn:firebolt:capability:discovery:entity-info\"},{\"name\":\"deprecated\"}],\"summary\":\"Provide information about a program entity and its available watchable assets, such as entitlement status and price, via either a push or pull call flow.\",\"description\":\"Provide information about a program entity and its available watchable assets, such as entitlement status and price, via either a push or pull call flow. Includes information about the program entity and its relevant associated entities, such as extras, previews, and, in the case of TV series, seasons and episodes.\\n\\nSee the `EntityInfo` and `WayToWatch` data structures below for more information.\\n\\nThe app only needs to implement Pull support for `entityInfo` at this time.\",\"params\":[{\"name\":\"correlationId\",\"required\":true,\"schema\":{\"type\":[\"string\",\"null\"]}},{\"name\":\"result\",\"required\":true,\"schema\":{\"$ref\":\"#/x-schemas/Discovery/EntityInfoResult\"},\"summary\":\"The entityInfo data.\"}],\"result\":{\"name\":\"success\",\"summary\":\"True if the push operation is successful\",\"schema\":{\"type\":\"boolean\"}},\"examples\":[{\"name\":\"Send entity info for a movie to the platform.\",\"params\":[{\"name\":\"correlationId\",\"value\":null},{\"name\":\"result\",\"value\":{\"expires\":\"2025-01-01T00:00:00.000Z\",\"entity\":{\"identifiers\":{\"entityId\":\"345\"},\"entityType\":\"program\",\"programType\":\"movie\",\"title\":\"Cool Runnings\",\"synopsis\":\"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Pulvinar sapien et ligula ullamcorper malesuada proin libero nunc.\",\"releaseDate\":\"1993-01-01T00:00:00.000Z\",\"contentRatings\":[{\"scheme\":\"US-Movie\",\"rating\":\"PG\"},{\"scheme\":\"CA-Movie\",\"rating\":\"G\"}],\"waysToWatch\":[{\"identifiers\":{\"assetId\":\"123\"},\"expires\":\"2025-01-01T00:00:00.000Z\",\"entitled\":true,\"entitledExpires\":\"2025-01-01T00:00:00.000Z\",\"offeringType\":\"buy\",\"price\":2.99,\"videoQuality\":[\"UHD\"],\"audioProfile\":[\"dolbyAtmos\"],\"audioLanguages\":[\"en\"],\"closedCaptions\":[\"en\"],\"subtitles\":[\"es\"],\"audioDescriptions\":[\"en\"]}]}}}],\"result\":{\"name\":\"success\",\"value\":true}},{\"name\":\"Send entity info for a movie with a trailer to the platform.\",\"params\":[{\"name\":\"correlationId\",\"value\":null},{\"name\":\"result\",\"value\":{\"expires\":\"2025-01-01T00:00:00.000Z\",\"entity\":{\"identifiers\":{\"entityId\":\"345\"},\"entityType\":\"program\",\"programType\":\"movie\",\"title\":\"Cool Runnings\",\"synopsis\":\"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Pulvinar sapien et ligula ullamcorper malesuada proin libero nunc.\",\"releaseDate\":\"1993-01-01T00:00:00.000Z\",\"contentRatings\":[{\"scheme\":\"US-Movie\",\"rating\":\"PG\"},{\"scheme\":\"CA-Movie\",\"rating\":\"G\"}],\"waysToWatch\":[{\"identifiers\":{\"assetId\":\"123\"},\"expires\":\"2025-01-01T00:00:00.000Z\",\"entitled\":true,\"entitledExpires\":\"2025-01-01T00:00:00.000Z\",\"offeringType\":\"buy\",\"price\":2.99,\"videoQuality\":[\"UHD\"],\"audioProfile\":[\"dolbyAtmos\"],\"audioLanguages\":[\"en\"],\"closedCaptions\":[\"en\"],\"subtitles\":[\"es\"],\"audioDescriptions\":[\"en\"]}]},\"related\":[{\"identifiers\":{\"entityId\":\"345\"},\"entityType\":\"program\",\"programType\":\"preview\",\"title\":\"Cool Runnings Trailer\",\"waysToWatch\":[{\"identifiers\":{\"assetId\":\"123111\",\"entityId\":\"345\"},\"entitled\":true,\"videoQuality\":[\"HD\"],\"audioProfile\":[\"dolbyAtmos\"],\"audioLanguages\":[\"en\"],\"closedCaptions\":[\"en\"]}]}]}}],\"result\":{\"name\":\"success\",\"value\":true}},{\"name\":\"Send entity info for a TV Series with seasons and episodes to the platform.\",\"params\":[{\"name\":\"correlationId\",\"value\":null},{\"name\":\"result\",\"value\":{\"expires\":\"2025-01-01T00:00:00.000Z\",\"entity\":{\"identifiers\":{\"entityId\":\"98765\"},\"entityType\":\"program\",\"programType\":\"series\",\"title\":\"Perfect Strangers\",\"synopsis\":\"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Pulvinar sapien et ligula ullamcorper malesuada proin libero nunc.\",\"releaseDate\":\"1986-01-01T00:00:00.000Z\",\"contentRatings\":[{\"scheme\":\"US-TV\",\"rating\":\"TV-PG\"}]},\"related\":[{\"identifiers\":{\"entityId\":\"111\",\"seriesId\":\"98765\"},\"entityType\":\"program\",\"programType\":\"season\",\"seasonNumber\":1,\"title\":\"Perfect Strangers Season 3\",\"contentRatings\":[{\"scheme\":\"US-TV\",\"rating\":\"TV-PG\"}],\"waysToWatch\":[{\"identifiers\":{\"assetId\":\"556\",\"entityId\":\"111\",\"seriesId\":\"98765\"},\"entitled\":true,\"offeringType\":\"free\",\"videoQuality\":[\"SD\"],\"audioProfile\":[\"stereo\"],\"audioLanguages\":[\"en\"],\"closedCaptions\":[\"en\"]}]},{\"identifiers\":{\"entityId\":\"111\",\"seriesId\":\"98765\"},\"entityType\":\"program\",\"programType\":\"episode\",\"seasonNumber\":1,\"episodeNumber\":1,\"title\":\"Knock Knock, Who's There?\",\"synopsis\":\"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Pulvinar sapien et ligula ullamcorper malesuada proin libero nunc.\",\"releaseDate\":\"1986-03-25T00:00:00.000Z\",\"contentRatings\":[{\"scheme\":\"US-TV\",\"rating\":\"TV-PG\"}],\"waysToWatch\":[{\"identifiers\":{\"assetId\":\"556\",\"entityId\":\"111\",\"seriesId\":\"98765\"},\"entitled\":true,\"offeringType\":\"free\",\"videoQuality\":[\"SD\"],\"audioProfile\":[\"stereo\"],\"audioLanguages\":[\"en\"],\"closedCaptions\":[\"en\"]}]},{\"identifiers\":{\"entityId\":\"112\",\"seriesId\":\"98765\"},\"entityType\":\"program\",\"programType\":\"episode\",\"seasonNumber\":1,\"episodeNumber\":2,\"title\":\"Picture This\",\"synopsis\":\"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Pulvinar sapien et ligula ullamcorper malesuada proin libero nunc.\",\"releaseDate\":\"1986-04-01T00:00:00.000Z\",\"contentRatings\":[{\"scheme\":\"US-TV\",\"rating\":\"TV-PG\"}],\"waysToWatch\":[{\"identifiers\":{\"assetId\":\"557\",\"entityId\":\"112\",\"seriesId\":\"98765\"},\"entitled\":true,\"offeringType\":\"free\",\"videoQuality\":[\"SD\"],\"audioProfile\":[\"stereo\"],\"audioLanguages\":[\"en\"],\"closedCaptions\":[\"en\"]}]}]}}],\"result\":{\"name\":\"result\",\"value\":true}}]},{\"name\":\"Discovery.purchasedContent\",\"tags\":[{\"name\":\"polymorphic-pull\"},{\"name\":\"capabilities\",\"x-provides\":\"xrn:firebolt:capability:discovery:purchased-content\"},{\"name\":\"deprecated\"}],\"summary\":\"Provide a list of purchased content for the authenticated account, such as rentals and electronic sell through purchases.\",\"params\":[{\"name\":\"correlationId\",\"required\":true,\"schema\":{\"type\":[\"string\",\"null\"]}},{\"name\":\"result\",\"required\":true,\"schema\":{\"$ref\":\"#/x-schemas/Discovery/PurchasedContentResult\"},\"summary\":\"The data for the purchasedContent\"}],\"result\":{\"name\":\"success\",\"summary\":\"True if the push operation is successful\",\"schema\":{\"type\":\"boolean\"}},\"examples\":[{\"name\":\"Inform the platform of the user's purchased content\",\"params\":[{\"name\":\"correlationId\",\"value\":null},{\"name\":\"result\",\"value\":{\"totalCount\":10,\"expires\":\"2025-01-01T00:00:00.000Z\",\"entries\":[{\"identifiers\":{\"entityId\":\"345\"},\"entityType\":\"program\",\"programType\":\"movie\",\"title\":\"Cool Runnings\",\"synopsis\":\"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Pulvinar sapien et ligula ullamcorper malesuada proin libero nunc.\",\"releaseDate\":\"1993-01-01T00:00:00.000Z\",\"contentRatings\":[{\"scheme\":\"US-Movie\",\"rating\":\"PG\"},{\"scheme\":\"CA-Movie\",\"rating\":\"G\"}],\"waysToWatch\":[{\"identifiers\":{\"assetId\":\"123\"},\"expires\":\"2025-01-01T00:00:00.000Z\",\"entitled\":true,\"entitledExpires\":\"2025-01-01T00:00:00.000Z\",\"offeringType\":\"buy\",\"price\":2.99,\"videoQuality\":[\"UHD\"],\"audioProfile\":[\"dolbyAtmos\"],\"audioLanguages\":[\"en\"],\"closedCaptions\":[\"en\"],\"subtitles\":[\"es\"],\"audioDescriptions\":[\"en\"]}]}]}}],\"result\":{\"name\":\"success\",\"value\":true}}],\"description\":\"Return content purchased by the user, such as rentals and electronic sell through purchases.\\n\\nThe app should return the user's 100 most recent purchases in `entries`. The total count of purchases must be provided in `count`. If `count` is greater than the total number of `entries`, the UI may provide a link into the app to see the complete purchase list.\\n\\nThe `EntityInfo` object returned is not required to have `waysToWatch` populated, but it is recommended that it do so in case the UI wants to surface additional information on the purchases screen.\\n\\nThe app should implement both Push and Pull methods for `purchasedContent`.\\n\\nThe app should actively push `purchasedContent` when:\\n\\n* The app becomes Active.\\n* When the state of the purchasedContent set has changed.\\n* The app goes into Inactive or Background state, if there is a chance a change event has been missed.\"},{\"name\":\"Discovery.watched\",\"summary\":\"Notify the platform that content was partially or completely watched\",\"tags\":[{\"name\":\"polymorphic-reducer\"},{\"name\":\"capabilities\",\"x-uses\":[\"xrn:firebolt:capability:discovery:watched\"]}],\"params\":[{\"name\":\"entityId\",\"required\":true,\"schema\":{\"type\":\"string\"},\"summary\":\"The entity Id of the watched content.\"},{\"name\":\"progress\",\"summary\":\"How much of the content has been watched (percentage as (0-0.999) for VOD, number of seconds for live)\",\"schema\":{\"type\":\"number\",\"minimum\":0}},{\"name\":\"completed\",\"summary\":\"Whether or not this viewing is considered \\\"complete,\\\" per the app's definition thereof\",\"schema\":{\"type\":\"boolean\"}},{\"name\":\"watchedOn\",\"summary\":\"Date/Time the content was watched, ISO 8601 Date/Time\",\"schema\":{\"type\":\"string\",\"format\":\"date-time\"}}],\"result\":{\"name\":\"success\",\"summary\":\"whether the call was successful or not\",\"schema\":{\"type\":\"boolean\"}},\"examples\":[{\"name\":\"Notifying the platform of watched content\",\"params\":[{\"name\":\"entityId\",\"value\":\"partner.com/entity/123\"},{\"name\":\"progress\",\"value\":0.95},{\"name\":\"completed\",\"value\":true},{\"name\":\"watchedOn\",\"value\":\"2021-04-23T18:25:43.511Z\"}],\"result\":{\"name\":\"success\",\"value\":true}}]},{\"name\":\"Discovery.watchNext\",\"summary\":\"Suggest a call-to-action for this app on the platform home screen\",\"tags\":[{\"name\":\"capabilities\",\"x-uses\":[\"xrn:firebolt:capability:discovery:watch-next\"]}],\"params\":[{\"name\":\"title\",\"summary\":\"The title of this call to action\",\"schema\":{\"$ref\":\"#/x-schemas/Types/LocalizedString\"},\"required\":true},{\"name\":\"identifiers\",\"summary\":\"A set of content identifiers for this call to action\",\"schema\":{\"$ref\":\"#/x-schemas/Entertainment/ContentIdentifiers\"},\"required\":true},{\"name\":\"expires\",\"summary\":\"When this call to action should no longer be presented to users\",\"schema\":{\"type\":\"string\",\"format\":\"date-time\"}},{\"name\":\"images\",\"summary\":\"A set of images for this call to action\",\"schema\":{\"type\":\"object\",\"patternProperties\":{\"^.*$\":{\"$ref\":\"#/x-schemas/Types/LocalizedString\"}}}}],\"result\":{\"name\":\"success\",\"summary\":\"whether the call was successful or not\",\"schema\":{\"type\":\"boolean\"}},\"examples\":[{\"name\":\"Suggest a watch-next tile for the home screen\",\"params\":[{\"name\":\"title\",\"value\":\"A Cool Show\"},{\"name\":\"identifiers\",\"value\":{\"entityId\":\"partner.com/entity/123\"}},{\"name\":\"expires\",\"value\":\"2021-04-23T18:25:43.511Z\"},{\"name\":\"images\",\"value\":{\"3x4\":{\"en-US\":\"https://i.ytimg.com/vi/4r7wHMg5Yjg/maxresdefault.jpg\",\"es\":\"https://i.ytimg.com/vi/4r7wHMg5Yjg/maxresdefault.jpg\"},\"16x9\":{\"en\":\"https://i.ytimg.com/vi/4r7wHMg5Yjg/maxresdefault.jpg\"}}}],\"result\":{\"name\":\"success\",\"value\":true}},{\"name\":\"Suggest a watch-next tile for the home screen\",\"params\":[{\"name\":\"title\",\"value\":\"A Fantastic Show\"},{\"name\":\"identifiers\",\"value\":{\"entityId\":\"partner.com/entity/456\"}}],\"result\":{\"name\":\"success\",\"value\":true}}]},{\"name\":\"Discovery.entitlements\",\"tags\":[{\"name\":\"capabilities\",\"x-uses\":[\"xrn:firebolt:capability:discovery:content-access\"]},{\"name\":\"deprecated\",\"x-since\":\"0.10.0\",\"x-alternative\":\"Discovery.contentAccess()\"}],\"summary\":\"Inform the platform of the users latest entitlements w/in this app.\",\"params\":[{\"name\":\"entitlements\",\"summary\":\"Array of entitlement objects\",\"schema\":{\"type\":\"array\",\"items\":{\"$ref\":\"#/x-schemas/Entertainment/Entitlement\"}},\"required\":true}],\"result\":{\"name\":\"success\",\"summary\":\"whether the call was successful or not\",\"schema\":{\"type\":\"boolean\"}},\"examples\":[{\"name\":\"Update user's entitlements\",\"params\":[{\"name\":\"entitlements\",\"value\":[{\"entitlementId\":\"partner.com/entitlement/123\",\"startTime\":\"2021-04-23T18:25:43.511Z\",\"endTime\":\"2021-04-23T18:25:43.511Z\"},{\"entitlementId\":\"partner.com/entitlement/456\",\"startTime\":\"2021-04-23T18:25:43.511Z\",\"endTime\":\"2021-04-23T18:25:43.511Z\"}]}],\"result\":{\"name\":\"success\",\"value\":true}}]},{\"name\":\"Discovery.contentAccess\",\"summary\":\"Inform the platform of what content the user can access either by discovering it or consuming it. Availabilities determine which content is discoverable to a user, while entitlements determine if the user can currently consume that content. Content can be available but not entitled, this means that user can see the content but when they try to open it they must gain an entitlement either through purchase or subscription upgrade. In case the access changed off-device, this API should be called any time the app comes to the foreground to refresh the access. This API should also be called any time the availabilities or entitlements change within the app for any reason. Typical reasons may include the user signing into an account or upgrading a subscription. Less common cases can cause availabilities to change, such as moving to a new service location. When availabilities or entitlements are removed from the subscriber (such as when the user signs out), then an empty array should be given. To clear both, use the Discovery.clearContentAccess convenience API.\",\"tags\":[{\"name\":\"capabilities\",\"x-uses\":[\"xrn:firebolt:capability:discovery:content-access\"]}],\"params\":[{\"name\":\"ids\",\"summary\":\"A list of identifiers that represent content that is discoverable or consumable for the subscriber\",\"schema\":{\"$ref\":\"#/components/schemas/ContentAccessIdentifiers\"},\"required\":true}],\"result\":{\"name\":\"result\",\"schema\":{\"const\":null}},\"examples\":[{\"name\":\"Update subscriber's availabilities\",\"params\":[{\"name\":\"ids\",\"value\":{\"availabilities\":[{\"type\":\"channel-lineup\",\"id\":\"partner.com/availability/123\",\"startTime\":\"2021-04-23T18:25:43.511Z\",\"endTime\":\"2021-04-23T18:25:43.511Z\"},{\"type\":\"channel-lineup\",\"id\":\"partner.com/availability/456\",\"startTime\":\"2021-04-23T18:25:43.511Z\",\"endTime\":\"2021-04-23T18:25:43.511Z\"}]}}],\"result\":{\"name\":\"result\",\"value\":null}},{\"name\":\"Update subscriber's availabilities and entitlements\",\"params\":[{\"name\":\"ids\",\"value\":{\"availabilities\":[{\"type\":\"channel-lineup\",\"id\":\"partner.com/availability/123\",\"startTime\":\"2021-04-23T18:25:43.511Z\",\"endTime\":\"2021-04-23T18:25:43.511Z\"},{\"type\":\"channel-lineup\",\"id\":\"partner.com/availability/456\",\"startTime\":\"2021-04-23T18:25:43.511Z\",\"endTime\":\"2021-04-23T18:25:43.511Z\"}],\"entitlements\":[{\"entitlementId\":\"123\",\"startTime\":\"2025-01-01T00:00:00.000Z\",\"endTime\":\"2025-01-01T00:00:00.000Z\"}]}}],\"result\":{\"name\":\"result\",\"value\":null}},{\"name\":\"Update subscriber's entitlements\",\"params\":[{\"name\":\"ids\",\"value\":{\"entitlements\":[{\"entitlementId\":\"123\",\"startTime\":\"2025-01-01T00:00:00.000Z\",\"endTime\":\"2025-01-01T00:00:00.000Z\"}]}}],\"result\":{\"name\":\"result\",\"value\":null}},{\"name\":\"Clear a subscriber's entitlements\",\"params\":[{\"name\":\"ids\",\"value\":{\"entitlements\":[]}}],\"result\":{\"name\":\"result\",\"value\":null}},{\"name\":\"Clear a subscriber's availabilities\",\"params\":[{\"name\":\"ids\",\"value\":{\"availabilities\":[]}}],\"result\":{\"name\":\"result\",\"value\":null}}]},{\"name\":\"Discovery.clearContentAccess\",\"summary\":\"Clear both availabilities and entitlements from the subscriber. This is equivalent of calling `Discovery.contentAccess({ availabilities: [], entitlements: []})`. This is typically called when the user signs out of an account.\",\"tags\":[{\"name\":\"capabilities\",\"x-uses\":[\"xrn:firebolt:capability:discovery:content-access\"]}],\"params\":[],\"result\":{\"name\":\"result\",\"schema\":{\"const\":null}},\"examples\":[{\"name\":\"Clear subscriber's availabilities and entitlements\",\"params\":[],\"result\":{\"name\":\"result\",\"value\":null}}]},{\"name\":\"Discovery.launch\",\"tags\":[{\"name\":\"capabilities\",\"x-uses\":[\"xrn:firebolt:capability:lifecycle:launch\"]}],\"summary\":\"Launch or foreground the specified app, and optionally instructs it to navigate to the specified user action. \\n For the Primary Experience, the appId can be any one of: \\n\\n - xrn:firebolt:application-type:main \\n\\n - xrn:firebolt:application-type:settings\",\"params\":[{\"name\":\"appId\",\"required\":true,\"summary\":\"The durable app Id of the app to launch\",\"schema\":{\"type\":\"string\"}},{\"name\":\"intent\",\"required\":false,\"summary\":\"An optional `NavigationIntent` with details about what part of the app to show first, and context around how/why it was launched\",\"schema\":{\"$ref\":\"#/x-schemas/Intents/NavigationIntent\"}}],\"result\":{\"name\":\"success\",\"summary\":\"whether the call was successful or not\",\"schema\":{\"type\":\"boolean\"}},\"examples\":[{\"name\":\"Launch the 'Foo' app to it's home screen.\",\"params\":[{\"name\":\"appId\",\"value\":\"foo\"},{\"name\":\"intent\",\"value\":{\"action\":\"home\",\"context\":{\"source\":\"voice\"}}}],\"result\":{\"name\":\"success\",\"value\":true}},{\"name\":\"Launch the 'Foo' app to it's own page for a specific entity.\",\"params\":[{\"name\":\"appId\",\"value\":\"foo\"},{\"name\":\"intent\",\"value\":{\"action\":\"entity\",\"data\":{\"entityType\":\"program\",\"programType\":\"movie\",\"entityId\":\"example-movie-id\"},\"context\":{\"source\":\"voice\"}}}],\"result\":{\"name\":\"success\",\"value\":true}},{\"name\":\"Launch the 'Foo' app to a fullscreen playback experience for a specific entity.\",\"params\":[{\"name\":\"appId\",\"value\":\"foo\"},{\"name\":\"intent\",\"value\":{\"action\":\"playback\",\"data\":{\"entityType\":\"program\",\"programType\":\"movie\",\"entityId\":\"example-movie-id\"},\"context\":{\"source\":\"voice\"}}}],\"result\":{\"name\":\"success\",\"value\":true}},{\"name\":\"Launch the Aggregated Experience to a global page for a specific entity.\",\"params\":[{\"name\":\"appId\",\"value\":\"xrn:firebolt:application-type:main\"},{\"name\":\"intent\",\"value\":{\"action\":\"entity\",\"data\":{\"entityType\":\"program\",\"programType\":\"movie\",\"entityId\":\"example-movie-id\"},\"context\":{\"source\":\"voice\"}}}],\"result\":{\"name\":\"success\",\"value\":true}},{\"name\":\"Launch the Aggregated Experience to a global page for the company / partner with the ID 'foo'.\",\"params\":[{\"name\":\"appId\",\"value\":\"xrn:firebolt:application-type:main\"},{\"name\":\"intent\",\"value\":{\"action\":\"section\",\"data\":{\"sectionName\":\"company:foo\"},\"context\":{\"source\":\"voice\"}}}],\"result\":{\"name\":\"success\",\"value\":true}},{\"name\":\"Launch the Aggregated Experience to it's home screen, as if the Home remote button was pressed.\",\"params\":[{\"name\":\"appId\",\"value\":\"xrn:firebolt:application-type:main\"},{\"name\":\"intent\",\"value\":{\"action\":\"home\",\"context\":{\"source\":\"voice\"}}}],\"result\":{\"name\":\"success\",\"value\":true}},{\"name\":\"Launch the Aggregated Experience to it's search screen.\",\"params\":[{\"name\":\"appId\",\"value\":\"xrn:firebolt:application-type:main\"},{\"name\":\"intent\",\"value\":{\"action\":\"search\",\"context\":{\"source\":\"voice\"}}}],\"result\":{\"name\":\"success\",\"value\":true}},{\"name\":\"Launch the Aggregated Experience to it's settings screen.\",\"params\":[{\"name\":\"appId\",\"value\":\"xrn:firebolt:application-type:settings\"},{\"name\":\"intent\",\"value\":{\"action\":\"section\",\"data\":{\"sectionName\":\"settings\"},\"context\":{\"source\":\"voice\"}}}],\"result\":{\"name\":\"success\",\"value\":true}},{\"name\":\"Launch the Aggregated Experience to it's linear/epg guide.\",\"params\":[{\"name\":\"appId\",\"value\":\"xrn:firebolt:application-type:main\"},{\"name\":\"intent\",\"value\":{\"action\":\"section\",\"data\":{\"sectionName\":\"guide\"},\"context\":{\"source\":\"voice\"}}}],\"result\":{\"name\":\"success\",\"value\":true}},{\"name\":\"Launch the Aggregated Experience to the App Store details page for a specific app with the ID 'foo'.\",\"params\":[{\"name\":\"appId\",\"value\":\"xrn:firebolt:application-type:main \"},{\"name\":\"intent\",\"value\":{\"action\":\"section\",\"data\":{\"sectionName\":\"app:foo\"},\"context\":{\"source\":\"voice\"}}}],\"result\":{\"name\":\"success\",\"value\":true}}]},{\"name\":\"Discovery.onNavigateTo\",\"tags\":[{\"name\":\"event\"},{\"name\":\"capabilities\",\"x-uses\":[\"xrn:firebolt:capability:discovery:navigate-to\"]}],\"summary\":\"listen to `navigateTo` events\",\"params\":[{\"name\":\"listen\",\"required\":true,\"schema\":{\"type\":\"boolean\"}}],\"result\":{\"name\":\"value\",\"summary\":\"An object describing where in the app the user intends to navigate to\",\"schema\":{\"anyOf\":[{\"$ref\":\"#/x-schemas/Types/ListenResponse\"},{\"$ref\":\"#/x-schemas/Intents/NavigationIntent\"}]}},\"examples\":[{\"name\":\"Listening for `navigateTo` events\",\"params\":[{\"name\":\"listen\",\"value\":true}],\"result\":{\"name\":\"event\",\"value\":{\"action\":\"search\",\"data\":{\"query\":\"a cool show\"},\"context\":{\"campaign\":\"unknown\",\"source\":\"voice\"}}}}]},{\"name\":\"Discovery.signIn\",\"tags\":[{\"name\":\"calls-metrics\"},{\"name\":\"capabilities\",\"x-uses\":[\"xrn:firebolt:capability:discovery:sign-in-status\"]}],\"summary\":\"Inform the platform that your user is signed in, for increased visibility in search & discovery. Sign-in state is used separately from what content can be access through entitlements and availabilities. Sign-in state may be used when deciding whether to choose this app to handle a user intent. For instance, if the user tries to launch something generic like playing music from an artist, only a signed-in app will be chosen. If the user wants to tune to a channel, only a signed-in app will be chosen to handle that intent. While signIn can optionally include entitlements as those typically change at signIn time, it is recommended to make a separate call to Discovery.contentAccess for entitlements. signIn is not only for when a user explicitly enters login credentials. If an app does not require any credentials from the user to consume content, such as in a free app, then the app should call signIn immediately on launch.\",\"params\":[{\"name\":\"entitlements\",\"summary\":\"Optional array of Entitlements, in case of a different user account, or a long time since last sign-in.\",\"schema\":{\"type\":\"array\",\"items\":{\"$ref\":\"#/x-schemas/Entertainment/Entitlement\"}},\"required\":false}],\"result\":{\"name\":\"success\",\"schema\":{\"type\":\"boolean\"}},\"examples\":[{\"name\":\"Send signIn metric\",\"params\":[],\"result\":{\"name\":\"success\",\"value\":true}},{\"name\":\"Send signIn notification with entitlements\",\"params\":[{\"name\":\"entitlements\",\"value\":[{\"entitlementId\":\"123\",\"startTime\":\"2025-01-01T00:00:00.000Z\",\"endTime\":\"2025-01-01T00:00:00.000Z\"}]}],\"result\":{\"name\":\"success\",\"value\":true}}]},{\"name\":\"Discovery.signOut\",\"tags\":[{\"name\":\"calls-metrics\"},{\"name\":\"capabilities\",\"x-uses\":[\"xrn:firebolt:capability:discovery:sign-in-status\"]}],\"summary\":\"Inform the platform that your user has signed out. See `Discovery.signIn` for more details on how the sign-in state is used.signOut will NOT clear entitlements, the app should make a separate call to Discovery.clearContentAccess. Apps should also call signOut when a login token has expired and the user is now in a signed-out state.\",\"params\":[],\"result\":{\"name\":\"success\",\"schema\":{\"type\":\"boolean\"}},\"examples\":[{\"name\":\"Send signOut notification\",\"params\":[],\"result\":{\"name\":\"success\",\"value\":true}}]},{\"name\":\"Discovery.userInterest\",\"summary\":\"Send an entity that the user has expressed interest in to the platform.\",\"tags\":[{\"name\":\"capabilities\",\"x-provides\":\"xrn:firebolt:capability:discovery:interest\"}],\"params\":[{\"name\":\"type\",\"required\":true,\"schema\":{\"$ref\":\"#/x-schemas/Discovery/InterestType\"}},{\"name\":\"reason\",\"required\":true,\"schema\":{\"$ref\":\"#/x-schemas/Discovery/InterestReason\"}},{\"name\":\"entity\",\"required\":true,\"schema\":{\"$ref\":\"#/x-schemas/Entity/EntityDetails\"}}],\"result\":{\"name\":\"result\",\"schema\":{\"type\":\"null\"}},\"examples\":[{\"name\":\"Default Example\",\"params\":[{\"name\":\"type\",\"value\":\"interest\"},{\"name\":\"reason\",\"value\":\"playlist\"},{\"name\":\"entity\",\"value\":{\"identifiers\":{\"entityId\":\"345\",\"entityType\":\"program\",\"programType\":\"movie\"},\"info\":{}}}],\"result\":{\"name\":\"result\",\"value\":null}}]},{\"name\":\"Discovery.onRequestUserInterest\",\"tags\":[{\"name\":\"rpc-only\"},{\"name\":\"event\",\"x-response-name\":\"entity\",\"x-response\":{\"$ref\":\"#/x-schemas/Entity/EntityDetails\",\"examples\":[{\"identifiers\":{\"entityId\":\"345\",\"entityType\":\"program\",\"programType\":\"movie\"},\"info\":{\"title\":\"Cool Runnings\",\"synopsis\":\"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Pulvinar sapien et ligula ullamcorper malesuada proin libero nunc.\",\"releaseDate\":\"1993-01-01T00:00:00.000Z\",\"contentRatings\":[{\"scheme\":\"US-Movie\",\"rating\":\"PG\"},{\"scheme\":\"CA-Movie\",\"rating\":\"G\"}]}}]},\"x-error\":{\"type\":\"object\",\"additionalProperties\":false,\"required\":[\"code\",\"message\"],\"properties\":{\"code\":{\"title\":\"errorObjectCode\",\"description\":\"A Number that indicates the error type that occurred. This MUST be an integer. The error codes from and including -32768 to -32000 are reserved for pre-defined errors. These pre-defined errors SHOULD be assumed to be returned from any JSON-RPC api.\",\"type\":\"integer\"},\"message\":{\"title\":\"errorObjectMessage\",\"description\":\"A String providing a short description of the error. The message SHOULD be limited to a concise single sentence.\",\"type\":\"string\"},\"data\":{\"title\":\"errorObjectData\",\"description\":\"A Primitive or Structured value that contains additional information about the error. This may be omitted. The value of this member is defined by the Server (e.g. detailed error information, nested errors etc.).\"}}}},{\"name\":\"capabilities\",\"x-provides\":\"xrn:firebolt:capability:discovery:interest\"}],\"summary\":\"Provide information about the entity currently displayed or selected on the screen.\",\"description\":\"Provide information about the entity currently displayed or selected on the screen.\",\"params\":[{\"name\":\"listen\",\"required\":true,\"schema\":{\"type\":\"boolean\"}}],\"result\":{\"name\":\"request\",\"schema\":{\"anyOf\":[{\"$ref\":\"#/x-schemas/Types/ListenResponse\"},{\"type\":\"object\",\"required\":[\"correlationId\",\"parameters\"],\"properties\":{\"correlationId\":{\"type\":\"string\"},\"parameters\":{\"$ref\":\"#/components/schemas/UserInterestProviderParameters\"}},\"additionalProperties\":false}]}},\"examples\":[{\"name\":\"Default Example\",\"params\":[{\"name\":\"listen\",\"value\":true}],\"result\":{\"name\":\"request\",\"value\":{\"correlationId\":\"xyz\",\"parameters\":{\"type\":\"interest\",\"reason\":\"playlist\"}}}}]},{\"name\":\"Discovery.onPolicyChanged\",\"summary\":\"get the discovery policy\",\"params\":[{\"name\":\"listen\",\"required\":true,\"schema\":{\"type\":\"boolean\"}}],\"tags\":[{\"name\":\"subscriber\",\"x-subscriber-for\":\"Discovery.policy\"},{\"name\":\"event\",\"x-alternative\":\"policy\"},{\"name\":\"capabilities\",\"x-uses\":[\"xrn:firebolt:capability:discovery:policy\"]}],\"result\":{\"name\":\"policy\",\"summary\":\"discovery policy opt-in/outs\",\"schema\":{\"anyOf\":[{\"$ref\":\"#/x-schemas/Types/ListenResponse\"},{\"$ref\":\"#/components/schemas/DiscoveryPolicy\"}]}},\"examples\":[{\"name\":\"Getting the discovery policy\",\"params\":[{\"name\":\"listen\",\"value\":true}],\"result\":{\"name\":\"Default Result\",\"value\":{\"enableRecommendations\":true,\"shareWatchHistory\":true,\"rememberWatchedPrograms\":true}}}]},{\"name\":\"Discovery.onPullEntityInfo\",\"tags\":[{\"name\":\"polymorphic-pull-event\"},{\"name\":\"event\",\"x-pulls-for\":\"entityInfo\"},{\"name\":\"capabilities\",\"x-provides\":\"xrn:firebolt:capability:discovery:entity-info\"},{\"name\":\"deprecated\"}],\"summary\":\"Provide information about a program entity and its available watchable assets, such as entitlement status and price, via either a push or pull call flow.\",\"description\":\"Provide information about a program entity and its available watchable assets, such as entitlement status and price, via either a push or pull call flow. Includes information about the program entity and its relevant associated entities, such as extras, previews, and, in the case of TV series, seasons and episodes.\\n\\nSee the `EntityInfo` and `WayToWatch` data structures below for more information.\\n\\nThe app only needs to implement Pull support for `entityInfo` at this time.\",\"params\":[{\"name\":\"listen\",\"required\":true,\"schema\":{\"type\":\"boolean\"}}],\"result\":{\"name\":\"request\",\"summary\":\"A EntityInfoFederatedRequest object.\",\"schema\":{\"anyOf\":[{\"$ref\":\"#/x-schemas/Types/ListenResponse\"},{\"$ref\":\"#/components/schemas/EntityInfoFederatedRequest\"}]}},\"examples\":[{\"name\":\"Send entity info for a movie to the platform.\",\"params\":[{\"name\":\"listen\",\"value\":true}],\"result\":{\"name\":\"result\",\"value\":{\"correlationId\":\"xyz\",\"parameters\":{\"entityId\":\"345\"}}}},{\"name\":\"Send entity info for a movie with a trailer to the platform.\",\"params\":[{\"name\":\"listen\",\"value\":true}],\"result\":{\"name\":\"result\",\"value\":{\"correlationId\":\"xyz\",\"parameters\":{\"entityId\":\"345\"}}}},{\"name\":\"Send entity info for a TV Series with seasons and episodes to the platform.\",\"params\":[{\"name\":\"listen\",\"value\":true}],\"result\":{\"name\":\"result\",\"value\":{\"correlationId\":\"xyz\",\"parameters\":{\"entityId\":\"345\"}}}}]},{\"name\":\"Discovery.onPullPurchasedContent\",\"tags\":[{\"name\":\"polymorphic-pull-event\"},{\"name\":\"event\",\"x-pulls-for\":\"purchasedContent\"},{\"name\":\"capabilities\",\"x-provides\":\"xrn:firebolt:capability:discovery:purchased-content\"},{\"name\":\"deprecated\"}],\"summary\":\"Provide a list of purchased content for the authenticated account, such as rentals and electronic sell through purchases.\",\"params\":[{\"name\":\"listen\",\"required\":true,\"schema\":{\"type\":\"boolean\"}}],\"result\":{\"name\":\"request\",\"summary\":\"A PurchasedContentFederatedRequest object.\",\"schema\":{\"anyOf\":[{\"$ref\":\"#/x-schemas/Types/ListenResponse\"},{\"$ref\":\"#/components/schemas/PurchasedContentFederatedRequest\"}]}},\"examples\":[{\"name\":\"Inform the platform of the user's purchased content\",\"params\":[{\"name\":\"listen\",\"value\":true}],\"result\":{\"name\":\"result\",\"value\":{\"correlationId\":\"xyz\",\"parameters\":{\"limit\":100}}}}],\"description\":\"Return content purchased by the user, such as rentals and electronic sell through purchases.\\n\\nThe app should return the user's 100 most recent purchases in `entries`. The total count of purchases must be provided in `count`. If `count` is greater than the total number of `entries`, the UI may provide a link into the app to see the complete purchase list.\\n\\nThe `EntityInfo` object returned is not required to have `waysToWatch` populated, but it is recommended that it do so in case the UI wants to surface additional information on the purchases screen.\\n\\nThe app should implement both Push and Pull methods for `purchasedContent`.\\n\\nThe app should actively push `purchasedContent` when:\\n\\n* The app becomes Active.\\n* When the state of the purchasedContent set has changed.\\n* The app goes into Inactive or Background state, if there is a chance a change event has been missed.\"},{\"name\":\"Discovery.userInterestResponse\",\"tags\":[{\"name\":\"rpc-only\"},{\"name\":\"capabilities\",\"x-provides\":\"xrn:firebolt:capability:discovery:interest\",\"x-response-for\":\"Discovery.onRequestUserInterest\"}],\"summary\":\"Internal API for .onRequestUserInterest Provider to send back response.\",\"description\":\"Provide information about the entity currently displayed or selected on the screen.\",\"params\":[{\"name\":\"correlationId\",\"schema\":{\"type\":\"string\"},\"required\":true},{\"name\":\"result\",\"schema\":{\"$ref\":\"#/x-schemas/Entity/EntityDetails\",\"examples\":[{\"identifiers\":{\"entityId\":\"345\",\"entityType\":\"program\",\"programType\":\"movie\"},\"info\":{\"title\":\"Cool Runnings\",\"synopsis\":\"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Pulvinar sapien et ligula ullamcorper malesuada proin libero nunc.\",\"releaseDate\":\"1993-01-01T00:00:00.000Z\",\"contentRatings\":[{\"scheme\":\"US-Movie\",\"rating\":\"PG\"},{\"scheme\":\"CA-Movie\",\"rating\":\"G\"}]}}]},\"required\":true}],\"result\":{\"name\":\"result\",\"schema\":{\"type\":\"null\"}},\"examples\":[{\"name\":\"Example\",\"params\":[{\"name\":\"correlationId\",\"value\":\"123\"},{\"name\":\"result\",\"value\":{\"identifiers\":{\"entityId\":\"345\",\"entityType\":\"program\",\"programType\":\"movie\"},\"info\":{\"title\":\"Cool Runnings\",\"synopsis\":\"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Pulvinar sapien et ligula ullamcorper malesuada proin libero nunc.\",\"releaseDate\":\"1993-01-01T00:00:00.000Z\",\"contentRatings\":[{\"scheme\":\"US-Movie\",\"rating\":\"PG\"},{\"scheme\":\"CA-Movie\",\"rating\":\"G\"}]}}}],\"result\":{\"name\":\"result\",\"value\":null}}]},{\"name\":\"Discovery.userInterestError\",\"tags\":[{\"name\":\"rpc-only\"},{\"name\":\"capabilities\",\"x-provides\":\"xrn:firebolt:capability:discovery:interest\",\"x-error-for\":\"Discovery.onRequestUserInterest\"}],\"summary\":\"Internal API for .onRequestUserInterest Provider to send back error.\",\"description\":\"Provide information about the entity currently displayed or selected on the screen.\",\"params\":[{\"name\":\"correlationId\",\"schema\":{\"type\":\"string\"},\"required\":true},{\"name\":\"error\",\"schema\":{\"type\":\"object\",\"additionalProperties\":false,\"required\":[\"code\",\"message\"],\"properties\":{\"code\":{\"title\":\"errorObjectCode\",\"description\":\"A Number that indicates the error type that occurred. This MUST be an integer. The error codes from and including -32768 to -32000 are reserved for pre-defined errors. These pre-defined errors SHOULD be assumed to be returned from any JSON-RPC api.\",\"type\":\"integer\"},\"message\":{\"title\":\"errorObjectMessage\",\"description\":\"A String providing a short description of the error. The message SHOULD be limited to a concise single sentence.\",\"type\":\"string\"},\"data\":{\"title\":\"errorObjectData\",\"description\":\"A Primitive or Structured value that contains additional information about the error. This may be omitted. The value of this member is defined by the Server (e.g. detailed error information, nested errors etc.).\"}}},\"required\":true}],\"result\":{\"name\":\"result\",\"schema\":{\"type\":\"null\"}},\"examples\":[{\"name\":\"Example 1\",\"params\":[{\"name\":\"correlationId\",\"value\":\"123\"},{\"name\":\"error\",\"value\":{\"code\":1,\"message\":\"Error\"}}],\"result\":{\"name\":\"result\",\"value\":null}}]},{\"name\":\"Internal.initialize\",\"tags\":[{\"name\":\"rpc-only\"},{\"name\":\"capabilities\",\"x-uses\":[\"xrn:firebolt:capability:lifecycle:initialize\"]}],\"summary\":\"Initialize the SDK / FEE session.\",\"description\":\"A single version of the Firebolt SDK is compiled into each app. When an app starts up, the SDK **MUST** call this method as soon as possible and **before** any other JSON-RPC methods are sent.\",\"params\":[{\"name\":\"version\",\"required\":true,\"schema\":{\"$ref\":\"#/x-schemas/Types/SemanticVersion\"},\"summary\":\"The semantic version of the SDK.\"}],\"result\":{\"name\":\"session\",\"summary\":\"Info about the SDK/FEE session\",\"schema\":{\"$ref\":\"#/components/schemas/InitializeResult\"}},\"examples\":[{\"name\":\"Default Example\",\"params\":[{\"name\":\"version\",\"value\":{\"major\":1,\"minor\":0,\"patch\":0,\"readable\":\"Firebolt SDK 1.0.0\"}}],\"result\":{\"name\":\"Default Result\",\"value\":{\"version\":{\"major\":1,\"minor\":0,\"patch\":0,\"readable\":\"Firebolt FEE 1.0.0\"}}}}]},{\"name\":\"Keyboard.email\",\"tags\":[{\"name\":\"capabilities\",\"x-provided-by\":\"Keyboard.onRequestEmail\",\"x-uses\":[\"xrn:firebolt:capability:input:keyboard\"],\"x-allow-focus\":true}],\"summary\":\"Prompt the user for their email address with a simplified list of choices.\",\"params\":[{\"name\":\"type\",\"summary\":\"Why the email is being requested, e.g. sign on or sign up\",\"required\":true,\"schema\":{\"$ref\":\"#/components/schemas/EmailUsage\"}},{\"name\":\"message\",\"summary\":\"The message to display while prompting\",\"required\":false,\"schema\":{\"type\":\"string\"}}],\"result\":{\"name\":\"email\",\"summary\":\"the selected or entered email\",\"schema\":{\"type\":\"string\"}},\"examples\":[{\"name\":\"Prompt the user to select or type an email address\",\"params\":[{\"name\":\"type\",\"value\":\"signIn\"},{\"name\":\"message\",\"value\":\"Enter your email to sign into this app\"}],\"result\":{\"name\":\"Default Result\",\"value\":\"user@domain.com\"}},{\"name\":\"Prompt the user to type an email address to sign up\",\"params\":[{\"name\":\"type\",\"value\":\"signUp\"},{\"name\":\"message\",\"value\":\"Enter your email to sign up for this app\"}],\"result\":{\"name\":\"Default Result\",\"value\":\"user@domain.com\"}}]},{\"name\":\"Keyboard.password\",\"tags\":[{\"name\":\"capabilities\",\"x-provided-by\":\"Keyboard.onRequestPassword\",\"x-uses\":[\"xrn:firebolt:capability:input:keyboard\"],\"x-allow-focus\":true}],\"summary\":\"Show the password entry keyboard, with typing obfuscated from visibility\",\"params\":[{\"name\":\"message\",\"summary\":\"The message to display while prompting\",\"required\":false,\"schema\":{\"type\":\"string\"}}],\"result\":{\"name\":\"value\",\"summary\":\"the selected or entered password\",\"schema\":{\"type\":\"string\"}},\"examples\":[{\"name\":\"Prompt the user to enter their password\",\"params\":[{\"name\":\"message\",\"value\":\"Enter your password\"}],\"result\":{\"name\":\"Default Result\",\"value\":\"abc123\"}}]},{\"name\":\"Keyboard.standard\",\"tags\":[{\"name\":\"capabilities\",\"x-provided-by\":\"Keyboard.onRequestStandard\",\"x-uses\":[\"xrn:firebolt:capability:input:keyboard\"],\"x-allow-focus\":true}],\"summary\":\"Show the standard platform keyboard, and return the submitted value\",\"params\":[{\"name\":\"message\",\"summary\":\"The message to display while prompting\",\"required\":true,\"schema\":{\"type\":\"string\"}}],\"result\":{\"name\":\"value\",\"summary\":\"the selected or entered text\",\"schema\":{\"type\":\"string\"}},\"examples\":[{\"name\":\"Prompt the user for an arbitrary string\",\"params\":[{\"name\":\"message\",\"value\":\"Enter the name you'd like to associate with this device\"}],\"result\":{\"name\":\"Default Result\",\"value\":\"Living Room\"}}]},{\"name\":\"Lifecycle.ready\",\"tags\":[{\"name\":\"calls-metrics\"},{\"name\":\"capabilities\",\"x-uses\":[\"xrn:firebolt:capability:lifecycle:ready\"]},{\"name\":\"exclude-from-sdk\"}],\"summary\":\"Notify the platform that the app is ready\",\"params\":[],\"result\":{\"name\":\"result\",\"schema\":{\"const\":null}},\"examples\":[{\"name\":\"Let the platform know that your app is ready\",\"params\":[],\"result\":{\"name\":\"Default Result\",\"value\":null}}]},{\"name\":\"Lifecycle.close\",\"tags\":[{\"name\":\"capabilities\",\"x-uses\":[\"xrn:firebolt:capability:lifecycle:state\"]}],\"summary\":\"Request that the platform move your app out of focus\",\"params\":[{\"name\":\"reason\",\"summary\":\"The reason the app is requesting to be closed\",\"required\":true,\"schema\":{\"$ref\":\"#/x-schemas/Lifecycle/CloseReason\"}}],\"result\":{\"name\":\"success\",\"schema\":{\"const\":null}},\"examples\":[{\"name\":\"Close the app when the user presses back on the app home screen\",\"params\":[{\"name\":\"reason\",\"value\":\"remoteButton\"}],\"result\":{\"name\":\"Default Result\",\"value\":null}},{\"name\":\"Close the app when the user selects an exit menu item\",\"params\":[{\"name\":\"reason\",\"value\":\"userExit\"}],\"result\":{\"name\":\"Default Result\",\"value\":null}}]},{\"name\":\"Lifecycle.finished\",\"tags\":[{\"name\":\"exclude-from-sdk\"},{\"name\":\"capabilities\",\"x-uses\":[\"xrn:firebolt:capability:lifecycle:state\"]}],\"summary\":\"Notify the platform that the app is done unloading\",\"params\":[],\"result\":{\"name\":\"results\",\"schema\":{\"const\":null}},\"examples\":[{\"name\":\"Default Example\",\"params\":[],\"result\":{\"name\":\"Default Result\",\"value\":null}}]},{\"name\":\"Lifecycle.state\",\"summary\":\"Get the current state of the app. This function is **synchronous**.\",\"tags\":[{\"name\":\"synchronous\"},{\"name\":\"exclude-from-sdk\"},{\"name\":\"capabilities\",\"x-uses\":[\"xrn:firebolt:capability:lifecycle:state\"]}],\"params\":[],\"result\":{\"name\":\"state\",\"summary\":\"the current state of the app.\",\"schema\":{\"$ref\":\"#/x-schemas/Lifecycle/LifecycleState\"}},\"examples\":[{\"name\":\"Default Example\",\"params\":[],\"result\":{\"name\":\"Default Result\",\"value\":\"foreground\"}}]},{\"name\":\"Lifecycle.onInactive\",\"tags\":[{\"name\":\"event\"},{\"name\":\"capabilities\",\"x-uses\":[\"xrn:firebolt:capability:lifecycle:state\"]}],\"summary\":\"Listen to the inactive event\",\"params\":[{\"name\":\"listen\",\"required\":true,\"schema\":{\"type\":\"boolean\"}}],\"result\":{\"name\":\"value\",\"schema\":{\"anyOf\":[{\"$ref\":\"#/x-schemas/Types/ListenResponse\"},{\"$ref\":\"#/components/schemas/LifecycleEvent\"}]}},\"examples\":[{\"name\":\"Default Example\",\"params\":[{\"name\":\"listen\",\"value\":true}],\"result\":{\"name\":\"Default Result\",\"value\":{\"state\":\"inactive\",\"previous\":\"initializing\"}}}]},{\"name\":\"Lifecycle.onForeground\",\"tags\":[{\"name\":\"event\"},{\"name\":\"capabilities\",\"x-uses\":[\"xrn:firebolt:capability:lifecycle:state\"]}],\"summary\":\"Listen to the foreground event\",\"params\":[{\"name\":\"listen\",\"required\":true,\"schema\":{\"type\":\"boolean\"}}],\"result\":{\"name\":\"value\",\"schema\":{\"anyOf\":[{\"$ref\":\"#/x-schemas/Types/ListenResponse\"},{\"$ref\":\"#/components/schemas/LifecycleEvent\"}]}},\"examples\":[{\"name\":\"Default Example\",\"params\":[{\"name\":\"listen\",\"value\":true}],\"result\":{\"name\":\"Default Result\",\"value\":{\"state\":\"foreground\",\"previous\":\"inactive\"}}},{\"name\":\"Move to foreground via remote branded buton\",\"params\":[{\"name\":\"listen\",\"value\":true}],\"result\":{\"name\":\"value\",\"value\":{\"state\":\"foreground\",\"previous\":\"inactive\",\"source\":\"remote\"}}}]},{\"name\":\"Lifecycle.onBackground\",\"tags\":[{\"name\":\"event\"},{\"name\":\"capabilities\",\"x-uses\":[\"xrn:firebolt:capability:lifecycle:state\"]}],\"summary\":\"Listen to the background event\",\"params\":[{\"name\":\"listen\",\"required\":true,\"schema\":{\"type\":\"boolean\"}}],\"result\":{\"name\":\"value\",\"schema\":{\"anyOf\":[{\"$ref\":\"#/x-schemas/Types/ListenResponse\"},{\"$ref\":\"#/components/schemas/LifecycleEvent\"}]}},\"examples\":[{\"name\":\"Default Example\",\"params\":[{\"name\":\"listen\",\"value\":true}],\"result\":{\"name\":\"Default Result\",\"value\":{\"state\":\"background\",\"previous\":\"foreground\"}}}]},{\"name\":\"Lifecycle.onSuspended\",\"tags\":[{\"name\":\"event\"},{\"name\":\"capabilities\",\"x-uses\":[\"xrn:firebolt:capability:lifecycle:state\"]}],\"summary\":\"Listen to the suspended event\",\"params\":[{\"name\":\"listen\",\"required\":true,\"schema\":{\"type\":\"boolean\"}}],\"result\":{\"name\":\"value\",\"schema\":{\"anyOf\":[{\"$ref\":\"#/x-schemas/Types/ListenResponse\"},{\"$ref\":\"#/components/schemas/LifecycleEvent\"}]}},\"examples\":[{\"name\":\"Default Example\",\"params\":[{\"name\":\"listen\",\"value\":true}],\"result\":{\"name\":\"Default Result\",\"value\":{\"state\":\"suspended\",\"previous\":\"inactive\"}}}]},{\"name\":\"Lifecycle.onUnloading\",\"tags\":[{\"name\":\"event\"},{\"name\":\"capabilities\",\"x-uses\":[\"xrn:firebolt:capability:lifecycle:state\"]}],\"summary\":\"Listen to the unloading event\",\"params\":[{\"name\":\"listen\",\"required\":true,\"schema\":{\"type\":\"boolean\"}}],\"result\":{\"name\":\"value\",\"schema\":{\"anyOf\":[{\"$ref\":\"#/x-schemas/Types/ListenResponse\"},{\"$ref\":\"#/components/schemas/LifecycleEvent\"}]}},\"examples\":[{\"name\":\"Default Example\",\"params\":[{\"name\":\"listen\",\"value\":true}],\"result\":{\"name\":\"Default Result\",\"value\":{\"state\":\"unloading\",\"previous\":\"inactive\"}}}]},{\"name\":\"Localization.locality\",\"tags\":[{\"name\":\"capabilities\",\"x-uses\":[\"xrn:firebolt:capability:localization:locality\"]},{\"name\":\"property\"}],\"summary\":\"Get the locality/city the device is located in\",\"params\":[],\"result\":{\"name\":\"locality\",\"summary\":\"the device city\",\"schema\":{\"$ref\":\"#/x-schemas/Localization/Locality\"}},\"examples\":[{\"name\":\"Default example #1\",\"params\":[],\"result\":{\"name\":\"Default Result\",\"value\":\"Philadelphia\"}},{\"name\":\"Default example #2\",\"params\":[],\"result\":{\"name\":\"Default Result\",\"value\":\"Rockville\"}}]},{\"name\":\"Localization.postalCode\",\"tags\":[{\"name\":\"property\"},{\"name\":\"capabilities\",\"x-uses\":[\"xrn:firebolt:capability:localization:postal-code\"]}],\"summary\":\"Get the postal code the device is located in\",\"params\":[],\"result\":{\"name\":\"postalCode\",\"summary\":\"the device postal code\",\"schema\":{\"type\":\"string\"}},\"examples\":[{\"name\":\"Default example #1\",\"params\":[],\"result\":{\"name\":\"Default Result\",\"value\":\"19103\"}},{\"name\":\"Default example #2\",\"params\":[],\"result\":{\"name\":\"Default Result\",\"value\":\"20850\"}}]},{\"name\":\"Localization.countryCode\",\"tags\":[{\"name\":\"property\"},{\"name\":\"capabilities\",\"x-uses\":[\"xrn:firebolt:capability:localization:country-code\"]}],\"summary\":\"Get the ISO 3166-1 alpha-2 code for the country device is located in\",\"params\":[],\"result\":{\"name\":\"code\",\"summary\":\"the device country code\",\"schema\":{\"$ref\":\"#/x-schemas/Localization/CountryCode\"}},\"examples\":[{\"name\":\"Default example #1\",\"params\":[],\"result\":{\"name\":\"Default Result\",\"value\":\"US\"}},{\"name\":\"Default example #2\",\"params\":[],\"result\":{\"name\":\"Default Result\",\"value\":\"UK\"}}]},{\"name\":\"Localization.language\",\"summary\":\"Get the ISO 639 1/2 code for the preferred language\",\"params\":[],\"tags\":[{\"name\":\"deprecated\",\"x-since\":\"0.17.0\",\"x-alternative\":\"Localization.locale\"},{\"name\":\"property\"},{\"name\":\"capabilities\",\"x-uses\":[\"xrn:firebolt:capability:localization:language\"]}],\"result\":{\"name\":\"lang\",\"summary\":\"the device language\",\"schema\":{\"$ref\":\"#/x-schemas/Localization/Language\"}},\"examples\":[{\"name\":\"Default example #1\",\"params\":[],\"result\":{\"name\":\"Default Result\",\"value\":\"en\"}},{\"name\":\"Default example #2\",\"params\":[],\"result\":{\"name\":\"Default Result\",\"value\":\"es\"}}]},{\"name\":\"Localization.preferredAudioLanguages\",\"summary\":\"A prioritized list of ISO 639 1/2 codes for the preferred audio languages on this device.\",\"params\":[],\"tags\":[{\"name\":\"property\"},{\"name\":\"capabilities\",\"x-uses\":[\"xrn:firebolt:capability:localization:language\"]}],\"result\":{\"name\":\"languages\",\"summary\":\"the preferred audio languages\",\"schema\":{\"type\":\"array\",\"items\":{\"$ref\":\"#/x-schemas/Localization/ISO639_2Language\"}}},\"examples\":[{\"name\":\"Default Example\",\"params\":[],\"result\":{\"name\":\"Default Result\",\"value\":[\"spa\",\"eng\"]}},{\"name\":\"Default Example #2\",\"params\":[],\"result\":{\"name\":\"Default Result\",\"value\":[\"eng\",\"spa\"]}}]},{\"name\":\"Localization.locale\",\"tags\":[{\"name\":\"property\"},{\"name\":\"capabilities\",\"x-uses\":[\"xrn:firebolt:capability:localization:locale\"]}],\"summary\":\"Get the *full* BCP 47 code, including script, region, variant, etc., for the preferred langauage/locale\",\"params\":[],\"result\":{\"name\":\"locale\",\"summary\":\"the device locale\",\"schema\":{\"$ref\":\"#/x-schemas/Localization/Locale\"}},\"examples\":[{\"name\":\"Default example #1\",\"params\":[],\"result\":{\"name\":\"Default Result\",\"value\":\"en-US\"}},{\"name\":\"Default example #2\",\"params\":[],\"result\":{\"name\":\"Default Result\",\"value\":\"es-US\"}}]},{\"name\":\"Localization.latlon\",\"tags\":[{\"name\":\"capabilities\",\"x-uses\":[\"xrn:firebolt:capability:localization:location\"]}],\"summary\":\"Get the approximate latitude and longitude coordinates of the device location\",\"params\":[],\"result\":{\"name\":\"latlong\",\"summary\":\"lat/long tuple\",\"schema\":{\"$ref\":\"#/components/schemas/LatLon\"}},\"examples\":[{\"name\":\"Default Example\",\"params\":[],\"result\":{\"name\":\"Default Result\",\"value\":[39.9549,75.1699]}}]},{\"name\":\"Localization.additionalInfo\",\"tags\":[{\"name\":\"capabilities\",\"x-uses\":[\"xrn:firebolt:capability:localization:additional-info\"]}],\"summary\":\"Get any platform-specific localization information\",\"params\":[],\"result\":{\"name\":\"info\",\"summary\":\"the additional info\",\"schema\":{\"type\":\"object\",\"additionalProperties\":{\"type\":[\"number\",\"string\",\"boolean\"],\"maxLength\":1024},\"maxProperties\":32}},\"examples\":[{\"name\":\"Default Example\",\"params\":[],\"result\":{\"name\":\"info\",\"value\":{}}}]},{\"name\":\"Localization.onLocalityChanged\",\"tags\":[{\"name\":\"subscriber\",\"x-subscriber-for\":\"Localization.locality\"},{\"name\":\"event\",\"x-alternative\":\"locality\"},{\"name\":\"capabilities\",\"x-uses\":[\"xrn:firebolt:capability:localization:locality\"]}],\"summary\":\"Get the locality/city the device is located in\",\"params\":[{\"name\":\"listen\",\"required\":true,\"schema\":{\"type\":\"boolean\"}}],\"result\":{\"name\":\"locality\",\"summary\":\"the device city\",\"schema\":{\"anyOf\":[{\"$ref\":\"#/x-schemas/Types/ListenResponse\"},{\"$ref\":\"#/x-schemas/Localization/Locality\"}]}},\"examples\":[{\"name\":\"Default example #1\",\"params\":[{\"name\":\"listen\",\"value\":true}],\"result\":{\"name\":\"Default Result\",\"value\":\"Philadelphia\"}},{\"name\":\"Default example #2\",\"params\":[{\"name\":\"listen\",\"value\":true}],\"result\":{\"name\":\"Default Result\",\"value\":\"Rockville\"}}]},{\"name\":\"Localization.onPostalCodeChanged\",\"tags\":[{\"name\":\"subscriber\",\"x-subscriber-for\":\"Localization.postalCode\"},{\"name\":\"event\",\"x-alternative\":\"postalCode\"},{\"name\":\"capabilities\",\"x-uses\":[\"xrn:firebolt:capability:localization:postal-code\"]}],\"summary\":\"Get the postal code the device is located in\",\"params\":[{\"name\":\"listen\",\"required\":true,\"schema\":{\"type\":\"boolean\"}}],\"result\":{\"name\":\"postalCode\",\"summary\":\"the device postal code\",\"schema\":{\"anyOf\":[{\"$ref\":\"#/x-schemas/Types/ListenResponse\"},{\"type\":\"string\"}]}},\"examples\":[{\"name\":\"Default example #1\",\"params\":[{\"name\":\"listen\",\"value\":true}],\"result\":{\"name\":\"Default Result\",\"value\":\"19103\"}},{\"name\":\"Default example #2\",\"params\":[{\"name\":\"listen\",\"value\":true}],\"result\":{\"name\":\"Default Result\",\"value\":\"20850\"}}]},{\"name\":\"Localization.onCountryCodeChanged\",\"tags\":[{\"name\":\"subscriber\",\"x-subscriber-for\":\"Localization.countryCode\"},{\"name\":\"event\",\"x-alternative\":\"countryCode\"},{\"name\":\"capabilities\",\"x-uses\":[\"xrn:firebolt:capability:localization:country-code\"]}],\"summary\":\"Get the ISO 3166-1 alpha-2 code for the country device is located in\",\"params\":[{\"name\":\"listen\",\"required\":true,\"schema\":{\"type\":\"boolean\"}}],\"result\":{\"name\":\"code\",\"summary\":\"the device country code\",\"schema\":{\"anyOf\":[{\"$ref\":\"#/x-schemas/Types/ListenResponse\"},{\"$ref\":\"#/x-schemas/Localization/CountryCode\"}]}},\"examples\":[{\"name\":\"Default example #1\",\"params\":[{\"name\":\"listen\",\"value\":true}],\"result\":{\"name\":\"Default Result\",\"value\":\"US\"}},{\"name\":\"Default example #2\",\"params\":[{\"name\":\"listen\",\"value\":true}],\"result\":{\"name\":\"Default Result\",\"value\":\"UK\"}}]},{\"name\":\"Localization.onLanguageChanged\",\"summary\":\"Get the ISO 639 1/2 code for the preferred language\",\"params\":[{\"name\":\"listen\",\"required\":true,\"schema\":{\"type\":\"boolean\"}}],\"tags\":[{\"name\":\"subscriber\",\"x-subscriber-for\":\"Localization.language\"},{\"name\":\"event\",\"x-alternative\":\"language\"},{\"name\":\"deprecated\",\"x-since\":\"0.17.0\",\"x-alternative\":\"Localization.locale\"},{\"name\":\"capabilities\",\"x-uses\":[\"xrn:firebolt:capability:localization:language\"]}],\"result\":{\"name\":\"lang\",\"summary\":\"the device language\",\"schema\":{\"anyOf\":[{\"$ref\":\"#/x-schemas/Types/ListenResponse\"},{\"$ref\":\"#/x-schemas/Localization/Language\"}]}},\"examples\":[{\"name\":\"Default example #1\",\"params\":[{\"name\":\"listen\",\"value\":true}],\"result\":{\"name\":\"Default Result\",\"value\":\"en\"}},{\"name\":\"Default example #2\",\"params\":[{\"name\":\"listen\",\"value\":true}],\"result\":{\"name\":\"Default Result\",\"value\":\"es\"}}]},{\"name\":\"Localization.onPreferredAudioLanguagesChanged\",\"summary\":\"A prioritized list of ISO 639 1/2 codes for the preferred audio languages on this device.\",\"params\":[{\"name\":\"listen\",\"required\":true,\"schema\":{\"type\":\"boolean\"}}],\"tags\":[{\"name\":\"subscriber\",\"x-subscriber-for\":\"Localization.preferredAudioLanguages\"},{\"name\":\"event\",\"x-alternative\":\"preferredAudioLanguages\"},{\"name\":\"capabilities\",\"x-uses\":[\"xrn:firebolt:capability:localization:language\"]}],\"result\":{\"name\":\"languages\",\"summary\":\"the preferred audio languages\",\"schema\":{\"anyOf\":[{\"$ref\":\"#/x-schemas/Types/ListenResponse\"},{\"type\":\"array\",\"items\":{\"$ref\":\"#/x-schemas/Localization/ISO639_2Language\"}}]}},\"examples\":[{\"name\":\"Default Example\",\"params\":[{\"name\":\"listen\",\"value\":true}],\"result\":{\"name\":\"Default Result\",\"value\":[\"spa\",\"eng\"]}},{\"name\":\"Default Example #2\",\"params\":[{\"name\":\"listen\",\"value\":true}],\"result\":{\"name\":\"Default Result\",\"value\":[\"eng\",\"spa\"]}}]},{\"name\":\"Localization.onLocaleChanged\",\"tags\":[{\"name\":\"subscriber\",\"x-subscriber-for\":\"Localization.locale\"},{\"name\":\"event\",\"x-alternative\":\"locale\"},{\"name\":\"capabilities\",\"x-uses\":[\"xrn:firebolt:capability:localization:locale\"]}],\"summary\":\"Get the *full* BCP 47 code, including script, region, variant, etc., for the preferred langauage/locale\",\"params\":[{\"name\":\"listen\",\"required\":true,\"schema\":{\"type\":\"boolean\"}}],\"result\":{\"name\":\"locale\",\"summary\":\"the device locale\",\"schema\":{\"anyOf\":[{\"$ref\":\"#/x-schemas/Types/ListenResponse\"},{\"$ref\":\"#/x-schemas/Localization/Locale\"}]}},\"examples\":[{\"name\":\"Default example #1\",\"params\":[{\"name\":\"listen\",\"value\":true}],\"result\":{\"name\":\"Default Result\",\"value\":\"en-US\"}},{\"name\":\"Default example #2\",\"params\":[{\"name\":\"listen\",\"value\":true}],\"result\":{\"name\":\"Default Result\",\"value\":\"es-US\"}}]},{\"name\":\"Metrics.ready\",\"tags\":[{\"name\":\"rpc-only\"},{\"name\":\"capabilities\",\"x-uses\":[\"xrn:firebolt:capability:metrics:general\"]}],\"summary\":\"Inform the platform that your app is minimally usable. This method is called automatically by `Lifecycle.ready()`\",\"params\":[],\"result\":{\"name\":\"success\",\"schema\":{\"type\":\"boolean\"}},\"examples\":[{\"name\":\"Send ready metric\",\"params\":[],\"result\":{\"name\":\"success\",\"value\":true}}]},{\"name\":\"Metrics.signIn\",\"tags\":[{\"name\":\"rpc-only\"},{\"name\":\"capabilities\",\"x-uses\":[\"xrn:firebolt:capability:metrics:general\"]}],\"summary\":\"Log a sign in event, called by Discovery.signIn().\",\"params\":[],\"result\":{\"name\":\"success\",\"schema\":{\"type\":\"boolean\"}},\"examples\":[{\"name\":\"Send signIn metric\",\"params\":[],\"result\":{\"name\":\"success\",\"value\":true}},{\"name\":\"Send signIn metric with entitlements\",\"params\":[{\"name\":\"entitlements\",\"value\":[{\"entitlementId\":\"123\",\"startTime\":\"2025-01-01T00:00:00.000Z\",\"endTime\":\"2025-01-01T00:00:00.000Z\"}]}],\"result\":{\"name\":\"success\",\"value\":true}}]},{\"name\":\"Metrics.signOut\",\"tags\":[{\"name\":\"rpc-only\"},{\"name\":\"capabilities\",\"x-uses\":[\"xrn:firebolt:capability:metrics:general\"]}],\"summary\":\"Log a sign out event, called by Discovery.signOut().\",\"params\":[],\"result\":{\"name\":\"success\",\"schema\":{\"type\":\"boolean\"}},\"examples\":[{\"name\":\"Send signOut metric\",\"params\":[],\"result\":{\"name\":\"success\",\"value\":true}}]},{\"name\":\"Metrics.startContent\",\"tags\":[{\"name\":\"capabilities\",\"x-uses\":[\"xrn:firebolt:capability:metrics:general\"]}],\"summary\":\"Inform the platform that your user has started content.\",\"params\":[{\"name\":\"entityId\",\"summary\":\"Optional entity ID of the content.\",\"schema\":{\"type\":\"string\"},\"required\":false}],\"result\":{\"name\":\"success\",\"schema\":{\"type\":\"boolean\"}},\"examples\":[{\"name\":\"Send startContent metric\",\"params\":[],\"result\":{\"name\":\"success\",\"value\":true}},{\"name\":\"Send startContent metric w/ entity\",\"params\":[{\"name\":\"entityId\",\"value\":\"abc\"}],\"result\":{\"name\":\"success\",\"value\":true}}]},{\"name\":\"Metrics.stopContent\",\"tags\":[{\"name\":\"capabilities\",\"x-uses\":[\"xrn:firebolt:capability:metrics:general\"]}],\"summary\":\"Inform the platform that your user has stopped content.\",\"params\":[{\"name\":\"entityId\",\"summary\":\"Optional entity ID of the content.\",\"schema\":{\"type\":\"string\"},\"required\":false}],\"result\":{\"name\":\"success\",\"schema\":{\"type\":\"boolean\"}},\"examples\":[{\"name\":\"Send stopContent metric\",\"params\":[],\"result\":{\"name\":\"success\",\"value\":true}},{\"name\":\"Send stopContent metric w/ entity\",\"params\":[{\"name\":\"entityId\",\"value\":\"abc\"}],\"result\":{\"name\":\"success\",\"value\":true}}]},{\"name\":\"Metrics.page\",\"tags\":[{\"name\":\"capabilities\",\"x-uses\":[\"xrn:firebolt:capability:metrics:general\"]}],\"summary\":\"Inform the platform that your user has navigated to a page or view.\",\"params\":[{\"name\":\"pageId\",\"summary\":\"Page ID of the content.\",\"schema\":{\"type\":\"string\"},\"required\":true}],\"result\":{\"name\":\"success\",\"schema\":{\"type\":\"boolean\"}},\"examples\":[{\"name\":\"Send page metric\",\"params\":[{\"name\":\"pageId\",\"value\":\"xyz\"}],\"result\":{\"name\":\"success\",\"value\":true}},{\"name\":\"Send startContent metric w/ entity\",\"params\":[{\"name\":\"pageId\",\"value\":\"home\"}],\"result\":{\"name\":\"success\",\"value\":true}}]},{\"name\":\"Metrics.action\",\"tags\":[{\"name\":\"capabilities\",\"x-uses\":[\"xrn:firebolt:capability:metrics:general\"]}],\"summary\":\"Inform the platform of something not covered by other Metrics APIs.\",\"params\":[{\"name\":\"category\",\"summary\":\"The category of action being logged. Must be 'user' for user-initated actions or 'app' for all other actions\",\"schema\":{\"type\":\"string\",\"enum\":[\"user\",\"app\"]},\"required\":true},{\"name\":\"type\",\"summary\":\"A short, indexible identifier for the action, e.g. 'SignIn Prompt Displayed'\",\"schema\":{\"type\":\"string\",\"maxLength\":256},\"required\":true},{\"name\":\"parameters\",\"schema\":{\"$ref\":\"#/x-schemas/Types/FlatMap\"},\"required\":false}],\"result\":{\"name\":\"success\",\"schema\":{\"type\":\"boolean\"}},\"examples\":[{\"name\":\"Send foo action\",\"params\":[{\"name\":\"category\",\"value\":\"user\"},{\"name\":\"type\",\"value\":\"The user did foo\"}],\"result\":{\"name\":\"success\",\"value\":true}}]},{\"name\":\"Metrics.error\",\"tags\":[{\"name\":\"capabilities\",\"x-uses\":[\"xrn:firebolt:capability:metrics:general\"]}],\"summary\":\"Inform the platform of an error that has occured in your app.\",\"params\":[{\"name\":\"type\",\"summary\":\"The type of error\",\"schema\":{\"$ref\":\"#/components/schemas/ErrorType\"},\"required\":true},{\"name\":\"code\",\"summary\":\"an app-specific error code\",\"schema\":{\"type\":\"string\"},\"required\":true},{\"name\":\"description\",\"summary\":\"A short description of the error\",\"schema\":{\"type\":\"string\"},\"required\":true},{\"name\":\"visible\",\"summary\":\"Whether or not this error was visible to the user.\",\"schema\":{\"type\":\"boolean\"},\"required\":true},{\"name\":\"parameters\",\"summary\":\"Optional additional parameters to be logged with the error\",\"schema\":{\"$ref\":\"#/x-schemas/Types/FlatMap\"},\"required\":false}],\"result\":{\"name\":\"success\",\"schema\":{\"type\":\"boolean\"}},\"examples\":[{\"name\":\"Send error metric\",\"params\":[{\"name\":\"type\",\"value\":\"media\"},{\"name\":\"code\",\"value\":\"MEDIA-STALLED\"},{\"name\":\"description\",\"value\":\"playback stalled\"},{\"name\":\"visible\",\"value\":true}],\"result\":{\"name\":\"success\",\"value\":true}}]},{\"name\":\"Metrics.mediaLoadStart\",\"tags\":[{\"name\":\"capabilities\",\"x-uses\":[\"xrn:firebolt:capability:metrics:media\"]}],\"summary\":\"Called when setting the URL of a media asset to play, in order to infer load time.\",\"params\":[{\"name\":\"entityId\",\"summary\":\"The entityId of the media.\",\"schema\":{\"type\":\"string\"},\"required\":true}],\"result\":{\"name\":\"success\",\"schema\":{\"type\":\"boolean\"}},\"examples\":[{\"name\":\"Send loadstart metric.\",\"params\":[{\"name\":\"entityId\",\"value\":\"345\"}],\"result\":{\"name\":\"success\",\"value\":true}}]},{\"name\":\"Metrics.mediaPlay\",\"tags\":[{\"name\":\"capabilities\",\"x-uses\":[\"xrn:firebolt:capability:metrics:media\"]}],\"summary\":\"Called when media playback should start due to autoplay, user-initiated play, or unpausing.\",\"params\":[{\"name\":\"entityId\",\"summary\":\"The entityId of the media.\",\"schema\":{\"type\":\"string\"},\"required\":true}],\"result\":{\"name\":\"success\",\"schema\":{\"type\":\"boolean\"}},\"examples\":[{\"name\":\"Send play metric.\",\"params\":[{\"name\":\"entityId\",\"value\":\"345\"}],\"result\":{\"name\":\"success\",\"value\":true}}]},{\"name\":\"Metrics.mediaPlaying\",\"tags\":[{\"name\":\"capabilities\",\"x-uses\":[\"xrn:firebolt:capability:metrics:media\"]}],\"summary\":\"Called when media playback actually starts due to autoplay, user-initiated play, unpausing, or recovering from a buffering interuption.\",\"params\":[{\"name\":\"entityId\",\"summary\":\"The entityId of the media.\",\"schema\":{\"type\":\"string\"},\"required\":true}],\"result\":{\"name\":\"success\",\"schema\":{\"type\":\"boolean\"}},\"examples\":[{\"name\":\"Send playing metric.\",\"params\":[{\"name\":\"entityId\",\"value\":\"345\"}],\"result\":{\"name\":\"success\",\"value\":true}}]},{\"name\":\"Metrics.mediaPause\",\"tags\":[{\"name\":\"capabilities\",\"x-uses\":[\"xrn:firebolt:capability:metrics:media\"]}],\"summary\":\"Called when media playback will pause due to an intentional pause operation.\",\"params\":[{\"name\":\"entityId\",\"summary\":\"The entityId of the media.\",\"schema\":{\"type\":\"string\"},\"required\":true}],\"result\":{\"name\":\"success\",\"schema\":{\"type\":\"boolean\"}},\"examples\":[{\"name\":\"Send pause metric.\",\"params\":[{\"name\":\"entityId\",\"value\":\"345\"}],\"result\":{\"name\":\"success\",\"value\":true}}]},{\"name\":\"Metrics.mediaWaiting\",\"tags\":[{\"name\":\"capabilities\",\"x-uses\":[\"xrn:firebolt:capability:metrics:media\"]}],\"summary\":\"Called when media playback will halt due to a network, buffer, or other unintentional constraint.\",\"params\":[{\"name\":\"entityId\",\"summary\":\"The entityId of the media.\",\"schema\":{\"type\":\"string\"},\"required\":true}],\"result\":{\"name\":\"success\",\"schema\":{\"type\":\"boolean\"}},\"examples\":[{\"name\":\"Send waiting metric.\",\"params\":[{\"name\":\"entityId\",\"value\":\"345\"}],\"result\":{\"name\":\"success\",\"value\":true}}]},{\"name\":\"Metrics.mediaProgress\",\"tags\":[{\"name\":\"capabilities\",\"x-uses\":[\"xrn:firebolt:capability:metrics:media\"]}],\"summary\":\"Called every 60 seconds as media playback progresses.\",\"params\":[{\"name\":\"entityId\",\"summary\":\"The entityId of the media.\",\"schema\":{\"type\":\"string\"},\"required\":true},{\"name\":\"progress\",\"summary\":\"Progress of playback, as a decimal percentage (0-0.999) for content with a known duration, or an integer number of seconds (0-86400) for content with an unknown duration.\",\"schema\":{\"$ref\":\"#/components/schemas/MediaPosition\"},\"required\":true}],\"result\":{\"name\":\"success\",\"schema\":{\"type\":\"boolean\"}},\"examples\":[{\"name\":\"Send progress metric.\",\"params\":[{\"name\":\"entityId\",\"value\":\"345\"},{\"name\":\"progress\",\"value\":0.75}],\"result\":{\"name\":\"success\",\"value\":true}}]},{\"name\":\"Metrics.mediaSeeking\",\"tags\":[{\"name\":\"capabilities\",\"x-uses\":[\"xrn:firebolt:capability:metrics:media\"]}],\"summary\":\"Called when a seek is initiated during media playback.\",\"params\":[{\"name\":\"entityId\",\"summary\":\"The entityId of the media.\",\"schema\":{\"type\":\"string\"},\"required\":true},{\"name\":\"target\",\"summary\":\"Target destination of the seek, as a decimal percentage (0-0.999) for content with a known duration, or an integer number of seconds (0-86400) for content with an unknown duration.\",\"schema\":{\"$ref\":\"#/components/schemas/MediaPosition\"},\"required\":true}],\"result\":{\"name\":\"success\",\"schema\":{\"type\":\"boolean\"}},\"examples\":[{\"name\":\"Send seeking metric.\",\"params\":[{\"name\":\"entityId\",\"value\":\"345\"},{\"name\":\"target\",\"value\":0.5}],\"result\":{\"name\":\"success\",\"value\":true}}]},{\"name\":\"Metrics.mediaSeeked\",\"tags\":[{\"name\":\"capabilities\",\"x-uses\":[\"xrn:firebolt:capability:metrics:media\"]}],\"summary\":\"Called when a seek is completed during media playback.\",\"params\":[{\"name\":\"entityId\",\"summary\":\"The entityId of the media.\",\"schema\":{\"type\":\"string\"},\"required\":true},{\"name\":\"position\",\"summary\":\"Resulting position of the seek operation, as a decimal percentage (0-0.999) for content with a known duration, or an integer number of seconds (0-86400) for content with an unknown duration.\",\"schema\":{\"$ref\":\"#/components/schemas/MediaPosition\"},\"required\":true}],\"result\":{\"name\":\"success\",\"schema\":{\"type\":\"boolean\"}},\"examples\":[{\"name\":\"Send seeked metric.\",\"params\":[{\"name\":\"entityId\",\"value\":\"345\"},{\"name\":\"position\",\"value\":0.51}],\"result\":{\"name\":\"success\",\"value\":true}}]},{\"name\":\"Metrics.mediaRateChange\",\"tags\":[{\"name\":\"capabilities\",\"x-uses\":[\"xrn:firebolt:capability:metrics:media\"]}],\"summary\":\"Called when the playback rate of media is changed.\",\"params\":[{\"name\":\"entityId\",\"summary\":\"The entityId of the media.\",\"schema\":{\"type\":\"string\"},\"required\":true},{\"name\":\"rate\",\"summary\":\"The new playback rate.\",\"schema\":{\"type\":\"number\"},\"required\":true}],\"result\":{\"name\":\"success\",\"schema\":{\"type\":\"boolean\"}},\"examples\":[{\"name\":\"Send ratechange metric.\",\"params\":[{\"name\":\"entityId\",\"value\":\"345\"},{\"name\":\"rate\",\"value\":2}],\"result\":{\"name\":\"success\",\"value\":true}}]},{\"name\":\"Metrics.mediaRenditionChange\",\"tags\":[{\"name\":\"capabilities\",\"x-uses\":[\"xrn:firebolt:capability:metrics:media\"]}],\"summary\":\"Called when the playback rendition (e.g. bitrate, dimensions, profile, etc) is changed.\",\"params\":[{\"name\":\"entityId\",\"summary\":\"The entityId of the media.\",\"schema\":{\"type\":\"string\"},\"required\":true},{\"name\":\"bitrate\",\"summary\":\"The new bitrate in kbps.\",\"schema\":{\"type\":\"number\"},\"required\":true},{\"name\":\"width\",\"summary\":\"The new resolution width.\",\"schema\":{\"type\":\"number\"},\"required\":true},{\"name\":\"height\",\"summary\":\"The new resolution height.\",\"schema\":{\"type\":\"number\"},\"required\":true},{\"name\":\"profile\",\"summary\":\"A description of the new profile, e.g. 'HDR' etc.\",\"schema\":{\"type\":\"string\"},\"required\":false}],\"result\":{\"name\":\"success\",\"schema\":{\"type\":\"boolean\"}},\"examples\":[{\"name\":\"Send renditionchange metric.\",\"params\":[{\"name\":\"entityId\",\"value\":\"345\"},{\"name\":\"bitrate\",\"value\":5000},{\"name\":\"width\",\"value\":1920},{\"name\":\"height\",\"value\":1080},{\"name\":\"profile\",\"value\":\"HDR+\"}],\"result\":{\"name\":\"success\",\"value\":true}}]},{\"name\":\"Metrics.mediaEnded\",\"tags\":[{\"name\":\"capabilities\",\"x-uses\":[\"xrn:firebolt:capability:metrics:media\"]}],\"summary\":\"Called when playback has stopped because the end of the media was reached.\",\"params\":[{\"name\":\"entityId\",\"summary\":\"The entityId of the media.\",\"schema\":{\"type\":\"string\"},\"required\":true}],\"result\":{\"name\":\"success\",\"schema\":{\"type\":\"boolean\"}},\"examples\":[{\"name\":\"Send ended metric.\",\"params\":[{\"name\":\"entityId\",\"value\":\"345\"}],\"result\":{\"name\":\"success\",\"value\":true}}]},{\"name\":\"Metrics.appInfo\",\"tags\":[{\"name\":\"capabilities\",\"x-uses\":[\"xrn:firebolt:capability:metrics:general\"]}],\"summary\":\"Inform the platform about an app's build info.\",\"params\":[{\"name\":\"build\",\"summary\":\"The build / version of this app.\",\"schema\":{\"type\":\"string\"},\"required\":true}],\"result\":{\"name\":\"result\",\"schema\":{\"type\":\"null\"}},\"examples\":[{\"name\":\"Send appInfo metric\",\"params\":[{\"name\":\"build\",\"value\":\"1.2.2\"}],\"result\":{\"name\":\"result\",\"value\":null}}]},{\"name\":\"Parameters.initialization\",\"tags\":[{\"name\":\"capabilities\",\"x-uses\":[\"xrn:firebolt:capability:lifecycle:state\"]}],\"summary\":\"Returns any initialization parameters for the app, e.g. initialial `NavigationIntent`.\",\"params\":[],\"result\":{\"name\":\"init\",\"summary\":\"The initialization parameters.\",\"schema\":{\"$ref\":\"#/components/schemas/AppInitialization\"}},\"examples\":[{\"name\":\"Default Example\",\"params\":[],\"result\":{\"name\":\"init\",\"value\":{\"lmt\":0,\"us_privacy\":\"1-Y-\",\"discovery\":{\"navigateTo\":{\"action\":\"entity\",\"data\":{\"entityId\":\"abc\",\"entityType\":\"program\",\"programType\":\"movie\"},\"context\":{\"source\":\"voice\"}}}}}}]},{\"name\":\"Profile.approveContentRating\",\"tags\":[{\"name\":\"capabilities\",\"x-uses\":[\"xrn:firebolt:capability:approve:content\"]}],\"summary\":\"Verifies that the current profile should have access to mature/adult content.\",\"params\":[],\"result\":{\"name\":\"allow\",\"summary\":\"Whether or not to allow access\",\"schema\":{\"type\":\"boolean\"}},\"examples\":[{\"name\":\"Default Example\",\"params\":[],\"result\":{\"name\":\"allow\",\"value\":false}}]},{\"name\":\"Profile.approvePurchase\",\"tags\":[{\"name\":\"capabilities\",\"x-uses\":[\"xrn:firebolt:capability:approve:purchase\"]}],\"summary\":\"Verifies that the current profile should have access to making purchases.\",\"params\":[],\"result\":{\"name\":\"allow\",\"summary\":\"Whether or not to allow access\",\"schema\":{\"type\":\"boolean\"}},\"examples\":[{\"name\":\"Default Example\",\"params\":[],\"result\":{\"name\":\"allow\",\"value\":false}}]},{\"name\":\"Profile.flags\",\"tags\":[{\"name\":\"capabilities\",\"x-uses\":[\"xrn:firebolt:capability:profile:flags\"]}],\"summary\":\"Get a map of profile flags for the current session.\",\"params\":[],\"result\":{\"name\":\"flags\",\"summary\":\"The profile flags.\",\"schema\":{\"$ref\":\"#/x-schemas/Types/FlatMap\"}},\"examples\":[{\"name\":\"Default Example\",\"params\":[],\"result\":{\"name\":\"flags\",\"value\":{\"userExperience\":\"1000\"}}}]},{\"name\":\"SecondScreen.protocols\",\"summary\":\"Get the supported second screen discovery protocols\",\"tags\":[{\"name\":\"capabilities\",\"x-uses\":[\"xrn:firebolt:capability:secondscreen:protocol\"]}],\"params\":[],\"result\":{\"name\":\"protocols\",\"summary\":\"the supported protocols\",\"schema\":{\"$ref\":\"#/x-schemas/Types/BooleanMap\"}},\"examples\":[{\"name\":\"Default Example\",\"params\":[],\"result\":{\"name\":\"Default Result\",\"value\":{\"dial1.7\":true}}}]},{\"name\":\"SecondScreen.device\",\"tags\":[{\"name\":\"capabilities\",\"x-uses\":[\"xrn:firebolt:capability:protocol:dial\"]}],\"summary\":\"Get the broadcasted id for the device\",\"params\":[{\"name\":\"type\",\"summary\":\"The type of second screen protocol, e.g. \\\"dial\\\"\",\"required\":false,\"schema\":{\"type\":\"string\"}}],\"result\":{\"name\":\"deviceId\",\"summary\":\"the device id\",\"schema\":{\"type\":\"string\"}},\"examples\":[{\"name\":\"Default Example\",\"params\":[],\"result\":{\"name\":\"Default Result\",\"value\":\"device-id\"}}]},{\"name\":\"SecondScreen.friendlyName\",\"summary\":\"Get the broadcasted friendly name for the device\",\"params\":[],\"tags\":[{\"name\":\"property:readonly\"},{\"name\":\"capabilities\",\"x-uses\":[\"xrn:firebolt:capability:protocol:dial\"]}],\"result\":{\"name\":\"friendlyName\",\"summary\":\"the device friendly-name\",\"schema\":{\"type\":\"string\"}},\"examples\":[{\"name\":\"Default Example\",\"params\":[],\"result\":{\"name\":\"friendlyName\",\"value\":\"Living Room\"}}]},{\"name\":\"SecondScreen.onLaunchRequest\",\"tags\":[{\"name\":\"event\"},{\"name\":\"capabilities\",\"x-uses\":[\"xrn:firebolt:capability:protocol:dial\"]}],\"summary\":\"Listen to the launchRequest event\",\"params\":[{\"name\":\"listen\",\"required\":true,\"schema\":{\"type\":\"boolean\"}}],\"result\":{\"name\":\"launchRequestEvent\",\"summary\":\"Dispatched when a second screen device on the local network has requested this app to be launched\",\"schema\":{\"anyOf\":[{\"$ref\":\"#/x-schemas/Types/ListenResponse\"},{\"$ref\":\"#/x-schemas/SecondScreen/SecondScreenEvent\"}]}},\"examples\":[{\"name\":\"Default Example\",\"params\":[{\"name\":\"listen\",\"value\":true}],\"result\":{\"name\":\"Default Result\",\"value\":{\"type\":\"dial\",\"version\":\"1.7\",\"data\":\"{\\\"code\\\":\\\"AQDPQZiQcb3KQ7gY7yy5tHTMbbkGHR9Zjp-KL53H3eKBZIeAt7O9UKYPu6B21l2UZVmIqkFXDXBmXvK4g2e3EgZtjMNmKPsTltgnRl95DImtOXjSpWtTjSaOkW4w1kZKUTwLKdwVWTzBVH8ERHorvLU6vCGOVHxXt65LNwdl5HKRweShVC1V9QsyvRnQS61ov0UclmrH_xZML2Bt-Q-rZFjey5MjwupIb4x4f53XUJMhjHpDHoIUKrjpdPDQvK2a\\\",\\\"friendlyName\\\":\\\"Operator_TX061AEI\\\",\\\"UDN\\\":\\\"608fef11-2800-482a-962b-23a6690c93c1\\\"}\"}}}]},{\"name\":\"SecondScreen.onCloseRequest\",\"tags\":[{\"name\":\"event\"},{\"name\":\"capabilities\",\"x-uses\":[\"xrn:firebolt:capability:protocol:dial\"]}],\"summary\":\"Listen to the closeRequest event\",\"params\":[{\"name\":\"listen\",\"required\":true,\"schema\":{\"type\":\"boolean\"}}],\"result\":{\"name\":\"closeRequestEvent\",\"schema\":{\"anyOf\":[{\"$ref\":\"#/x-schemas/Types/ListenResponse\"},{\"$ref\":\"#/x-schemas/SecondScreen/SecondScreenEvent\"}]}},\"examples\":[{\"name\":\"Default Example\",\"params\":[{\"name\":\"listen\",\"value\":true}],\"result\":{\"name\":\"Default Result\",\"value\":{\"type\":\"dial\",\"version\":\"1.7\"}}}]},{\"name\":\"SecondScreen.onFriendlyNameChanged\",\"summary\":\"Get the broadcasted friendly name for the device\",\"params\":[{\"name\":\"listen\",\"required\":true,\"schema\":{\"type\":\"boolean\"}}],\"tags\":[{\"name\":\"subscriber\",\"x-subscriber-for\":\"SecondScreen.friendlyName\"},{\"name\":\"event\",\"x-alternative\":\"friendlyName\"},{\"name\":\"capabilities\",\"x-uses\":[\"xrn:firebolt:capability:protocol:dial\"]}],\"result\":{\"name\":\"friendlyName\",\"summary\":\"the device friendly-name\",\"schema\":{\"anyOf\":[{\"$ref\":\"#/x-schemas/Types/ListenResponse\"},{\"type\":\"string\"}]}},\"examples\":[{\"name\":\"Default Example\",\"params\":[{\"name\":\"listen\",\"value\":true}],\"result\":{\"name\":\"friendlyName\",\"value\":\"Living Room\"}}]},{\"name\":\"SecureStorage.get\",\"summary\":\"Get stored value by key\",\"tags\":[{\"name\":\"capabilities\",\"x-uses\":[\"xrn:firebolt:capability:storage:secure\"]}],\"params\":[{\"name\":\"scope\",\"summary\":\"The scope of the key/value\",\"schema\":{\"$ref\":\"#/components/schemas/StorageScope\"},\"required\":true},{\"name\":\"key\",\"summary\":\"Key to get\",\"schema\":{\"type\":\"string\"},\"required\":true}],\"result\":{\"name\":\"value\",\"summary\":\"The retrieved value, if found.\",\"schema\":{\"oneOf\":[{\"type\":\"string\"},{\"type\":\"null\"}]}},\"examples\":[{\"name\":\"Successfully retrieve a refresh token with key authRefreshToken\",\"params\":[{\"name\":\"scope\",\"value\":\"device\"},{\"name\":\"key\",\"value\":\"authRefreshToken\"}],\"result\":{\"name\":\"value\",\"value\":\"VGhpcyBub3QgYSByZWFsIHRva2VuLgo=\"}},{\"name\":\"Attempt to retrieve a key with no value set\",\"params\":[{\"name\":\"scope\",\"value\":\"account\"},{\"name\":\"key\",\"value\":\"authRefreshToken\"}],\"result\":{\"name\":\"value\",\"value\":null}}]},{\"name\":\"SecureStorage.set\",\"summary\":\"Set or update a secure data value\",\"tags\":[{\"name\":\"capabilities\",\"x-uses\":[\"xrn:firebolt:capability:storage:secure\"]}],\"params\":[{\"name\":\"scope\",\"summary\":\"The scope of the data key\",\"schema\":{\"$ref\":\"#/components/schemas/StorageScope\"},\"required\":true},{\"name\":\"key\",\"summary\":\"Key to set\",\"schema\":{\"type\":\"string\"},\"required\":true},{\"name\":\"value\",\"summary\":\"Value to set\",\"schema\":{\"type\":\"string\"},\"required\":true},{\"name\":\"options\",\"summary\":\"Optional parameters to set\",\"schema\":{\"$ref\":\"#/components/schemas/StorageOptions\"},\"required\":false}],\"result\":{\"name\":\"success\",\"schema\":{\"const\":null}},\"examples\":[{\"name\":\"Set a refresh token with name authRefreshToken with optional paramter\",\"params\":[{\"name\":\"scope\",\"value\":\"device\"},{\"name\":\"key\",\"value\":\"authRefreshToken\"},{\"name\":\"value\",\"value\":\"VGhpcyBub3QgYSByZWFsIHRva2VuLgo=\"},{\"name\":\"options\",\"value\":{\"ttl\":600}}],\"result\":{\"name\":\"defaultResult\",\"value\":null}},{\"name\":\"Set a refresh token with name authRefreshToken without optional parameter\",\"params\":[{\"name\":\"scope\",\"value\":\"account\"},{\"name\":\"key\",\"value\":\"authRefreshToken\"},{\"name\":\"value\",\"value\":\"VGhpcyBub3QgYSByZWFsIHRva2VuLgo=\"}],\"result\":{\"name\":\"defaultResult\",\"value\":null}}]},{\"name\":\"SecureStorage.remove\",\"summary\":\"Remove a secure data value\",\"tags\":[{\"name\":\"capabilities\",\"x-uses\":[\"xrn:firebolt:capability:storage:secure\"]}],\"params\":[{\"name\":\"scope\",\"summary\":\"The scope of the data key\",\"schema\":{\"$ref\":\"#/components/schemas/StorageScope\"},\"required\":true},{\"name\":\"key\",\"summary\":\"Key to remove\",\"schema\":{\"type\":\"string\"},\"required\":true}],\"result\":{\"name\":\"success\",\"summary\":\"\",\"schema\":{\"const\":null}},\"examples\":[{\"name\":\"Remove the value with key authRefreshToken for device\",\"params\":[{\"name\":\"scope\",\"value\":\"device\"},{\"name\":\"key\",\"value\":\"authRefreshToken\"}],\"result\":{\"name\":\"defaultResult\",\"value\":null}},{\"name\":\"Remove the value with key authRefreshToken for account\",\"params\":[{\"name\":\"scope\",\"value\":\"account\"},{\"name\":\"key\",\"value\":\"authRefreshToken\"}],\"result\":{\"name\":\"defaultResult\",\"value\":null}}]},{\"name\":\"SecureStorage.clear\",\"summary\":\"Clears all the secure data values\",\"tags\":[{\"name\":\"capabilities\",\"x-uses\":[\"xrn:firebolt:capability:storage:secure\"]}],\"params\":[{\"name\":\"scope\",\"summary\":\"The scope of the key/value\",\"schema\":{\"$ref\":\"#/components/schemas/StorageScope\"},\"required\":true}],\"result\":{\"name\":\"success\",\"summary\":\"\",\"schema\":{\"const\":null}},\"examples\":[{\"name\":\"Clears all the data values of storage\",\"params\":[{\"name\":\"scope\",\"value\":\"account\"}],\"result\":{\"name\":\"defaultResult\",\"value\":null}}]}],\"components\":{\"schemas\":{\"InitializeResult\":{\"title\":\"InitializeResult\",\"type\":\"object\",\"required\":[\"version\"],\"properties\":{\"version\":{\"$ref\":\"#/x-schemas/Types/SemanticVersion\",\"description\":\"The semantic version of the FEE.\"}},\"additionalProperties\":false},\"AudioDescriptionSettings\":{\"title\":\"AudioDescriptionSettings\",\"type\":\"object\",\"required\":[\"enabled\"],\"properties\":{\"enabled\":{\"type\":\"boolean\",\"description\":\"Whether or not audio descriptions should be enabled by default\"}}},\"ChallengeRequestor\":{\"title\":\"ChallengeRequestor\",\"type\":\"object\",\"required\":[\"id\",\"name\"],\"properties\":{\"id\":{\"type\":\"string\",\"description\":\"The id of the app that requested the challenge\"},\"name\":{\"type\":\"string\",\"description\":\"The name of the app that requested the challenge\"}}},\"Challenge\":{\"title\":\"Challenge\",\"type\":\"object\",\"required\":[\"capability\",\"requestor\"],\"properties\":{\"capability\":{\"type\":\"string\",\"description\":\"The capability that is being requested by the user to approve\"},\"requestor\":{\"description\":\"The identity of which app is requesting access to this capability\",\"$ref\":\"#/components/schemas/ChallengeRequestor\"}}},\"AdPolicy\":{\"title\":\"AdPolicy\",\"description\":\"Describes various ad playback enforcement rules that the app should follow.\",\"type\":\"object\",\"properties\":{\"skipRestriction\":{\"$ref\":\"#/x-schemas/Advertising/SkipRestriction\"},\"limitAdTracking\":{\"type\":\"boolean\"}}},\"AdConfigurationOptions\":{\"title\":\"AdConfigurationOptions\",\"type\":\"object\",\"properties\":{\"coppa\":{\"type\":\"boolean\",\"description\":\"Whether or not the app requires US COPPA compliance.\"},\"environment\":{\"type\":\"string\",\"enum\":[\"prod\",\"test\"],\"default\":\"prod\",\"description\":\"Whether the app is running in a production or test mode.\"},\"authenticationEntity\":{\"type\":\"string\",\"description\":\"The authentication provider, when it is separate entity than the app provider, e.g. an MVPD.\"}}},\"AdvertisingIdOptions\":{\"title\":\"AdvertisingIdOptions\",\"type\":\"object\",\"properties\":{\"scope\":{\"type\":\"object\",\"description\":\"Provides the options to send scope type and id to select desired advertising id\",\"required\":[\"type\",\"id\"],\"properties\":{\"type\":{\"type\":\"string\",\"enum\":[\"browse\",\"content\"],\"default\":\"browse\",\"description\":\"The scope type, which will determine where to show advertisement\"},\"id\":{\"type\":\"string\",\"description\":\"A value that identifies a specific scope within the scope type\"}}}}},\"AdvertisingIdResult\":{\"title\":\"AdvertisingIdResult\",\"type\":\"object\",\"properties\":{\"ifa\":{\"type\":\"string\",\"description\":\"UUID conforming to IAB standard\"},\"ifa_type\":{\"type\":\"string\",\"description\":\"source of the IFA as defined by IAB\"},\"lmt\":{\"type\":\"string\",\"enum\":[\"0\",\"1\"],\"description\":\"boolean that if set to 1, user has requested ad tracking and measurement is disabled\"}},\"required\":[\"ifa\",\"ifa_type\",\"lmt\"]},\"TokenType\":{\"title\":\"TokenType\",\"type\":\"string\",\"enum\":[\"platform\",\"device\",\"distributor\"]},\"AuthenticationTokenResult\":{\"title\":\"AuthenticationTokenResult\",\"type\":\"object\",\"properties\":{\"value\":{\"type\":\"string\"},\"expires\":{\"type\":\"string\",\"format\":\"date-time\"},\"type\":{\"type\":\"string\"}},\"required\":[\"value\"]},\"CapabilityOption\":{\"title\":\"CapabilityOption\",\"type\":\"object\",\"properties\":{\"role\":{\"$ref\":\"#/x-schemas/Capabilities/Role\",\"description\":\"Which role of the capability to check the state of, default will be 'use'\",\"default\":\"use\"}}},\"Resolution\":{\"oneOf\":[{\"type\":\"array\",\"items\":[{\"type\":\"integer\",\"const\":720,\"description\":\"Width in pixels\"},{\"type\":\"integer\",\"const\":480,\"description\":\"Height in pixels\"}],\"additionalItems\":false,\"minItems\":2,\"maxItems\":2},{\"type\":\"array\",\"items\":[{\"type\":\"integer\",\"const\":720,\"description\":\"Width in pixels\"},{\"type\":\"integer\",\"const\":576,\"description\":\"Height in pixels\"}],\"additionalItems\":false,\"minItems\":2,\"maxItems\":2},{\"type\":\"array\",\"items\":[{\"type\":\"integer\",\"const\":1280,\"description\":\"Width in pixels\"},{\"type\":\"integer\",\"const\":720,\"description\":\"Height in pixels\"}],\"additionalItems\":false,\"minItems\":2,\"maxItems\":2},{\"type\":\"array\",\"items\":[{\"type\":\"integer\",\"const\":1920,\"description\":\"Width in pixels\"},{\"type\":\"integer\",\"const\":1080,\"description\":\"Height in pixels\"}],\"additionalItems\":false,\"minItems\":2,\"maxItems\":2},{\"type\":\"array\",\"items\":[{\"type\":\"integer\",\"const\":3840,\"description\":\"Width in pixels\"},{\"type\":\"integer\",\"const\":2160,\"description\":\"Height in pixels\"}],\"additionalItems\":false,\"minItems\":2,\"maxItems\":2}]},\"NetworkType\":{\"title\":\"NetworkType\",\"type\":\"string\",\"enum\":[\"wifi\",\"ethernet\",\"hybrid\"],\"description\":\"The type of network that is currently active\"},\"NetworkState\":{\"title\":\"NetworkState\",\"type\":\"string\",\"enum\":[\"connected\",\"disconnected\"],\"description\":\"The type of network that is currently active\"},\"AudioProfiles\":{\"title\":\"AudioProfiles\",\"type\":\"object\",\"properties\":{\"stereo\":{\"type\":\"boolean\"},\"dolbyDigital5.1\":{\"type\":\"boolean\"},\"dolbyDigital5.1+\":{\"type\":\"boolean\"},\"dolbyAtmos\":{\"type\":\"boolean\"}},\"required\":[\"stereo\",\"dolbyDigital5.1\",\"dolbyDigital5.1+\",\"dolbyAtmos\"]},\"HDRFormatMap\":{\"title\":\"HDRFormatMap\",\"type\":\"object\",\"properties\":{\"hdr10\":{\"type\":\"boolean\"},\"hdr10Plus\":{\"type\":\"boolean\"},\"dolbyVision\":{\"type\":\"boolean\"},\"hlg\":{\"type\":\"boolean\"}},\"required\":[\"hdr10\",\"hdr10Plus\",\"dolbyVision\",\"hlg\"],\"description\":\"The type of HDR format\"},\"HDCPVersionMap\":{\"title\":\"HDCPVersionMap\",\"type\":\"object\",\"properties\":{\"hdcp1.4\":{\"type\":\"boolean\"},\"hdcp2.2\":{\"type\":\"boolean\"}},\"required\":[\"hdcp1.4\",\"hdcp2.2\"],\"description\":\"The type of HDCP versions\"},\"DeviceVersion\":{\"title\":\"DeviceVersion\",\"type\":\"object\",\"properties\":{\"sdk\":{\"$ref\":\"#/x-schemas/Types/SemanticVersion\",\"description\":\"The Firebolt SDK version\"},\"api\":{\"$ref\":\"#/x-schemas/Types/SemanticVersion\",\"description\":\"The latest Firebolt API version supported by the current device.\"},\"firmware\":{\"$ref\":\"#/x-schemas/Types/SemanticVersion\",\"description\":\"The firmware version as reported by the device\"},\"os\":{\"$ref\":\"#/x-schemas/Types/SemanticVersion\",\"description\":\"**Deprecated** Use `firmware`, instead.\"},\"debug\":{\"type\":\"string\",\"description\":\"Detailed version as a string, for debugging purposes\"}},\"required\":[\"api\",\"firmware\",\"os\"]},\"NetworkInfoResult\":{\"title\":\"NetworkInfoResult\",\"type\":\"object\",\"properties\":{\"state\":{\"$ref\":\"#/components/schemas/NetworkState\"},\"type\":{\"$ref\":\"#/components/schemas/NetworkType\"}},\"required\":[\"state\",\"type\"]},\"DiscoveryPolicy\":{\"title\":\"DiscoveryPolicy\",\"type\":\"object\",\"required\":[\"enableRecommendations\",\"shareWatchHistory\",\"rememberWatchedPrograms\"],\"properties\":{\"enableRecommendations\":{\"type\":\"boolean\",\"description\":\"Whether or not to the user has enabled history-based recommendations\"},\"shareWatchHistory\":{\"type\":\"boolean\",\"description\":\"Whether or not the user has enabled app watch history data to be shared with the platform\"},\"rememberWatchedPrograms\":{\"type\":\"boolean\",\"description\":\"Whether or not the user has enabled watch history\"}}},\"FederatedRequest\":{\"title\":\"FederatedRequest\",\"type\":\"object\",\"properties\":{\"correlationId\":{\"type\":\"string\"}},\"required\":[\"correlationId\"],\"propertyNames\":{\"enum\":[\"correlationId\",\"parameters\"]},\"examples\":[{\"correlationId\":\"xyz\"}]},\"FederatedResponse\":{\"title\":\"FederatedResponse\",\"type\":\"object\",\"properties\":{\"correlationId\":{\"type\":\"string\"}},\"required\":[\"correlationId\",\"result\"],\"propertyNames\":{\"enum\":[\"correlationId\",\"result\"]},\"examples\":[{\"correlationId\":\"xyz\"}]},\"EntityInfoFederatedRequest\":{\"title\":\"EntityInfoFederatedRequest\",\"allOf\":[{\"$ref\":\"#/components/schemas/FederatedRequest\"},{\"type\":\"object\",\"properties\":{\"parameters\":{\"$ref\":\"#/components/schemas/EntityInfoParameters\"}},\"required\":[\"correlationId\",\"parameters\"]}],\"examples\":[{\"correlationId\":\"xyz\",\"parameters\":{\"entityId\":\"345\"}}]},\"EntityInfoParameters\":{\"title\":\"EntityInfoParameters\",\"type\":\"object\",\"properties\":{\"entityId\":{\"type\":\"string\"},\"assetId\":{\"type\":\"string\"}},\"required\":[\"entityId\"],\"additionalProperties\":false,\"examples\":[{\"entityId\":\"345\"}]},\"PurchasedContentFederatedRequest\":{\"title\":\"PurchasedContentFederatedRequest\",\"allOf\":[{\"$ref\":\"#/components/schemas/FederatedRequest\"},{\"type\":\"object\",\"properties\":{\"parameters\":{\"$ref\":\"#/components/schemas/PurchasedContentParameters\"}},\"required\":[\"correlationId\",\"parameters\"]}],\"examples\":[{\"correlationId\":\"xyz\",\"parameters\":{\"limit\":100}}]},\"PurchasedContentParameters\":{\"title\":\"PurchasedContentParameters\",\"type\":\"object\",\"properties\":{\"limit\":{\"type\":\"integer\",\"minimum\":-1},\"offeringType\":{\"$ref\":\"#/x-schemas/Entertainment/OfferingType\"},\"programType\":{\"$ref\":\"#/x-schemas/Entertainment/ProgramType\"}},\"required\":[\"limit\"],\"additionalProperties\":false,\"examples\":[{\"limit\":100}]},\"Availability\":{\"title\":\"Availability\",\"type\":\"object\",\"properties\":{\"type\":{\"type\":\"string\",\"enum\":[\"channel-lineup\",\"program-lineup\"]},\"id\":{\"type\":\"string\"},\"catalogId\":{\"type\":\"string\"},\"startTime\":{\"type\":\"string\",\"format\":\"date-time\"},\"endTime\":{\"type\":\"string\",\"format\":\"date-time\"}},\"required\":[\"type\",\"id\"]},\"ContentAccessIdentifiers\":{\"title\":\"ContentAccessIdentifiers\",\"type\":\"object\",\"properties\":{\"availabilities\":{\"type\":\"array\",\"items\":{\"$ref\":\"#/components/schemas/Availability\"},\"description\":\"A list of identifiers that represent what content is discoverable for the subscriber. Excluding availabilities will cause no change to the availabilities that are stored for this subscriber. Providing an empty array will clear the subscriber's availabilities\"},\"entitlements\":{\"type\":\"array\",\"items\":{\"$ref\":\"#/x-schemas/Entertainment/Entitlement\"},\"description\":\"A list of identifiers that represent what content is consumable for the subscriber. Excluding entitlements will cause no change to the entitlements that are stored for this subscriber. Providing an empty array will clear the subscriber's entitlements\"}},\"required\":[]},\"UserInterestProviderParameters\":{\"title\":\"UserInterestProviderParameters\",\"type\":\"object\",\"required\":[\"type\",\"reason\"],\"properties\":{\"type\":{\"$ref\":\"#/x-schemas/Discovery/InterestType\"},\"reason\":{\"$ref\":\"#/x-schemas/Discovery/InterestReason\"}}},\"HDMIPortId\":{\"type\":\"string\",\"pattern\":\"^HDMI[0-9]+$\"},\"EDIDVersion\":{\"title\":\"EDIDVersion\",\"type\":\"string\",\"enum\":[\"1.4\",\"2.0\",\"unknown\"]},\"HDMISignalStatus\":{\"type\":\"string\",\"enum\":[\"none\",\"stable\",\"unstable\",\"unsupported\",\"unknown\"]},\"EmailUsage\":{\"title\":\"EmailUsage\",\"type\":\"string\",\"enum\":[\"signIn\",\"signUp\"]},\"KeyboardParameters\":{\"title\":\"KeyboardParameters\",\"type\":\"object\",\"required\":[\"message\"],\"properties\":{\"message\":{\"description\":\"The message to display to the user so the user knows what they are entering\",\"type\":\"string\"}},\"examples\":[{\"type\":\"standard\",\"message\":\"Enter your user name.\"}]},\"LifecycleEvent\":{\"title\":\"LifecycleEvent\",\"description\":\"A an object describing the previous and current states\",\"type\":\"object\",\"required\":[\"state\",\"previous\"],\"properties\":{\"state\":{\"$ref\":\"#/x-schemas/Lifecycle/LifecycleState\",\"description\":\"The current lifcycle state\"},\"previous\":{\"$ref\":\"#/x-schemas/Lifecycle/LifecycleState\",\"description\":\"The previous lifcycle state\"},\"source\":{\"type\":\"string\",\"enum\":[\"voice\",\"remote\"],\"description\":\"The source of the lifecycle change.\"}}},\"LatLon\":{\"type\":\"array\",\"items\":[{\"type\":\"number\"},{\"type\":\"number\"}],\"additionalItems\":false,\"minItems\":2,\"maxItems\":2},\"MediaPosition\":{\"title\":\"MediaPosition\",\"description\":\"Represents a position inside playback content, as a decimal percentage (0-0.999) for content with a known duration, or an integer number of seconds (0-86400) for content with an unknown duration.\",\"oneOf\":[{\"const\":0},{\"type\":\"number\",\"exclusiveMinimum\":0,\"exclusiveMaximum\":1},{\"type\":\"integer\",\"minimum\":1,\"maximum\":86400}]},\"ErrorType\":{\"title\":\"ErrorType\",\"type\":\"string\",\"enum\":[\"network\",\"media\",\"restriction\",\"entitlement\",\"other\"]},\"EventObjectPrimitives\":{\"title\":\"EventObjectPrimitives\",\"anyOf\":[{\"type\":\"string\",\"maxLength\":256},{\"type\":\"number\"},{\"type\":\"integer\"},{\"type\":\"boolean\"},{\"type\":\"null\"}]},\"EventObject\":{\"title\":\"EventObject\",\"type\":\"object\",\"maxProperties\":256,\"additionalProperties\":{\"anyOf\":[{\"$ref\":\"#/components/schemas/EventObjectPrimitives\"},{\"type\":\"array\",\"maxItems\":256,\"items\":{\"anyOf\":[{\"$ref\":\"#/components/schemas/EventObjectPrimitives\"},{\"$ref\":\"#/components/schemas/EventObject\"}]}},{\"$ref\":\"#/components/schemas/EventObject\"}]}},\"AppInitialization\":{\"title\":\"AppInitialization\",\"type\":\"object\",\"properties\":{\"us_privacy\":{\"type\":\"string\",\"description\":\"The IAB US Privacy string.\"},\"lmt\":{\"type\":\"integer\",\"description\":\"The IAB limit ad tracking opt out value.\"},\"discovery\":{\"type\":\"object\",\"properties\":{\"navigateTo\":{\"$ref\":\"#/x-schemas/Intents/NavigationIntent\"}}},\"secondScreen\":{\"type\":\"object\",\"properties\":{\"launchRequest\":{\"$ref\":\"#/x-schemas/SecondScreen/SecondScreenEvent\"}}}}},\"PinChallenge\":{\"title\":\"PinChallenge\",\"type\":\"object\",\"required\":[\"requestor\",\"pinSpace\"],\"properties\":{\"pinSpace\":{\"type\":\"string\",\"description\":\"The pin space that this challenge is for\",\"enum\":[\"purchase\",\"content\"]},\"capability\":{\"type\":\"string\",\"description\":\"The capability that is gated by a pin challenge\"},\"requestor\":{\"description\":\"The identity of which app is requesting access to this capability\",\"$ref\":\"#/components/schemas/ChallengeRequestor\"}}},\"ResultReason\":{\"title\":\"ResultReason\",\"type\":\"string\",\"description\":\"The reason for the result of challenging the user\",\"enum\":[\"noPinRequired\",\"noPinRequiredWindow\",\"exceededPinFailures\",\"correctPin\",\"cancelled\"]},\"StorageScope\":{\"title\":\"StorageScope\",\"type\":\"string\",\"enum\":[\"device\",\"account\"],\"description\":\"The scope of the data\"},\"StorageOptions\":{\"title\":\"StorageOptions\",\"type\":\"object\",\"required\":[\"ttl\"],\"properties\":{\"ttl\":{\"type\":\"number\",\"description\":\"Seconds from set time before the data expires and is removed\"}}},\"AppInfo\":{\"description\":\"Information about an app that a grant was for\",\"type\":\"object\",\"properties\":{\"id\":{\"type\":\"string\"},\"title\":{\"type\":\"string\"}},\"additionalProperties\":false,\"required\":[\"id\"]},\"GrantState\":{\"description\":\"The state the grant is in\",\"type\":\"string\",\"enum\":[\"granted\",\"denied\"]},\"WifiSecurityMode\":{\"title\":\"WifiSecurityMode\",\"description\":\"Security Mode supported for Wifi\",\"type\":\"string\",\"enum\":[\"none\",\"wep64\",\"wep128\",\"wpaPskTkip\",\"wpaPskAes\",\"wpa2PskTkip\",\"wpa2PskAes\",\"wpaEnterpriseTkip\",\"wpaEnterpriseAes\",\"wpa2EnterpriseTkip\",\"wpa2EnterpriseAes\",\"wpa2Psk\",\"wpa2Enterprise\",\"wpa3PskAes\",\"wpa3Sae\"]},\"WifiSignalStrength\":{\"title\":\"WifiSignalStrength\",\"description\":\"Strength of Wifi signal, value is negative based on RSSI specification.\",\"type\":\"integer\",\"default\":-255,\"minimum\":-255,\"maximum\":0},\"WifiFrequency\":{\"title\":\"WifiFrequency\",\"description\":\"Wifi Frequency in Ghz, example 2.4Ghz and 5Ghz.\",\"type\":\"number\",\"default\":0,\"minimum\":0},\"AccessPoint\":{\"title\":\"AccessPoint\",\"description\":\"Properties of a scanned wifi list item.\",\"type\":\"object\",\"properties\":{\"ssid\":{\"type\":\"string\",\"description\":\"Name of the wifi.\"},\"securityMode\":{\"$ref\":\"#/components/schemas/WifiSecurityMode\"},\"signalStrength\":{\"$ref\":\"#/components/schemas/WifiSignalStrength\"},\"frequency\":{\"$ref\":\"#/components/schemas/WifiFrequency\"}}}}},\"x-schemas\":{\"Types\":{\"uri\":\"https://meta.comcast.com/firebolt/types\",\"SemanticVersion\":{\"title\":\"SemanticVersion\",\"type\":\"object\",\"properties\":{\"major\":{\"type\":\"integer\",\"minimum\":0},\"minor\":{\"type\":\"integer\",\"minimum\":0},\"patch\":{\"type\":\"integer\",\"minimum\":0},\"readable\":{\"type\":\"string\"}},\"required\":[\"major\",\"minor\",\"patch\",\"readable\"],\"additionalProperties\":false},\"ListenResponse\":{\"title\":\"ListenResponse\",\"type\":\"object\",\"required\":[\"event\",\"listening\"],\"properties\":{\"event\":{\"type\":\"string\",\"pattern\":\"[a-zA-Z]+\\\\.on[A-Z][a-zA-Z]+\"},\"listening\":{\"type\":\"boolean\"}},\"additionalProperties\":false},\"ProviderRequest\":{\"title\":\"ProviderRequest\",\"type\":\"object\",\"required\":[\"correlationId\"],\"additionalProperties\":false,\"properties\":{\"correlationId\":{\"type\":\"string\",\"description\":\"The id that was passed in to the event that triggered a provider method to be called\"},\"parameters\":{\"description\":\"The result of the provider response.\",\"type\":[\"object\",\"null\"]}}},\"AudioProfile\":{\"title\":\"AudioProfile\",\"type\":\"string\",\"enum\":[\"stereo\",\"dolbyDigital5.1\",\"dolbyDigital5.1+\",\"dolbyAtmos\"]},\"LocalizedString\":{\"title\":\"LocalizedString\",\"description\":\"Localized string supports either a simple `string` or a Map of language codes to strings. When using a simple `string`, the current preferred langauge from `Localization.langauge()` is assumed.\",\"oneOf\":[{\"type\":\"string\"},{\"type\":\"object\",\"additionalProperties\":{\"type\":\"string\"}}],\"examples\":[\"A simple string, with no language code\",{\"en\":\"This is english\",\"es\":\"esto es español\"}]},\"FlatMap\":{\"type\":\"object\",\"additionalProperties\":{\"oneOf\":[{\"type\":\"string\"},{\"type\":\"number\"},{\"type\":\"boolean\"}]}},\"BooleanMap\":{\"title\":\"BooleanMap\",\"type\":\"object\",\"additionalProperties\":{\"type\":\"boolean\"}},\"Timeout\":{\"title\":\"Timeout\",\"description\":\"Defines the timeout in seconds. If the threshold for timeout is passed for any operation without a result it will throw an error.\",\"type\":\"integer\",\"default\":0,\"minimum\":0,\"maximum\":9999}},\"Accessibility\":{\"uri\":\"https://meta.comcast.com/firebolt/accessibility\",\"ClosedCaptionsSettings\":{\"title\":\"ClosedCaptionsSettings\",\"type\":\"object\",\"required\":[\"enabled\"],\"properties\":{\"enabled\":{\"type\":\"boolean\",\"description\":\"Whether or not closed-captions should be enabled by default\"},\"styles\":{\"$ref\":\"#/x-schemas/Accessibility/ClosedCaptionsStyles\"},\"preferredLanguages\":{\"type\":\"array\",\"items\":{\"$ref\":\"#/x-schemas/Localization/ISO639_2Language\"}}},\"examples\":[{\"enabled\":true,\"styles\":{\"fontFamily\":\"monospaced_serif\",\"fontSize\":1,\"fontColor\":\"#ffffff\",\"fontEdge\":\"none\",\"fontEdgeColor\":\"#7F7F7F\",\"fontOpacity\":100,\"backgroundColor\":\"#000000\",\"backgroundOpacity\":100,\"textAlign\":\"center\",\"textAlignVertical\":\"middle\",\"windowColor\":\"white\",\"windowOpacity\":50},\"preferredLanguages\":[\"eng\",\"spa\"]}]},\"VoiceGuidanceSettings\":{\"title\":\"VoiceGuidanceSettings\",\"type\":\"object\",\"required\":[\"enabled\"],\"properties\":{\"enabled\":{\"type\":\"boolean\",\"description\":\"Whether or not voice guidance should be enabled by default\"},\"speed\":{\"$ref\":\"#/x-schemas/Accessibility/VoiceSpeed\",\"description\":\"The speed at which voice guidance speech will be read back to the user\"}},\"examples\":[{\"enabled\":true,\"speed\":2}]},\"VoiceSpeed\":{\"title\":\"VoiceSpeed\",\"type\":\"number\",\"minimum\":0.5,\"maximum\":2},\"ClosedCaptionsStyles\":{\"title\":\"ClosedCaptionsStyles\",\"type\":\"object\",\"description\":\"The default styles to use when displaying closed-captions\",\"properties\":{\"fontFamily\":{\"$ref\":\"#/x-schemas/Accessibility/FontFamily\"},\"fontSize\":{\"$ref\":\"#/x-schemas/Accessibility/FontSize\"},\"fontColor\":{\"$ref\":\"#/x-schemas/Accessibility/Color\"},\"fontEdge\":{\"$ref\":\"#/x-schemas/Accessibility/FontEdge\"},\"fontEdgeColor\":{\"$ref\":\"#/x-schemas/Accessibility/Color\"},\"fontOpacity\":{\"$ref\":\"#/x-schemas/Accessibility/Opacity\"},\"backgroundColor\":{\"$ref\":\"#/x-schemas/Accessibility/Color\"},\"backgroundOpacity\":{\"$ref\":\"#/x-schemas/Accessibility/Opacity\"},\"textAlign\":{\"$ref\":\"#/x-schemas/Accessibility/HorizontalAlignment\"},\"textAlignVertical\":{\"$ref\":\"#/x-schemas/Accessibility/VerticalAlignment\"},\"windowColor\":{\"$ref\":\"#/x-schemas/Accessibility/Color\"},\"windowOpacity\":{\"$ref\":\"#/x-schemas/Accessibility/Opacity\"}}},\"FontFamily\":{\"type\":[\"string\",\"null\"],\"enum\":[\"monospaced_serif\",\"proportional_serif\",\"monospaced_sanserif\",\"proportional_sanserif\",\"smallcaps\",\"cursive\",\"casual\",null]},\"FontSize\":{\"type\":[\"number\",\"null\"],\"minimum\":0},\"Color\":{\"type\":[\"string\",\"null\"]},\"FontEdge\":{\"type\":[\"string\",\"null\"],\"enum\":[\"none\",\"raised\",\"depressed\",\"uniform\",\"drop_shadow_left\",\"drop_shadow_right\",null]},\"Opacity\":{\"type\":[\"number\",\"null\"],\"minimum\":0,\"maximum\":100},\"HorizontalAlignment\":{\"type\":[\"string\",\"null\"]},\"VerticalAlignment\":{\"type\":[\"string\",\"null\"]}},\"Localization\":{\"uri\":\"https://meta.comcast.com/firebolt/localization\",\"ISO639_2Language\":{\"type\":\"string\",\"pattern\":\"^[a-z]{3}$\"},\"Locality\":{\"type\":\"string\"},\"CountryCode\":{\"type\":\"string\",\"pattern\":\"^[A-Z]{2}$\"},\"Language\":{\"type\":\"string\",\"pattern\":\"^[A-Za-z]{2}$\"},\"Locale\":{\"type\":\"string\",\"pattern\":\"^[a-zA-Z]+([a-zA-Z0-9\\\\-]*)$\"},\"TimeZone\":{\"type\":\"string\",\"pattern\":\"^[-+_/ A-Za-z 0-9]*$\"}},\"Advertising\":{\"uri\":\"https://meta.comcast.com/firebolt/advertising\",\"SkipRestriction\":{\"title\":\"SkipRestriction\",\"$comment\":\"xrn:advertising:policy:skipRestriction:\",\"type\":\"string\",\"enum\":[\"none\",\"adsUnwatched\",\"adsAll\",\"all\"],\"description\":\"The advertisement skip restriction.\\n\\nApplies to fast-forward/rewind (e.g. trick mode), seeking over an entire opportunity (e.g. jump), seeking out of what's currently playing, and \\\"Skip this ad...\\\" features. Seeking over multiple ad opportunities only requires playback of the _last_ opportunity, not all opportunities, preceding the seek destination.\\n\\n| Value | Description |\\n|--------------|--------------------------------------------------------------------------------|\\n| none |No fast-forward, jump, or skip restrictions |\\n| adsUnwatched | Restrict fast-forward, jump, and skip for unwatched ad opportunities only. |\\n| adsAll | Restrict fast-forward, jump, and skip for all ad opportunities |\\n| all | Restrict fast-forward, jump, and skip for all ad opportunities and all content |\\n\\nNamespace: `xrn:advertising:policy:skipRestriction:`\\n\\n\"}},\"Capabilities\":{\"uri\":\"https://meta.comcast.com/firebolt/capabilities\",\"Capability\":{\"title\":\"Capability\",\"type\":\"string\",\"description\":\"A Capability is a discrete unit of functionality that a Firebolt device might be able to perform.\",\"pattern\":\"^xrn:firebolt:capability:([a-z0-9\\\\-]+)((:[a-z0-9\\\\-]+)?)$\"},\"CapabilityInfo\":{\"title\":\"CapabilityInfo\",\"type\":\"object\",\"required\":[\"supported\",\"available\",\"use\",\"manage\",\"provide\"],\"properties\":{\"capability\":{\"$ref\":\"#/x-schemas/Capabilities/Capability\"},\"supported\":{\"type\":\"boolean\",\"description\":\"Provides info whether the capability is supported\"},\"available\":{\"type\":\"boolean\",\"description\":\"Provides info whether the capability is available\"},\"use\":{\"$ref\":\"#/x-schemas/Capabilities/CapPermissionStatus\"},\"manage\":{\"$ref\":\"#/x-schemas/Capabilities/CapPermissionStatus\"},\"provide\":{\"$ref\":\"#/x-schemas/Capabilities/CapPermissionStatus\"},\"details\":{\"type\":\"array\",\"items\":{\"$ref\":\"#/x-schemas/Capabilities/DenyReason\"},\"minItems\":1,\"maxItems\":6}},\"additionalProperties\":false,\"examples\":[{\"capability\":\"xrn:firebolt:capability:keyboard\",\"supported\":true,\"available\":true,\"use\":{\"permitted\":true,\"granted\":true},\"manage\":{\"permitted\":true,\"granted\":true},\"provide\":{\"permitted\":true,\"granted\":true}}]},\"Permission\":{\"title\":\"Permission\",\"description\":\"A capability combined with a Role, which an app may be permitted (by a distributor) or granted (by an end user).\",\"type\":\"object\",\"required\":[\"capability\"],\"properties\":{\"role\":{\"$ref\":\"#/x-schemas/Capabilities/Role\"},\"capability\":{\"$ref\":\"#/x-schemas/Capabilities/Capability\"}},\"additionalProperties\":false},\"Role\":{\"title\":\"Role\",\"description\":\"Role provides access level for the app for a given capability.\",\"type\":\"string\",\"enum\":[\"use\",\"manage\",\"provide\"]},\"CapPermissionStatus\":{\"type\":\"object\",\"properties\":{\"permitted\":{\"type\":\"boolean\",\"description\":\"Provides info whether the capability is permitted\"},\"granted\":{\"oneOf\":[{\"type\":\"boolean\",\"description\":\"Provides info whether the capability is granted\"},{\"const\":null}]}},\"additionalProperties\":false},\"DenyReason\":{\"title\":\"DenyReason\",\"description\":\"Reasons why a Capability might not be invokable\",\"type\":\"string\",\"enum\":[\"unpermitted\",\"unsupported\",\"disabled\",\"unavailable\",\"grantDenied\",\"ungranted\"]}},\"Discovery\":{\"uri\":\"https://meta.comcast.com/firebolt/discovery\",\"InterestType\":{\"title\":\"InterestType\",\"type\":\"string\",\"enum\":[\"interest\",\"disinterest\"]},\"InterestReason\":{\"title\":\"InterestReason\",\"type\":\"string\",\"enum\":[\"playlist\",\"reaction\",\"recording\"]},\"EntityInfoResult\":{\"title\":\"EntityInfoResult\",\"description\":\"The result for an `entityInfo()` push or pull.\",\"type\":\"object\",\"properties\":{\"expires\":{\"type\":\"string\",\"format\":\"date-time\"},\"entity\":{\"$ref\":\"#/x-schemas/Entertainment/EntityInfo\"},\"related\":{\"type\":\"array\",\"items\":{\"$ref\":\"#/x-schemas/Entertainment/EntityInfo\"}}},\"required\":[\"expires\",\"entity\"],\"additionalProperties\":false},\"PurchasedContentResult\":{\"title\":\"PurchasedContentResult\",\"type\":\"object\",\"properties\":{\"expires\":{\"type\":\"string\",\"format\":\"date-time\"},\"totalCount\":{\"type\":\"integer\",\"minimum\":0},\"entries\":{\"type\":\"array\",\"items\":{\"$ref\":\"#/x-schemas/Entertainment/EntityInfo\"}}},\"required\":[\"expires\",\"totalCount\",\"entries\"],\"additionalProperties\":false}},\"Entity\":{\"uri\":\"https://meta.comcast.com/firebolt/entity\",\"EntityDetails\":{\"title\":\"EntityDetails\",\"type\":\"object\",\"required\":[\"identifiers\"],\"properties\":{\"identifiers\":{\"$ref\":\"#/x-schemas/Entity/Entity\"},\"info\":{\"$ref\":\"#/x-schemas/Entity/Metadata\"},\"waysToWatch\":{\"type\":\"array\",\"items\":{\"$ref\":\"#/x-schemas/Entertainment/WayToWatch\"},\"description\":\"An array of ways a user is might watch this entity, regardless of entitlements.\"}}},\"Entity\":{\"oneOf\":[{\"$ref\":\"#/x-schemas/Entity/ProgramEntity\"},{\"$ref\":\"#/x-schemas/Entity/MusicEntity\"},{\"$ref\":\"#/x-schemas/Entity/ChannelEntity\"},{\"$ref\":\"#/x-schemas/Entity/UntypedEntity\"},{\"$ref\":\"#/x-schemas/Entity/PlaylistEntity\"}]},\"Metadata\":{\"title\":\"Metadata\",\"type\":\"object\",\"properties\":{\"title\":{\"type\":\"string\",\"description\":\"Title of the entity.\"},\"synopsis\":{\"type\":\"string\",\"description\":\"Short description of the entity.\"},\"seasonNumber\":{\"type\":\"number\",\"description\":\"For TV seasons, the season number. For TV episodes, the season that the episode belongs to.\"},\"seasonCount\":{\"type\":\"number\",\"description\":\"For TV series, seasons, and episodes, the total number of seasons.\"},\"episodeNumber\":{\"type\":\"number\",\"description\":\"For TV episodes, the episode number.\"},\"episodeCount\":{\"type\":\"number\",\"description\":\"For TV seasons and episodes, the total number of episodes in the current season.\"},\"releaseDate\":{\"type\":\"string\",\"format\":\"date-time\",\"description\":\"The date that the program or entity was released or first aired.\"},\"contentRatings\":{\"type\":\"array\",\"items\":{\"$ref\":\"#/x-schemas/Entertainment/ContentRating\"},\"description\":\"A list of ContentRating objects, describing the entity's ratings in various rating schemes.\"}}},\"ProgramEntity\":{\"title\":\"ProgramEntity\",\"oneOf\":[{\"$ref\":\"#/x-schemas/Entity/MovieEntity\"},{\"$ref\":\"#/x-schemas/Entity/TVEpisodeEntity\"},{\"$ref\":\"#/x-schemas/Entity/TVSeasonEntity\"},{\"$ref\":\"#/x-schemas/Entity/TVSeriesEntity\"},{\"$ref\":\"#/x-schemas/Entity/AdditionalEntity\"}]},\"MusicEntity\":{\"title\":\"MusicEntity\",\"type\":\"object\",\"properties\":{\"entityType\":{\"const\":\"music\"},\"musicType\":{\"$ref\":\"#/x-schemas/Entertainment/MusicType\"},\"entityId\":{\"type\":\"string\"}},\"required\":[\"entityType\",\"musicType\",\"entityId\"]},\"ChannelEntity\":{\"title\":\"ChannelEntity\",\"type\":\"object\",\"properties\":{\"entityType\":{\"const\":\"channel\"},\"channelType\":{\"type\":\"string\",\"enum\":[\"streaming\",\"overTheAir\"]},\"entityId\":{\"type\":\"string\",\"description\":\"ID of the channel, in the target App's scope.\"},\"appContentData\":{\"type\":\"string\",\"maxLength\":256}},\"required\":[\"entityType\",\"channelType\",\"entityId\"],\"additionalProperties\":false},\"UntypedEntity\":{\"title\":\"UntypedEntity\",\"allOf\":[{\"description\":\"A Firebolt compliant representation of the remaining entity types.\",\"type\":\"object\",\"required\":[\"entityId\"],\"properties\":{\"entityId\":{\"type\":\"string\"},\"assetId\":{\"type\":\"string\"},\"appContentData\":{\"type\":\"string\",\"maxLength\":256}},\"additionalProperties\":false}],\"examples\":[{\"entityId\":\"an-entity\"}]},\"PlaylistEntity\":{\"title\":\"PlaylistEntity\",\"description\":\"A Firebolt compliant representation of a Playlist entity.\",\"type\":\"object\",\"required\":[\"entityType\",\"entityId\"],\"properties\":{\"entityType\":{\"const\":\"playlist\"},\"entityId\":{\"type\":\"string\"},\"assetId\":{\"type\":\"string\"},\"appContentData\":{\"type\":\"string\",\"maxLength\":256}},\"additionalProperties\":false,\"examples\":[{\"entityType\":\"playlist\",\"entityId\":\"playlist/xyz\"}]},\"MovieEntity\":{\"title\":\"MovieEntity\",\"description\":\"A Firebolt compliant representation of a Movie entity.\",\"type\":\"object\",\"required\":[\"entityType\",\"programType\",\"entityId\"],\"properties\":{\"entityType\":{\"const\":\"program\"},\"programType\":{\"const\":\"movie\"},\"entityId\":{\"type\":\"string\"},\"assetId\":{\"type\":\"string\"},\"appContentData\":{\"type\":\"string\",\"maxLength\":256}},\"additionalProperties\":false,\"examples\":[{\"entityType\":\"program\",\"programType\":\"movie\",\"entityId\":\"el-camino\"}]},\"TVEpisodeEntity\":{\"title\":\"TVEpisodeEntity\",\"description\":\"A Firebolt compliant representation of a TV Episode entity.\",\"type\":\"object\",\"required\":[\"entityType\",\"programType\",\"entityId\",\"seriesId\",\"seasonId\"],\"properties\":{\"entityType\":{\"const\":\"program\"},\"programType\":{\"const\":\"episode\"},\"entityId\":{\"type\":\"string\"},\"seriesId\":{\"type\":\"string\"},\"seasonId\":{\"type\":\"string\"},\"assetId\":{\"type\":\"string\"},\"appContentData\":{\"type\":\"string\",\"maxLength\":256}},\"additionalProperties\":false,\"examples\":[{\"entityType\":\"program\",\"programType\":\"episode\",\"entityId\":\"breaking-bad-pilot\",\"seriesId\":\"breaking-bad\",\"seasonId\":\"breaking-bad-season-1\"}]},\"TVSeasonEntity\":{\"title\":\"TVSeasonEntity\",\"description\":\"A Firebolt compliant representation of a TV Season entity.\",\"type\":\"object\",\"required\":[\"entityType\",\"programType\",\"entityId\",\"seriesId\"],\"properties\":{\"entityType\":{\"const\":\"program\"},\"programType\":{\"const\":\"season\"},\"entityId\":{\"type\":\"string\"},\"seriesId\":{\"type\":\"string\"},\"assetId\":{\"type\":\"string\"},\"appContentData\":{\"type\":\"string\",\"maxLength\":256}},\"additionalProperties\":false,\"examples\":[{\"entityType\":\"program\",\"programType\":\"season\",\"entityId\":\"breaking-bad-season-1\",\"seriesId\":\"breaking-bad\"}]},\"TVSeriesEntity\":{\"title\":\"TVSeriesEntity\",\"description\":\"A Firebolt compliant representation of a TV Series entity.\",\"type\":\"object\",\"required\":[\"entityType\",\"programType\",\"entityId\"],\"properties\":{\"entityType\":{\"const\":\"program\"},\"programType\":{\"const\":\"series\"},\"entityId\":{\"type\":\"string\"},\"assetId\":{\"type\":\"string\"},\"appContentData\":{\"type\":\"string\",\"maxLength\":256}},\"additionalProperties\":false,\"examples\":[{\"entityType\":\"program\",\"programType\":\"series\",\"entityId\":\"breaking-bad\"}]},\"AdditionalEntity\":{\"title\":\"AdditionalEntity\",\"description\":\"A Firebolt compliant representation of the remaining program entity types.\",\"type\":\"object\",\"required\":[\"entityType\",\"programType\",\"entityId\"],\"properties\":{\"entityType\":{\"const\":\"program\"},\"programType\":{\"type\":\"string\",\"enum\":[\"concert\",\"sportingEvent\",\"preview\",\"other\",\"advertisement\",\"musicVideo\",\"minisode\",\"extra\"]},\"entityId\":{\"type\":\"string\"},\"assetId\":{\"type\":\"string\"},\"appContentData\":{\"type\":\"string\",\"maxLength\":256}},\"additionalProperties\":false,\"examples\":[{\"entityType\":\"program\",\"programType\":\"concert\",\"entityId\":\"live-aid\"}]},\"PlayableEntity\":{\"title\":\"PlayableEntity\",\"anyOf\":[{\"$ref\":\"#/x-schemas/Entity/MovieEntity\"},{\"$ref\":\"#/x-schemas/Entity/TVEpisodeEntity\"},{\"$ref\":\"#/x-schemas/Entity/PlaylistEntity\"},{\"$ref\":\"#/x-schemas/Entity/MusicEntity\"},{\"$ref\":\"#/x-schemas/Entity/AdditionalEntity\"}]}},\"Entertainment\":{\"uri\":\"https://meta.comcast.com/firebolt/entertainment\",\"WayToWatch\":{\"title\":\"WayToWatch\",\"type\":\"object\",\"required\":[\"identifiers\",\"audioProfile\"],\"properties\":{\"identifiers\":{\"$ref\":\"#/x-schemas/Entertainment/ContentIdentifiers\"},\"expires\":{\"type\":\"string\",\"format\":\"date-time\",\"description\":\"Time when the WayToWatch is no longer available.\"},\"entitled\":{\"type\":\"boolean\",\"description\":\"Specify if the user is entitled to watch the entity.\"},\"entitledExpires\":{\"type\":\"string\",\"format\":\"date-time\",\"description\":\"Time when the entity is no longer entitled.\"},\"offeringType\":{\"$ref\":\"#/x-schemas/Entertainment/OfferingType\"},\"hasAds\":{\"type\":\"boolean\",\"description\":\"True if the streamable asset contains ads.\"},\"price\":{\"type\":\"number\",\"description\":\"For \\\"buy\\\" and \\\"rent\\\" WayToWatch, the price to buy or rent in the user's preferred currency.\"},\"videoQuality\":{\"type\":\"array\",\"items\":{\"type\":\"string\",\"enum\":[\"SD\",\"HD\",\"UHD\"]},\"description\":\"List of the video qualities available via the WayToWatch.\"},\"audioProfile\":{\"type\":\"array\",\"items\":{\"$ref\":\"#/x-schemas/Types/AudioProfile\"},\"description\":\"List of the audio types available via the WayToWatch.\"},\"audioLanguages\":{\"type\":\"array\",\"items\":{\"type\":\"string\"},\"description\":\"List of audio track languages available on the WayToWatch. The first is considered the primary language. Languages are expressed as ISO 639 1/2 codes.\"},\"closedCaptions\":{\"type\":\"array\",\"items\":{\"type\":\"string\"},\"description\":\"List of languages for which closed captions are available on the WayToWatch. Languages are expressed as ISO 639 1/2 codes.\"},\"subtitles\":{\"type\":\"array\",\"items\":{\"type\":\"string\"},\"description\":\"List of languages for which subtitles are available on the WayToWatch. Languages are expressed as ISO 639 1/2 codes.\"},\"audioDescriptions\":{\"type\":\"array\",\"items\":{\"type\":\"string\"},\"description\":\"List of languages for which audio descriptions (DVD) as available on the WayToWatch. Languages are expressed as ISO 639 1/2 codes.\"}},\"description\":\"A WayToWatch describes a way to watch a video program. It may describe a single\\nstreamable asset or a set of streamable assets. For example, an app provider may\\ndescribe HD, SD, and UHD assets as individual WayToWatch objects or rolled into\\na single WayToWatch.\\n\\nIf the WayToWatch represents a single streamable asset, the provided\\nContentIdentifiers must be sufficient to play back the specific asset when sent\\nvia a playback intent or deep link. If the WayToWatch represents multiple\\nstreamable assets, the provided ContentIdentifiers must be sufficient to\\nplayback one of the assets represented with no user action. In this scenario,\\nthe app SHOULD choose the best asset for the user based on their device and\\nsettings. The ContentIdentifiers MUST also be sufficient for navigating the user\\nto the appropriate entity or detail screen via an entity intent.\\n\\nThe app should set the `entitled` property to indicate if the user can watch, or\\nnot watch, the asset without making a purchase. If the entitlement is known to\\nexpire at a certain time (e.g., a rental), the app should also provide the\\n`entitledExpires` property. If the entitlement is not expired, the UI will use\\nthe `entitled` property to display watchable assets to the user, adjust how\\nassets are presented to the user, and how intents into the app are generated.\\nFor example, the the Aggregated Experience could render a \\\"Watch\\\" button for an\\nentitled asset versus a \\\"Subscribe\\\" button for an non-entitled asset.\\n\\nThe app should set the `offeringType` to define how the content may be\\nauthorized. The UI will use this to adjust how content is presented to the user.\\n\\nA single WayToWatch cannot represent streamable assets available via multiple\\npurchase paths. If, for example, an asset has both Buy, Rent and Subscription\\navailability, the three different entitlement paths MUST be represented as\\nmultiple WayToWatch objects.\\n\\n`price` should be populated for WayToWatch objects with `buy` or `rent`\\n`offeringType`. If the WayToWatch represents a set of assets with various price\\npoints, the `price` provided must be the lowest available price.\"},\"OfferingType\":{\"title\":\"OfferingType\",\"type\":\"string\",\"enum\":[\"free\",\"subscribe\",\"buy\",\"rent\"],\"description\":\"The offering type of the WayToWatch.\"},\"ContentIdentifiers\":{\"title\":\"ContentIdentifiers\",\"type\":\"object\",\"properties\":{\"assetId\":{\"type\":\"string\",\"description\":\"Identifies a particular playable asset. For example, the HD version of a particular movie separate from the UHD version.\"},\"entityId\":{\"type\":\"string\",\"description\":\"Identifies an entity, such as a Movie, TV Series or TV Episode.\"},\"seasonId\":{\"type\":\"string\",\"description\":\"The TV Season for a TV Episode.\"},\"seriesId\":{\"type\":\"string\",\"description\":\"The TV Series for a TV Episode or TV Season.\"},\"appContentData\":{\"type\":\"string\",\"description\":\"App-specific content identifiers.\",\"maxLength\":1024}},\"description\":\"The ContentIdentifiers object is how the app identifies an entity or asset to\\nthe Firebolt platform. These ids are used to look up metadata and deep link into\\nthe app.\\n\\nApps do not need to provide all ids. They only need to provide the minimum\\nrequired to target a playable stream or an entity detail screen via a deep link.\\nIf an id isn't needed to get to those pages, it doesn't need to be included.\"},\"ContentRating\":{\"title\":\"ContentRating\",\"type\":\"object\",\"required\":[\"scheme\",\"rating\"],\"properties\":{\"scheme\":{\"type\":\"string\",\"enum\":[\"CA-Movie\",\"CA-TV\",\"CA-Movie-Fr\",\"CA-TV-Fr\",\"US-Movie\",\"US-TV\"],\"description\":\"The rating scheme.\"},\"rating\":{\"type\":\"string\",\"description\":\"The content rating.\"},\"advisories\":{\"type\":\"array\",\"items\":{\"type\":\"string\"},\"description\":\"Optional list of subratings or content advisories.\"}},\"description\":\"A ContentRating represents an age or content based of an entity. Supported rating schemes and associated types are below.\\n\\n## United States\\n\\n`US-Movie` (MPAA):\\n\\nRatings: `NR`, `G`, `PG`, `PG13`, `R`, `NC17`\\n\\nAdvisories: `AT`, `BN`, `SL`, `SS`, `N`, `V`\\n\\n`US-TV` (Vchip):\\n\\nRatings: `TVY`, `TVY7`, `TVG`, `TVPG`, `TV14`, `TVMA`\\n\\nAdvisories: `FV`, `D`, `L`, `S`, `V`\\n\\n## Canada\\n\\n`CA-Movie` (OFRB):\\n\\nRatings: `G`, `PG`, `14A`, `18A`, `R`, `E`\\n\\n`CA-TV` (AGVOT)\\n\\nRatings: `E`, `C`, `C8`, `G`, `PG`, `14+`, `18+`\\n\\nAdvisories: `C`, `C8`, `G`, `PG`, `14+`, `18+`\\n\\n`CA-Movie-Fr` (Canadian French language movies):\\n\\nRatings: `G`, `8+`, `13+`, `16+`, `18+`\\n\\n`CA-TV-Fr` (Canadian French language TV):\\n\\nRatings: `G`, `8+`, `13+`, `16+`, `18+`\\n\"},\"MusicType\":{\"title\":\"MusicType\",\"type\":\"string\",\"description\":\"In the case of a music `entityType`, specifies the type of music entity.\",\"enum\":[\"song\",\"album\"]},\"Entitlement\":{\"title\":\"Entitlement\",\"type\":\"object\",\"properties\":{\"entitlementId\":{\"type\":\"string\"},\"startTime\":{\"type\":\"string\",\"format\":\"date-time\"},\"endTime\":{\"type\":\"string\",\"format\":\"date-time\"}},\"required\":[\"entitlementId\"]},\"EntityInfo\":{\"title\":\"EntityInfo\",\"description\":\"An EntityInfo object represents an \\\"entity\\\" on the platform. Currently, only entities of type `program` are supported. `programType` must be supplied to identify the program type.\\n\\nAdditionally, EntityInfo objects must specify a properly formed\\nContentIdentifiers object, `entityType`, and `title`. The app should provide\\nthe `synopsis` property for a good user experience if the content\\nmetadata is not available another way.\\n\\nThe ContentIdentifiers must be sufficient for navigating the user to the\\nappropriate entity or detail screen via a `detail` intent or deep link.\\n\\nEntityInfo objects must provide at least one WayToWatch object when returned as\\npart of an `entityInfo` method and a streamable asset is available to the user.\\nIt is optional for the `purchasedContent` method, but recommended because the UI\\nmay use those data.\",\"type\":\"object\",\"required\":[\"identifiers\",\"entityType\",\"title\"],\"properties\":{\"identifiers\":{\"$ref\":\"#/x-schemas/Entertainment/ContentIdentifiers\"},\"title\":{\"type\":\"string\",\"description\":\"Title of the entity.\"},\"entityType\":{\"type\":\"string\",\"enum\":[\"program\",\"music\"],\"description\":\"The type of the entity, e.g. `program` or `music`.\"},\"programType\":{\"$ref\":\"#/x-schemas/Entertainment/ProgramType\"},\"musicType\":{\"$ref\":\"#/x-schemas/Entertainment/MusicType\"},\"synopsis\":{\"type\":\"string\",\"description\":\"Short description of the entity.\"},\"seasonNumber\":{\"type\":\"number\",\"description\":\"For TV seasons, the season number. For TV episodes, the season that the episode belongs to.\"},\"seasonCount\":{\"type\":\"number\",\"description\":\"For TV series, seasons, and episodes, the total number of seasons.\"},\"episodeNumber\":{\"type\":\"number\",\"description\":\"For TV episodes, the episode number.\"},\"episodeCount\":{\"type\":\"number\",\"description\":\"For TV seasons and episodes, the total number of episodes in the current season.\"},\"releaseDate\":{\"type\":\"string\",\"format\":\"date-time\",\"description\":\"The date that the program or entity was released or first aired.\"},\"contentRatings\":{\"type\":\"array\",\"items\":{\"$ref\":\"#/x-schemas/Entertainment/ContentRating\"},\"description\":\"A list of ContentRating objects, describing the entity's ratings in various rating schemes.\"},\"waysToWatch\":{\"type\":\"array\",\"items\":{\"$ref\":\"#/x-schemas/Entertainment/WayToWatch\"},\"description\":\"An array of ways a user is might watch this entity, regardless of entitlements.\"}},\"if\":{\"properties\":{\"entityType\":{\"const\":\"program\"}}},\"then\":{\"required\":[\"programType\"],\"not\":{\"required\":[\"musicType\"]}},\"else\":{\"required\":[\"musicType\"],\"not\":{\"required\":[\"programType\"]}}},\"ProgramType\":{\"title\":\"ProgramType\",\"type\":\"string\",\"description\":\"In the case of a program `entityType`, specifies the program type.\",\"enum\":[\"movie\",\"episode\",\"season\",\"series\",\"other\",\"preview\",\"extra\",\"concert\",\"sportingEvent\",\"advertisement\",\"musicVideo\",\"minisode\"]}},\"Intents\":{\"uri\":\"https://meta.comcast.com/firebolt/intents\",\"NavigationIntent\":{\"title\":\"NavigationIntent\",\"description\":\"A Firebolt compliant representation of a user intention to navigate to a specific place in an app.\",\"anyOf\":[{\"$ref\":\"#/x-schemas/Intents/HomeIntent\"},{\"$ref\":\"#/x-schemas/Intents/LaunchIntent\"},{\"$ref\":\"#/x-schemas/Intents/EntityIntent\"},{\"$ref\":\"#/x-schemas/Intents/PlaybackIntent\"},{\"$ref\":\"#/x-schemas/Intents/SearchIntent\"},{\"$ref\":\"#/x-schemas/Intents/SectionIntent\"},{\"$ref\":\"#/x-schemas/Intents/TuneIntent\"},{\"$ref\":\"#/x-schemas/Intents/PlayEntityIntent\"},{\"$ref\":\"#/x-schemas/Intents/PlayQueryIntent\"}]},\"HomeIntent\":{\"description\":\"A Firebolt compliant representation of a user intention to navigate an app to it's home screen, and bring that app to the foreground if needed.\",\"title\":\"HomeIntent\",\"allOf\":[{\"title\":\"HomeIntent\",\"$ref\":\"#/x-schemas/Intents/Intent\"},{\"title\":\"HomeIntent\",\"$ref\":\"#/x-schemas/Intents/IntentProperties\"},{\"title\":\"HomeIntent\",\"type\":\"object\",\"properties\":{\"action\":{\"const\":\"home\"}},\"not\":{\"required\":[\"data\"]}}],\"examples\":[{\"action\":\"home\",\"context\":{\"source\":\"voice\"}}]},\"LaunchIntent\":{\"description\":\"A Firebolt compliant representation of a user intention to launch an app.\",\"title\":\"LaunchIntent\",\"allOf\":[{\"$ref\":\"#/x-schemas/Intents/Intent\"},{\"$ref\":\"#/x-schemas/Intents/IntentProperties\"},{\"type\":\"object\",\"properties\":{\"action\":{\"const\":\"launch\"}},\"not\":{\"required\":[\"data\"]}}],\"examples\":[{\"action\":\"launch\",\"context\":{\"source\":\"voice\"}}]},\"EntityIntent\":{\"description\":\"A Firebolt compliant representation of a user intention to navigate an app to a specific entity page, and bring that app to the foreground if needed.\",\"title\":\"EntityIntent\",\"allOf\":[{\"$ref\":\"#/x-schemas/Intents/Intent\"},{\"$ref\":\"#/x-schemas/Intents/IntentProperties\"},{\"type\":\"object\",\"required\":[\"data\"],\"properties\":{\"action\":{\"const\":\"entity\"},\"data\":{\"$ref\":\"#/x-schemas/Entity/Entity\"}}}],\"examples\":[{\"action\":\"entity\",\"context\":{\"source\":\"voice\"},\"data\":{\"entityType\":\"program\",\"programType\":\"movie\",\"entityId\":\"el-camino\"}}]},\"PlaybackIntent\":{\"description\":\"A Firebolt compliant representation of a user intention to navigate an app to a the video player for a specific, playable entity, and bring that app to the foreground if needed.\",\"title\":\"PlaybackIntent\",\"allOf\":[{\"$ref\":\"#/x-schemas/Intents/Intent\"},{\"$ref\":\"#/x-schemas/Intents/IntentProperties\"},{\"type\":\"object\",\"required\":[\"data\"],\"properties\":{\"action\":{\"const\":\"playback\"},\"data\":{\"$ref\":\"#/x-schemas/Entity/PlayableEntity\"}}}],\"examples\":[{\"action\":\"playback\",\"data\":{\"entityType\":\"program\",\"programType\":\"episode\",\"entityId\":\"breaking-bad-pilot\",\"seriesId\":\"breaking-bad\",\"seasonId\":\"breaking-bad-season-1\"},\"context\":{\"source\":\"voice\"}}]},\"SearchIntent\":{\"description\":\"A Firebolt compliant representation of a user intention to navigate an app to it's search UI with a search term populated, and bring that app to the foreground if needed.\",\"title\":\"SearchIntent\",\"allOf\":[{\"$ref\":\"#/x-schemas/Intents/Intent\"},{\"$ref\":\"#/x-schemas/Intents/IntentProperties\"},{\"type\":\"object\",\"properties\":{\"action\":{\"const\":\"search\"},\"data\":{\"type\":\"object\",\"required\":[\"query\"],\"properties\":{\"query\":{\"type\":\"string\"},\"suggestions\":{\"type\":\"array\",\"items\":{\"$ref\":\"#/x-schemas/Entity/Entity\"}}},\"additionalProperties\":false}}}],\"examples\":[{\"action\":\"search\",\"data\":{\"query\":\"walter white\"},\"context\":{\"source\":\"voice\"}}]},\"SectionIntent\":{\"description\":\"A Firebolt compliant representation of a user intention to navigate an app to a section not covered by `home`, `entity`, `player`, or `search`, and bring that app to the foreground if needed.\",\"title\":\"SectionIntent\",\"allOf\":[{\"$ref\":\"#/x-schemas/Intents/Intent\"},{\"$ref\":\"#/x-schemas/Intents/IntentProperties\"},{\"type\":\"object\",\"properties\":{\"action\":{\"const\":\"section\"},\"data\":{\"type\":\"object\",\"required\":[\"sectionName\"],\"properties\":{\"sectionName\":{\"type\":\"string\"}},\"additionalProperties\":false}},\"required\":[\"data\"]}],\"examples\":[{\"action\":\"section\",\"data\":{\"sectionName\":\"settings\"},\"context\":{\"source\":\"voice\"}}]},\"TuneIntent\":{\"description\":\"A Firebolt compliant representation of a user intention to 'tune' to a traditional over-the-air broadcast, or an OTT Stream from an OTT or vMVPD App.\",\"title\":\"TuneIntent\",\"allOf\":[{\"$ref\":\"#/x-schemas/Intents/Intent\"},{\"$ref\":\"#/x-schemas/Intents/IntentProperties\"},{\"type\":\"object\",\"required\":[\"data\"],\"properties\":{\"action\":{\"const\":\"tune\"},\"data\":{\"type\":\"object\",\"required\":[\"entity\"],\"additionalProperties\":false,\"properties\":{\"entity\":{\"$ref\":\"#/x-schemas/Entity/ChannelEntity\"},\"options\":{\"description\":\"The options property of the data property MUST have only one of the following fields.\",\"type\":\"object\",\"required\":[],\"additionalProperties\":false,\"minProperties\":1,\"maxProperties\":1,\"properties\":{\"assetId\":{\"type\":\"string\",\"description\":\"The ID of a specific 'listing', as scoped by the target App's ID-space, which the App should begin playback from.\"},\"restartCurrentProgram\":{\"type\":\"boolean\",\"description\":\"Denotes that the App should start playback at the most recent program boundary, rather than 'live.'\"},\"time\":{\"type\":\"string\",\"format\":\"date-time\",\"description\":\"ISO 8601 Date/Time where the App should begin playback from.\"}}}}}}}],\"examples\":[{\"action\":\"tune\",\"data\":{\"entity\":{\"entityType\":\"channel\",\"channelType\":\"streaming\",\"entityId\":\"an-ott-channel\"},\"options\":{\"restartCurrentProgram\":true}},\"context\":{\"source\":\"voice\"}}]},\"PlayEntityIntent\":{\"description\":\"A Firebolt compliant representation of a user intention to navigate an app to a the video player for a specific, playable entity, and bring that app to the foreground if needed.\",\"title\":\"PlayEntityIntent\",\"allOf\":[{\"$ref\":\"#/x-schemas/Intents/Intent\"},{\"$ref\":\"#/x-schemas/Intents/IntentProperties\"},{\"type\":\"object\",\"required\":[\"data\"],\"properties\":{\"action\":{\"const\":\"play-entity\"},\"data\":{\"type\":\"object\",\"properties\":{\"entity\":{\"$ref\":\"#/x-schemas/Entity/PlayableEntity\"},\"options\":{\"type\":\"object\",\"properties\":{\"playFirstId\":{\"type\":\"string\"},\"playFirstTrack\":{\"type\":\"integer\",\"minimum\":1}},\"additionalProperties\":false}},\"required\":[\"entity\"],\"propertyNames\":{\"enum\":[\"entity\",\"options\"]},\"if\":{\"properties\":{\"entity\":{\"type\":\"object\",\"required\":[\"entityType\"],\"properties\":{\"entityType\":{\"const\":\"playlist\"}}}}},\"then\":{\"type\":\"object\",\"properties\":{\"options\":{\"type\":\"object\",\"maxProperties\":1}}},\"else\":{\"type\":\"object\",\"properties\":{\"options\":{\"type\":\"object\",\"maxProperties\":0}}}}}}],\"examples\":[{\"action\":\"play-entity\",\"data\":{\"entity\":{\"entityType\":\"playlist\",\"entityId\":\"playlist/xyz\"},\"options\":{\"playFirstId\":\"song/xyz\"}},\"context\":{\"source\":\"voice\"}},{\"action\":\"play-entity\",\"data\":{\"entity\":{\"entityType\":\"playlist\",\"entityId\":\"playlist/xyz\"},\"options\":{\"playFirstTrack\":3}},\"context\":{\"source\":\"voice\"}}]},\"PlayQueryIntent\":{\"description\":\"A Firebolt compliant representation of a user intention to navigate an app to a the video player for an abstract query to be searched for and played by the app.\",\"title\":\"PlayQueryIntent\",\"allOf\":[{\"$ref\":\"#/x-schemas/Intents/Intent\"},{\"$ref\":\"#/x-schemas/Intents/IntentProperties\"},{\"type\":\"object\",\"required\":[\"data\"],\"properties\":{\"action\":{\"const\":\"play-query\"},\"data\":{\"type\":\"object\",\"properties\":{\"query\":{\"type\":\"string\"},\"options\":{\"type\":\"object\",\"properties\":{\"programTypes\":{\"type\":\"array\",\"items\":{\"$ref\":\"#/x-schemas/Entertainment/ProgramType\"}},\"musicTypes\":{\"type\":\"array\",\"items\":{\"$ref\":\"#/x-schemas/Entertainment/MusicType\"}}},\"additionalProperties\":false}},\"required\":[\"query\"],\"propertyNames\":{\"enum\":[\"query\",\"options\"]}}}}],\"examples\":[{\"action\":\"play-query\",\"data\":{\"query\":\"Ed Sheeran\"},\"context\":{\"source\":\"voice\"}},{\"action\":\"play-query\",\"data\":{\"query\":\"Ed Sheeran\",\"options\":{\"programTypes\":[\"movie\"]}},\"context\":{\"source\":\"voice\"}},{\"action\":\"play-query\",\"data\":{\"query\":\"Ed Sheeran\",\"options\":{\"programTypes\":[\"movie\"],\"musicTypes\":[\"song\"]}},\"context\":{\"source\":\"voice\"}}]},\"Intent\":{\"description\":\"A Firebolt compliant representation of a user intention.\",\"type\":\"object\",\"required\":[\"action\",\"context\"],\"properties\":{\"action\":{\"type\":\"string\"},\"context\":{\"type\":\"object\",\"required\":[\"source\"],\"properties\":{\"source\":{\"type\":\"string\"}}}}},\"IntentProperties\":{\"type\":\"object\",\"propertyNames\":{\"enum\":[\"action\",\"data\",\"context\"]}}},\"Lifecycle\":{\"uri\":\"https://meta.comcast.com/firebolt/lifecycle\",\"CloseReason\":{\"title\":\"CloseReason\",\"description\":\"The application close reason\",\"type\":\"string\",\"enum\":[\"remoteButton\",\"userExit\",\"done\",\"error\"]},\"LifecycleState\":{\"title\":\"LifecycleState\",\"description\":\"The application lifecycle state\",\"type\":\"string\",\"enum\":[\"initializing\",\"inactive\",\"foreground\",\"background\",\"unloading\",\"suspended\"]}},\"SecondScreen\":{\"uri\":\"https://meta.comcast.com/firebolt/secondscreen\",\"SecondScreenEvent\":{\"title\":\"SecondScreenEvent\",\"description\":\"An a message notification from a second screen device\",\"type\":\"object\",\"required\":[\"type\"],\"properties\":{\"type\":{\"type\":\"string\",\"enum\":[\"dial\"]},\"version\":{\"type\":\"string\"},\"data\":{\"type\":\"string\"}}}}}}"); + +/***/ }), + +/***/ "./node_modules/@firebolt-js/sdk/dist/lib/Accessibility/defaults.mjs": +/*!***************************************************************************!*\ + !*** ./node_modules/@firebolt-js/sdk/dist/lib/Accessibility/defaults.mjs ***! + \***************************************************************************/ +/*! exports provided: default */ +/***/ (function(__webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var _Prop_MockProps_mjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Prop/MockProps.mjs */ "./node_modules/@firebolt-js/sdk/dist/lib/Prop/MockProps.mjs"); +/* + * Copyright 2021 Comcast Cable Communications Management, LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + */ + + +/* harmony default export */ __webpack_exports__["default"] = ({ + closedCaptions: { + enabled: true, + styles: { + fontFamily: 'monospaced_sanserif', + fontSize: 1, + fontColor: '#ffffff', + fontEdge: 'none', + fontEdgeColor: '#7F7F7F', + fontOpacity: 100, + backgroundColor: '#000000', + backgroundOpacity: 100, + textAlign: 'center', + textAlignVertical: 'middle', + windowColor: 'white', + windowOpacity: 50, + }, + preferredLanguages: ['eng', 'spa'], + }, + closedCaptionsSettings: function (params) { + return _Prop_MockProps_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].mock( + 'Accessibility', + 'closedCaptionsSettings', + params, + undefined, + 0, + { + enabled: true, + styles: { + fontFamily: 'monospaced_sanserif', + fontSize: 1, + fontColor: '#ffffff', + fontEdge: 'none', + fontEdgeColor: '#7F7F7F', + fontOpacity: 100, + backgroundColor: '#000000', + backgroundOpacity: 100, + textAlign: 'center', + textAlignVertical: 'middle', + windowColor: 'white', + windowOpacity: 50, + }, + preferredLanguages: ['eng', 'spa'], + }, + ) + }, + voiceGuidance: { enabled: true, speed: 2 }, + voiceGuidanceSettings: function (params) { + return _Prop_MockProps_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].mock( + 'Accessibility', + 'voiceGuidanceSettings', + params, + undefined, + 0, + { enabled: true, speed: 2 }, + ) + }, + audioDescriptionSettings: function (params) { + return _Prop_MockProps_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].mock( + 'Accessibility', + 'audioDescriptionSettings', + params, + undefined, + 0, + { enabled: true }, + ) + }, +}); + + +/***/ }), + +/***/ "./node_modules/@firebolt-js/sdk/dist/lib/Accessibility/index.mjs": +/*!************************************************************************!*\ + !*** ./node_modules/@firebolt-js/sdk/dist/lib/Accessibility/index.mjs ***! + \************************************************************************/ +/*! exports provided: default */ +/***/ (function(__webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var _Transport_index_mjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Transport/index.mjs */ "./node_modules/@firebolt-js/sdk/dist/lib/Transport/index.mjs"); +/* harmony import */ var _Events_index_mjs__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Events/index.mjs */ "./node_modules/@firebolt-js/sdk/dist/lib/Events/index.mjs"); +/* harmony import */ var _Prop_index_mjs__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Prop/index.mjs */ "./node_modules/@firebolt-js/sdk/dist/lib/Prop/index.mjs"); +/* + * Copyright 2021 Comcast Cable Communications Management, LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + */ + + + + + + +Object(_Events_index_mjs__WEBPACK_IMPORTED_MODULE_1__["registerEvents"])('Accessibility', [ + 'audioDescriptionSettingsChanged', + 'closedCaptionsSettingsChanged', + 'voiceGuidanceSettingsChanged', +]) + +_Transport_index_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].registerDeprecatedMethod( + 'Accessibility', + 'closedCaptions', + 'Use Accessibility.closedCaptionsSettings() instead.', +) +_Transport_index_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].registerDeprecatedMethod( + 'Accessibility', + 'voiceGuidance', + 'Use Accessibility.voiceGuidanceSettings() instead.', +) + +// onAudioDescriptionSettingsChanged is accessed via listen('audioDescriptionSettingsChanged, ...) + +// onClosedCaptionsSettingsChanged is accessed via listen('closedCaptionsSettingsChanged, ...) + +// onVoiceGuidanceSettingsChanged is accessed via listen('voiceGuidanceSettingsChanged, ...) + +// Methods +function audioDescriptionSettings() { + let callbackOrValue = arguments[0] + let params = {} + + // x-subscriber-type: global + if (arguments.length === 1 && typeof arguments[0] === 'function') { + callbackOrValue = arguments[0] + params = {} + } + + return _Prop_index_mjs__WEBPACK_IMPORTED_MODULE_2__["default"].prop( + 'Accessibility', + 'audioDescriptionSettings', + params, + callbackOrValue, + false, + true, + 0, + ) +} +function clear(...args) { + return _Events_index_mjs__WEBPACK_IMPORTED_MODULE_1__["default"].clear('Accessibility', ...args) +} + +function closedCaptions() { + const transforms = null + + return _Transport_index_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].send('Accessibility', 'closedCaptions', {}, transforms) +} +function closedCaptionsSettings() { + let callbackOrValue = arguments[0] + let params = {} + + // x-subscriber-type: global + if (arguments.length === 1 && typeof arguments[0] === 'function') { + callbackOrValue = arguments[0] + params = {} + } + + return _Prop_index_mjs__WEBPACK_IMPORTED_MODULE_2__["default"].prop( + 'Accessibility', + 'closedCaptionsSettings', + params, + callbackOrValue, + false, + true, + 0, + ) +} +function listen(...args) { + return _Events_index_mjs__WEBPACK_IMPORTED_MODULE_1__["default"].listen('Accessibility', ...args) +} + +function once(...args) { + return _Events_index_mjs__WEBPACK_IMPORTED_MODULE_1__["default"].once('Accessibility', ...args) +} + +function voiceGuidance() { + const transforms = null + + return _Transport_index_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].send('Accessibility', 'voiceGuidance', {}, transforms) +} +function voiceGuidanceSettings() { + let callbackOrValue = arguments[0] + let params = {} + + // x-subscriber-type: global + if (arguments.length === 1 && typeof arguments[0] === 'function') { + callbackOrValue = arguments[0] + params = {} + } + + return _Prop_index_mjs__WEBPACK_IMPORTED_MODULE_2__["default"].prop( + 'Accessibility', + 'voiceGuidanceSettings', + params, + callbackOrValue, + false, + true, + 0, + ) +} + +/* harmony default export */ __webpack_exports__["default"] = ({ + Events: { + CLOSED_CAPTIONS_SETTINGS_CHANGED: 'closedCaptionsSettingsChanged', + VOICE_GUIDANCE_SETTINGS_CHANGED: 'voiceGuidanceSettingsChanged', + AUDIO_DESCRIPTION_SETTINGS_CHANGED: 'audioDescriptionSettingsChanged', + }, + + /** + * + */ + FontFamily: { + MONOSPACED_SERIF: 'monospaced_serif', + PROPORTIONAL_SERIF: 'proportional_serif', + MONOSPACED_SANSERIF: 'monospaced_sanserif', + PROPORTIONAL_SANSERIF: 'proportional_sanserif', + SMALLCAPS: 'smallcaps', + CURSIVE: 'cursive', + CASUAL: 'casual', + }, + + /** + * + */ + FontEdge: { + NONE: 'none', + RAISED: 'raised', + DEPRESSED: 'depressed', + UNIFORM: 'uniform', + DROP_SHADOW_LEFT: 'drop_shadow_left', + DROP_SHADOW_RIGHT: 'drop_shadow_right', + }, + + audioDescriptionSettings, + clear, + closedCaptions, + closedCaptionsSettings, + listen, + once, + voiceGuidance, + voiceGuidanceSettings, +}); + + +/***/ }), + +/***/ "./node_modules/@firebolt-js/sdk/dist/lib/Account/defaults.mjs": +/*!*********************************************************************!*\ + !*** ./node_modules/@firebolt-js/sdk/dist/lib/Account/defaults.mjs ***! + \*********************************************************************/ +/*! exports provided: default */ +/***/ (function(__webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var _Prop_MockProps_mjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Prop/MockProps.mjs */ "./node_modules/@firebolt-js/sdk/dist/lib/Prop/MockProps.mjs"); +/* + * Copyright 2021 Comcast Cable Communications Management, LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + */ + + +/* harmony default export */ __webpack_exports__["default"] = ({ + id: function (params) { + return _Prop_MockProps_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].mock('Account', 'id', params, undefined, 0, '123') + }, + uid: function (params) { + return _Prop_MockProps_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].mock( + 'Account', + 'uid', + params, + undefined, + 0, + 'ee6723b8-7ab3-462c-8d93-dbf61227998e', + ) + }, +}); + + +/***/ }), + +/***/ "./node_modules/@firebolt-js/sdk/dist/lib/Account/index.mjs": +/*!******************************************************************!*\ + !*** ./node_modules/@firebolt-js/sdk/dist/lib/Account/index.mjs ***! + \******************************************************************/ +/*! exports provided: default */ +/***/ (function(__webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var _Transport_index_mjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Transport/index.mjs */ "./node_modules/@firebolt-js/sdk/dist/lib/Transport/index.mjs"); +/* harmony import */ var _Prop_index_mjs__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Prop/index.mjs */ "./node_modules/@firebolt-js/sdk/dist/lib/Prop/index.mjs"); +/* + * Copyright 2021 Comcast Cable Communications Management, LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + */ + + + + +// Methods +function id() { + let callbackOrValue = arguments[0] + let params = {} + + // x-subscriber-type: global + if (arguments.length === 1 && typeof arguments[0] === 'function') { + callbackOrValue = arguments[0] + params = {} + } + + return _Prop_index_mjs__WEBPACK_IMPORTED_MODULE_1__["default"].prop('Account', 'id', params, callbackOrValue, true, true, 0) +} +function uid() { + let callbackOrValue = arguments[0] + let params = {} + + // x-subscriber-type: global + if (arguments.length === 1 && typeof arguments[0] === 'function') { + callbackOrValue = arguments[0] + params = {} + } + + return _Prop_index_mjs__WEBPACK_IMPORTED_MODULE_1__["default"].prop('Account', 'uid', params, callbackOrValue, true, true, 0) +} + +/* harmony default export */ __webpack_exports__["default"] = ({ + id, + uid, +}); + + +/***/ }), + +/***/ "./node_modules/@firebolt-js/sdk/dist/lib/Advertising/defaults.mjs": +/*!*************************************************************************!*\ + !*** ./node_modules/@firebolt-js/sdk/dist/lib/Advertising/defaults.mjs ***! + \*************************************************************************/ +/*! exports provided: default */ +/***/ (function(__webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var _Prop_MockProps_mjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Prop/MockProps.mjs */ "./node_modules/@firebolt-js/sdk/dist/lib/Prop/MockProps.mjs"); +/* + * Copyright 2021 Comcast Cable Communications Management, LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + */ + + +/* harmony default export */ __webpack_exports__["default"] = ({ + config: { + adServerUrl: 'https://demo.v.fwmrm.net/ad/p/1', + adServerUrlTemplate: + 'https://demo.v.fwmrm.net/ad/p/1?flag=+sltp+exvt+slcb+emcr+amcb+aeti&prof=12345:caf_allinone_profile &nw=12345&mode=live&vdur=123&caid=a110523018&asnw=372464&csid=gmott_ios_tablet_watch_live_ESPNU&ssnw=372464&vip=198.205.92.1&resp=vmap1&metr=1031&pvrn=12345&vprn=12345&vcid=1X0Ce7L3xRWlTeNhc7br8Q%3D%3D', + adNetworkId: '519178', + adProfileId: '12345:caf_allinone_profile', + adSiteSectionId: 'caf_allinone_profile_section', + adOptOut: true, + privacyData: + 'ew0KICAicGR0IjogImdkcDp2MSIsDQogICJ1c19wcml2YWN5IjogIjEtTi0iLA0KICAibG10IjogIjEiIA0KfQ0K', + ifaValue: '01234567-89AB-CDEF-GH01-23456789ABCD', + ifa: 'ewogICJ2YWx1ZSI6ICIwMTIzNDU2Ny04OUFCLUNERUYtR0gwMS0yMzQ1Njc4OUFCQ0QiLAogICJpZmFfdHlwZSI6ICJzc3BpZCIsCiAgImxtdCI6ICIwIgp9Cg==', + appName: 'FutureToday', + appBundleId: 'FutureToday.comcast', + distributorAppId: '1001', + deviceAdAttributes: + 'ewogICJib0F0dHJpYnV0ZXNGb3JSZXZTaGFyZUlkIjogIjEyMzQiCn0=', + coppa: 0, + authenticationEntity: '60f72475281cfba3852413bd53e957f6', + }, + policy: function (params) { + return _Prop_MockProps_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].mock('Advertising', 'policy', params, undefined, 0, { + skipRestriction: 'adsUnwatched', + limitAdTracking: false, + }) + }, + advertisingId: { + ifa: '01234567-89AB-CDEF-GH01-23456789ABCD', + ifa_type: 'sspid', + lmt: '0', + }, + deviceAttributes: {}, + appBundleId: 'app.operator', +}); + + +/***/ }), + +/***/ "./node_modules/@firebolt-js/sdk/dist/lib/Advertising/index.mjs": +/*!**********************************************************************!*\ + !*** ./node_modules/@firebolt-js/sdk/dist/lib/Advertising/index.mjs ***! + \**********************************************************************/ +/*! exports provided: default */ +/***/ (function(__webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var _Transport_index_mjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Transport/index.mjs */ "./node_modules/@firebolt-js/sdk/dist/lib/Transport/index.mjs"); +/* harmony import */ var _Events_index_mjs__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Events/index.mjs */ "./node_modules/@firebolt-js/sdk/dist/lib/Events/index.mjs"); +/* harmony import */ var _Prop_index_mjs__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Prop/index.mjs */ "./node_modules/@firebolt-js/sdk/dist/lib/Prop/index.mjs"); +/* + * Copyright 2021 Comcast Cable Communications Management, LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + */ + + + + + + +Object(_Events_index_mjs__WEBPACK_IMPORTED_MODULE_1__["registerEvents"])('Advertising', ['policyChanged']) + +// onPolicyChanged is accessed via listen('policyChanged, ...) + +// Methods + +function advertisingId(options) { + const transforms = null + + return _Transport_index_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].send('Advertising', 'advertisingId', { options }, transforms) +} + +function appBundleId() { + const transforms = null + + return _Transport_index_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].send('Advertising', 'appBundleId', {}, transforms) +} +function clear(...args) { + return _Events_index_mjs__WEBPACK_IMPORTED_MODULE_1__["default"].clear('Advertising', ...args) +} + +function config(options) { + const transforms = null + + return _Transport_index_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].send('Advertising', 'config', { options }, transforms) +} + +function deviceAttributes() { + const transforms = null + + return _Transport_index_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].send('Advertising', 'deviceAttributes', {}, transforms) +} +function listen(...args) { + return _Events_index_mjs__WEBPACK_IMPORTED_MODULE_1__["default"].listen('Advertising', ...args) +} + +function once(...args) { + return _Events_index_mjs__WEBPACK_IMPORTED_MODULE_1__["default"].once('Advertising', ...args) +} + +function policy() { + let callbackOrValue = arguments[0] + let params = {} + + // x-subscriber-type: global + if (arguments.length === 1 && typeof arguments[0] === 'function') { + callbackOrValue = arguments[0] + params = {} + } + + return _Prop_index_mjs__WEBPACK_IMPORTED_MODULE_2__["default"].prop( + 'Advertising', + 'policy', + params, + callbackOrValue, + false, + true, + 0, + ) +} + +/* harmony default export */ __webpack_exports__["default"] = ({ + Events: { + POLICY_CHANGED: 'policyChanged', + }, + + /** + * The advertisement skip restriction. + +Applies to fast-forward/rewind (e.g. trick mode), seeking over an entire opportunity (e.g. jump), seeking out of what's currently playing, and "Skip this ad..." features. Seeking over multiple ad opportunities only requires playback of the _last_ opportunity, not all opportunities, preceding the seek destination. + +| Value | Description | +|--------------|--------------------------------------------------------------------------------| +| none |No fast-forward, jump, or skip restrictions | +| adsUnwatched | Restrict fast-forward, jump, and skip for unwatched ad opportunities only. | +| adsAll | Restrict fast-forward, jump, and skip for all ad opportunities | +| all | Restrict fast-forward, jump, and skip for all ad opportunities and all content | + +Namespace: `xrn:advertising:policy:skipRestriction:` + + + */ + SkipRestriction: { + NONE: 'none', + ADS_UNWATCHED: 'adsUnwatched', + ADS_ALL: 'adsAll', + ALL: 'all', + }, + + advertisingId, + appBundleId, + clear, + config, + deviceAttributes, + listen, + once, + policy, +}); + + +/***/ }), + +/***/ "./node_modules/@firebolt-js/sdk/dist/lib/Authentication/defaults.mjs": +/*!****************************************************************************!*\ + !*** ./node_modules/@firebolt-js/sdk/dist/lib/Authentication/defaults.mjs ***! + \****************************************************************************/ +/*! exports provided: default */ +/***/ (function(__webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var _Prop_MockProps_mjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Prop/MockProps.mjs */ "./node_modules/@firebolt-js/sdk/dist/lib/Prop/MockProps.mjs"); +/* + * Copyright 2021 Comcast Cable Communications Management, LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + */ + + +/* harmony default export */ __webpack_exports__["default"] = ({ + token: { + value: + 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c', + expires: '2022-04-23T18:25:43.511Z', + type: 'platform', + }, + device: + 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c', + session: + 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c', + root: 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c', +}); + + +/***/ }), + +/***/ "./node_modules/@firebolt-js/sdk/dist/lib/Authentication/index.mjs": +/*!*************************************************************************!*\ + !*** ./node_modules/@firebolt-js/sdk/dist/lib/Authentication/index.mjs ***! + \*************************************************************************/ +/*! exports provided: default */ +/***/ (function(__webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var _Transport_index_mjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Transport/index.mjs */ "./node_modules/@firebolt-js/sdk/dist/lib/Transport/index.mjs"); +/* + * Copyright 2021 Comcast Cable Communications Management, LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + */ + + + +_Transport_index_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].registerDeprecatedMethod( + 'Authentication', + 'token', + 'Use Authentication module has individual methods for each token type. instead.', +) + +// Methods + +function device() { + const transforms = null + + return _Transport_index_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].send('Authentication', 'device', {}, transforms) +} + +function root() { + const transforms = null + + return _Transport_index_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].send('Authentication', 'root', {}, transforms) +} + +function session() { + const transforms = null + + return _Transport_index_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].send('Authentication', 'session', {}, transforms) +} + +function token(type, options) { + const transforms = null + + return _Transport_index_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].send( + 'Authentication', + 'token', + { type, options }, + transforms, + ) +} + +/* harmony default export */ __webpack_exports__["default"] = ({ + /** + * + */ + TokenType: { + PLATFORM: 'platform', + DEVICE: 'device', + DISTRIBUTOR: 'distributor', + }, + + device, + root, + session, + token, +}); + + +/***/ }), + +/***/ "./node_modules/@firebolt-js/sdk/dist/lib/Capabilities/defaults.mjs": +/*!**************************************************************************!*\ + !*** ./node_modules/@firebolt-js/sdk/dist/lib/Capabilities/defaults.mjs ***! + \**************************************************************************/ +/*! exports provided: default */ +/***/ (function(__webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var _Prop_MockProps_mjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Prop/MockProps.mjs */ "./node_modules/@firebolt-js/sdk/dist/lib/Prop/MockProps.mjs"); +/* + * Copyright 2021 Comcast Cable Communications Management, LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + */ + + +/* harmony default export */ __webpack_exports__["default"] = ({ + supported: true, + available: true, + permitted: true, + granted: true, + info: [ + { + capability: 'xrn:firebolt:capability:device:model', + supported: true, + available: true, + use: { permitted: true, granted: true }, + manage: { permitted: true, granted: true }, + provide: { permitted: true, granted: true }, + }, + { + capability: 'xrn:firebolt:capability:input:keyboard', + supported: true, + available: true, + use: { permitted: true, granted: true }, + manage: { permitted: true, granted: true }, + provide: { permitted: true, granted: true }, + }, + { + capability: 'xrn:firebolt:capability:protocol:bluetoothle', + supported: false, + available: false, + use: { permitted: true, granted: true }, + manage: { permitted: true, granted: true }, + provide: { permitted: true, granted: true }, + details: ['unsupported'], + }, + { + capability: 'xrn:firebolt:capability:token:device', + supported: true, + available: true, + use: { permitted: true, granted: true }, + manage: { permitted: true, granted: true }, + provide: { permitted: true, granted: true }, + }, + { + capability: 'xrn:firebolt:capability:token:platform', + supported: true, + available: false, + use: { permitted: true, granted: true }, + manage: { permitted: true, granted: true }, + provide: { permitted: true, granted: true }, + details: ['unavailable'], + }, + { + capability: 'xrn:firebolt:capability:protocol:moca', + supported: true, + available: false, + use: { permitted: true, granted: true }, + manage: { permitted: true, granted: true }, + provide: { permitted: true, granted: true }, + details: ['disabled', 'unavailable'], + }, + { + capability: 'xrn:firebolt:capability:wifi:scan', + supported: true, + available: true, + use: { permitted: true, granted: true }, + manage: { permitted: true, granted: true }, + provide: { permitted: true, granted: true }, + details: ['unpermitted'], + }, + { + capability: 'xrn:firebolt:capability:localization:postal-code', + supported: true, + available: true, + use: { permitted: true, granted: null }, + manage: { permitted: true, granted: true }, + provide: { permitted: true, granted: true }, + details: ['ungranted'], + }, + { + capability: 'xrn:firebolt:capability:localization:postal-code', + supported: true, + available: true, + use: { permitted: true, granted: true }, + manage: { permitted: true, granted: true }, + provide: { permitted: true, granted: true }, + details: ['ungranted'], + }, + { + capability: 'xrn:firebolt:capability:localization:locality', + supported: true, + available: true, + use: { permitted: true, granted: true }, + manage: { permitted: true, granted: true }, + provide: { permitted: true, granted: true }, + details: ['grantDenied', 'ungranted'], + }, + ], + request: [ + { + capability: 'xrn:firebolt:capability:commerce:purchase', + supported: true, + available: true, + use: { permitted: true, granted: true }, + manage: { permitted: true, granted: true }, + provide: { permitted: true, granted: true }, + }, + ], +}); + + +/***/ }), + +/***/ "./node_modules/@firebolt-js/sdk/dist/lib/Capabilities/index.mjs": +/*!***********************************************************************!*\ + !*** ./node_modules/@firebolt-js/sdk/dist/lib/Capabilities/index.mjs ***! + \***********************************************************************/ +/*! exports provided: default */ +/***/ (function(__webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var _Transport_index_mjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Transport/index.mjs */ "./node_modules/@firebolt-js/sdk/dist/lib/Transport/index.mjs"); +/* harmony import */ var _Events_index_mjs__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Events/index.mjs */ "./node_modules/@firebolt-js/sdk/dist/lib/Events/index.mjs"); +/* + * Copyright 2021 Comcast Cable Communications Management, LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + */ + + + + + + +Object(_Events_index_mjs__WEBPACK_IMPORTED_MODULE_1__["registerEvents"])('Capabilities', [ + 'available', + 'granted', + 'revoked', + 'unavailable', +]) + +// onAvailable is accessed via listen('available, ...) + +Object(_Events_index_mjs__WEBPACK_IMPORTED_MODULE_1__["registerEventContext"])('Capabilities', 'available', ['capability']) +// onGranted is accessed via listen('granted, ...) + +Object(_Events_index_mjs__WEBPACK_IMPORTED_MODULE_1__["registerEventContext"])('Capabilities', 'granted', ['role', 'capability']) +// onRevoked is accessed via listen('revoked, ...) + +Object(_Events_index_mjs__WEBPACK_IMPORTED_MODULE_1__["registerEventContext"])('Capabilities', 'revoked', ['role', 'capability']) +// onUnavailable is accessed via listen('unavailable, ...) + +Object(_Events_index_mjs__WEBPACK_IMPORTED_MODULE_1__["registerEventContext"])('Capabilities', 'unavailable', ['capability']) + +// Methods + +function available(capability) { + const transforms = null + + return _Transport_index_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].send('Capabilities', 'available', { capability }, transforms) +} +function clear(...args) { + return _Events_index_mjs__WEBPACK_IMPORTED_MODULE_1__["default"].clear('Capabilities', ...args) +} + +function granted(capability, options) { + const transforms = null + + return _Transport_index_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].send( + 'Capabilities', + 'granted', + { capability, options }, + transforms, + ) +} + +function info(capabilities) { + const transforms = null + + return _Transport_index_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].send('Capabilities', 'info', { capabilities }, transforms) +} +function listen(...args) { + return _Events_index_mjs__WEBPACK_IMPORTED_MODULE_1__["default"].listen('Capabilities', ...args) +} + +function once(...args) { + return _Events_index_mjs__WEBPACK_IMPORTED_MODULE_1__["default"].once('Capabilities', ...args) +} + +function permitted(capability, options) { + const transforms = null + + return _Transport_index_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].send( + 'Capabilities', + 'permitted', + { capability, options }, + transforms, + ) +} + +function request(grants) { + const transforms = null + + return _Transport_index_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].send('Capabilities', 'request', { grants }, transforms) +} + +function supported(capability) { + const transforms = null + + return _Transport_index_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].send('Capabilities', 'supported', { capability }, transforms) +} + +/* harmony default export */ __webpack_exports__["default"] = ({ + Events: { + AVAILABLE: 'available', + UNAVAILABLE: 'unavailable', + GRANTED: 'granted', + REVOKED: 'revoked', + }, + + /** + * Role provides access level for the app for a given capability. + */ + Role: { + USE: 'use', + MANAGE: 'manage', + PROVIDE: 'provide', + }, + + /** + * Reasons why a Capability might not be invokable + */ + DenyReason: { + UNPERMITTED: 'unpermitted', + UNSUPPORTED: 'unsupported', + DISABLED: 'disabled', + UNAVAILABLE: 'unavailable', + GRANT_DENIED: 'grantDenied', + UNGRANTED: 'ungranted', + }, + + available, + clear, + granted, + info, + listen, + once, + permitted, + request, + supported, +}); + + +/***/ }), + +/***/ "./node_modules/@firebolt-js/sdk/dist/lib/Device/defaults.mjs": +/*!********************************************************************!*\ + !*** ./node_modules/@firebolt-js/sdk/dist/lib/Device/defaults.mjs ***! + \********************************************************************/ +/*! exports provided: default */ +/***/ (function(__webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var _Prop_MockProps_mjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Prop/MockProps.mjs */ "./node_modules/@firebolt-js/sdk/dist/lib/Prop/MockProps.mjs"); +/* + * Copyright 2021 Comcast Cable Communications Management, LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + */ + + +/* harmony default export */ __webpack_exports__["default"] = ({ + id: function (params) { + return _Prop_MockProps_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].mock('Device', 'id', params, undefined, 0, '123') + }, + distributor: function (params) { + return _Prop_MockProps_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].mock( + 'Device', + 'distributor', + params, + undefined, + 0, + 'Company', + ) + }, + platform: function (params) { + return _Prop_MockProps_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].mock('Device', 'platform', params, undefined, 0, 'WPE') + }, + uid: function (params) { + return _Prop_MockProps_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].mock( + 'Device', + 'uid', + params, + undefined, + 0, + 'ee6723b8-7ab3-462c-8d93-dbf61227998e', + ) + }, + type: function (params) { + return _Prop_MockProps_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].mock('Device', 'type', params, undefined, 0, 'STB') + }, + model: function (params) { + return _Prop_MockProps_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].mock('Device', 'model', params, undefined, 0, 'xi6') + }, + sku: function (params) { + return _Prop_MockProps_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].mock('Device', 'sku', params, undefined, 0, 'AX061AEI') + }, + make: function (params) { + return _Prop_MockProps_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].mock('Device', 'make', params, undefined, 0, 'Arris') + }, + version: function (params) { + return _Prop_MockProps_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].mock('Device', 'version', params, undefined, 0, { + sdk: { major: 0, minor: 8, patch: 0, readable: 'Firebolt JS SDK v0.8.0' }, + api: { major: 0, minor: 8, patch: 0, readable: 'Firebolt API v0.8.0' }, + firmware: { + major: 1, + minor: 2, + patch: 3, + readable: 'Device Firmware v1.2.3', + }, + os: { major: 0, minor: 1, patch: 0, readable: 'Firebolt OS v0.1.0' }, + debug: 'Non-parsable build info for error logging only.', + }) + }, + hdcp: function (params) { + return _Prop_MockProps_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].mock('Device', 'hdcp', params, undefined, 0, { + 'hdcp1.4': true, + 'hdcp2.2': true, + }) + }, + hdr: function (params) { + return _Prop_MockProps_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].mock('Device', 'hdr', params, undefined, 0, { + hdr10: true, + hdr10Plus: true, + dolbyVision: true, + hlg: true, + }) + }, + audio: function (params) { + return _Prop_MockProps_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].mock('Device', 'audio', params, undefined, 0, { + stereo: true, + 'dolbyDigital5.1': true, + 'dolbyDigital5.1+': true, + dolbyAtmos: true, + }) + }, + screenResolution: function (params) { + return _Prop_MockProps_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].mock( + 'Device', + 'screenResolution', + params, + undefined, + 0, + [1920, 1080], + ) + }, + videoResolution: function (params) { + return _Prop_MockProps_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].mock( + 'Device', + 'videoResolution', + params, + undefined, + 0, + [1920, 1080], + ) + }, + name: function (params) { + return _Prop_MockProps_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].mock('Device', 'name', params, undefined, 0, 'Living Room') + }, + network: function (params) { + return _Prop_MockProps_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].mock('Device', 'network', params, undefined, 0, { + state: 'connected', + type: 'wifi', + }) + }, +}); + + +/***/ }), + +/***/ "./node_modules/@firebolt-js/sdk/dist/lib/Device/index.mjs": +/*!*****************************************************************!*\ + !*** ./node_modules/@firebolt-js/sdk/dist/lib/Device/index.mjs ***! + \*****************************************************************/ +/*! exports provided: default */ +/***/ (function(__webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var _Transport_index_mjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Transport/index.mjs */ "./node_modules/@firebolt-js/sdk/dist/lib/Transport/index.mjs"); +/* harmony import */ var _Events_index_mjs__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Events/index.mjs */ "./node_modules/@firebolt-js/sdk/dist/lib/Events/index.mjs"); +/* harmony import */ var _Prop_index_mjs__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Prop/index.mjs */ "./node_modules/@firebolt-js/sdk/dist/lib/Prop/index.mjs"); +/* + * Copyright 2021 Comcast Cable Communications Management, LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + */ + + + + + + +Object(_Events_index_mjs__WEBPACK_IMPORTED_MODULE_1__["registerEvents"])('Device', [ + 'audioChanged', + 'deviceNameChanged', + 'hdcpChanged', + 'hdrChanged', + 'nameChanged', + 'networkChanged', + 'screenResolutionChanged', + 'videoResolutionChanged', +]) + +_Transport_index_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].registerDeprecatedMethod( + 'Device', + 'screenResolution', + 'Use Use non-Firebolt APIs specific to your platform, e.g. W3C APIs instead.', +) +_Transport_index_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].registerDeprecatedMethod( + 'Device', + 'onDeviceNameChanged', + 'Use Device.name() instead.', +) +_Transport_index_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].registerDeprecatedMethod( + 'Device', + 'onScreenResolutionChanged', + 'Use screenResolution instead.', +) + +function version() { + return new Promise((resolve, reject) => { + _Transport_index_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].send('device', 'version') + .then((v) => { + v = v || {} + v.sdk = v.sdk || {} + v.sdk.major = parseInt('1') + v.sdk.minor = parseInt('4') + v.sdk.patch = parseInt('1') + v.sdk.readable = 'Firebolt Core SDK 1.4.1' + resolve(v) + }) + .catch((error) => { + reject(error) + }) + }) +} + +// Methods +function audio() { + let callbackOrValue = arguments[0] + let params = {} + + // x-subscriber-type: global + if (arguments.length === 1 && typeof arguments[0] === 'function') { + callbackOrValue = arguments[0] + params = {} + } + + return _Prop_index_mjs__WEBPACK_IMPORTED_MODULE_2__["default"].prop('Device', 'audio', params, callbackOrValue, false, true, 0) +} +function clear(...args) { + return _Events_index_mjs__WEBPACK_IMPORTED_MODULE_1__["default"].clear('Device', ...args) +} + +function distributor() { + let callbackOrValue = arguments[0] + let params = {} + + // x-subscriber-type: global + if (arguments.length === 1 && typeof arguments[0] === 'function') { + callbackOrValue = arguments[0] + params = {} + } + + return _Prop_index_mjs__WEBPACK_IMPORTED_MODULE_2__["default"].prop( + 'Device', + 'distributor', + params, + callbackOrValue, + true, + true, + 0, + ) +} +function hdcp() { + let callbackOrValue = arguments[0] + let params = {} + + // x-subscriber-type: global + if (arguments.length === 1 && typeof arguments[0] === 'function') { + callbackOrValue = arguments[0] + params = {} + } + + return _Prop_index_mjs__WEBPACK_IMPORTED_MODULE_2__["default"].prop('Device', 'hdcp', params, callbackOrValue, false, true, 0) +} +function hdr() { + let callbackOrValue = arguments[0] + let params = {} + + // x-subscriber-type: global + if (arguments.length === 1 && typeof arguments[0] === 'function') { + callbackOrValue = arguments[0] + params = {} + } + + return _Prop_index_mjs__WEBPACK_IMPORTED_MODULE_2__["default"].prop('Device', 'hdr', params, callbackOrValue, false, true, 0) +} +function id() { + let callbackOrValue = arguments[0] + let params = {} + + // x-subscriber-type: global + if (arguments.length === 1 && typeof arguments[0] === 'function') { + callbackOrValue = arguments[0] + params = {} + } + + return _Prop_index_mjs__WEBPACK_IMPORTED_MODULE_2__["default"].prop('Device', 'id', params, callbackOrValue, true, true, 0) +} +function listen(...args) { + return _Events_index_mjs__WEBPACK_IMPORTED_MODULE_1__["default"].listen('Device', ...args) +} + +function make() { + let callbackOrValue = arguments[0] + let params = {} + + // x-subscriber-type: global + if (arguments.length === 1 && typeof arguments[0] === 'function') { + callbackOrValue = arguments[0] + params = {} + } + + return _Prop_index_mjs__WEBPACK_IMPORTED_MODULE_2__["default"].prop('Device', 'make', params, callbackOrValue, true, true, 0) +} +function model() { + let callbackOrValue = arguments[0] + let params = {} + + // x-subscriber-type: global + if (arguments.length === 1 && typeof arguments[0] === 'function') { + callbackOrValue = arguments[0] + params = {} + } + + return _Prop_index_mjs__WEBPACK_IMPORTED_MODULE_2__["default"].prop('Device', 'model', params, callbackOrValue, true, true, 0) +} +function name() { + let callbackOrValue = arguments[0] + let params = {} + + // x-subscriber-type: global + if (arguments.length === 1 && typeof arguments[0] === 'function') { + callbackOrValue = arguments[0] + params = {} + } + + return _Prop_index_mjs__WEBPACK_IMPORTED_MODULE_2__["default"].prop('Device', 'name', params, callbackOrValue, false, true, 0) +} +function network() { + let callbackOrValue = arguments[0] + let params = {} + + // x-subscriber-type: global + if (arguments.length === 1 && typeof arguments[0] === 'function') { + callbackOrValue = arguments[0] + params = {} + } + + return _Prop_index_mjs__WEBPACK_IMPORTED_MODULE_2__["default"].prop('Device', 'network', params, callbackOrValue, false, true, 0) +} +function once(...args) { + return _Events_index_mjs__WEBPACK_IMPORTED_MODULE_1__["default"].once('Device', ...args) +} + +function platform() { + let callbackOrValue = arguments[0] + let params = {} + + // x-subscriber-type: global + if (arguments.length === 1 && typeof arguments[0] === 'function') { + callbackOrValue = arguments[0] + params = {} + } + + return _Prop_index_mjs__WEBPACK_IMPORTED_MODULE_2__["default"].prop('Device', 'platform', params, callbackOrValue, true, true, 0) +} +function screenResolution() { + let callbackOrValue = arguments[0] + let params = {} + + // x-subscriber-type: global + if (arguments.length === 1 && typeof arguments[0] === 'function') { + callbackOrValue = arguments[0] + params = {} + } + + return _Prop_index_mjs__WEBPACK_IMPORTED_MODULE_2__["default"].prop( + 'Device', + 'screenResolution', + params, + callbackOrValue, + false, + true, + 0, + ) +} +function sku() { + let callbackOrValue = arguments[0] + let params = {} + + // x-subscriber-type: global + if (arguments.length === 1 && typeof arguments[0] === 'function') { + callbackOrValue = arguments[0] + params = {} + } + + return _Prop_index_mjs__WEBPACK_IMPORTED_MODULE_2__["default"].prop('Device', 'sku', params, callbackOrValue, true, true, 0) +} +function type() { + let callbackOrValue = arguments[0] + let params = {} + + // x-subscriber-type: global + if (arguments.length === 1 && typeof arguments[0] === 'function') { + callbackOrValue = arguments[0] + params = {} + } + + return _Prop_index_mjs__WEBPACK_IMPORTED_MODULE_2__["default"].prop('Device', 'type', params, callbackOrValue, true, true, 0) +} +function uid() { + let callbackOrValue = arguments[0] + let params = {} + + // x-subscriber-type: global + if (arguments.length === 1 && typeof arguments[0] === 'function') { + callbackOrValue = arguments[0] + params = {} + } + + return _Prop_index_mjs__WEBPACK_IMPORTED_MODULE_2__["default"].prop('Device', 'uid', params, callbackOrValue, true, true, 0) +} +function videoResolution() { + let callbackOrValue = arguments[0] + let params = {} + + // x-subscriber-type: global + if (arguments.length === 1 && typeof arguments[0] === 'function') { + callbackOrValue = arguments[0] + params = {} + } + + return _Prop_index_mjs__WEBPACK_IMPORTED_MODULE_2__["default"].prop( + 'Device', + 'videoResolution', + params, + callbackOrValue, + false, + true, + 0, + ) +} + +/* harmony default export */ __webpack_exports__["default"] = ({ + Events: { + DEVICE_NAME_CHANGED: 'deviceNameChanged', + NAME_CHANGED: 'nameChanged', + HDCP_CHANGED: 'hdcpChanged', + HDR_CHANGED: 'hdrChanged', + AUDIO_CHANGED: 'audioChanged', + SCREEN_RESOLUTION_CHANGED: 'screenResolutionChanged', + VIDEO_RESOLUTION_CHANGED: 'videoResolutionChanged', + NETWORK_CHANGED: 'networkChanged', + }, + + /** + * The type of network that is currently active + */ + NetworkState: { + CONNECTED: 'connected', + DISCONNECTED: 'disconnected', + }, + + /** + * The type of network that is currently active + */ + NetworkType: { + WIFI: 'wifi', + ETHERNET: 'ethernet', + HYBRID: 'hybrid', + }, + + version, + audio, + clear, + distributor, + hdcp, + hdr, + id, + listen, + make, + model, + name, + network, + once, + platform, + screenResolution, + sku, + type, + uid, + videoResolution, +}); + + +/***/ }), + +/***/ "./node_modules/@firebolt-js/sdk/dist/lib/Discovery/defaults.mjs": +/*!***********************************************************************!*\ + !*** ./node_modules/@firebolt-js/sdk/dist/lib/Discovery/defaults.mjs ***! + \***********************************************************************/ +/*! exports provided: default */ +/***/ (function(__webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var _Prop_MockProps_mjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Prop/MockProps.mjs */ "./node_modules/@firebolt-js/sdk/dist/lib/Prop/MockProps.mjs"); +/* + * Copyright 2021 Comcast Cable Communications Management, LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + */ + + +/* harmony default export */ __webpack_exports__["default"] = ({ + policy: function (params) { + return _Prop_MockProps_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].mock('Discovery', 'policy', params, undefined, 0, { + enableRecommendations: true, + shareWatchHistory: true, + rememberWatchedPrograms: true, + }) + }, + entityInfo: true, + purchasedContent: true, + watched: true, + watchNext: true, + entitlements: true, + contentAccess: null, + clearContentAccess: null, + launch: true, + signIn: true, + signOut: true, + userInterest: null, + userInterestResponse: null, + userInterestError: null, +}); + + +/***/ }), + +/***/ "./node_modules/@firebolt-js/sdk/dist/lib/Discovery/index.mjs": +/*!********************************************************************!*\ + !*** ./node_modules/@firebolt-js/sdk/dist/lib/Discovery/index.mjs ***! + \********************************************************************/ +/*! exports provided: default */ +/***/ (function(__webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var _Transport_index_mjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Transport/index.mjs */ "./node_modules/@firebolt-js/sdk/dist/lib/Transport/index.mjs"); +/* harmony import */ var _Events_index_mjs__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Events/index.mjs */ "./node_modules/@firebolt-js/sdk/dist/lib/Events/index.mjs"); +/* harmony import */ var _ProvideManager_index_mjs__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../ProvideManager/index.mjs */ "./node_modules/@firebolt-js/sdk/dist/lib/ProvideManager/index.mjs"); +/* harmony import */ var _Prop_index_mjs__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../Prop/index.mjs */ "./node_modules/@firebolt-js/sdk/dist/lib/Prop/index.mjs"); +/* harmony import */ var _Metrics_index_mjs__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../Metrics/index.mjs */ "./node_modules/@firebolt-js/sdk/dist/lib/Metrics/index.mjs"); +/* + * Copyright 2021 Comcast Cable Communications Management, LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + */ + + + + + + + + +Object(_Events_index_mjs__WEBPACK_IMPORTED_MODULE_1__["registerEvents"])('Discovery', ['navigateTo', 'policyChanged']) + +Object(_ProvideManager_index_mjs__WEBPACK_IMPORTED_MODULE_2__["registerProviderInterface"])( + 'xrn:firebolt:capability:discovery:interest', + 'Discovery', + [{ name: 'userInterest', focus: false, response: true, parameters: true }], +) + +_Transport_index_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].registerDeprecatedMethod( + 'Discovery', + 'entityInfo', + 'Use null instead.', +) +_Transport_index_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].registerDeprecatedMethod( + 'Discovery', + 'purchasedContent', + 'Use null instead.', +) +_Transport_index_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].registerDeprecatedMethod( + 'Discovery', + 'entitlements', + 'Use Discovery.contentAccess() instead.', +) +_Transport_index_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].registerDeprecatedMethod( + 'Discovery', + 'onPullEntityInfo', + 'Use null instead.', +) +_Transport_index_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].registerDeprecatedMethod( + 'Discovery', + 'onPullPurchasedContent', + 'Use null instead.', +) + +// onNavigateTo is accessed via listen('navigateTo, ...) + +// onPolicyChanged is accessed via listen('policyChanged, ...) + +// Methods +function clear(...args) { + return _Events_index_mjs__WEBPACK_IMPORTED_MODULE_1__["default"].clear('Discovery', ...args) +} + +function clearContentAccess() { + const transforms = null + + return _Transport_index_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].send('Discovery', 'clearContentAccess', {}, transforms) +} + +function contentAccess(ids) { + const transforms = null + + return _Transport_index_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].send('Discovery', 'contentAccess', { ids }, transforms) +} + +function entitlements(entitlements) { + const transforms = null + + return _Transport_index_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].send( + 'Discovery', + 'entitlements', + { entitlements }, + transforms, + ) +} + +let entityInfoHasCallback = false + +function entityInfo(data) { + if (arguments.length === 1 && typeof arguments[0] === 'function') { + if (entityInfoHasCallback) { + return Promise.reject('Cannot register more than one entityInfo handler.') + } + + const callback = arguments[0] + entityInfoHasCallback = true + return _Events_index_mjs__WEBPACK_IMPORTED_MODULE_1__["default"].listen('Discovery', 'pullEntityInfo', (request) => { + if (typeof request === 'boolean') return + + try { + const result = callback(request.parameters) + .then((result) => { + const params = { + correlationId: request.correlationId, + result: result, + } + _Transport_index_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].send('Discovery', 'entityInfo', params).catch((error) => { + const msg = + typeof error === 'string' + ? error + : error.message || 'Unknown Error' + console.error( + `Failed to send entityInfo pull response through Transport Layer: ${msg}`, + ) + }) + }) + .catch((error) => { + const msg = + typeof error === 'string' + ? error + : error.message || 'Unknown Error' + console.error(`App 'entityInfo' callback failed: ${msg}`) + }) + } catch (error) { + const msg = + typeof error === 'string' ? error : error.message || 'Unknown Error' + console.error(`App 'entityInfo' callback failed: ${msg}`) + } + }) + } else { + return _Transport_index_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].send('Discovery', 'entityInfo', { + correlationId: null, + result: data, + }) + } +} + +function launch(appId, intent) { + const transforms = null + + return _Transport_index_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].send('Discovery', 'launch', { appId, intent }, transforms) +} +function listen(...args) { + return _Events_index_mjs__WEBPACK_IMPORTED_MODULE_1__["default"].listen('Discovery', ...args) +} + +function once(...args) { + return _Events_index_mjs__WEBPACK_IMPORTED_MODULE_1__["default"].once('Discovery', ...args) +} + +function policy() { + let callbackOrValue = arguments[0] + let params = {} + + // x-subscriber-type: global + if (arguments.length === 1 && typeof arguments[0] === 'function') { + callbackOrValue = arguments[0] + params = {} + } + + return _Prop_index_mjs__WEBPACK_IMPORTED_MODULE_3__["default"].prop( + 'Discovery', + 'policy', + params, + callbackOrValue, + false, + true, + 0, + ) +} +function provide(capability, provider) { + return _ProvideManager_index_mjs__WEBPACK_IMPORTED_MODULE_2__["default"].provide(capability, provider) +} + +let purchasedContentHasCallback = false + +function purchasedContent(data) { + if (arguments.length === 1 && typeof arguments[0] === 'function') { + if (purchasedContentHasCallback) { + return Promise.reject( + 'Cannot register more than one purchasedContent handler.', + ) + } + + const callback = arguments[0] + purchasedContentHasCallback = true + return _Events_index_mjs__WEBPACK_IMPORTED_MODULE_1__["default"].listen('Discovery', 'pullPurchasedContent', (request) => { + if (typeof request === 'boolean') return + + try { + const result = callback(request.parameters) + .then((result) => { + const params = { + correlationId: request.correlationId, + result: result, + } + _Transport_index_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].send('Discovery', 'purchasedContent', params).catch( + (error) => { + const msg = + typeof error === 'string' + ? error + : error.message || 'Unknown Error' + console.error( + `Failed to send purchasedContent pull response through Transport Layer: ${msg}`, + ) + }, + ) + }) + .catch((error) => { + const msg = + typeof error === 'string' + ? error + : error.message || 'Unknown Error' + console.error(`App 'purchasedContent' callback failed: ${msg}`) + }) + } catch (error) { + const msg = + typeof error === 'string' ? error : error.message || 'Unknown Error' + console.error(`App 'purchasedContent' callback failed: ${msg}`) + } + }) + } else { + return _Transport_index_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].send('Discovery', 'purchasedContent', { + correlationId: null, + result: data, + }) + } +} + + + +function signIn(entitlements) { + const transforms = null + + const p = _Transport_index_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].send('Discovery', 'signIn', { entitlements }, transforms) + + p.then((_) => { + setTimeout((_) => { + Object(_Metrics_index_mjs__WEBPACK_IMPORTED_MODULE_4__["signIn"])(entitlements) + }) + }).catch((error) => { + const msg = + typeof error === 'string' ? error : error.message || 'Unknown Error' + console.error(`Metrics 'signIn' callback failed: ${msg}`) + }) + + return p +} + + + +function signOut() { + const transforms = null + + const p = _Transport_index_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].send('Discovery', 'signOut', {}, transforms) + + p.then((_) => { + setTimeout((_) => { + Object(_Metrics_index_mjs__WEBPACK_IMPORTED_MODULE_4__["signOut"])() + }) + }).catch((error) => { + const msg = + typeof error === 'string' ? error : error.message || 'Unknown Error' + console.error(`Metrics 'signOut' callback failed: ${msg}`) + }) + + return p +} + +function userInterest(type, reason, entity) { + const transforms = null + + return _Transport_index_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].send( + 'Discovery', + 'userInterest', + { type, reason, entity }, + transforms, + ) +} + +function watched(entityId, progress, completed, watchedOn) { + const transforms = null + + if (arguments.length === 1 && Array.isArray(arguments[0])) { + return _Transport_index_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].send('Discovery', 'watched', arguments[0], transforms) + } else { + return _Transport_index_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].send( + 'Discovery', + 'watched', + { entityId, progress, completed, watchedOn }, + transforms, + ) + } +} + +function watchNext(title, identifiers, expires, images) { + const transforms = null + + return _Transport_index_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].send( + 'Discovery', + 'watchNext', + { title, identifiers, expires, images }, + transforms, + ) +} + +/* harmony default export */ __webpack_exports__["default"] = ({ + Events: { + NAVIGATE_TO: 'navigateTo', + POLICY_CHANGED: 'policyChanged', + PULL_ENTITY_INFO: 'pullEntityInfo', + PULL_PURCHASED_CONTENT: 'pullPurchasedContent', + }, + + /** + * + */ + InterestType: { + INTEREST: 'interest', + DISINTEREST: 'disinterest', + }, + + /** + * + */ + InterestReason: { + PLAYLIST: 'playlist', + REACTION: 'reaction', + RECORDING: 'recording', + }, + + /** + * In the case of a program `entityType`, specifies the program type. + */ + ProgramType: { + MOVIE: 'movie', + EPISODE: 'episode', + SEASON: 'season', + SERIES: 'series', + OTHER: 'other', + PREVIEW: 'preview', + EXTRA: 'extra', + CONCERT: 'concert', + SPORTING_EVENT: 'sportingEvent', + ADVERTISEMENT: 'advertisement', + MUSIC_VIDEO: 'musicVideo', + MINISODE: 'minisode', + }, + + /** + * In the case of a music `entityType`, specifies the type of music entity. + */ + MusicType: { + SONG: 'song', + ALBUM: 'album', + }, + + /** + * The offering type of the WayToWatch. + */ + OfferingType: { + FREE: 'free', + SUBSCRIBE: 'subscribe', + BUY: 'buy', + RENT: 'rent', + }, + + /** + * + */ + AudioProfile: { + STEREO: 'stereo', + DOLBY_DIGITAL_5_1: 'dolbyDigital5.1', + DOLBY_DIGITAL_5_1_PLUS: 'dolbyDigital5.1+', + DOLBY_ATMOS: 'dolbyAtmos', + }, + + clear, + clearContentAccess, + contentAccess, + entitlements, + entityInfo, + launch, + listen, + once, + policy, + provide, + purchasedContent, + signIn, + signOut, + userInterest, + watched, + watchNext, +}); + + +/***/ }), + +/***/ "./node_modules/@firebolt-js/sdk/dist/lib/Events/index.mjs": +/*!*****************************************************************!*\ + !*** ./node_modules/@firebolt-js/sdk/dist/lib/Events/index.mjs ***! + \*****************************************************************/ +/*! exports provided: emit, registerEvents, registerEventContext, prioritize, default */ +/***/ (function(__webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "emit", function() { return emit; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "registerEvents", function() { return registerEvents; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "registerEventContext", function() { return registerEventContext; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "prioritize", function() { return prioritize; }); +/* harmony import */ var _Transport_index_mjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Transport/index.mjs */ "./node_modules/@firebolt-js/sdk/dist/lib/Transport/index.mjs"); +/* harmony import */ var _Transport_MockTransport_mjs__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Transport/MockTransport.mjs */ "./node_modules/@firebolt-js/sdk/dist/lib/Transport/MockTransport.mjs"); +/* + * Copyright 2021 Comcast Cable Communications Management, LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + */ + + + + +let listenerId = 0 + +// holds two maps of ${module}.${event} => listenerId, e.g. callback method id +// note that one callback can listen to multiple events, e.g. 'discovery.*' +// internal is only available via a private export that we use to ensure our modules know about +// events before the apps using the SDK (otherwise state errors can happen) +const listeners = { + internal: {}, + external: {}, + + // Several convenience functions below for checking both internal & external lists w/ one operation + + // gets a merge list of ids for a single event key + get: (key) => { + return Object.assign( + Object.assign({}, listeners.internal[key]), + listeners.external[key], + ) + }, + // adds a callback/id to a key on the external list only + set: (key, id, value) => { + listeners.external[key] = listeners.external[key] || {} + listeners.external[key][id] = value + }, + // adds a callback/id to a key on the internal list only + setInternal: (key, id, value) => { + listeners.internal[key] = listeners.internal[key] || {} + listeners.internal[key][id] = value + }, + // finds the key for an id in either list (it can only be in one) + find: (id) => { + let key + ;[listeners.internal, listeners.external].find((group) => { + key = Object.keys(group).find((key) => group[key][id]) + if (key) return true + }) + return key + }, + // removes an id from either list + remove: (id) => { + ;[listeners.internal, listeners.external].forEach((group) => { + Object.keys(group).forEach((key) => { + if (group[key] && group[key][id]) { + delete group[key][id] + if (Object.values(group[key]).length === 0) { + delete group[key] + } + } + }) + }) + }, + // removes a key from both lists if _internal is true, otherwise only the external list + removeKey: (key, _internal = false) => { + _internal && listeners.internal[key] && delete listeners.internal[key] + listeners.external[key] && delete listeners.external[key] + }, + // gives a list of all keys + keys: () => { + return Array.from( + new Set( + Object.keys(listeners.internal).concat(Object.keys(listeners.external)), + ), + ) + }, + // counts how many listeners are in a key across both lists + count: (key) => { + return Object.values(listeners.get(key)).length + }, +} + +// holds a map of RPC Ids => Context Key, e.g. the RPC id of an onEvent call mapped to the corresponding context parameters key for that RPC call +const keys = {} + +// holds a map of ${module}.${event} => Transport.send calls (only called once per event) +// note that the keys here MUST NOT contain wild cards +const oncers = [] +const validEvents = {} +const validContext = {} + +let transportInitialized = false + +const emit = (id, value) => { + callCallbacks(listeners.internal[keys[id]], [value]) + callCallbacks(listeners.external[keys[id]], [value]) +} + +const registerEvents = (module, events) => { + validEvents[module.toLowerCase()] = events.concat() +} + +const registerEventContext = (module, event, context) => { + validContext[module.toLowerCase()] = validContext[module.toLowerCase()] || {} + validContext[module.toLowerCase()][event] = context.concat() +} + +const callCallbacks = (cbs, args) => { + cbs && + Object.keys(cbs).forEach((listenerId) => { + let callback = cbs[listenerId] + if (oncers.indexOf(parseInt(listenerId)) >= 0) { + oncers.splice(oncers.indexOf(parseInt(listenerId)), 1) + delete cbs[listenerId] + } + callback.apply(null, args) + }) +} + +const doListen = function ( + module, + event, + callback, + context, + once, + internal = false, +) { + init() + + if (typeof callback !== 'function') { + return Promise.reject('No valid callback function provided.') + } else { + if (module === '*') { + return Promise.reject('No valid module name provided') + } + + const wildcard = event === '*' + const events = wildcard ? validEvents[module] : [event] // explodes wildcards into an array + const promises = [] + const hasContext = Object.values(context).length > 0 + const contextKey = Object.keys(context) + .sort() + .map((key) => key + '=' + JSON.stringify(context[key])) + .join('&') + + listenerId++ + + if (once) { + oncers.push(listenerId) + } + + events.forEach((event) => { + const key = module + '.' + event + (hasContext ? `.${contextKey}` : '') + + if (Object.values(listeners.get(key)).length === 0) { + const args = Object.assign({ listen: true }, context) + const { id, promise } = _Transport_index_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].listen( + module, + 'on' + event[0].toUpperCase() + event.substring(1), + args, + ) + keys[id] = key + promises.push(promise) + } + + const setter = internal ? listeners.setInternal : listeners.set + + if (wildcard) { + setter(key, '' + listenerId, (value) => callback(event, value)) + } else { + setter(key, '' + listenerId, callback) + } + }) + + let resolve, reject + let p = new Promise((res, rej) => { + resolve = res + reject = rej + }) + + if (promises.length) { + Promise.all(promises) + .then((responses) => { + resolve(listenerId) + }) + .catch((error) => { + // Promise.all rejects if at least one promise rejects... we don't want that behavior here + // TODO: Do something better than fail silently + if (event === '*') { + resolve(listenerId) + } else { + reject(error) + } + }) + } else { + resolve(listenerId) + } + return p + } +} + +const getListenArgs = function (...args) { + const callback = args.pop() + const [module, event, context] = getClearArgs(...args) + + return [module, event, callback, context] +} + +const getClearArgs = function (...args) { + const module = (args.shift() || '*').toLowerCase() + const event = args.shift() || '*' + const context = {} + + for (let i = 0; args.length; i++) { + context[validContext[module][event][i]] = args.shift() + } + + return [module, event, context] +} + +const once = function (...args) { + const [module, event, callback, context] = getListenArgs(...args) + return doListen(module, event, callback, context, true) +} + +const listen = function (...args) { + const [module, event, callback, context] = getListenArgs(...args) + return doListen(module, event, callback, context, false) +} + +const clear = function (...args) { + if (args && args.length && typeof args[0] === 'number') { + return doClear(args[0]) + } else if (args && args.length && typeof args[1] === 'number') { + return doClear(args[1]) + } else { + const [moduleOrId, event, context] = getClearArgs(...args) + return doClear(moduleOrId, event, context) + } +} + +// calls doListen with a priority flag for internal listeners to get priority +const prioritize = function (...args) { + const [module, event, callback, context] = getListenArgs(...args) + return doListen(module, event, callback, context, false, true) +} + +const unsubscribe = (key, context) => { + const [module, event] = key.split('.').slice(0, 2) + const args = Object.assign({ listen: false }, context) + _Transport_index_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].send(module, 'on' + event[0].toUpperCase() + event.substr(1), args) +} + +// TODO: clear needs to go through Transport Layer +const doClear = function (moduleOrId = false, event = false, context) { + if (event === '*') { + event = false + } + + if (typeof moduleOrId === 'number') { + const searchId = moduleOrId.toString() + const key = listeners.find(searchId) + + if (key) { + listeners.remove(searchId) + if (listeners.count(key) === 0) { + unsubscribe(key) + } + return true + } + return false + } else { + if (!moduleOrId && !event) { + listeners.keys().forEach((key) => { + listeners.removeKey(key) + unsubscribe(key) + }) + } else if (!event) { + listeners.keys().forEach((key) => { + if (key.indexOf(moduleOrId.toLowerCase()) === 0) { + listeners.removeKey(key) + unsubscribe(key) + } + }) + } else { + const hasContext = Object.values(context).length > 0 + const contextKey = Object.keys(context) + .sort() + .map((key) => key + '=' + JSON.stringify(context[key])) + .join('&') + const key = + moduleOrId + '.' + event + (hasContext ? `.${contextKey}` : '') + + listeners.removeKey(key) + unsubscribe(key, context) + } + } +} + +const init = () => { + if (!transportInitialized) { + _Transport_index_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].addEventEmitter(emit) + Object(_Transport_MockTransport_mjs__WEBPACK_IMPORTED_MODULE_1__["setMockListener"])(listen) + transportInitialized = true + } +} + +/* harmony default export */ __webpack_exports__["default"] = ({ + listen: listen, + once: once, + clear: clear, + broadcast(event, value) { + emit(Object.entries(keys).find(([k, v]) => v === 'app.' + event)[0], value) + }, +}); + + +/***/ }), + +/***/ "./node_modules/@firebolt-js/sdk/dist/lib/Keyboard/defaults.mjs": +/*!**********************************************************************!*\ + !*** ./node_modules/@firebolt-js/sdk/dist/lib/Keyboard/defaults.mjs ***! + \**********************************************************************/ +/*! exports provided: default */ +/***/ (function(__webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var _Prop_MockProps_mjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Prop/MockProps.mjs */ "./node_modules/@firebolt-js/sdk/dist/lib/Prop/MockProps.mjs"); +/* + * Copyright 2021 Comcast Cable Communications Management, LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + */ + + +/* harmony default export */ __webpack_exports__["default"] = ({ + email: 'user@domain.com', + password: 'abc123', + standard: 'Living Room', +}); + + +/***/ }), + +/***/ "./node_modules/@firebolt-js/sdk/dist/lib/Keyboard/index.mjs": +/*!*******************************************************************!*\ + !*** ./node_modules/@firebolt-js/sdk/dist/lib/Keyboard/index.mjs ***! + \*******************************************************************/ +/*! exports provided: default */ +/***/ (function(__webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var _Transport_index_mjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Transport/index.mjs */ "./node_modules/@firebolt-js/sdk/dist/lib/Transport/index.mjs"); +/* + * Copyright 2021 Comcast Cable Communications Management, LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + */ + + + +// Methods + +function email(type, message) { + const transforms = null + + return _Transport_index_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].send('Keyboard', 'email', { type, message }, transforms) +} + +function password(message) { + const transforms = null + + return _Transport_index_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].send('Keyboard', 'password', { message }, transforms) +} + +function standard(message) { + const transforms = null + + return _Transport_index_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].send('Keyboard', 'standard', { message }, transforms) +} + +/* harmony default export */ __webpack_exports__["default"] = ({ + /** + * + */ + EmailUsage: { + SIGN_IN: 'signIn', + SIGN_UP: 'signUp', + }, + + email, + password, + standard, +}); + + +/***/ }), + +/***/ "./node_modules/@firebolt-js/sdk/dist/lib/Lifecycle/defaults.mjs": +/*!***********************************************************************!*\ + !*** ./node_modules/@firebolt-js/sdk/dist/lib/Lifecycle/defaults.mjs ***! + \***********************************************************************/ +/*! exports provided: default */ +/***/ (function(__webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var _Transport_MockTransport_mjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Transport/MockTransport.mjs */ "./node_modules/@firebolt-js/sdk/dist/lib/Transport/MockTransport.mjs"); +/* + * Copyright 2021 Comcast Cable Communications Management, LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + */ + + + +let inactive = { state: 'inactive', previous: 'initializing' } +let foreground = { state: 'foreground', previous: 'inactive' } +let background = { state: 'background', previous: 'foreground' } +let suspended = { state: 'suspended', previous: 'inactive' } +let unloading = { state: 'unloading', previous: 'inactive' } + +const emit = (value) => { + _Transport_MockTransport_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].event('Lifecycle', value.state, value) +} + +const win = typeof window !== 'undefined' ? window : {} +const automation = win.__firebolt ? !!win.__firebolt.automation : false + +/* harmony default export */ __webpack_exports__["default"] = ({ + ready: function () { + inactive.previous = 'initializing' + setTimeout(() => emit(inactive), automation ? 1 : 500) + foreground.previous = 'inactive' + setTimeout(() => emit(foreground), automation ? 2 : 1000) + }, + + close: function (params) { + let reason = params.reason + if (reason === 'remoteButton') { + inactive.previous = 'foreground' + setTimeout(() => emit(inactive), automation ? 1 : 500) + } else if (['userExit', 'error'].includes(reason)) { + inactive.previous = 'foreground' + unloading.previous = 'inactive' + setTimeout(() => emit(inactive), automation ? 1 : 500) + setTimeout(() => emit(unloading), automation ? 2 : 1000) + } else { + throw 'Invalid close reason' + } + }, + + finished: function () { + if (win.location) win.location.href = 'about:blank' + }, +}); + + +/***/ }), + +/***/ "./node_modules/@firebolt-js/sdk/dist/lib/Lifecycle/index.mjs": +/*!********************************************************************!*\ + !*** ./node_modules/@firebolt-js/sdk/dist/lib/Lifecycle/index.mjs ***! + \********************************************************************/ +/*! exports provided: store, default */ +/***/ (function(__webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "store", function() { return store; }); +/* harmony import */ var _Transport_index_mjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Transport/index.mjs */ "./node_modules/@firebolt-js/sdk/dist/lib/Transport/index.mjs"); +/* harmony import */ var _Events_index_mjs__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Events/index.mjs */ "./node_modules/@firebolt-js/sdk/dist/lib/Events/index.mjs"); +/* harmony import */ var _Metrics_index_mjs__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Metrics/index.mjs */ "./node_modules/@firebolt-js/sdk/dist/lib/Metrics/index.mjs"); +/* + * Copyright 2021 Comcast Cable Communications Management, LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + */ + + + + + + + +Object(_Events_index_mjs__WEBPACK_IMPORTED_MODULE_1__["registerEvents"])('Lifecycle', [ + 'background', + 'foreground', + 'inactive', + 'suspended', + 'unloading', +]) + +const store = { + _current: 'initializing', + get current() { + return this._current + }, +} + +async function ready() { + let readyRes + await Object(_Events_index_mjs__WEBPACK_IMPORTED_MODULE_1__["prioritize"])('Lifecycle', (event, value) => { + store._current = event + }) + readyRes = await _Transport_index_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].send('lifecycle', 'ready', {}) + setTimeout((_) => { + Object(_Metrics_index_mjs__WEBPACK_IMPORTED_MODULE_2__["ready"])() + }) + return readyRes +} + +// Methods +function clear(...args) { + return _Events_index_mjs__WEBPACK_IMPORTED_MODULE_1__["default"].clear('Lifecycle', ...args) +} + +function close(reason) { + const transforms = null + + return _Transport_index_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].send('Lifecycle', 'close', { reason }, transforms) +} +function listen(...args) { + return _Events_index_mjs__WEBPACK_IMPORTED_MODULE_1__["default"].listen('Lifecycle', ...args) +} + +function once(...args) { + return _Events_index_mjs__WEBPACK_IMPORTED_MODULE_1__["default"].once('Lifecycle', ...args) +} + +function state() { + return store.current +} + +function finished() { + if (store.current === 'unloading') { + return _Transport_index_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].send('lifecycle', 'finished') + } else { + throw 'Cannot call finished() except when in the unloading transition' + } +} + +// public API +/* harmony default export */ __webpack_exports__["default"] = ({ + Events: { + INACTIVE: 'inactive', + FOREGROUND: 'foreground', + BACKGROUND: 'background', + SUSPENDED: 'suspended', + UNLOADING: 'unloading', + }, + + /** + * The application close reason + */ + CloseReason: { + REMOTE_BUTTON: 'remoteButton', + USER_EXIT: 'userExit', + DONE: 'done', + ERROR: 'error', + }, + + /** + * The application lifecycle state + */ + LifecycleState: { + INITIALIZING: 'initializing', + INACTIVE: 'inactive', + FOREGROUND: 'foreground', + BACKGROUND: 'background', + UNLOADING: 'unloading', + SUSPENDED: 'suspended', + }, + + ready, + state, + finished, + + clear, + close, + listen, + once, +}); + + +/***/ }), + +/***/ "./node_modules/@firebolt-js/sdk/dist/lib/Localization/defaults.mjs": +/*!**************************************************************************!*\ + !*** ./node_modules/@firebolt-js/sdk/dist/lib/Localization/defaults.mjs ***! + \**************************************************************************/ +/*! exports provided: default */ +/***/ (function(__webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var _Prop_MockProps_mjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Prop/MockProps.mjs */ "./node_modules/@firebolt-js/sdk/dist/lib/Prop/MockProps.mjs"); +/* + * Copyright 2021 Comcast Cable Communications Management, LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + */ + + +/* harmony default export */ __webpack_exports__["default"] = ({ + locality: function (params) { + return _Prop_MockProps_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].mock( + 'Localization', + 'locality', + params, + undefined, + 0, + 'Philadelphia', + ) + }, + postalCode: function (params) { + return _Prop_MockProps_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].mock( + 'Localization', + 'postalCode', + params, + undefined, + 0, + '19103', + ) + }, + countryCode: function (params) { + return _Prop_MockProps_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].mock( + 'Localization', + 'countryCode', + params, + undefined, + 0, + 'US', + ) + }, + language: function (params) { + return _Prop_MockProps_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].mock( + 'Localization', + 'language', + params, + undefined, + 0, + 'en', + ) + }, + preferredAudioLanguages: function (params) { + return _Prop_MockProps_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].mock( + 'Localization', + 'preferredAudioLanguages', + params, + undefined, + 0, + ['spa', 'eng'], + ) + }, + locale: function (params) { + return _Prop_MockProps_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].mock( + 'Localization', + 'locale', + params, + undefined, + 0, + 'en-US', + ) + }, + latlon: [39.9549, 75.1699], + additionalInfo: {}, +}); + + +/***/ }), + +/***/ "./node_modules/@firebolt-js/sdk/dist/lib/Localization/index.mjs": +/*!***********************************************************************!*\ + !*** ./node_modules/@firebolt-js/sdk/dist/lib/Localization/index.mjs ***! + \***********************************************************************/ +/*! exports provided: default */ +/***/ (function(__webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var _Transport_index_mjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Transport/index.mjs */ "./node_modules/@firebolt-js/sdk/dist/lib/Transport/index.mjs"); +/* harmony import */ var _Events_index_mjs__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Events/index.mjs */ "./node_modules/@firebolt-js/sdk/dist/lib/Events/index.mjs"); +/* harmony import */ var _Prop_index_mjs__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Prop/index.mjs */ "./node_modules/@firebolt-js/sdk/dist/lib/Prop/index.mjs"); +/* + * Copyright 2021 Comcast Cable Communications Management, LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + */ + + + + + + +Object(_Events_index_mjs__WEBPACK_IMPORTED_MODULE_1__["registerEvents"])('Localization', [ + 'countryCodeChanged', + 'languageChanged', + 'localeChanged', + 'localityChanged', + 'postalCodeChanged', + 'preferredAudioLanguagesChanged', +]) + +_Transport_index_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].registerDeprecatedMethod( + 'Localization', + 'language', + 'Use Localization.locale instead.', +) +_Transport_index_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].registerDeprecatedMethod( + 'Localization', + 'onLanguageChanged', + 'Use language instead.', +) + +// onCountryCodeChanged is accessed via listen('countryCodeChanged, ...) + +// onLanguageChanged is accessed via listen('languageChanged, ...) + +// onLocaleChanged is accessed via listen('localeChanged, ...) + +// onLocalityChanged is accessed via listen('localityChanged, ...) + +// onPostalCodeChanged is accessed via listen('postalCodeChanged, ...) + +// onPreferredAudioLanguagesChanged is accessed via listen('preferredAudioLanguagesChanged, ...) + +// Methods + +function additionalInfo() { + const transforms = null + + return _Transport_index_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].send('Localization', 'additionalInfo', {}, transforms) +} +function clear(...args) { + return _Events_index_mjs__WEBPACK_IMPORTED_MODULE_1__["default"].clear('Localization', ...args) +} + +function countryCode() { + let callbackOrValue = arguments[0] + let params = {} + + // x-subscriber-type: global + if (arguments.length === 1 && typeof arguments[0] === 'function') { + callbackOrValue = arguments[0] + params = {} + } + + return _Prop_index_mjs__WEBPACK_IMPORTED_MODULE_2__["default"].prop( + 'Localization', + 'countryCode', + params, + callbackOrValue, + false, + true, + 0, + ) +} +function language() { + let callbackOrValue = arguments[0] + let params = {} + + // x-subscriber-type: global + if (arguments.length === 1 && typeof arguments[0] === 'function') { + callbackOrValue = arguments[0] + params = {} + } + + return _Prop_index_mjs__WEBPACK_IMPORTED_MODULE_2__["default"].prop( + 'Localization', + 'language', + params, + callbackOrValue, + false, + true, + 0, + ) +} + +function latlon() { + const transforms = null + + return _Transport_index_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].send('Localization', 'latlon', {}, transforms) +} +function listen(...args) { + return _Events_index_mjs__WEBPACK_IMPORTED_MODULE_1__["default"].listen('Localization', ...args) +} + +function locale() { + let callbackOrValue = arguments[0] + let params = {} + + // x-subscriber-type: global + if (arguments.length === 1 && typeof arguments[0] === 'function') { + callbackOrValue = arguments[0] + params = {} + } + + return _Prop_index_mjs__WEBPACK_IMPORTED_MODULE_2__["default"].prop( + 'Localization', + 'locale', + params, + callbackOrValue, + false, + true, + 0, + ) +} +function locality() { + let callbackOrValue = arguments[0] + let params = {} + + // x-subscriber-type: global + if (arguments.length === 1 && typeof arguments[0] === 'function') { + callbackOrValue = arguments[0] + params = {} + } + + return _Prop_index_mjs__WEBPACK_IMPORTED_MODULE_2__["default"].prop( + 'Localization', + 'locality', + params, + callbackOrValue, + false, + true, + 0, + ) +} +function once(...args) { + return _Events_index_mjs__WEBPACK_IMPORTED_MODULE_1__["default"].once('Localization', ...args) +} + +function postalCode() { + let callbackOrValue = arguments[0] + let params = {} + + // x-subscriber-type: global + if (arguments.length === 1 && typeof arguments[0] === 'function') { + callbackOrValue = arguments[0] + params = {} + } + + return _Prop_index_mjs__WEBPACK_IMPORTED_MODULE_2__["default"].prop( + 'Localization', + 'postalCode', + params, + callbackOrValue, + false, + true, + 0, + ) +} +function preferredAudioLanguages() { + let callbackOrValue = arguments[0] + let params = {} + + // x-subscriber-type: global + if (arguments.length === 1 && typeof arguments[0] === 'function') { + callbackOrValue = arguments[0] + params = {} + } + + return _Prop_index_mjs__WEBPACK_IMPORTED_MODULE_2__["default"].prop( + 'Localization', + 'preferredAudioLanguages', + params, + callbackOrValue, + false, + true, + 0, + ) +} + +/* harmony default export */ __webpack_exports__["default"] = ({ + Events: { + LOCALITY_CHANGED: 'localityChanged', + POSTAL_CODE_CHANGED: 'postalCodeChanged', + COUNTRY_CODE_CHANGED: 'countryCodeChanged', + LANGUAGE_CHANGED: 'languageChanged', + PREFERRED_AUDIO_LANGUAGES_CHANGED: 'preferredAudioLanguagesChanged', + LOCALE_CHANGED: 'localeChanged', + }, + + additionalInfo, + clear, + countryCode, + language, + latlon, + listen, + locale, + locality, + once, + postalCode, + preferredAudioLanguages, +}); + + +/***/ }), + +/***/ "./node_modules/@firebolt-js/sdk/dist/lib/Log/index.mjs": +/*!**************************************************************!*\ + !*** ./node_modules/@firebolt-js/sdk/dist/lib/Log/index.mjs ***! + \**************************************************************/ +/*! exports provided: default */ +/***/ (function(__webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var _Settings_index_mjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Settings/index.mjs */ "./node_modules/@firebolt-js/sdk/dist/lib/Settings/index.mjs"); +/* + * Copyright 2021 Comcast Cable Communications Management, LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + */ + + + +const prepLog = (type, args) => { + const colors = { + Info: 'green', + Debug: 'gray', + Warn: 'orange', + Error: 'red', + } + + args = Array.from(args) + return [ + '%c' + + (args.length > 1 && typeof args[0] === 'string' ? args.shift() : type), + 'background-color: ' + + colors[type] + + '; color: white; padding: 2px 4px; border-radius: 2px', + args, + ] +} + +/* harmony default export */ __webpack_exports__["default"] = ({ + info() { + _Settings_index_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].get('platform', 'log') && + console.log.apply(console, prepLog('Info', arguments)) + }, + debug() { + _Settings_index_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].get('platform', 'log') && + console.debug.apply(console, prepLog('Debug', arguments)) + }, + error() { + _Settings_index_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].get('platform', 'log') && + console.error.apply(console, prepLog('Error', arguments)) + }, + warn() { + _Settings_index_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].get('platform', 'log') && + console.warn.apply(console, prepLog('Warn', arguments)) + }, +}); + + +/***/ }), + +/***/ "./node_modules/@firebolt-js/sdk/dist/lib/Metrics/defaults.mjs": +/*!*********************************************************************!*\ + !*** ./node_modules/@firebolt-js/sdk/dist/lib/Metrics/defaults.mjs ***! + \*********************************************************************/ +/*! exports provided: default */ +/***/ (function(__webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var _Prop_MockProps_mjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Prop/MockProps.mjs */ "./node_modules/@firebolt-js/sdk/dist/lib/Prop/MockProps.mjs"); +/* + * Copyright 2021 Comcast Cable Communications Management, LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + */ + + +/* harmony default export */ __webpack_exports__["default"] = ({ + ready: true, + signIn: true, + signOut: true, + startContent: true, + stopContent: true, + page: true, + action: true, + error: true, + mediaLoadStart: true, + mediaPlay: true, + mediaPlaying: true, + mediaPause: true, + mediaWaiting: true, + mediaProgress: true, + mediaSeeking: true, + mediaSeeked: true, + mediaRateChange: true, + mediaRenditionChange: true, + mediaEnded: true, + appInfo: null, +}); + + +/***/ }), + +/***/ "./node_modules/@firebolt-js/sdk/dist/lib/Metrics/index.mjs": +/*!******************************************************************!*\ + !*** ./node_modules/@firebolt-js/sdk/dist/lib/Metrics/index.mjs ***! + \******************************************************************/ +/*! exports provided: default, ready, signIn, signOut */ +/***/ (function(__webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ready", function() { return ready; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "signIn", function() { return signIn; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "signOut", function() { return signOut; }); +/* harmony import */ var _Transport_index_mjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Transport/index.mjs */ "./node_modules/@firebolt-js/sdk/dist/lib/Transport/index.mjs"); +/* + * Copyright 2021 Comcast Cable Communications Management, LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + */ + + + +function ready() { + return _Transport_index_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].send('metrics', 'ready', {}) +} + +function signIn() { + return _Transport_index_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].send('metrics', 'signIn', {}) +} + +function signOut() { + return _Transport_index_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].send('metrics', 'signOut', {}) +} + +// Methods + +function action(category, type, parameters) { + const transforms = null + + return _Transport_index_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].send( + 'Metrics', + 'action', + { category, type, parameters }, + transforms, + ) +} + +function appInfo(build) { + const transforms = null + + return _Transport_index_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].send('Metrics', 'appInfo', { build }, transforms) +} + +function error(type, code, description, visible, parameters) { + const transforms = null + + return _Transport_index_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].send( + 'Metrics', + 'error', + { type, code, description, visible, parameters }, + transforms, + ) +} + +function mediaEnded(entityId) { + const transforms = null + + return _Transport_index_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].send('Metrics', 'mediaEnded', { entityId }, transforms) +} + +function mediaLoadStart(entityId) { + const transforms = null + + return _Transport_index_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].send('Metrics', 'mediaLoadStart', { entityId }, transforms) +} + +function mediaPause(entityId) { + const transforms = null + + return _Transport_index_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].send('Metrics', 'mediaPause', { entityId }, transforms) +} + +function mediaPlay(entityId) { + const transforms = null + + return _Transport_index_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].send('Metrics', 'mediaPlay', { entityId }, transforms) +} + +function mediaPlaying(entityId) { + const transforms = null + + return _Transport_index_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].send('Metrics', 'mediaPlaying', { entityId }, transforms) +} + +function mediaProgress(entityId, progress) { + const transforms = null + + return _Transport_index_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].send( + 'Metrics', + 'mediaProgress', + { entityId, progress }, + transforms, + ) +} + +function mediaRateChange(entityId, rate) { + const transforms = null + + return _Transport_index_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].send( + 'Metrics', + 'mediaRateChange', + { entityId, rate }, + transforms, + ) +} + +function mediaRenditionChange(entityId, bitrate, width, height, profile) { + const transforms = null + + return _Transport_index_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].send( + 'Metrics', + 'mediaRenditionChange', + { entityId, bitrate, width, height, profile }, + transforms, + ) +} + +function mediaSeeked(entityId, position) { + const transforms = null + + return _Transport_index_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].send( + 'Metrics', + 'mediaSeeked', + { entityId, position }, + transforms, + ) +} + +function mediaSeeking(entityId, target) { + const transforms = null + + return _Transport_index_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].send( + 'Metrics', + 'mediaSeeking', + { entityId, target }, + transforms, + ) +} + +function mediaWaiting(entityId) { + const transforms = null + + return _Transport_index_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].send('Metrics', 'mediaWaiting', { entityId }, transforms) +} + +function page(pageId) { + const transforms = null + + return _Transport_index_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].send('Metrics', 'page', { pageId }, transforms) +} + +function startContent(entityId) { + const transforms = null + + return _Transport_index_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].send('Metrics', 'startContent', { entityId }, transforms) +} + +function stopContent(entityId) { + const transforms = null + + return _Transport_index_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].send('Metrics', 'stopContent', { entityId }, transforms) +} + +/* harmony default export */ __webpack_exports__["default"] = ({ + /** + * + */ + ErrorType: { + NETWORK: 'network', + MEDIA: 'media', + RESTRICTION: 'restriction', + ENTITLEMENT: 'entitlement', + OTHER: 'other', + }, + + action, + appInfo, + error, + mediaEnded, + mediaLoadStart, + mediaPause, + mediaPlay, + mediaPlaying, + mediaProgress, + mediaRateChange, + mediaRenditionChange, + mediaSeeked, + mediaSeeking, + mediaWaiting, + page, + startContent, + stopContent, +}); + + + + +/***/ }), + +/***/ "./node_modules/@firebolt-js/sdk/dist/lib/Parameters/defaults.mjs": +/*!************************************************************************!*\ + !*** ./node_modules/@firebolt-js/sdk/dist/lib/Parameters/defaults.mjs ***! + \************************************************************************/ +/*! exports provided: default */ +/***/ (function(__webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var _Prop_MockProps_mjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Prop/MockProps.mjs */ "./node_modules/@firebolt-js/sdk/dist/lib/Prop/MockProps.mjs"); +/* + * Copyright 2021 Comcast Cable Communications Management, LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + */ + + +/* harmony default export */ __webpack_exports__["default"] = ({ + initialization: { + lmt: 0, + us_privacy: '1-Y-', + discovery: { + navigateTo: { + action: 'entity', + data: { entityId: 'abc', entityType: 'program', programType: 'movie' }, + context: { source: 'voice' }, + }, + }, + }, +}); + + +/***/ }), + +/***/ "./node_modules/@firebolt-js/sdk/dist/lib/Parameters/index.mjs": +/*!*********************************************************************!*\ + !*** ./node_modules/@firebolt-js/sdk/dist/lib/Parameters/index.mjs ***! + \*********************************************************************/ +/*! exports provided: default */ +/***/ (function(__webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var _Transport_index_mjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Transport/index.mjs */ "./node_modules/@firebolt-js/sdk/dist/lib/Transport/index.mjs"); +/* + * Copyright 2021 Comcast Cable Communications Management, LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + */ + + + +// Methods + +function initialization() { + const transforms = null + + return _Transport_index_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].send('Parameters', 'initialization', {}, transforms) +} + +/* harmony default export */ __webpack_exports__["default"] = ({ + /** + * In the case of a program `entityType`, specifies the program type. + */ + ProgramType: { + MOVIE: 'movie', + EPISODE: 'episode', + SEASON: 'season', + SERIES: 'series', + OTHER: 'other', + PREVIEW: 'preview', + EXTRA: 'extra', + CONCERT: 'concert', + SPORTING_EVENT: 'sportingEvent', + ADVERTISEMENT: 'advertisement', + MUSIC_VIDEO: 'musicVideo', + MINISODE: 'minisode', + }, + + /** + * In the case of a music `entityType`, specifies the type of music entity. + */ + MusicType: { + SONG: 'song', + ALBUM: 'album', + }, + + initialization, +}); + + +/***/ }), + +/***/ "./node_modules/@firebolt-js/sdk/dist/lib/Platform/defaults.mjs": +/*!**********************************************************************!*\ + !*** ./node_modules/@firebolt-js/sdk/dist/lib/Platform/defaults.mjs ***! + \**********************************************************************/ +/*! exports provided: default */ +/***/ (function(__webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var _Accessibility_defaults_mjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Accessibility/defaults.mjs */ "./node_modules/@firebolt-js/sdk/dist/lib/Accessibility/defaults.mjs"); +/* harmony import */ var _Device_defaults_mjs__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Device/defaults.mjs */ "./node_modules/@firebolt-js/sdk/dist/lib/Device/defaults.mjs"); +/* harmony import */ var _Localization_defaults_mjs__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Localization/defaults.mjs */ "./node_modules/@firebolt-js/sdk/dist/lib/Localization/defaults.mjs"); +/* + * Copyright 2021 Comcast Cable Communications Management, LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + */ + + + + + +/* harmony default export */ __webpack_exports__["default"] = ({ + localization: _Localization_defaults_mjs__WEBPACK_IMPORTED_MODULE_2__["default"], + device: _Device_defaults_mjs__WEBPACK_IMPORTED_MODULE_1__["default"], + accessibility: _Accessibility_defaults_mjs__WEBPACK_IMPORTED_MODULE_0__["default"], +}); + + +/***/ }), + +/***/ "./node_modules/@firebolt-js/sdk/dist/lib/Platform/index.mjs": +/*!*******************************************************************!*\ + !*** ./node_modules/@firebolt-js/sdk/dist/lib/Platform/index.mjs ***! + \*******************************************************************/ +/*! exports provided: default */ +/***/ (function(__webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var _Accessibility_index_mjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Accessibility/index.mjs */ "./node_modules/@firebolt-js/sdk/dist/lib/Accessibility/index.mjs"); +/* harmony import */ var _Device_index_mjs__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Device/index.mjs */ "./node_modules/@firebolt-js/sdk/dist/lib/Device/index.mjs"); +/* harmony import */ var _Localization_index_mjs__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Localization/index.mjs */ "./node_modules/@firebolt-js/sdk/dist/lib/Localization/index.mjs"); +/* + * Copyright 2021 Comcast Cable Communications Management, LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + */ + + + + + +// public API +/* harmony default export */ __webpack_exports__["default"] = ({ + Localization: _Localization_index_mjs__WEBPACK_IMPORTED_MODULE_2__["default"], + Device: _Device_index_mjs__WEBPACK_IMPORTED_MODULE_1__["default"], + Accessibility: _Accessibility_index_mjs__WEBPACK_IMPORTED_MODULE_0__["default"], +}); + + +/***/ }), + +/***/ "./node_modules/@firebolt-js/sdk/dist/lib/Profile/defaults.mjs": +/*!*********************************************************************!*\ + !*** ./node_modules/@firebolt-js/sdk/dist/lib/Profile/defaults.mjs ***! + \*********************************************************************/ +/*! exports provided: default */ +/***/ (function(__webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var _Prop_MockProps_mjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Prop/MockProps.mjs */ "./node_modules/@firebolt-js/sdk/dist/lib/Prop/MockProps.mjs"); +/* + * Copyright 2021 Comcast Cable Communications Management, LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + */ + + +/* harmony default export */ __webpack_exports__["default"] = ({ + approveContentRating: false, + approvePurchase: false, + flags: { userExperience: '1000' }, +}); + + +/***/ }), + +/***/ "./node_modules/@firebolt-js/sdk/dist/lib/Profile/index.mjs": +/*!******************************************************************!*\ + !*** ./node_modules/@firebolt-js/sdk/dist/lib/Profile/index.mjs ***! + \******************************************************************/ +/*! exports provided: default */ +/***/ (function(__webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var _Transport_index_mjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Transport/index.mjs */ "./node_modules/@firebolt-js/sdk/dist/lib/Transport/index.mjs"); +/* + * Copyright 2021 Comcast Cable Communications Management, LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + */ + + + +// Methods + +function approveContentRating() { + const transforms = null + + return _Transport_index_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].send('Profile', 'approveContentRating', {}, transforms) +} + +function approvePurchase() { + const transforms = null + + return _Transport_index_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].send('Profile', 'approvePurchase', {}, transforms) +} + +function flags() { + const transforms = null + + return _Transport_index_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].send('Profile', 'flags', {}, transforms) +} + +/* harmony default export */ __webpack_exports__["default"] = ({ + approveContentRating, + approvePurchase, + flags, +}); + + +/***/ }), + +/***/ "./node_modules/@firebolt-js/sdk/dist/lib/Prop/MockProps.mjs": +/*!*******************************************************************!*\ + !*** ./node_modules/@firebolt-js/sdk/dist/lib/Prop/MockProps.mjs ***! + \*******************************************************************/ +/*! exports provided: default */ +/***/ (function(__webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var _Transport_MockTransport_mjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Transport/MockTransport.mjs */ "./node_modules/@firebolt-js/sdk/dist/lib/Transport/MockTransport.mjs"); +/* harmony import */ var _Router_mjs__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./Router.mjs */ "./node_modules/@firebolt-js/sdk/dist/lib/Prop/Router.mjs"); + + + +const mocks = {} + +function mock(module, method, params, value, contextParameterCount, def) { + const type = Object(_Router_mjs__WEBPACK_IMPORTED_MODULE_1__["default"])(params, value, contextParameterCount) + const hash = contextParameterCount + ? '.' + + Object.keys(params) + .filter((key) => key !== 'value') + .map((key) => params[key]) + .join('.') + : '' + const key = `${module}.${method}${hash}` + + if (type === 'getter') { + const value = mocks.hasOwnProperty(key) ? mocks[key] : def + return value + } else if (type === 'subscriber') { + } else if (type === 'setter') { + mocks[key] = value + _Transport_MockTransport_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].event(module, `${method}Changed`, { value }) + return null + } +} + +/* harmony default export */ __webpack_exports__["default"] = ({ + mock: mock, +}); + + +/***/ }), + +/***/ "./node_modules/@firebolt-js/sdk/dist/lib/Prop/Router.mjs": +/*!****************************************************************!*\ + !*** ./node_modules/@firebolt-js/sdk/dist/lib/Prop/Router.mjs ***! + \****************************************************************/ +/*! exports provided: default */ +/***/ (function(__webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony default export */ __webpack_exports__["default"] = (function (params, callbackOrValue, contextParameterCount) { + const numArgs = params ? Object.values(params).length : 0 + + if (numArgs === contextParameterCount && callbackOrValue === undefined) { + // getter + return 'getter' + } else if ( + numArgs === contextParameterCount && + typeof callbackOrValue === 'function' + ) { + // subscribe + return 'subscriber' + } else if (numArgs === 0 && typeof callbackOrValue === 'function') { + // for x-subscriber-type: global + return 'subscriber' + } else if ( + numArgs === contextParameterCount && + callbackOrValue !== undefined + ) { + // setter + return 'setter' + } + + return null +}); + + +/***/ }), + +/***/ "./node_modules/@firebolt-js/sdk/dist/lib/Prop/index.mjs": +/*!***************************************************************!*\ + !*** ./node_modules/@firebolt-js/sdk/dist/lib/Prop/index.mjs ***! + \***************************************************************/ +/*! exports provided: default */ +/***/ (function(__webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var _Transport_index_mjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Transport/index.mjs */ "./node_modules/@firebolt-js/sdk/dist/lib/Transport/index.mjs"); +/* harmony import */ var _Events_index_mjs__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Events/index.mjs */ "./node_modules/@firebolt-js/sdk/dist/lib/Events/index.mjs"); +/* harmony import */ var _Router_mjs__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./Router.mjs */ "./node_modules/@firebolt-js/sdk/dist/lib/Prop/Router.mjs"); + + + + +function prop( + moduleName, + key, + params, + callbackOrValue = undefined, + immutable, + readonly, + contextParameterCount, +) { + const numArgs = Object.values(params).length + const type = Object(_Router_mjs__WEBPACK_IMPORTED_MODULE_2__["default"])(params, callbackOrValue, contextParameterCount) + + if (type === 'getter') { + return _Transport_index_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].send(moduleName, key, params) + } else if (type === 'subscriber') { + // subscriber + if (immutable) { + throw new Error('Cannot subscribe to an immutable property') + } + return _Events_index_mjs__WEBPACK_IMPORTED_MODULE_1__["default"].listen( + moduleName, + key + 'Changed', + ...Object.values(params), + callbackOrValue, + ) + } else if (type === 'setter') { + // setter + if (immutable) { + throw new Error('Cannot set a value to an immutable property') + } + if (readonly) { + throw new Error('Cannot set a value to a readonly property') + } + return _Transport_index_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].send( + moduleName, + 'set' + key[0].toUpperCase() + key.substring(1), + Object.assign( + { + value: callbackOrValue, + }, + params, + ), + ) + } else if (numArgs < contextParameterCount) { + throw new Error( + 'Cannot get a value without all required context parameters.', + ) + } else { + throw new Error('Property accessed with unexpected number of parameters.') + } +} + +/* harmony default export */ __webpack_exports__["default"] = ({ + prop: prop, +}); + + +/***/ }), + +/***/ "./node_modules/@firebolt-js/sdk/dist/lib/ProvideManager/index.mjs": +/*!*************************************************************************!*\ + !*** ./node_modules/@firebolt-js/sdk/dist/lib/ProvideManager/index.mjs ***! + \*************************************************************************/ +/*! exports provided: registerProviderInterface, default */ +/***/ (function(__webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "registerProviderInterface", function() { return registerProviderInterface; }); +/* harmony import */ var _Transport_index_mjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Transport/index.mjs */ "./node_modules/@firebolt-js/sdk/dist/lib/Transport/index.mjs"); +/* harmony import */ var _Events_index_mjs__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Events/index.mjs */ "./node_modules/@firebolt-js/sdk/dist/lib/Events/index.mjs"); +/* + * Copyright 2021 Comcast Cable Communications Management, LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + */ + + + + +const providerInterfaces = {} + +const registerProviderInterface = (capability, module, methods) => { + if (providerInterfaces[capability]) { + throw `Capability ${capability} has multiple provider interfaces registered.` + } + + methods.forEach((m) => (m.name = `${module}.${m.name}`)) + providerInterfaces[capability] = methods.concat() +} + +const provide = function (capability, provider) { + const methods = [] + const iface = providerInterfaces[capability] + + if (provider.constructor.name !== 'Object') { + methods.push( + ...Object.getOwnPropertyNames(Object.getPrototypeOf(provider)).filter( + (item) => + typeof provider[item] === 'function' && item !== 'constructor', + ), + ) + } else { + methods.push( + ...Object.getOwnPropertyNames(provider).filter( + (item) => typeof provider[item] === 'function', + ), + ) + } + + if (!iface) { + throw 'Ignoring unknown provider capability.' + } + + // make sure every interfaced method exists in the providers methods list + const valid = iface.every((method) => + methods.find((m) => m === method.name.split('.').pop()), + ) + + if (!valid) { + throw `Provider that does not fully implement ${capability}:\n\t${iface + .map((m) => m.name.split('.').pop()) + .join('\n\t')}` + } + + iface.forEach((imethod) => { + const parts = imethod.name.split('.') + const method = parts.pop() + const module = parts.pop().toLowerCase() + const defined = !!methods.find((m) => m === method) + + if (!defined) { + return // returns from this cycle of iface.forEach + } + + _Events_index_mjs__WEBPACK_IMPORTED_MODULE_1__["default"].listen( + module, + `request${method.charAt(0).toUpperCase() + method.substr(1)}`, + function (request) { + const providerCallArgs = [] + + // only pass in parameters object if schema exists + if (imethod.parameters) { + providerCallArgs.push(request.parameters) + } else { + providerCallArgs.push(null) + } + + const session = { + correlationId: () => { + return request.correlationId + }, + } + + // only pass in the focus handshake if needed + if (imethod.focus) { + session.focus = () => { + _Transport_index_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].send(module, `${method}Focus`, { + correlationId: request.correlationId, + }) + } + } + + providerCallArgs.push(session) + + const response = { + correlationId: request.correlationId, + } + let handleError = (error) => { + response.error = { + code: error.code || 1000, // todo: should be some reserved code for "Unknown" + message: + error.message || + `An error occured while calling provided ${method} method.`, + } + + if (error.data) { + response.error.data = JSON.parse(JSON.stringify(error.data)) + } + + _Transport_index_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].send(module, `${method}Error`, response) + } + + try { + const result = provider[method].apply(provider, providerCallArgs) + + if (!(result instanceof Promise)) { + throw `Provider method ${method} did not return a Promise.` + } + + result + .then((result) => { + if (imethod.response) { + // void results should be null in the JSONRPC message + response.result = result == null ? null : result + } + + _Transport_index_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].send(module, `${method}Response`, response) + }) + .catch((err) => handleError(err)) + } catch (error) { + handleError(error) + } + }, + ) + }) +} + +/* harmony default export */ __webpack_exports__["default"] = ({ + provide, +}); + + +/***/ }), + +/***/ "./node_modules/@firebolt-js/sdk/dist/lib/Results/index.mjs": +/*!******************************************************************!*\ + !*** ./node_modules/@firebolt-js/sdk/dist/lib/Results/index.mjs ***! + \******************************************************************/ +/*! exports provided: default */ +/***/ (function(__webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var _Transport_index_mjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Transport/index.mjs */ "./node_modules/@firebolt-js/sdk/dist/lib/Transport/index.mjs"); + + +/* +methods = Map +*/ + +function transform(result, transforms) { + if (!transforms || !transforms.methods) { + return result + } + + const { methods } = transforms + const transformed = JSON.parse(JSON.stringify(result)) + + Object.keys(methods).forEach((key) => { + const method_info = methods[key] + const rpc_method = method_info['x-method'] + const [module, method] = rpc_method.split('.') + const params = {} + params[method_info['x-this-param']] = transformed + transformed[key] = (...args) => { + // copy the args into the correct RPC param names + for (var i = 0; i < args.length; i++) { + params[method_info['x-additional-params'][i]] = args[i] + } + return _Transport_index_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].send(module.toLowerCase(), method, params) + } + }) + return transformed +} + +/* harmony default export */ __webpack_exports__["default"] = ({ + transform, +}); + + +/***/ }), + +/***/ "./node_modules/@firebolt-js/sdk/dist/lib/SecondScreen/defaults.mjs": +/*!**************************************************************************!*\ + !*** ./node_modules/@firebolt-js/sdk/dist/lib/SecondScreen/defaults.mjs ***! + \**************************************************************************/ +/*! exports provided: default */ +/***/ (function(__webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var _Prop_MockProps_mjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Prop/MockProps.mjs */ "./node_modules/@firebolt-js/sdk/dist/lib/Prop/MockProps.mjs"); +/* + * Copyright 2021 Comcast Cable Communications Management, LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + */ + + +/* harmony default export */ __webpack_exports__["default"] = ({ + protocols: { 'dial1.7': true }, + device: 'device-id', + friendlyName: function (params) { + return _Prop_MockProps_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].mock( + 'SecondScreen', + 'friendlyName', + params, + undefined, + 0, + 'Living Room', + ) + }, +}); + + +/***/ }), + +/***/ "./node_modules/@firebolt-js/sdk/dist/lib/SecondScreen/index.mjs": +/*!***********************************************************************!*\ + !*** ./node_modules/@firebolt-js/sdk/dist/lib/SecondScreen/index.mjs ***! + \***********************************************************************/ +/*! exports provided: default */ +/***/ (function(__webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var _Transport_index_mjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Transport/index.mjs */ "./node_modules/@firebolt-js/sdk/dist/lib/Transport/index.mjs"); +/* harmony import */ var _Events_index_mjs__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Events/index.mjs */ "./node_modules/@firebolt-js/sdk/dist/lib/Events/index.mjs"); +/* harmony import */ var _Prop_index_mjs__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Prop/index.mjs */ "./node_modules/@firebolt-js/sdk/dist/lib/Prop/index.mjs"); +/* + * Copyright 2021 Comcast Cable Communications Management, LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + */ + + + + + + +Object(_Events_index_mjs__WEBPACK_IMPORTED_MODULE_1__["registerEvents"])('SecondScreen', [ + 'closeRequest', + 'friendlyNameChanged', + 'launchRequest', +]) + +// onCloseRequest is accessed via listen('closeRequest, ...) + +// onFriendlyNameChanged is accessed via listen('friendlyNameChanged, ...) + +// onLaunchRequest is accessed via listen('launchRequest, ...) + +// Methods +function clear(...args) { + return _Events_index_mjs__WEBPACK_IMPORTED_MODULE_1__["default"].clear('SecondScreen', ...args) +} + +function device(type) { + const transforms = null + + return _Transport_index_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].send('SecondScreen', 'device', { type }, transforms) +} +function friendlyName() { + let callbackOrValue = arguments[0] + let params = {} + + // x-subscriber-type: global + if (arguments.length === 1 && typeof arguments[0] === 'function') { + callbackOrValue = arguments[0] + params = {} + } + + return _Prop_index_mjs__WEBPACK_IMPORTED_MODULE_2__["default"].prop( + 'SecondScreen', + 'friendlyName', + params, + callbackOrValue, + false, + true, + 0, + ) +} +function listen(...args) { + return _Events_index_mjs__WEBPACK_IMPORTED_MODULE_1__["default"].listen('SecondScreen', ...args) +} + +function once(...args) { + return _Events_index_mjs__WEBPACK_IMPORTED_MODULE_1__["default"].once('SecondScreen', ...args) +} + +function protocols() { + const transforms = null + + return _Transport_index_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].send('SecondScreen', 'protocols', {}, transforms) +} + +/* harmony default export */ __webpack_exports__["default"] = ({ + Events: { + LAUNCH_REQUEST: 'launchRequest', + CLOSE_REQUEST: 'closeRequest', + FRIENDLY_NAME_CHANGED: 'friendlyNameChanged', + }, + + clear, + device, + friendlyName, + listen, + once, + protocols, +}); + + +/***/ }), + +/***/ "./node_modules/@firebolt-js/sdk/dist/lib/SecureStorage/defaults.mjs": +/*!***************************************************************************!*\ + !*** ./node_modules/@firebolt-js/sdk/dist/lib/SecureStorage/defaults.mjs ***! + \***************************************************************************/ +/*! exports provided: default */ +/***/ (function(__webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var _Prop_MockProps_mjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Prop/MockProps.mjs */ "./node_modules/@firebolt-js/sdk/dist/lib/Prop/MockProps.mjs"); +/* + * Copyright 2021 Comcast Cable Communications Management, LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + */ + + +/* harmony default export */ __webpack_exports__["default"] = ({ + get: 'VGhpcyBub3QgYSByZWFsIHRva2VuLgo=', + set: null, + remove: null, + clear: null, +}); + + +/***/ }), + +/***/ "./node_modules/@firebolt-js/sdk/dist/lib/SecureStorage/index.mjs": +/*!************************************************************************!*\ + !*** ./node_modules/@firebolt-js/sdk/dist/lib/SecureStorage/index.mjs ***! + \************************************************************************/ +/*! exports provided: default */ +/***/ (function(__webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var _Transport_index_mjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Transport/index.mjs */ "./node_modules/@firebolt-js/sdk/dist/lib/Transport/index.mjs"); +/* + * Copyright 2021 Comcast Cable Communications Management, LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + */ + + + +// Methods + +function clear(scope) { + const transforms = null + + return _Transport_index_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].send('SecureStorage', 'clear', { scope }, transforms) +} + +function get(scope, key) { + const transforms = null + + return _Transport_index_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].send('SecureStorage', 'get', { scope, key }, transforms) +} + +function remove(scope, key) { + const transforms = null + + return _Transport_index_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].send('SecureStorage', 'remove', { scope, key }, transforms) +} + +function set(scope, key, value, options) { + const transforms = null + + return _Transport_index_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].send( + 'SecureStorage', + 'set', + { scope, key, value, options }, + transforms, + ) +} + +/* harmony default export */ __webpack_exports__["default"] = ({ + /** + * The scope of the data + */ + StorageScope: { + DEVICE: 'device', + ACCOUNT: 'account', + }, + + clear, + get, + remove, + set, +}); + + +/***/ }), + +/***/ "./node_modules/@firebolt-js/sdk/dist/lib/Settings/index.mjs": +/*!*******************************************************************!*\ + !*** ./node_modules/@firebolt-js/sdk/dist/lib/Settings/index.mjs ***! + \*******************************************************************/ +/*! exports provided: initSettings, default */ +/***/ (function(__webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "initSettings", function() { return initSettings; }); +/* + * Copyright 2021 Comcast Cable Communications Management, LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + */ + +const settings = {} +const subscribers = {} + +const initSettings = (appSettings, platformSettings) => { + settings['app'] = appSettings + settings['platform'] = { + logLevel: 'WARN', + ...platformSettings, + } + settings['user'] = {} +} + +const publish = (key, value) => { + subscribers[key] && + subscribers[key].forEach((subscriber) => subscriber(value)) +} + +const dotGrab = (obj = {}, key) => { + const keys = key.split('.') + for (let i = 0; i < keys.length; i++) { + obj = obj[keys[i]] = obj[keys[i]] !== undefined ? obj[keys[i]] : {} + } + return typeof obj === 'object' + ? Object.keys(obj).length + ? obj + : undefined + : obj +} + +/* harmony default export */ __webpack_exports__["default"] = ({ + get(type, key, fallback = undefined) { + const val = dotGrab(settings[type], key) + return val !== undefined ? val : fallback + }, + has(type, key) { + return !!this.get(type, key) + }, + set(key, value) { + settings['user'][key] = value + publish(key, value) + }, + subscribe(key, callback) { + subscribers[key] = subscribers[key] || [] + subscribers[key].push(callback) + }, + unsubscribe(key, callback) { + if (callback) { + const index = + subscribers[key] && subscribers[key].findIndex((cb) => cb === callback) + index > -1 && subscribers[key].splice(index, 1) + } else { + if (key in subscribers) { + subscribers[key] = [] + } + } + }, + clearSubscribers() { + for (const key of Object.getOwnPropertyNames(subscribers)) { + delete subscribers[key] + } + }, + setLogLevel(logLevel) { + settings.platform.logLevel = logLevel + }, + getLogLevel() { + return settings.platform.logLevel + }, +}); + + +/***/ }), + +/***/ "./node_modules/@firebolt-js/sdk/dist/lib/Transport/LegacyTransport.mjs": +/*!******************************************************************************!*\ + !*** ./node_modules/@firebolt-js/sdk/dist/lib/Transport/LegacyTransport.mjs ***! + \******************************************************************************/ +/*! exports provided: default */ +/***/ (function(__webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return LegacyTransport; }); +/* + * Copyright 2021 Comcast Cable Communications Management, LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + */ + +const win = typeof window !== 'undefined' ? window : {} + +class LegacyTransport { + constructor(bridge) { + this.bridge = bridge + } + + send(msg) { + this.bridge.JSMessageChanged(msg, () => {}) + } + + receive(callback) { + win.$badger = win.$badger || {} + /** Hold on to real $badger callback and event methods so they can be called for non-jsonrpc messages */ + const badgerCallback = win.$badger.callback + ? win.$badger.callback.bind(win.$badger) + : null + const badgerEvent = win.$badger.event + ? win.$badger.event.bind(win.$badger) + : null + win.$badger.callback = (pid, success, json) => { + if (json.jsonrpc) { + callback(JSON.stringify(json)) + } else if (badgerCallback) { + badgerCallback(pid, success, json) + } + } + win.$badger.event = (handlerId, json) => { + if (json.jsonrpc) { + callback(JSON.stringify(json)) + } else if (badgerEvent) { + badgerEvent(handlerId, json) + } + } + } + + static isLegacy(transport) { + return ( + LegacyTransport.isXREProxy(transport) || + (transport.send === undefined && transport.JSMessageChanged) + ) + } + + static isXREProxy(transport) { + /** Set top boxes running XRE has a "Proxy" transport + * native object that intercepts ALL method calls, so we + * cannot test for transport.send existence because it will return true + * even though it actually is not supported. Check if some obscure method + * name like "proxyObjectTest" is defined. If it is then we know we are using a + * Proxy object and thus is legacy transport. + */ + return transport.proxyObjectTest !== undefined + } +} + + +/***/ }), + +/***/ "./node_modules/@firebolt-js/sdk/dist/lib/Transport/MockTransport.mjs": +/*!****************************************************************************!*\ + !*** ./node_modules/@firebolt-js/sdk/dist/lib/Transport/MockTransport.mjs ***! + \****************************************************************************/ +/*! exports provided: setMockListener, setMockResponses, default */ +/***/ (function(__webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "setMockListener", function() { return setMockListener; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "setMockResponses", function() { return setMockResponses; }); +/* + * Copyright 2021 Comcast Cable Communications Management, LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + */ + +const win = typeof window !== 'undefined' ? window : {} + +let listener +const setMockListener = (func) => { + listener = func +} + +let mock +const pending = [] +const eventMap = {} + +let callback +let testHarness + +if (win.__firebolt && win.__firebolt.testHarness) { + testHarness = win.__firebolt.testHarness +} + +function send(message) { + console.debug('Sending message to transport: ' + message) + let json = JSON.parse(message) + + // handle bulk sends + if (Array.isArray(json)) { + json.forEach((j) => send(JSON.stringify(j))) + return + } + + let [module, method] = json.method.split('.') + + if (testHarness && testHarness.onSend) { + testHarness.onSend(module, method, json.params, json.id) + } + + // store the ID of the first listen for each event + if (method.match(/^on[A-Z]/)) { + if (json.params.listen) { + eventMap[json.id] = + module.toLowerCase() + '.' + method[2].toLowerCase() + method.substr(3) + } else { + Object.keys(eventMap).forEach((key) => { + if ( + eventMap[key] === + module.toLowerCase() + + '.' + + method[2].toLowerCase() + + method.substr(3) + ) { + delete eventMap[key] + } + }) + } + } + + if (mock) handle(json) + else pending.push(json) +} + +function handle(json) { + let result + try { + result = getResult(json.method, json.params) + } catch (error) { + setTimeout(() => + callback( + JSON.stringify({ + jsonrpc: '2.0', + error: { + code: -32602, + message: + 'Invalid params (this is a mock error from the mock transport layer)', + }, + id: json.id, + }), + ), + ) + } + + setTimeout(() => + callback( + JSON.stringify({ + jsonrpc: '2.0', + result: result, + id: json.id, + }), + ), + ) +} + +function receive(_callback) { + callback = _callback + + if (testHarness && typeof testHarness.initialize === 'function') { + testHarness.initialize({ + emit: event, + listen: function (...args) { + listener(...args) + }, + }) + } +} + +function event(module, event, value) { + const listener = Object.entries(eventMap).find( + ([k, v]) => + v.toLowerCase() === module.toLowerCase() + '.' + event.toLowerCase(), + ) + if (listener) { + let message = JSON.stringify({ + jsonrpc: '2.0', + id: parseInt(listener[0]), + result: value, + }) + callback(message) + } +} + +function dotGrab(obj = {}, key) { + const keys = key.split('.') + let ref = obj + for (let i = 0; i < keys.length; i++) { + ref = (Object.entries(ref).find( + ([k, v]) => k.toLowerCase() === keys[i].toLowerCase(), + ) || [null, {}])[1] + } + return ref +} + +function getResult(method, params) { + let api = dotGrab(mock, method) + + if (method.match(/^[a-zA-Z]+\.on[A-Za-z]+$/)) { + api = { + event: method, + listening: true, + } + } + + if (typeof api === 'function') { + return params == null ? api() : api(params) + } else return api +} + +function setMockResponses(m) { + mock = m + + pending.forEach((json) => handle(json)) + pending.length = 0 +} + +/* harmony default export */ __webpack_exports__["default"] = ({ + send: send, + receive: receive, + event: event, +}); + + +/***/ }), + +/***/ "./node_modules/@firebolt-js/sdk/dist/lib/Transport/WebsocketTransport.mjs": +/*!*********************************************************************************!*\ + !*** ./node_modules/@firebolt-js/sdk/dist/lib/Transport/WebsocketTransport.mjs ***! + \*********************************************************************************/ +/*! exports provided: default */ +/***/ (function(__webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return WebsocketTransport; }); +const MAX_QUEUED_MESSAGES = 100 + +class WebsocketTransport { + constructor(endpoint) { + this._endpoint = endpoint + this._ws = null + this._connected = false + this._queue = [] + this._callbacks = [] + } + + send(msg) { + this._connect() + + if (this._connected) { + this._ws.send(msg) + } else { + if (this._queue.length < MAX_QUEUED_MESSAGES) { + this._queue.push(msg) + } + } + } + + receive(callback) { + if (!callback) return + this._connect() + this._callbacks.push(callback) + } + + _notifyCallbacks(message) { + for (let i = 0; i < this._callbacks.length; i++) { + setTimeout(() => this._callbacks[i](message), 1) + } + } + + _connect() { + if (this._ws) return + this._ws = new WebSocket(this._endpoint, ['jsonrpc']) + this._ws.addEventListener('message', (message) => { + this._notifyCallbacks(message.data) + }) + this._ws.addEventListener('error', (message) => {}) + this._ws.addEventListener('close', (message) => { + this._ws = null + this._connected = false + }) + this._ws.addEventListener('open', (message) => { + this._connected = true + for (let i = 0; i < this._queue.length; i++) { + this._ws.send(this._queue[i]) + } + this._queue = [] + }) + } +} + + +/***/ }), + +/***/ "./node_modules/@firebolt-js/sdk/dist/lib/Transport/index.mjs": +/*!********************************************************************!*\ + !*** ./node_modules/@firebolt-js/sdk/dist/lib/Transport/index.mjs ***! + \********************************************************************/ +/*! exports provided: default */ +/***/ (function(__webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return Transport; }); +/* harmony import */ var _MockTransport_mjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./MockTransport.mjs */ "./node_modules/@firebolt-js/sdk/dist/lib/Transport/MockTransport.mjs"); +/* harmony import */ var _queue_mjs__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./queue.mjs */ "./node_modules/@firebolt-js/sdk/dist/lib/Transport/queue.mjs"); +/* harmony import */ var _Settings_index_mjs__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Settings/index.mjs */ "./node_modules/@firebolt-js/sdk/dist/lib/Settings/index.mjs"); +/* harmony import */ var _LegacyTransport_mjs__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./LegacyTransport.mjs */ "./node_modules/@firebolt-js/sdk/dist/lib/Transport/LegacyTransport.mjs"); +/* harmony import */ var _WebsocketTransport_mjs__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./WebsocketTransport.mjs */ "./node_modules/@firebolt-js/sdk/dist/lib/Transport/WebsocketTransport.mjs"); +/* harmony import */ var _Results_index_mjs__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../Results/index.mjs */ "./node_modules/@firebolt-js/sdk/dist/lib/Results/index.mjs"); +/* + * Copyright 2021 Comcast Cable Communications Management, LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + */ + + + + + + + + +const LEGACY_TRANSPORT_SERVICE_NAME = 'com.comcast.BridgeObject_1' +let moduleInstance = null + +const isEventSuccess = (x) => + x && typeof x.event === 'string' && typeof x.listening === 'boolean' + +const win = typeof window !== 'undefined' ? window : {} + +class Transport { + constructor() { + this._promises = [] + this._transport = null + this._id = 1 + this._eventEmitters = [] + this._eventIds = [] + this._queue = new _queue_mjs__WEBPACK_IMPORTED_MODULE_1__["default"]() + this._deprecated = {} + this.isMock = false + } + + static addEventEmitter(emitter) { + Transport.get()._eventEmitters.push(emitter) + } + + static registerDeprecatedMethod(module, method, alternative) { + Transport.get()._deprecated[ + module.toLowerCase() + '.' + method.toLowerCase() + ] = { + alternative: alternative || '', + } + } + + _endpoint() { + if (win.__firebolt && win.__firebolt.endpoint) { + return win.__firebolt.endpoint + } + return null + } + + constructTransportLayer() { + let transport + const endpoint = this._endpoint() + if ( + endpoint && + (endpoint.startsWith('ws://') || endpoint.startsWith('wss://')) + ) { + transport = new _WebsocketTransport_mjs__WEBPACK_IMPORTED_MODULE_4__["default"](endpoint) + transport.receive(this.receiveHandler.bind(this)) + } else if ( + typeof win.ServiceManager !== 'undefined' && + win.ServiceManager && + win.ServiceManager.version + ) { + // Wire up the queue + transport = this._queue + // get the default bridge service, and flush the queue + win.ServiceManager.getServiceForJavaScript( + LEGACY_TRANSPORT_SERVICE_NAME, + (service) => { + if (_LegacyTransport_mjs__WEBPACK_IMPORTED_MODULE_3__["default"].isLegacy(service)) { + transport = new _LegacyTransport_mjs__WEBPACK_IMPORTED_MODULE_3__["default"](service) + } else { + transport = service + } + this.setTransportLayer(transport) + }, + ) + } else { + this.isMock = true + transport = _MockTransport_mjs__WEBPACK_IMPORTED_MODULE_0__["default"] + transport.receive(this.receiveHandler.bind(this)) + } + return transport + } + + setTransportLayer(tl) { + this._transport = tl + this._queue.flush(tl) + } + + static send(module, method, params, transforms) { + /** Transport singleton across all SDKs to keep single id map */ + return Transport.get()._send(module, method, params, transforms) + } + + static listen(module, method, params, transforms) { + return Transport.get()._sendAndGetId(module, method, params, transforms) + } + + _send(module, method, params, transforms) { + if (Array.isArray(module) && !method && !params) { + return this._batch(module) + } else { + return this._sendAndGetId(module, method, params, transforms).promise + } + } + + _sendAndGetId(module, method, params, transforms) { + const { promise, json, id } = this._processRequest( + module, + method, + params, + transforms, + ) + const msg = JSON.stringify(json) + if (_Settings_index_mjs__WEBPACK_IMPORTED_MODULE_2__["default"].getLogLevel() === 'DEBUG') { + console.debug('Sending message to transport: ' + msg) + } + this._transport.send(msg) + + return { id, promise } + } + + _batch(requests) { + const results = [] + const json = [] + + requests.forEach(({ module, method, params, transforms }) => { + const result = this._processRequest(module, method, params, transforms) + results.push({ + promise: result.promise, + id: result.id, + }) + json.push(result.json) + }) + + const msg = JSON.stringify(json) + if (_Settings_index_mjs__WEBPACK_IMPORTED_MODULE_2__["default"].getLogLevel() === 'DEBUG') { + console.debug('Sending message to transport: ' + msg) + } + this._transport.send(msg) + + return results + } + + _processRequest(module, method, params, transforms) { + const p = this._addPromiseToQueue(module, method, params, transforms) + const json = this._createRequestJSON(module, method, params) + + const result = { + promise: p, + json: json, + id: this._id, + } + + this._id++ + + return result + } + + _createRequestJSON(module, method, params) { + return { + jsonrpc: '2.0', + method: module.toLowerCase() + '.' + method, + params: params, + id: this._id, + } + } + + _addPromiseToQueue(module, method, params, transforms) { + return new Promise((resolve, reject) => { + this._promises[this._id] = {} + this._promises[this._id].promise = this + this._promises[this._id].resolve = resolve + this._promises[this._id].reject = reject + this._promises[this._id].transforms = transforms + + const deprecated = + this._deprecated[module.toLowerCase() + '.' + method.toLowerCase()] + if (deprecated) { + console.warn( + `WARNING: ${module}.${method}() is deprecated. ` + + deprecated.alternative, + ) + } + + // store the ID of the first listen for each event + // TODO: what about wild cards? + if (method.match(/^on[A-Z]/)) { + if (params.listen) { + this._eventIds.push(this._id) + } else { + this._eventIds = this._eventIds.filter((id) => id !== this._id) + } + } + }) + } + + /** + * If we have a global transport, use that. Otherwise, use the module-scoped transport instance. + * @returns {Transport} + */ + static get() { + /** Set up singleton and initialize it */ + win.__firebolt = win.__firebolt || {} + if (win.__firebolt.transport == null && moduleInstance == null) { + const transport = new Transport() + transport.init() + if (transport.isMock) { + /** We should use the mock transport built with the SDK, not a global */ + moduleInstance = transport + } else { + win.__firebolt = win.__firebolt || {} + win.__firebolt.transport = transport + } + win.__firebolt.setTransportLayer = + transport.setTransportLayer.bind(transport) + } + return win.__firebolt.transport ? win.__firebolt.transport : moduleInstance + } + + receiveHandler(message) { + if (_Settings_index_mjs__WEBPACK_IMPORTED_MODULE_2__["default"].getLogLevel() === 'DEBUG') { + console.debug('Received message from transport: ' + message) + } + const json = JSON.parse(message) + const p = this._promises[json.id] + + if (p) { + if (json.error) p.reject(json.error) + else { + // Do any module-specific transforms on the result + let result = json.result + + if (p.transforms) { + if (Array.isArray(json.result)) { + result = result.map((x) => _Results_index_mjs__WEBPACK_IMPORTED_MODULE_5__["default"].transform(x, p.transforms)) + } else { + result = _Results_index_mjs__WEBPACK_IMPORTED_MODULE_5__["default"].transform(result, p.transforms) + } + } + + p.resolve(result) + } + delete this._promises[json.id] + } + + // event responses need to be emitted, even after the listen call is resolved + if (this._eventIds.includes(json.id) && !isEventSuccess(json.result)) { + this._eventEmitters.forEach((emit) => { + emit(json.id, json.result) + }) + } + } + + init() { + Object(_Settings_index_mjs__WEBPACK_IMPORTED_MODULE_2__["initSettings"])({}, { log: true }) + this._queue.receive(this.receiveHandler.bind(this)) + if (win.__firebolt) { + if (win.__firebolt.mockTransportLayer === true) { + this.isMock = true + this.setTransportLayer(_MockTransport_mjs__WEBPACK_IMPORTED_MODULE_0__["default"]) + } else if (win.__firebolt.getTransportLayer) { + this.setTransportLayer(win.__firebolt.getTransportLayer()) + } + } + if (this._transport == null) { + this._transport = this.constructTransportLayer() + } + } +} +win.__firebolt = win.__firebolt || {} +win.__firebolt.setTransportLayer = (transport) => { + Transport.get().setTransportLayer(transport) +} + + +/***/ }), + +/***/ "./node_modules/@firebolt-js/sdk/dist/lib/Transport/queue.mjs": +/*!********************************************************************!*\ + !*** ./node_modules/@firebolt-js/sdk/dist/lib/Transport/queue.mjs ***! + \********************************************************************/ +/*! exports provided: default */ +/***/ (function(__webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return Queue; }); +/* + * Copyright 2021 Comcast Cable Communications Management, LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + */ + +class Queue { + constructor() { + this._callback = null + this._queue = [] + } + + send(json) { + this._queue.push(json) + } + + receive(_callback) { + this._callback = _callback + } + + flush(transport) { + transport.receive(this._callback) + this._queue.forEach((item) => transport.send(item)) + } +} + + +/***/ }), + +/***/ "./node_modules/@firebolt-js/sdk/dist/lib/firebolt.mjs": +/*!*************************************************************!*\ + !*** ./node_modules/@firebolt-js/sdk/dist/lib/firebolt.mjs ***! + \*************************************************************/ +/*! exports provided: Accessibility, Account, Advertising, Authentication, Capabilities, Device, Discovery, Keyboard, Lifecycle, Localization, Metrics, Parameters, Profile, SecondScreen, SecureStorage, Platform, Log, Events, Settings */ +/***/ (function(__webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var _Transport_MockTransport_mjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./Transport/MockTransport.mjs */ "./node_modules/@firebolt-js/sdk/dist/lib/Transport/MockTransport.mjs"); +/* harmony import */ var _Accessibility_defaults_mjs__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./Accessibility/defaults.mjs */ "./node_modules/@firebolt-js/sdk/dist/lib/Accessibility/defaults.mjs"); +/* harmony import */ var _Account_defaults_mjs__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./Account/defaults.mjs */ "./node_modules/@firebolt-js/sdk/dist/lib/Account/defaults.mjs"); +/* harmony import */ var _Advertising_defaults_mjs__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./Advertising/defaults.mjs */ "./node_modules/@firebolt-js/sdk/dist/lib/Advertising/defaults.mjs"); +/* harmony import */ var _Authentication_defaults_mjs__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./Authentication/defaults.mjs */ "./node_modules/@firebolt-js/sdk/dist/lib/Authentication/defaults.mjs"); +/* harmony import */ var _Capabilities_defaults_mjs__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./Capabilities/defaults.mjs */ "./node_modules/@firebolt-js/sdk/dist/lib/Capabilities/defaults.mjs"); +/* harmony import */ var _Device_defaults_mjs__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./Device/defaults.mjs */ "./node_modules/@firebolt-js/sdk/dist/lib/Device/defaults.mjs"); +/* harmony import */ var _Discovery_defaults_mjs__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./Discovery/defaults.mjs */ "./node_modules/@firebolt-js/sdk/dist/lib/Discovery/defaults.mjs"); +/* harmony import */ var _Keyboard_defaults_mjs__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./Keyboard/defaults.mjs */ "./node_modules/@firebolt-js/sdk/dist/lib/Keyboard/defaults.mjs"); +/* harmony import */ var _Lifecycle_defaults_mjs__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./Lifecycle/defaults.mjs */ "./node_modules/@firebolt-js/sdk/dist/lib/Lifecycle/defaults.mjs"); +/* harmony import */ var _Localization_defaults_mjs__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./Localization/defaults.mjs */ "./node_modules/@firebolt-js/sdk/dist/lib/Localization/defaults.mjs"); +/* harmony import */ var _Metrics_defaults_mjs__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ./Metrics/defaults.mjs */ "./node_modules/@firebolt-js/sdk/dist/lib/Metrics/defaults.mjs"); +/* harmony import */ var _Parameters_defaults_mjs__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ./Parameters/defaults.mjs */ "./node_modules/@firebolt-js/sdk/dist/lib/Parameters/defaults.mjs"); +/* harmony import */ var _Profile_defaults_mjs__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ./Profile/defaults.mjs */ "./node_modules/@firebolt-js/sdk/dist/lib/Profile/defaults.mjs"); +/* harmony import */ var _SecondScreen_defaults_mjs__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ./SecondScreen/defaults.mjs */ "./node_modules/@firebolt-js/sdk/dist/lib/SecondScreen/defaults.mjs"); +/* harmony import */ var _SecureStorage_defaults_mjs__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ./SecureStorage/defaults.mjs */ "./node_modules/@firebolt-js/sdk/dist/lib/SecureStorage/defaults.mjs"); +/* harmony import */ var _Platform_defaults_mjs__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(/*! ./Platform/defaults.mjs */ "./node_modules/@firebolt-js/sdk/dist/lib/Platform/defaults.mjs"); +/* harmony import */ var _Accessibility_index_mjs__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(/*! ./Accessibility/index.mjs */ "./node_modules/@firebolt-js/sdk/dist/lib/Accessibility/index.mjs"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Accessibility", function() { return _Accessibility_index_mjs__WEBPACK_IMPORTED_MODULE_17__["default"]; }); + +/* harmony import */ var _Account_index_mjs__WEBPACK_IMPORTED_MODULE_18__ = __webpack_require__(/*! ./Account/index.mjs */ "./node_modules/@firebolt-js/sdk/dist/lib/Account/index.mjs"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Account", function() { return _Account_index_mjs__WEBPACK_IMPORTED_MODULE_18__["default"]; }); + +/* harmony import */ var _Advertising_index_mjs__WEBPACK_IMPORTED_MODULE_19__ = __webpack_require__(/*! ./Advertising/index.mjs */ "./node_modules/@firebolt-js/sdk/dist/lib/Advertising/index.mjs"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Advertising", function() { return _Advertising_index_mjs__WEBPACK_IMPORTED_MODULE_19__["default"]; }); + +/* harmony import */ var _Authentication_index_mjs__WEBPACK_IMPORTED_MODULE_20__ = __webpack_require__(/*! ./Authentication/index.mjs */ "./node_modules/@firebolt-js/sdk/dist/lib/Authentication/index.mjs"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Authentication", function() { return _Authentication_index_mjs__WEBPACK_IMPORTED_MODULE_20__["default"]; }); + +/* harmony import */ var _Capabilities_index_mjs__WEBPACK_IMPORTED_MODULE_21__ = __webpack_require__(/*! ./Capabilities/index.mjs */ "./node_modules/@firebolt-js/sdk/dist/lib/Capabilities/index.mjs"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Capabilities", function() { return _Capabilities_index_mjs__WEBPACK_IMPORTED_MODULE_21__["default"]; }); + +/* harmony import */ var _Device_index_mjs__WEBPACK_IMPORTED_MODULE_22__ = __webpack_require__(/*! ./Device/index.mjs */ "./node_modules/@firebolt-js/sdk/dist/lib/Device/index.mjs"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Device", function() { return _Device_index_mjs__WEBPACK_IMPORTED_MODULE_22__["default"]; }); + +/* harmony import */ var _Discovery_index_mjs__WEBPACK_IMPORTED_MODULE_23__ = __webpack_require__(/*! ./Discovery/index.mjs */ "./node_modules/@firebolt-js/sdk/dist/lib/Discovery/index.mjs"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Discovery", function() { return _Discovery_index_mjs__WEBPACK_IMPORTED_MODULE_23__["default"]; }); + +/* harmony import */ var _Keyboard_index_mjs__WEBPACK_IMPORTED_MODULE_24__ = __webpack_require__(/*! ./Keyboard/index.mjs */ "./node_modules/@firebolt-js/sdk/dist/lib/Keyboard/index.mjs"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Keyboard", function() { return _Keyboard_index_mjs__WEBPACK_IMPORTED_MODULE_24__["default"]; }); + +/* harmony import */ var _Lifecycle_index_mjs__WEBPACK_IMPORTED_MODULE_25__ = __webpack_require__(/*! ./Lifecycle/index.mjs */ "./node_modules/@firebolt-js/sdk/dist/lib/Lifecycle/index.mjs"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Lifecycle", function() { return _Lifecycle_index_mjs__WEBPACK_IMPORTED_MODULE_25__["default"]; }); + +/* harmony import */ var _Localization_index_mjs__WEBPACK_IMPORTED_MODULE_26__ = __webpack_require__(/*! ./Localization/index.mjs */ "./node_modules/@firebolt-js/sdk/dist/lib/Localization/index.mjs"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Localization", function() { return _Localization_index_mjs__WEBPACK_IMPORTED_MODULE_26__["default"]; }); + +/* harmony import */ var _Metrics_index_mjs__WEBPACK_IMPORTED_MODULE_27__ = __webpack_require__(/*! ./Metrics/index.mjs */ "./node_modules/@firebolt-js/sdk/dist/lib/Metrics/index.mjs"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Metrics", function() { return _Metrics_index_mjs__WEBPACK_IMPORTED_MODULE_27__["default"]; }); + +/* harmony import */ var _Parameters_index_mjs__WEBPACK_IMPORTED_MODULE_28__ = __webpack_require__(/*! ./Parameters/index.mjs */ "./node_modules/@firebolt-js/sdk/dist/lib/Parameters/index.mjs"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Parameters", function() { return _Parameters_index_mjs__WEBPACK_IMPORTED_MODULE_28__["default"]; }); + +/* harmony import */ var _Profile_index_mjs__WEBPACK_IMPORTED_MODULE_29__ = __webpack_require__(/*! ./Profile/index.mjs */ "./node_modules/@firebolt-js/sdk/dist/lib/Profile/index.mjs"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Profile", function() { return _Profile_index_mjs__WEBPACK_IMPORTED_MODULE_29__["default"]; }); + +/* harmony import */ var _SecondScreen_index_mjs__WEBPACK_IMPORTED_MODULE_30__ = __webpack_require__(/*! ./SecondScreen/index.mjs */ "./node_modules/@firebolt-js/sdk/dist/lib/SecondScreen/index.mjs"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SecondScreen", function() { return _SecondScreen_index_mjs__WEBPACK_IMPORTED_MODULE_30__["default"]; }); + +/* harmony import */ var _SecureStorage_index_mjs__WEBPACK_IMPORTED_MODULE_31__ = __webpack_require__(/*! ./SecureStorage/index.mjs */ "./node_modules/@firebolt-js/sdk/dist/lib/SecureStorage/index.mjs"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SecureStorage", function() { return _SecureStorage_index_mjs__WEBPACK_IMPORTED_MODULE_31__["default"]; }); + +/* harmony import */ var _Platform_index_mjs__WEBPACK_IMPORTED_MODULE_32__ = __webpack_require__(/*! ./Platform/index.mjs */ "./node_modules/@firebolt-js/sdk/dist/lib/Platform/index.mjs"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Platform", function() { return _Platform_index_mjs__WEBPACK_IMPORTED_MODULE_32__["default"]; }); + +/* harmony import */ var _Log_index_mjs__WEBPACK_IMPORTED_MODULE_33__ = __webpack_require__(/*! ./Log/index.mjs */ "./node_modules/@firebolt-js/sdk/dist/lib/Log/index.mjs"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Log", function() { return _Log_index_mjs__WEBPACK_IMPORTED_MODULE_33__["default"]; }); + +/* harmony import */ var _Events_index_mjs__WEBPACK_IMPORTED_MODULE_34__ = __webpack_require__(/*! ./Events/index.mjs */ "./node_modules/@firebolt-js/sdk/dist/lib/Events/index.mjs"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Events", function() { return _Events_index_mjs__WEBPACK_IMPORTED_MODULE_34__["default"]; }); + +/* harmony import */ var _Settings_index_mjs__WEBPACK_IMPORTED_MODULE_35__ = __webpack_require__(/*! ./Settings/index.mjs */ "./node_modules/@firebolt-js/sdk/dist/lib/Settings/index.mjs"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Settings", function() { return _Settings_index_mjs__WEBPACK_IMPORTED_MODULE_35__["default"]; }); + +/* + * Copyright 2021 Comcast Cable Communications Management, LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + */ + + + + + + + + + + + + + + + + + + + + +Object(_Transport_MockTransport_mjs__WEBPACK_IMPORTED_MODULE_0__["setMockResponses"])({ + Accessibility: _Accessibility_defaults_mjs__WEBPACK_IMPORTED_MODULE_1__["default"], + Account: _Account_defaults_mjs__WEBPACK_IMPORTED_MODULE_2__["default"], + Advertising: _Advertising_defaults_mjs__WEBPACK_IMPORTED_MODULE_3__["default"], + Authentication: _Authentication_defaults_mjs__WEBPACK_IMPORTED_MODULE_4__["default"], + Capabilities: _Capabilities_defaults_mjs__WEBPACK_IMPORTED_MODULE_5__["default"], + Device: _Device_defaults_mjs__WEBPACK_IMPORTED_MODULE_6__["default"], + Discovery: _Discovery_defaults_mjs__WEBPACK_IMPORTED_MODULE_7__["default"], + Keyboard: _Keyboard_defaults_mjs__WEBPACK_IMPORTED_MODULE_8__["default"], + Lifecycle: _Lifecycle_defaults_mjs__WEBPACK_IMPORTED_MODULE_9__["default"], + Localization: _Localization_defaults_mjs__WEBPACK_IMPORTED_MODULE_10__["default"], + Metrics: _Metrics_defaults_mjs__WEBPACK_IMPORTED_MODULE_11__["default"], + Parameters: _Parameters_defaults_mjs__WEBPACK_IMPORTED_MODULE_12__["default"], + Profile: _Profile_defaults_mjs__WEBPACK_IMPORTED_MODULE_13__["default"], + SecondScreen: _SecondScreen_defaults_mjs__WEBPACK_IMPORTED_MODULE_14__["default"], + SecureStorage: _SecureStorage_defaults_mjs__WEBPACK_IMPORTED_MODULE_15__["default"], + Platform: _Platform_defaults_mjs__WEBPACK_IMPORTED_MODULE_16__["default"], +}) + + + + + + + + + + + + + + + + + + + + + + +/***/ }), + +/***/ "./node_modules/@jsdevtools/ono/esm/constructor.js": +/*!*********************************************************!*\ + !*** ./node_modules/@jsdevtools/ono/esm/constructor.js ***! + \*********************************************************/ +/*! exports provided: Ono */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Ono", function() { return constructor; }); +/* harmony import */ var _extend_error__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./extend-error */ "./node_modules/@jsdevtools/ono/esm/extend-error.js"); +/* harmony import */ var _normalize__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./normalize */ "./node_modules/@jsdevtools/ono/esm/normalize.js"); +/* harmony import */ var _to_json__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./to-json */ "./node_modules/@jsdevtools/ono/esm/to-json.js"); + + + +const constructor = Ono; + +/** + * Creates an `Ono` instance for a specifc error type. + */ +// eslint-disable-next-line @typescript-eslint/naming-convention +function Ono(ErrorConstructor, options) { + options = Object(_normalize__WEBPACK_IMPORTED_MODULE_1__["normalizeOptions"])(options); + function ono(...args) { + let { originalError, props, message } = Object(_normalize__WEBPACK_IMPORTED_MODULE_1__["normalizeArgs"])(args, options); + // Create a new error of the specified type + let newError = new ErrorConstructor(message); + // Extend the error with the properties of the original error and the `props` object + return Object(_extend_error__WEBPACK_IMPORTED_MODULE_0__["extendError"])(newError, originalError, props); + } + ono[Symbol.species] = ErrorConstructor; + return ono; +} +/** + * Returns an object containing all properties of the given Error object, + * which can be used with `JSON.stringify()`. + */ +Ono.toJSON = function toJSON(error) { + return _to_json__WEBPACK_IMPORTED_MODULE_2__["toJSON"].call(error); +}; +/** + * Extends the given Error object with enhanced Ono functionality, such as nested stack traces, + * additional properties, and improved support for `JSON.stringify()`. + */ +Ono.extend = function extend(error, originalError, props) { + if (props || originalError instanceof Error) { + return Object(_extend_error__WEBPACK_IMPORTED_MODULE_0__["extendError"])(error, originalError, props); + } + else if (originalError) { + return Object(_extend_error__WEBPACK_IMPORTED_MODULE_0__["extendError"])(error, undefined, originalError); + } + else { + return Object(_extend_error__WEBPACK_IMPORTED_MODULE_0__["extendError"])(error); + } +}; +//# sourceMappingURL=constructor.js.map + +/***/ }), + +/***/ "./node_modules/@jsdevtools/ono/esm/extend-error.js": +/*!**********************************************************!*\ + !*** ./node_modules/@jsdevtools/ono/esm/extend-error.js ***! + \**********************************************************/ +/*! exports provided: extendError */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "extendError", function() { return extendError; }); +/* harmony import */ var _isomorphic_node__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./isomorphic.node */ "./node_modules/@jsdevtools/ono/esm/isomorphic.browser.js"); +/* harmony import */ var _stack__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./stack */ "./node_modules/@jsdevtools/ono/esm/stack.js"); +/* harmony import */ var _to_json__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./to-json */ "./node_modules/@jsdevtools/ono/esm/to-json.js"); + + + +const protectedProps = ["name", "message", "stack"]; +/** + * Extends the new error with the properties of the original error and the `props` object. + * + * @param newError - The error object to extend + * @param originalError - The original error object, if any + * @param props - Additional properties to add, if any + */ +function extendError(error, originalError, props) { + let onoError = error; + extendStack(onoError, originalError); + // Copy properties from the original error + if (originalError && typeof originalError === "object") { + mergeErrors(onoError, originalError); + } + // The default `toJSON` method doesn't output props like `name`, `message`, `stack`, etc. + // So replace it with one that outputs every property of the error. + onoError.toJSON = _to_json__WEBPACK_IMPORTED_MODULE_2__["toJSON"]; + // On Node.js, add support for the `util.inspect()` method + // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition + if (_isomorphic_node__WEBPACK_IMPORTED_MODULE_0__["addInspectMethod"]) { + Object(_isomorphic_node__WEBPACK_IMPORTED_MODULE_0__["addInspectMethod"])(onoError); + } + // Finally, copy custom properties that were specified by the user. + // These props OVERWRITE any previous props + if (props && typeof props === "object") { + Object.assign(onoError, props); + } + return onoError; +} +/** + * Extend the error stack to include its cause + */ +function extendStack(newError, originalError) { + let stackProp = Object.getOwnPropertyDescriptor(newError, "stack"); + if (Object(_stack__WEBPACK_IMPORTED_MODULE_1__["isLazyStack"])(stackProp)) { + Object(_stack__WEBPACK_IMPORTED_MODULE_1__["lazyJoinStacks"])(stackProp, newError, originalError); + } + else if (Object(_stack__WEBPACK_IMPORTED_MODULE_1__["isWritableStack"])(stackProp)) { + newError.stack = Object(_stack__WEBPACK_IMPORTED_MODULE_1__["joinStacks"])(newError, originalError); + } +} +/** + * Merges properties of the original error with the new error. + * + * @param newError - The error object to extend + * @param originalError - The original error object, if any + */ +function mergeErrors(newError, originalError) { + // Get the original error's keys + // NOTE: We specifically exclude properties that we have already set on the new error. + // This is _especially_ important for the `stack` property, because this property has + // a lazy getter in some environments + let keys = Object(_to_json__WEBPACK_IMPORTED_MODULE_2__["getDeepKeys"])(originalError, protectedProps); + // HACK: We have to cast the errors to `any` so we can use symbol indexers. + // see https://github.com/Microsoft/TypeScript/issues/1863 + let _newError = newError; + let _originalError = originalError; + for (let key of keys) { + if (_newError[key] === undefined) { + try { + _newError[key] = _originalError[key]; + } + catch (e) { + // This property is read-only, so it can't be copied + } + } + } +} +//# sourceMappingURL=extend-error.js.map + +/***/ }), + +/***/ "./node_modules/@jsdevtools/ono/esm/index.js": +/*!***************************************************!*\ + !*** ./node_modules/@jsdevtools/ono/esm/index.js ***! + \***************************************************/ +/*! exports provided: Ono, ono, default */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* WEBPACK VAR INJECTION */(function(module) {/* harmony import */ var _singleton__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./singleton */ "./node_modules/@jsdevtools/ono/esm/singleton.js"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ono", function() { return _singleton__WEBPACK_IMPORTED_MODULE_0__["ono"]; }); + +/* harmony import */ var _constructor__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./constructor */ "./node_modules/@jsdevtools/ono/esm/constructor.js"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Ono", function() { return _constructor__WEBPACK_IMPORTED_MODULE_1__["Ono"]; }); + +/* harmony import */ var _types__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./types */ "./node_modules/@jsdevtools/ono/esm/types.js"); +/* empty/unused harmony star reexport *//* eslint-env commonjs */ + + + + +/* harmony default export */ __webpack_exports__["default"] = (_singleton__WEBPACK_IMPORTED_MODULE_0__["ono"]); +// CommonJS default export hack +if ( true && typeof module.exports === "object") { + module.exports = Object.assign(module.exports.default, module.exports); +} +//# sourceMappingURL=index.js.map +/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../../../webpack/buildin/harmony-module.js */ "./node_modules/webpack/buildin/harmony-module.js")(module))) + +/***/ }), + +/***/ "./node_modules/@jsdevtools/ono/esm/isomorphic.browser.js": +/*!****************************************************************!*\ + !*** ./node_modules/@jsdevtools/ono/esm/isomorphic.browser.js ***! + \****************************************************************/ +/*! exports provided: format, addInspectMethod */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "format", function() { return format; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "addInspectMethod", function() { return addInspectMethod; }); +/** + * Ono supports custom formatters for error messages. In Node.js, it defaults + * to the `util.format()` function. In browsers, it defaults to `Array.join()`. + * + * The Node.js functionality can be used in a web browser via a polyfill, + * such as "format-util". + * + * @see https://github.com/tmpfs/format-util + */ +const format = false; +/** + * The `util.inspect()` functionality only applies to Node.js. + * We return the constant `false` here so that the Node-specific code gets removed by tree-shaking. + */ +const addInspectMethod = false; +//# sourceMappingURL=isomorphic.browser.js.map + +/***/ }), + +/***/ "./node_modules/@jsdevtools/ono/esm/normalize.js": +/*!*******************************************************!*\ + !*** ./node_modules/@jsdevtools/ono/esm/normalize.js ***! + \*******************************************************/ +/*! exports provided: normalizeOptions, normalizeArgs */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "normalizeOptions", function() { return normalizeOptions; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "normalizeArgs", function() { return normalizeArgs; }); +/* harmony import */ var _isomorphic_node__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./isomorphic.node */ "./node_modules/@jsdevtools/ono/esm/isomorphic.browser.js"); + +/** + * Normalizes Ono options, accounting for defaults and optional options. + */ +function normalizeOptions(options) { + options = options || {}; + return { + concatMessages: options.concatMessages === undefined ? true : Boolean(options.concatMessages), + format: options.format === undefined ? _isomorphic_node__WEBPACK_IMPORTED_MODULE_0__["format"] + : (typeof options.format === "function" ? options.format : false), + }; +} +/** + * Normalizes the Ono arguments, accounting for defaults, options, and optional arguments. + */ +function normalizeArgs(args, options) { + let originalError; + let props; + let formatArgs; + let message = ""; + // Determine which arguments were actually specified + if (typeof args[0] === "string") { + formatArgs = args; + } + else if (typeof args[1] === "string") { + if (args[0] instanceof Error) { + originalError = args[0]; + } + else { + props = args[0]; + } + formatArgs = args.slice(1); + } + else { + originalError = args[0]; + props = args[1]; + formatArgs = args.slice(2); + } + // If there are any format arguments, then format the error message + if (formatArgs.length > 0) { + if (options.format) { + message = options.format.apply(undefined, formatArgs); + } + else { + message = formatArgs.join(" "); + } + } + if (options.concatMessages && originalError && originalError.message) { + // The inner-error's message will be added to the new message + message += (message ? " \n" : "") + originalError.message; + } + return { originalError, props, message }; +} +//# sourceMappingURL=normalize.js.map + +/***/ }), + +/***/ "./node_modules/@jsdevtools/ono/esm/singleton.js": +/*!*******************************************************!*\ + !*** ./node_modules/@jsdevtools/ono/esm/singleton.js ***! + \*******************************************************/ +/*! exports provided: ono */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ono", function() { return singleton; }); +/* harmony import */ var _constructor__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./constructor */ "./node_modules/@jsdevtools/ono/esm/constructor.js"); + +const singleton = ono; + +ono.error = new _constructor__WEBPACK_IMPORTED_MODULE_0__["Ono"](Error); +ono.eval = new _constructor__WEBPACK_IMPORTED_MODULE_0__["Ono"](EvalError); +ono.range = new _constructor__WEBPACK_IMPORTED_MODULE_0__["Ono"](RangeError); +ono.reference = new _constructor__WEBPACK_IMPORTED_MODULE_0__["Ono"](ReferenceError); +ono.syntax = new _constructor__WEBPACK_IMPORTED_MODULE_0__["Ono"](SyntaxError); +ono.type = new _constructor__WEBPACK_IMPORTED_MODULE_0__["Ono"](TypeError); +ono.uri = new _constructor__WEBPACK_IMPORTED_MODULE_0__["Ono"](URIError); +const onoMap = ono; +/** + * Creates a new error with the specified message, properties, and/or inner error. + * If an inner error is provided, then the new error will match its type, if possible. + */ +function ono(...args) { + let originalError = args[0]; + // Is the first argument an Error-like object? + if (typeof originalError === "object" && typeof originalError.name === "string") { + // Try to find an Ono singleton method that matches this error type + for (let typedOno of Object.values(onoMap)) { + if (typeof typedOno === "function" && typedOno.name === "ono") { + let species = typedOno[Symbol.species]; + if (species && species !== Error && (originalError instanceof species || originalError.name === species.name)) { + // Create an error of the same type + return typedOno.apply(undefined, args); + } + } + } + } + // By default, create a base Error object + return ono.error.apply(undefined, args); +} +//# sourceMappingURL=singleton.js.map + +/***/ }), + +/***/ "./node_modules/@jsdevtools/ono/esm/stack.js": +/*!***************************************************!*\ + !*** ./node_modules/@jsdevtools/ono/esm/stack.js ***! + \***************************************************/ +/*! exports provided: isLazyStack, isWritableStack, joinStacks, lazyJoinStacks */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isLazyStack", function() { return isLazyStack; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isWritableStack", function() { return isWritableStack; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "joinStacks", function() { return joinStacks; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "lazyJoinStacks", function() { return lazyJoinStacks; }); +const newline = /\r?\n/; +const onoCall = /\bono[ @]/; +/** + * Is the property lazily computed? + */ +function isLazyStack(stackProp) { + return Boolean(stackProp && + stackProp.configurable && + typeof stackProp.get === "function"); +} +/** + * Is the stack property writable? + */ +function isWritableStack(stackProp) { + return Boolean( + // If there is no stack property, then it's writable, since assigning it will create it + !stackProp || + stackProp.writable || + typeof stackProp.set === "function"); +} +/** + * Appends the original `Error.stack` property to the new Error's stack. + */ +function joinStacks(newError, originalError) { + let newStack = popStack(newError.stack); + let originalStack = originalError ? originalError.stack : undefined; + if (newStack && originalStack) { + return newStack + "\n\n" + originalStack; + } + else { + return newStack || originalStack; + } +} +/** + * Calls `joinStacks` lazily, when the `Error.stack` property is accessed. + */ +function lazyJoinStacks(lazyStack, newError, originalError) { + if (originalError) { + Object.defineProperty(newError, "stack", { + get: () => { + let newStack = lazyStack.get.apply(newError); + return joinStacks({ stack: newStack }, originalError); + }, + enumerable: false, + configurable: true + }); + } + else { + lazyPopStack(newError, lazyStack); + } +} +/** + * Removes Ono from the stack, so that the stack starts at the original error location + */ +function popStack(stack) { + if (stack) { + let lines = stack.split(newline); + // Find the Ono call(s) in the stack, and remove them + let onoStart; + for (let i = 0; i < lines.length; i++) { + let line = lines[i]; + if (onoCall.test(line)) { + if (onoStart === undefined) { + // We found the first Ono call in the stack trace. + // There may be other subsequent Ono calls as well. + onoStart = i; + } + } + else if (onoStart !== undefined) { + // We found the first non-Ono call after one or more Ono calls. + // So remove the Ono call lines from the stack trace + lines.splice(onoStart, i - onoStart); + break; + } + } + if (lines.length > 0) { + return lines.join("\n"); + } + } + // If we get here, then the stack doesn't contain a call to `ono`. + // This may be due to minification or some optimization of the JS engine. + // So just return the stack as-is. + return stack; +} +/** + * Calls `popStack` lazily, when the `Error.stack` property is accessed. + */ +function lazyPopStack(error, lazyStack) { + Object.defineProperty(error, "stack", { + get: () => popStack(lazyStack.get.apply(error)), + enumerable: false, + configurable: true + }); +} +//# sourceMappingURL=stack.js.map + +/***/ }), + +/***/ "./node_modules/@jsdevtools/ono/esm/to-json.js": +/*!*****************************************************!*\ + !*** ./node_modules/@jsdevtools/ono/esm/to-json.js ***! + \*****************************************************/ +/*! exports provided: toJSON, getDeepKeys */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "toJSON", function() { return toJSON; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getDeepKeys", function() { return getDeepKeys; }); +const nonJsonTypes = ["function", "symbol", "undefined"]; +const protectedProps = ["constructor", "prototype", "__proto__"]; +const objectPrototype = Object.getPrototypeOf({}); +/** + * Custom JSON serializer for Error objects. + * Returns all built-in error properties, as well as extended properties. + */ +function toJSON() { + // HACK: We have to cast the objects to `any` so we can use symbol indexers. + // see https://github.com/Microsoft/TypeScript/issues/1863 + let pojo = {}; + let error = this; + for (let key of getDeepKeys(error)) { + if (typeof key === "string") { + let value = error[key]; + let type = typeof value; + if (!nonJsonTypes.includes(type)) { + pojo[key] = value; + } + } + } + return pojo; +} +/** + * Returns own, inherited, enumerable, non-enumerable, string, and symbol keys of `obj`. + * Does NOT return members of the base Object prototype, or the specified omitted keys. + */ +function getDeepKeys(obj, omit = []) { + let keys = []; + // Crawl the prototype chain, finding all the string and symbol keys + while (obj && obj !== objectPrototype) { + keys = keys.concat(Object.getOwnPropertyNames(obj), Object.getOwnPropertySymbols(obj)); + obj = Object.getPrototypeOf(obj); + } + // De-duplicate the list of keys + let uniqueKeys = new Set(keys); + // Remove any omitted keys + for (let key of omit.concat(protectedProps)) { + uniqueKeys.delete(key); + } + return uniqueKeys; +} +//# sourceMappingURL=to-json.js.map + +/***/ }), + +/***/ "./node_modules/@jsdevtools/ono/esm/types.js": +/*!***************************************************!*\ + !*** ./node_modules/@jsdevtools/ono/esm/types.js ***! + \***************************************************/ +/*! no exports provided */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var util__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! util */ "./node_modules/util/util.js"); +/* harmony import */ var util__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(util__WEBPACK_IMPORTED_MODULE_0__); + +//# sourceMappingURL=types.js.map + +/***/ }), + +/***/ "./node_modules/@lightningjs/core/dist/lightning.esm.js": +/*!**************************************************************!*\ + !*** ./node_modules/@lightningjs/core/dist/lightning.esm.js ***! + \**************************************************************/ +/*! exports provided: default */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* WEBPACK VAR INJECTION */(function(global) {/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return lightning; }); +/* + * Lightning v2.11.0 + * + * https://github.com/rdkcentral/Lightning + */ +class StageUtils { + static mergeNumbers(v1, v2, p) { + return v1 * p + v2 * (1 - p); + } + static rgb(r, g, b) { + return (r << 16) + (g << 8) + b + 255 * 16777216; + } + static rgba(r, g, b, a) { + return (r << 16) + (g << 8) + b + (a * 255 | 0) * 16777216; + } + static getRgbString(color) { + let r = (color / 65536 | 0) % 256; + let g = (color / 256 | 0) % 256; + let b = color % 256; + return "rgb(" + r + "," + g + "," + b + ")"; + } + static getRgbaString(color) { + let r = (color / 65536 | 0) % 256; + let g = (color / 256 | 0) % 256; + let b = color % 256; + let a = (color / 16777216 | 0) / 255; + return "rgba(" + r + "," + g + "," + b + "," + a.toFixed(4) + ")"; + } + static getRgbaStringFromArray(color) { + let r = Math.floor(color[0] * 255); + let g = Math.floor(color[1] * 255); + let b = Math.floor(color[2] * 255); + let a = Math.floor(color[3] * 255) / 255; + return "rgba(" + r + "," + g + "," + b + "," + a.toFixed(4) + ")"; + } + static getRgbaComponentsNormalized(argb) { + let r = (argb / 65536 | 0) % 256; + let g = (argb / 256 | 0) % 256; + let b = argb % 256; + let a = argb / 16777216 | 0; + return [r / 255, g / 255, b / 255, a / 255]; + } + static getRgbComponentsNormalized(argb) { + let r = (argb / 65536 | 0) % 256; + let g = (argb / 256 | 0) % 256; + let b = argb % 256; + return [r / 255, g / 255, b / 255]; + } + static getRgbaComponents(argb) { + let r = (argb / 65536 | 0) % 256; + let g = (argb / 256 | 0) % 256; + let b = argb % 256; + let a = argb / 16777216 | 0; + return [r, g, b, a]; + } + static getArgbNumber(rgba) { + rgba[0] = Math.max(0, Math.min(255, rgba[0])); + rgba[1] = Math.max(0, Math.min(255, rgba[1])); + rgba[2] = Math.max(0, Math.min(255, rgba[2])); + rgba[3] = Math.max(0, Math.min(255, rgba[3])); + let v = ((rgba[3] | 0) << 24) + ((rgba[0] | 0) << 16) + ((rgba[1] | 0) << 8) + (rgba[2] | 0); + if (v < 0) { + v = 4294967295 + v + 1; + } + return v; + } + static mergeColors(c1, c2, p) { + let r1 = (c1 / 65536 | 0) % 256; + let g1 = (c1 / 256 | 0) % 256; + let b1 = c1 % 256; + let a1 = c1 / 16777216 | 0; + let r2 = (c2 / 65536 | 0) % 256; + let g2 = (c2 / 256 | 0) % 256; + let b2 = c2 % 256; + let a2 = c2 / 16777216 | 0; + let r = r1 * p + r2 * (1 - p); + let g = g1 * p + g2 * (1 - p); + let b = b1 * p + b2 * (1 - p); + let a = a1 * p + a2 * (1 - p); + return Math.round(a) * 16777216 + Math.round(r) * 65536 + Math.round(g) * 256 + Math.round(b); + } + static mergeMultiColors(c, p) { + let r = 0, g = 0, b = 0, a = 0, t = 0; + let n = c.length; + for (let i = 0; i < n; i++) { + let r1 = (c[i] / 65536 | 0) % 256; + let g1 = (c[i] / 256 | 0) % 256; + let b1 = c[i] % 256; + let a1 = c[i] / 16777216 | 0; + r += r1 * p[i]; + g += g1 * p[i]; + b += b1 * p[i]; + a += a1 * p[i]; + t += p[i]; + } + t = 1 / t; + return Math.round(a * t) * 16777216 + Math.round(r * t) * 65536 + Math.round(g * t) * 256 + Math.round(b * t); + } + static mergeMultiColorsEqual(c) { + let r = 0, g = 0, b = 0, a = 0, t = 0; + let n = c.length; + for (let i = 0; i < n; i++) { + let r1 = (c[i] / 65536 | 0) % 256; + let g1 = (c[i] / 256 | 0) % 256; + let b1 = c[i] % 256; + let a1 = c[i] / 16777216 | 0; + r += r1; + g += g1; + b += b1; + a += a1; + t += 1; + } + t = 1 / t; + return Math.round(a * t) * 16777216 + Math.round(r * t) * 65536 + Math.round(g * t) * 256 + Math.round(b * t); + } + static mergeColorAlpha(c, alpha) { + let a = (c / 16777216 | 0) * alpha | 0; + return ((c >> 16 & 255) * a / 255 & 255) + ((c & 65280) * a / 255 & 65280) + (((c & 255) << 16) * a / 255 & 16711680) + (a << 24); + } + static rad(deg) { + return deg * (Math.PI / 180); + } + static getTimingBezier(a, b, c, d) { + let xc = 3 * a; + let xb = 3 * (c - a) - xc; + let xa = 1 - xc - xb; + let yc = 3 * b; + let yb = 3 * (d - b) - yc; + let ya = 1 - yc - yb; + return function(time) { + if (time >= 1) { + return 1; + } + if (time <= 0) { + return 0; + } + let t = 0.5, cbx, cbxd, dx; + for (let it = 0; it < 20; it++) { + cbx = t * (t * (t * xa + xb) + xc); + dx = time - cbx; + if (dx > -1e-8 && dx < 1e-8) { + return t * (t * (t * ya + yb) + yc); + } + cbxd = t * (t * (3 * xa) + 2 * xb) + xc; + if (cbxd > 1e-10 && cbxd < 1e-10) { + break; + } + t += dx / cbxd; + } + let minT = 0; + let maxT = 1; + for (let it = 0; it < 20; it++) { + t = 0.5 * (minT + maxT); + cbx = t * (t * (t * xa + xb) + xc); + dx = time - cbx; + if (dx > -1e-8 && dx < 1e-8) { + return t * (t * (t * ya + yb) + yc); + } + if (dx < 0) { + maxT = t; + } else { + minT = t; + } + } + }; + } + static getTimingFunction(str) { + switch (str) { + case "linear": + return function(time) { + return time; + }; + case "ease": + return StageUtils.getTimingBezier(0.25, 0.1, 0.25, 1); + case "ease-in": + return StageUtils.getTimingBezier(0.42, 0, 1, 1); + case "ease-out": + return StageUtils.getTimingBezier(0, 0, 0.58, 1); + case "ease-in-out": + return StageUtils.getTimingBezier(0.42, 0, 0.58, 1); + case "step-start": + return function() { + return 1; + }; + case "step-end": + return function(time) { + return time === 1 ? 1 : 0; + }; + default: + let s = "cubic-bezier("; + if (str && str.indexOf(s) === 0) { + let parts = str.substr(s.length, str.length - s.length - 1).split(","); + if (parts.length !== 4) { + console.warn("[Lightning] Unknown timing function: " + str); + return function(time) { + return time; + }; + } + let a = parseFloat(parts[0]); + let b = parseFloat(parts[1]); + let c = parseFloat(parts[2]); + let d = parseFloat(parts[3]); + if (isNaN(a) || isNaN(b) || isNaN(c) || isNaN(d)) { + console.warn("[Lightning] Unknown timing function: " + str); + return function(time) { + return time; + }; + } + return StageUtils.getTimingBezier(a, b, c, d); + } else { + console.warn("[Lightning] Unknown timing function: " + str); + return function(time) { + return time; + }; + } + } + } +} +let Utils$1 = class Utils { + static isFunction(value) { + return typeof value === "function"; + } + static isNumber(value) { + return typeof value === "number"; + } + static isInteger(value) { + return typeof value === "number" && value % 1 === 0; + } + static isBoolean(value) { + return value === true || value === false; + } + static isString(value) { + return typeof value === "string"; + } + static clone(v) { + if (Utils$1.isObjectLiteral(v) || Array.isArray(v)) { + return Utils$1.getDeepClone(v); + } else { + return v; + } + } + static cloneObjShallow(obj) { + let keys = Object.keys(obj); + let clone = {}; + for (let i = 0; i < keys.length; i++) { + clone[keys[i]] = obj[keys[i]]; + } + return clone; + } + static merge(obj1, obj2) { + let keys = Object.keys(obj2); + for (let i = 0; i < keys.length; i++) { + obj1[keys[i]] = obj2[keys[i]]; + } + return obj1; + } + static isObject(value) { + let type = typeof value; + return !!value && (type === "object" || type === "function"); + } + static isPlainObject(value) { + let type = typeof value; + return !!value && type === "object"; + } + static isObjectLiteral(value) { + return typeof value === "object" && value && value.constructor === Object; + } + static getArrayIndex(index, arr) { + return Utils$1.getModuloIndex(index, arr.length); + } + static getModuloIndex(index, len) { + if (len === 0) + return index; + while (index < 0) { + index += Math.ceil(-index / len) * len; + } + index = index % len; + return index; + } + static getDeepClone(obj) { + let i, c; + if (Utils$1.isFunction(obj)) { + return obj; + } + if (Array.isArray(obj)) { + c = []; + let keys = Object.keys(obj); + for (i = 0; i < keys.length; i++) { + c[keys[i]] = Utils$1.getDeepClone(obj[keys[i]]); + } + return c; + } else if (Utils$1.isObject(obj)) { + c = {}; + let keys = Object.keys(obj); + for (i = 0; i < keys.length; i++) { + c[keys[i]] = Utils$1.getDeepClone(obj[keys[i]]); + } + return c; + } else { + return obj; + } + } + static equalValues(v1, v2) { + if (typeof v1 !== typeof v2) + return false; + if (Utils$1.isObjectLiteral(v1)) { + return Utils$1.isObjectLiteral(v2) && Utils$1.equalObjectLiterals(v1, v2); + } else if (Array.isArray(v1)) { + return Array.isArray(v2) && Utils$1.equalArrays(v1, v2); + } else { + return v1 === v2; + } + } + static equalObjectLiterals(obj1, obj2) { + let keys1 = Object.keys(obj1); + let keys2 = Object.keys(obj2); + if (keys1.length !== keys2.length) { + return false; + } + for (let i = 0, n = keys1.length; i < n; i++) { + const k1 = keys1[i]; + const k2 = keys2[i]; + if (k1 !== k2) { + return false; + } + const v1 = obj1[k1]; + const v2 = obj2[k2]; + if (!Utils$1.equalValues(v1, v2)) { + return false; + } + } + return true; + } + static equalArrays(v1, v2) { + if (v1.length !== v2.length) { + return false; + } + for (let i = 0, n = v1.length; i < n; i++) { + if (!this.equalValues(v1[i], v2[i])) { + return false; + } + } + return true; + } + static setToArray(s) { + let result = []; + s.forEach(function(value) { + result.push(value); + }); + return result; + } + static iteratorToArray(iterator) { + let result = []; + let iteratorResult = iterator.next(); + while (!iteratorResult.done) { + result.push(iteratorResult.value); + iteratorResult = iterator.next(); + } + return result; + } + static isUcChar(charcode) { + return charcode >= 65 && charcode <= 90; + } +}; +Utils$1.isWeb = typeof window !== "undefined" && typeof sparkscene === "undefined"; +Utils$1.isWPE = Utils$1.isWeb && navigator.userAgent.indexOf("WPE") !== -1; +Utils$1.isSpark = typeof sparkscene !== "undefined"; +Utils$1.isNode = typeof window === "undefined" || Utils$1.isSpark; +Utils$1.isPS4 = Utils$1.isWeb && navigator.userAgent.indexOf("PlayStation 4") !== -1; +Utils$1.isZiggo = Utils$1.isWeb && (navigator.userAgent.indexOf("EOSSTB") !== -1 || navigator.userAgent.indexOf("HZNSTB") !== -1); +class Base { + static defaultSetter(obj, name, value) { + obj[name] = value; + } + static patchObject(obj, settings) { + if (!Utils$1.isObjectLiteral(settings)) { + console.error("[Lightning] Settings must be object literal"); + } else { + let names = Object.keys(settings); + for (let i = 0, n = names.length; i < n; i++) { + let name = names[i]; + this.patchObjectProperty(obj, name, settings[name]); + } + } + } + static patchObjectProperty(obj, name, value) { + let setter = obj.setSetting || Base.defaultSetter; + if (name.charAt(0) === "_") { + if (name !== "__create") { + console.error("[Lightning] Patch of private property '" + name + "' is not allowed"); + } + } else if (name !== "type") { + if (Utils$1.isFunction(value) && value.__local) { + value = value.__local(obj); + } + setter(obj, name, value); + } + } + static local(func) { + func.__local = true; + } +} +class SpacingCalculator { + static getSpacing(mode, numberOfItems, remainingSpace) { + const itemGaps = numberOfItems - 1; + let spacePerGap; + let spacingBefore, spacingBetween; + switch (mode) { + case "flex-start": + spacingBefore = 0; + spacingBetween = 0; + break; + case "flex-end": + spacingBefore = remainingSpace; + spacingBetween = 0; + break; + case "center": + spacingBefore = remainingSpace / 2; + spacingBetween = 0; + break; + case "space-between": + spacingBefore = 0; + spacingBetween = Math.max(0, remainingSpace) / itemGaps; + break; + case "space-around": + if (remainingSpace < 0) { + return this.getSpacing("center", numberOfItems, remainingSpace); + } else { + spacePerGap = remainingSpace / (itemGaps + 1); + spacingBefore = 0.5 * spacePerGap; + spacingBetween = spacePerGap; + } + break; + case "space-evenly": + if (remainingSpace < 0) { + return this.getSpacing("center", numberOfItems, remainingSpace); + } else { + spacePerGap = remainingSpace / (itemGaps + 2); + spacingBefore = spacePerGap; + spacingBetween = spacePerGap; + } + break; + case "stretch": + spacingBefore = 0; + spacingBetween = 0; + break; + default: + throw new Error("Unknown mode: " + mode); + } + return { spacingBefore, spacingBetween }; + } +} +class ContentAligner { + constructor(layout) { + this._layout = layout; + this._totalCrossAxisSize = 0; + } + get _lines() { + return this._layout._lines; + } + init() { + this._totalCrossAxisSize = this._getTotalCrossAxisSize(); + } + align() { + const crossAxisSize = this._layout.crossAxisSize; + const remainingSpace = crossAxisSize - this._totalCrossAxisSize; + const { spacingBefore, spacingBetween } = this._getSpacing(remainingSpace); + const lines = this._lines; + const mode = this._layout._flexContainer.alignContent; + let growSize = 0; + if (mode === "stretch" && lines.length && remainingSpace > 0) { + growSize = remainingSpace / lines.length; + } + let currentPos = spacingBefore; + for (let i = 0, n = lines.length; i < n; i++) { + const crossAxisLayoutOffset = currentPos; + const aligner = lines[i].createItemAligner(); + let finalCrossAxisLayoutSize = lines[i].crossAxisLayoutSize + growSize; + aligner.setCrossAxisLayoutSize(finalCrossAxisLayoutSize); + aligner.setCrossAxisLayoutOffset(crossAxisLayoutOffset); + aligner.align(); + if (aligner.recursiveResizeOccured) { + lines[i].setItemPositions(); + } + currentPos += finalCrossAxisLayoutSize; + currentPos += spacingBetween; + } + } + get totalCrossAxisSize() { + return this._totalCrossAxisSize; + } + _getTotalCrossAxisSize() { + const lines = this._lines; + let total = 0; + for (let i = 0, n = lines.length; i < n; i++) { + const line = lines[i]; + total += line.crossAxisLayoutSize; + } + return total; + } + _getSpacing(remainingSpace) { + const mode = this._layout._flexContainer.alignContent; + const numberOfItems = this._lines.length; + return SpacingCalculator.getSpacing(mode, numberOfItems, remainingSpace); + } +} +class FlexUtils { + static getParentAxisSizeWithPadding(item, horizontal) { + const target = item.target; + const parent = target.getParent(); + if (!parent) { + return 0; + } else { + const flexParent = item.flexParent; + if (flexParent) { + return this.getAxisLayoutSize(flexParent, horizontal) + this.getTotalPadding(flexParent, horizontal); + } else { + return horizontal ? parent.w : parent.h; + } + } + } + static getRelAxisSize(item, horizontal) { + if (horizontal) { + if (item.funcW) { + if (this._allowRelAxisSizeFunction(item, true)) { + return item.funcW(this.getParentAxisSizeWithPadding(item, true)); + } else { + return 0; + } + } else { + return item.originalWidth; + } + } else { + if (item.funcH) { + if (this._allowRelAxisSizeFunction(item, false)) { + return item.funcH(this.getParentAxisSizeWithPadding(item, false)); + } else { + return 0; + } + } else { + return item.originalHeight; + } + } + } + static _allowRelAxisSizeFunction(item, horizontal) { + const flexParent = item.flexParent; + if (flexParent && flexParent._flex._layout.isAxisFitToContents(horizontal)) { + return false; + } + return true; + } + static isZeroAxisSize(item, horizontal) { + if (horizontal) { + return !item.originalWidth && !item.funcW; + } else { + return !item.originalHeight && !item.funcH; + } + } + static getAxisLayoutPos(item, horizontal) { + return horizontal ? item.x : item.y; + } + static getAxisLayoutSize(item, horizontal) { + return horizontal ? item.w : item.h; + } + static setAxisLayoutPos(item, horizontal, pos) { + if (horizontal) { + item.x = pos; + } else { + item.y = pos; + } + } + static setAxisLayoutSize(item, horizontal, size) { + if (horizontal) { + item.w = size; + } else { + item.h = size; + } + } + static getAxisMinSize(item, horizontal) { + let minSize = this.getPlainAxisMinSize(item, horizontal); + let flexItemMinSize = 0; + if (item.isFlexItemEnabled()) { + flexItemMinSize = item._flexItem._getMinSizeSetting(horizontal); + } + const hasLimitedMinSize = flexItemMinSize > 0; + if (hasLimitedMinSize) { + minSize = Math.max(minSize, flexItemMinSize); + } + return minSize; + } + static getPlainAxisMinSize(item, horizontal) { + if (item.isFlexEnabled()) { + return item._flex._layout.getAxisMinSize(horizontal); + } else { + const isShrinkable = item.flexItem.shrink !== 0; + if (isShrinkable) { + return 0; + } else { + return this.getRelAxisSize(item, horizontal); + } + } + } + static resizeAxis(item, horizontal, size) { + if (item.isFlexEnabled()) { + const isMainAxis = item._flex._horizontal === horizontal; + if (isMainAxis) { + item._flex._layout.resizeMainAxis(size); + } else { + item._flex._layout.resizeCrossAxis(size); + } + } else { + this.setAxisLayoutSize(item, horizontal, size); + } + } + static getPaddingOffset(item, horizontal) { + if (item.isFlexEnabled()) { + const flex = item._flex; + if (horizontal) { + return flex.paddingLeft; + } else { + return flex.paddingTop; + } + } else { + return 0; + } + } + static getTotalPadding(item, horizontal) { + if (item.isFlexEnabled()) { + const flex = item._flex; + if (horizontal) { + return flex.paddingRight + flex.paddingLeft; + } else { + return flex.paddingTop + flex.paddingBottom; + } + } else { + return 0; + } + } + static getMarginOffset(item, horizontal) { + const flexItem = item.flexItem; + if (flexItem) { + if (horizontal) { + return flexItem.marginLeft; + } else { + return flexItem.marginTop; + } + } else { + return 0; + } + } + static getTotalMargin(item, horizontal) { + const flexItem = item.flexItem; + if (flexItem) { + if (horizontal) { + return flexItem.marginRight + flexItem.marginLeft; + } else { + return flexItem.marginTop + flexItem.marginBottom; + } + } else { + return 0; + } + } +} +class SizeShrinker { + constructor(line) { + this._line = line; + this._amountRemaining = 0; + this._shrunkSize = 0; + } + shrink(amount) { + this._shrunkSize = 0; + this._amountRemaining = amount; + let totalShrinkAmount = this._getTotalShrinkAmount(); + if (totalShrinkAmount) { + const items = this._line.items; + do { + let amountPerShrink = this._amountRemaining / totalShrinkAmount; + for (let i = this._line.startIndex; i <= this._line.endIndex; i++) { + const item = items[i]; + const flexItem = item.flexItem; + const shrinkAmount = flexItem.shrink; + const isShrinkableItem = shrinkAmount > 0; + if (isShrinkableItem) { + let shrink = shrinkAmount * amountPerShrink; + const minSize = flexItem._getMainAxisMinSize(); + const size = flexItem._getMainAxisLayoutSize(); + if (size > minSize) { + const maxShrink = size - minSize; + const isFullyShrunk = shrink >= maxShrink; + if (isFullyShrunk) { + shrink = maxShrink; + totalShrinkAmount -= shrinkAmount; + } + const finalSize = size - shrink; + flexItem._resizeMainAxis(finalSize); + this._shrunkSize += shrink; + this._amountRemaining -= shrink; + if (Math.abs(this._amountRemaining) < 1e-5) { + return; + } + } + } + } + } while (totalShrinkAmount && Math.abs(this._amountRemaining) > 1e-5); + } + } + _getTotalShrinkAmount() { + let total = 0; + const items = this._line.items; + for (let i = this._line.startIndex; i <= this._line.endIndex; i++) { + const item = items[i]; + const flexItem = item.flexItem; + if (flexItem.shrink) { + const minSize = flexItem._getMainAxisMinSize(); + const size = flexItem._getMainAxisLayoutSize(); + if (size > minSize) { + total += flexItem.shrink; + } + } + } + return total; + } + getShrunkSize() { + return this._shrunkSize; + } +} +class SizeGrower { + constructor(line) { + this._line = line; + this._amountRemaining = 0; + this._grownSize = 0; + } + grow(amount) { + this._grownSize = 0; + this._amountRemaining = amount; + let totalGrowAmount = this._getTotalGrowAmount(); + if (totalGrowAmount) { + const items = this._line.items; + do { + let amountPerGrow = this._amountRemaining / totalGrowAmount; + for (let i = this._line.startIndex; i <= this._line.endIndex; i++) { + const item = items[i]; + const flexItem = item.flexItem; + const growAmount = flexItem.grow; + const isGrowableItem = growAmount > 0; + if (isGrowableItem) { + let grow = growAmount * amountPerGrow; + const maxSize = flexItem._getMainAxisMaxSizeSetting(); + const size = flexItem._getMainAxisLayoutSize(); + if (maxSize > 0) { + if (size >= maxSize) { + grow = 0; + } else { + const maxGrow = maxSize - size; + const isFullyGrown = grow >= maxGrow; + if (isFullyGrown) { + grow = maxGrow; + totalGrowAmount -= growAmount; + } + } + } + if (grow > 0) { + const finalSize = size + grow; + flexItem._resizeMainAxis(finalSize); + this._grownSize += grow; + this._amountRemaining -= grow; + if (Math.abs(this._amountRemaining) < 1e-5) { + return; + } + } + } + } + } while (totalGrowAmount && Math.abs(this._amountRemaining) > 1e-5); + } + } + _getTotalGrowAmount() { + let total = 0; + const items = this._line.items; + for (let i = this._line.startIndex; i <= this._line.endIndex; i++) { + const item = items[i]; + const flexItem = item.flexItem; + if (flexItem.grow) { + const maxSize = flexItem._getMainAxisMaxSizeSetting(); + const size = flexItem._getMainAxisLayoutSize(); + if (maxSize === 0 || size < maxSize) { + total += flexItem.grow; + } + } + } + return total; + } + getGrownSize() { + return this._grownSize; + } +} +class ItemPositioner { + constructor(lineLayout) { + this._line = lineLayout; + } + get _layout() { + return this._line._layout; + } + position() { + const { spacingBefore, spacingBetween } = this._getSpacing(); + let currentPos = spacingBefore; + const items = this._line.items; + for (let i = this._line.startIndex; i <= this._line.endIndex; i++) { + const item = items[i]; + item.flexItem._setMainAxisLayoutPos(currentPos); + currentPos += item.flexItem._getMainAxisLayoutSizeWithPaddingAndMargin(); + currentPos += spacingBetween; + } + } + _getSpacing() { + const remainingSpace = this._line._availableSpace; + let mode = this._layout._flexContainer.justifyContent; + const numberOfItems = this._line.numberOfItems; + return SpacingCalculator.getSpacing(mode, numberOfItems, remainingSpace); + } +} +class ItemAligner { + constructor(line) { + this._line = line; + this._crossAxisLayoutSize = 0; + this._crossAxisLayoutOffset = 0; + this._alignItemsSetting = null; + this._recursiveResizeOccured = false; + this._isCrossAxisFitToContents = false; + } + get _layout() { + return this._line._layout; + } + get _flexContainer() { + return this._layout._flexContainer; + } + setCrossAxisLayoutSize(size) { + this._crossAxisLayoutSize = size; + } + setCrossAxisLayoutOffset(offset) { + this._crossAxisLayoutOffset = offset; + } + align() { + this._alignItemsSetting = this._flexContainer.alignItems; + this._isCrossAxisFitToContents = this._layout.isAxisFitToContents(!this._flexContainer._horizontal); + this._recursiveResizeOccured = false; + const items = this._line.items; + for (let i = this._line.startIndex; i <= this._line.endIndex; i++) { + const item = items[i]; + this._alignItem(item); + } + } + get recursiveResizeOccured() { + return this._recursiveResizeOccured; + } + _alignItem(item) { + const flexItem = item.flexItem; + let align = flexItem.alignSelf || this._alignItemsSetting; + if (align === "stretch" && this._preventStretch(flexItem)) { + align = "flex-start"; + } + if (align !== "stretch" && !this._isCrossAxisFitToContents) { + if (flexItem._hasRelCrossAxisSize()) { + flexItem._resetCrossAxisLayoutSize(); + } + } + switch (align) { + case "flex-start": + this._alignItemFlexStart(flexItem); + break; + case "flex-end": + this._alignItemFlexEnd(flexItem); + break; + case "center": + this._alignItemFlexCenter(flexItem); + break; + case "stretch": + this._alignItemStretch(flexItem); + break; + } + } + _alignItemFlexStart(flexItem) { + flexItem._setCrossAxisLayoutPos(this._crossAxisLayoutOffset); + } + _alignItemFlexEnd(flexItem) { + const itemCrossAxisSize = flexItem._getCrossAxisLayoutSizeWithPaddingAndMargin(); + flexItem._setCrossAxisLayoutPos(this._crossAxisLayoutOffset + (this._crossAxisLayoutSize - itemCrossAxisSize)); + } + _alignItemFlexCenter(flexItem) { + const itemCrossAxisSize = flexItem._getCrossAxisLayoutSizeWithPaddingAndMargin(); + const center = (this._crossAxisLayoutSize - itemCrossAxisSize) / 2; + flexItem._setCrossAxisLayoutPos(this._crossAxisLayoutOffset + center); + } + _alignItemStretch(flexItem) { + flexItem._setCrossAxisLayoutPos(this._crossAxisLayoutOffset); + const mainAxisLayoutSizeBeforeResize = flexItem._getMainAxisLayoutSize(); + let size = this._crossAxisLayoutSize - flexItem._getCrossAxisMargin() - flexItem._getCrossAxisPadding(); + const crossAxisMinSizeSetting = flexItem._getCrossAxisMinSizeSetting(); + if (crossAxisMinSizeSetting > 0) { + size = Math.max(size, crossAxisMinSizeSetting); + } + const crossAxisMaxSizeSetting = flexItem._getCrossAxisMaxSizeSetting(); + const crossAxisMaxSizeSettingEnabled = crossAxisMaxSizeSetting > 0; + if (crossAxisMaxSizeSettingEnabled) { + size = Math.min(size, crossAxisMaxSizeSetting); + } + flexItem._resizeCrossAxis(size); + const mainAxisLayoutSizeAfterResize = flexItem._getMainAxisLayoutSize(); + const recursiveResize = mainAxisLayoutSizeAfterResize !== mainAxisLayoutSizeBeforeResize; + if (recursiveResize) { + this._recursiveResizeOccured = true; + } + } + _preventStretch(flexItem) { + const hasFixedCrossAxisSize = flexItem._hasFixedCrossAxisSize(); + const forceStretch = flexItem.alignSelf === "stretch"; + return hasFixedCrossAxisSize && !forceStretch; + } +} +class LineLayout { + constructor(layout, startIndex, endIndex, availableSpace) { + this._layout = layout; + this.items = layout.items; + this.startIndex = startIndex; + this.endIndex = endIndex; + this._availableSpace = availableSpace; + } + performLayout() { + this._setItemSizes(); + this.setItemPositions(); + this._calcLayoutInfo(); + } + _setItemSizes() { + if (this._availableSpace > 0) { + this._growItemSizes(this._availableSpace); + } else if (this._availableSpace < 0) { + this._shrinkItemSizes(-this._availableSpace); + } + } + _growItemSizes(amount) { + const grower = new SizeGrower(this); + grower.grow(amount); + this._availableSpace -= grower.getGrownSize(); + } + _shrinkItemSizes(amount) { + const shrinker = new SizeShrinker(this); + shrinker.shrink(amount); + this._availableSpace += shrinker.getShrunkSize(); + } + setItemPositions() { + const positioner = new ItemPositioner(this); + positioner.position(); + } + createItemAligner() { + return new ItemAligner(this); + } + _calcLayoutInfo() { + this._calcCrossAxisMaxLayoutSize(); + } + getMainAxisMinSize() { + let mainAxisMinSize = 0; + for (let i = this.startIndex; i <= this.endIndex; i++) { + const item = this.items[i]; + mainAxisMinSize += item.flexItem._getMainAxisMinSizeWithPaddingAndMargin(); + } + return mainAxisMinSize; + } + get numberOfItems() { + return this.endIndex - this.startIndex + 1; + } + get crossAxisLayoutSize() { + const noSpecifiedCrossAxisSize = this._layout.isCrossAxisFitToContents() && !this._layout.resizingCrossAxis; + const shouldFitToContents = this._layout.isWrapping() || noSpecifiedCrossAxisSize; + if (shouldFitToContents) { + return this._crossAxisMaxLayoutSize; + } else { + return this._layout.crossAxisSize; + } + } + _calcCrossAxisMaxLayoutSize() { + this._crossAxisMaxLayoutSize = this._getCrossAxisMaxLayoutSize(); + } + _getCrossAxisMaxLayoutSize() { + let crossAxisMaxSize = 0; + for (let i = this.startIndex; i <= this.endIndex; i++) { + const item = this.items[i]; + crossAxisMaxSize = Math.max(crossAxisMaxSize, item.flexItem._getCrossAxisLayoutSizeWithPaddingAndMargin()); + } + return crossAxisMaxSize; + } +} +class LineLayouter { + constructor(layout) { + this._layout = layout; + this._mainAxisMinSize = -1; + this._crossAxisMinSize = -1; + this._mainAxisContentSize = 0; + } + get lines() { + return this._lines; + } + get mainAxisMinSize() { + if (this._mainAxisMinSize === -1) { + this._mainAxisMinSize = this._getMainAxisMinSize(); + } + return this._mainAxisMinSize; + } + get crossAxisMinSize() { + if (this._crossAxisMinSize === -1) { + this._crossAxisMinSize = this._getCrossAxisMinSize(); + } + return this._crossAxisMinSize; + } + get mainAxisContentSize() { + return this._mainAxisContentSize; + } + layoutLines() { + this._setup(); + const items = this._layout.items; + const wrap = this._layout.isWrapping(); + let startIndex = 0; + let i; + const n = items.length; + for (i = 0; i < n; i++) { + const item = items[i]; + this._layoutFlexItem(item); + const itemMainAxisSize = item.flexItem._getMainAxisLayoutSizeWithPaddingAndMargin(); + if (wrap && i > startIndex) { + const isOverflowing = this._curMainAxisPos + itemMainAxisSize > this._mainAxisSize; + if (isOverflowing) { + this._layoutLine(startIndex, i - 1); + this._curMainAxisPos = 0; + startIndex = i; + } + } + this._addToMainAxisPos(itemMainAxisSize); + } + if (startIndex < i) { + this._layoutLine(startIndex, i - 1); + } + } + _layoutFlexItem(item) { + if (item.isFlexEnabled()) { + item.flexLayout.updateTreeLayout(); + } else { + item.flexItem._resetLayoutSize(); + } + } + _setup() { + this._mainAxisSize = this._layout.mainAxisSize; + this._curMainAxisPos = 0; + this._maxMainAxisPos = 0; + this._lines = []; + this._mainAxisMinSize = -1; + this._crossAxisMinSize = -1; + this._mainAxisContentSize = 0; + } + _addToMainAxisPos(itemMainAxisSize) { + this._curMainAxisPos += itemMainAxisSize; + if (this._curMainAxisPos > this._maxMainAxisPos) { + this._maxMainAxisPos = this._curMainAxisPos; + } + } + _layoutLine(startIndex, endIndex) { + const availableSpace = this._getAvailableMainAxisLayoutSpace(); + const line = new LineLayout(this._layout, startIndex, endIndex, availableSpace); + line.performLayout(); + this._lines.push(line); + if (this._mainAxisContentSize === 0 || this._curMainAxisPos > this._mainAxisContentSize) { + this._mainAxisContentSize = this._curMainAxisPos; + } + } + _getAvailableMainAxisLayoutSpace() { + if (!this._layout.resizingMainAxis && this._layout.isMainAxisFitToContents()) { + return 0; + } else { + return this._mainAxisSize - this._curMainAxisPos; + } + } + _getCrossAxisMinSize() { + let crossAxisMinSize = 0; + const items = this._layout.items; + for (let i = 0, n = items.length; i < n; i++) { + const item = items[i]; + const itemCrossAxisMinSize = item.flexItem._getCrossAxisMinSizeWithPaddingAndMargin(); + crossAxisMinSize = Math.max(crossAxisMinSize, itemCrossAxisMinSize); + } + return crossAxisMinSize; + } + _getMainAxisMinSize() { + if (this._lines.length === 1) { + return this._lines[0].getMainAxisMinSize(); + } else { + return this._layout.mainAxisSize; + } + } +} +class ItemCoordinatesUpdater { + constructor(layout) { + this._layout = layout; + this._isReverse = this._flexContainer._reverse; + this._horizontalPaddingOffset = this._layout._getHorizontalPaddingOffset(); + this._verticalPaddingOffset = this._layout._getVerticalPaddingOffset(); + } + get _flexContainer() { + return this._layout._flexContainer; + } + finalize() { + const parentFlex = this._layout.getParentFlexContainer(); + if (parentFlex) { + const updater = new ItemCoordinatesUpdater(parentFlex._layout); + updater._finalizeItemAndChildren(this._flexContainer.item); + } else { + this._finalizeRoot(); + this._finalizeItems(); + } + } + _finalizeRoot() { + const item = this._flexContainer.item; + let x = FlexUtils.getAxisLayoutPos(item, true); + let y = FlexUtils.getAxisLayoutPos(item, false); + let w = FlexUtils.getAxisLayoutSize(item, true); + let h = FlexUtils.getAxisLayoutSize(item, false); + w += this._layout._getHorizontalPadding(); + h += this._layout._getVerticalPadding(); + item.clearRecalcFlag(); + item.setLayout(x, y, w, h); + } + _finalizeItems() { + const items = this._layout.items; + for (let i = 0, n = items.length; i < n; i++) { + const item = items[i]; + const validCache = this._validateItemCache(item); + this._finalizeItem(item); + if (!validCache) { + this._finalizeItemChildren(item); + } + } + } + _validateItemCache(item) { + if (item.recalc === 0) { + if (item.isFlexEnabled()) { + const layout = item._flex._layout; + const dimensionsMatchPreviousResult = item.w === item.target.w && item.h === item.target.h; + if (dimensionsMatchPreviousResult) { + return true; + } else { + const crossAxisSize = layout.crossAxisSize; + layout.performResizeMainAxis(layout.mainAxisSize); + layout.performResizeCrossAxis(crossAxisSize); + } + } + } + return false; + } + _finalizeItemAndChildren(item) { + this._finalizeItem(item); + this._finalizeItemChildren(item); + } + _finalizeItem(item) { + if (this._isReverse) { + this._reverseMainAxisLayoutPos(item); + } + let x = FlexUtils.getAxisLayoutPos(item, true); + let y = FlexUtils.getAxisLayoutPos(item, false); + let w = FlexUtils.getAxisLayoutSize(item, true); + let h = FlexUtils.getAxisLayoutSize(item, false); + x += this._horizontalPaddingOffset; + y += this._verticalPaddingOffset; + const flex = item.flex; + if (flex) { + w += item._flex._layout._getHorizontalPadding(); + h += item._flex._layout._getVerticalPadding(); + } + const flexItem = item.flexItem; + if (flexItem) { + x += flexItem._getHorizontalMarginOffset(); + y += flexItem._getVerticalMarginOffset(); + } + item.clearRecalcFlag(); + item.setLayout(x, y, w, h); + } + _finalizeItemChildren(item) { + const flex = item._flex; + if (flex) { + const updater = new ItemCoordinatesUpdater(flex._layout); + updater._finalizeItems(); + } + } + _reverseMainAxisLayoutPos(item) { + const endPos = item.flexItem._getMainAxisLayoutPos() + item.flexItem._getMainAxisLayoutSizeWithPaddingAndMargin(); + const reversedPos = this._layout.mainAxisSize - endPos; + item.flexItem._setMainAxisLayoutPos(reversedPos); + } +} +class FlexLayout { + constructor(flexContainer) { + this._flexContainer = flexContainer; + this._lineLayouter = new LineLayouter(this); + this._resizingMainAxis = false; + this._resizingCrossAxis = false; + this._cachedMainAxisSizeAfterLayout = 0; + this._cachedCrossAxisSizeAfterLayout = 0; + this._shrunk = false; + } + get shrunk() { + return this._shrunk; + } + get recalc() { + return this.item.recalc; + } + layoutTree() { + const isSubTree = this.item.flexParent !== null; + if (isSubTree) { + this._updateSubTreeLayout(); + } else { + this.updateTreeLayout(); + } + this.updateItemCoords(); + } + updateTreeLayout() { + if (this.recalc) { + this._performUpdateLayoutTree(); + } else { + this._performUpdateLayoutTreeFromCache(); + } + } + _performUpdateLayoutTree() { + this._setInitialAxisSizes(); + this._layoutAxes(); + this._refreshLayoutCache(); + } + _refreshLayoutCache() { + this._cachedMainAxisSizeAfterLayout = this.mainAxisSize; + this._cachedCrossAxisSizeAfterLayout = this.crossAxisSize; + } + _performUpdateLayoutTreeFromCache() { + const sizeMightHaveChanged = this.item.funcW || this.item.funcH; + if (sizeMightHaveChanged) { + this.item.enableLocalRecalcFlag(); + this._performUpdateLayoutTree(); + } else { + this.mainAxisSize = this._cachedMainAxisSizeAfterLayout; + this.crossAxisSize = this._cachedCrossAxisSizeAfterLayout; + } + } + updateItemCoords() { + const updater = new ItemCoordinatesUpdater(this); + updater.finalize(); + } + _updateSubTreeLayout() { + const crossAxisSize = this.crossAxisSize; + this._layoutMainAxis(); + this.performResizeCrossAxis(crossAxisSize); + } + _setInitialAxisSizes() { + if (this.item.isFlexItemEnabled()) { + this.item.flexItem._resetLayoutSize(); + } else { + this.mainAxisSize = this._getMainAxisBasis(); + this.crossAxisSize = this._getCrossAxisBasis(); + } + this._resizingMainAxis = false; + this._resizingCrossAxis = false; + this._shrunk = false; + } + _layoutAxes() { + this._layoutMainAxis(); + this._layoutCrossAxis(); + } + _layoutMainAxis() { + this._layoutLines(); + this._fitMainAxisSizeToContents(); + } + _layoutLines() { + this._lineLayouter.layoutLines(); + } + get _lines() { + return this._lineLayouter.lines; + } + _fitMainAxisSizeToContents() { + if (!this._resizingMainAxis) { + if (this.isMainAxisFitToContents()) { + this.mainAxisSize = this._lineLayouter.mainAxisContentSize; + } + } + } + _layoutCrossAxis() { + const aligner = new ContentAligner(this); + aligner.init(); + this._totalCrossAxisSize = aligner.totalCrossAxisSize; + this._fitCrossAxisSizeToContents(); + aligner.align(); + } + _fitCrossAxisSizeToContents() { + if (!this._resizingCrossAxis) { + if (this.isCrossAxisFitToContents()) { + this.crossAxisSize = this._totalCrossAxisSize; + } + } + } + isWrapping() { + return this._flexContainer.wrap; + } + isAxisFitToContents(horizontal) { + if (this._horizontal === horizontal) { + return this.isMainAxisFitToContents(); + } else { + return this.isCrossAxisFitToContents(); + } + } + isMainAxisFitToContents() { + return !this.isWrapping() && !this._hasFixedMainAxisBasis(); + } + isCrossAxisFitToContents() { + return !this._hasFixedCrossAxisBasis(); + } + _hasFixedMainAxisBasis() { + return !FlexUtils.isZeroAxisSize(this.item, this._horizontal); + } + _hasFixedCrossAxisBasis() { + return !FlexUtils.isZeroAxisSize(this.item, !this._horizontal); + } + getAxisMinSize(horizontal) { + if (this._horizontal === horizontal) { + return this._getMainAxisMinSize(); + } else { + return this._getCrossAxisMinSize(); + } + } + _getMainAxisMinSize() { + return this._lineLayouter.mainAxisMinSize; + } + _getCrossAxisMinSize() { + return this._lineLayouter.crossAxisMinSize; + } + resizeMainAxis(size) { + if (this.mainAxisSize !== size) { + if (this.recalc > 0) { + this.performResizeMainAxis(size); + } else { + if (this._checkValidCacheMainAxisResize()) { + this.mainAxisSize = size; + this._fitCrossAxisSizeToContents(); + } else { + this.item.enableLocalRecalcFlag(); + this.performResizeMainAxis(size); + } + } + } + } + _checkValidCacheMainAxisResize(size) { + const isFinalMainAxisSize = size === this.targetMainAxisSize; + if (isFinalMainAxisSize) { + return true; + } + const canIgnoreCacheMiss = !this.isCrossAxisFitToContents(); + if (canIgnoreCacheMiss) { + return true; + } + return false; + } + performResizeMainAxis(size) { + const isShrinking = size < this.mainAxisSize; + this._shrunk = isShrinking; + this.mainAxisSize = size; + this._resizingMainAxis = true; + this._layoutAxes(); + this._resizingMainAxis = false; + } + resizeCrossAxis(size) { + if (this.crossAxisSize !== size) { + if (this.recalc > 0) { + this.performResizeCrossAxis(size); + } else { + this.crossAxisSize = size; + } + } + } + performResizeCrossAxis(size) { + this.crossAxisSize = size; + this._resizingCrossAxis = true; + this._layoutCrossAxis(); + this._resizingCrossAxis = false; + } + get targetMainAxisSize() { + return this._horizontal ? this.item.target.w : this.item.target.h; + } + get targetCrossAxisSize() { + return this._horizontal ? this.item.target.h : this.item.target.w; + } + getParentFlexContainer() { + return this.item.isFlexItemEnabled() ? this.item.flexItem.ctr : null; + } + _getHorizontalPadding() { + return FlexUtils.getTotalPadding(this.item, true); + } + _getVerticalPadding() { + return FlexUtils.getTotalPadding(this.item, false); + } + _getHorizontalPaddingOffset() { + return FlexUtils.getPaddingOffset(this.item, true); + } + _getVerticalPaddingOffset() { + return FlexUtils.getPaddingOffset(this.item, false); + } + _getMainAxisBasis() { + return FlexUtils.getRelAxisSize(this.item, this._horizontal); + } + _getCrossAxisBasis() { + return FlexUtils.getRelAxisSize(this.item, !this._horizontal); + } + get _horizontal() { + return this._flexContainer._horizontal; + } + get _reverse() { + return this._flexContainer._reverse; + } + get item() { + return this._flexContainer.item; + } + get items() { + return this.item.items; + } + get resizingMainAxis() { + return this._resizingMainAxis; + } + get resizingCrossAxis() { + return this._resizingCrossAxis; + } + get numberOfItems() { + return this.items.length; + } + get mainAxisSize() { + return FlexUtils.getAxisLayoutSize(this.item, this._horizontal); + } + get crossAxisSize() { + return FlexUtils.getAxisLayoutSize(this.item, !this._horizontal); + } + set mainAxisSize(v) { + FlexUtils.setAxisLayoutSize(this.item, this._horizontal, v); + } + set crossAxisSize(v) { + FlexUtils.setAxisLayoutSize(this.item, !this._horizontal, v); + } +} +class FlexContainer { + constructor(item) { + this._item = item; + this._layout = new FlexLayout(this); + this._horizontal = true; + this._reverse = false; + this._wrap = false; + this._alignItems = "stretch"; + this._justifyContent = "flex-start"; + this._alignContent = "flex-start"; + this._paddingLeft = 0; + this._paddingTop = 0; + this._paddingRight = 0; + this._paddingBottom = 0; + } + get item() { + return this._item; + } + _changedDimensions() { + this._item.changedDimensions(); + } + _changedContents() { + this._item.changedContents(); + } + get direction() { + return (this._horizontal ? "row" : "column") + (this._reverse ? "-reverse" : ""); + } + set direction(f) { + if (this.direction === f) + return; + this._horizontal = f === "row" || f === "row-reverse"; + this._reverse = f === "row-reverse" || f === "column-reverse"; + this._changedContents(); + } + set wrap(v) { + this._wrap = v; + this._changedContents(); + } + get wrap() { + return this._wrap; + } + get alignItems() { + return this._alignItems; + } + set alignItems(v) { + if (this._alignItems === v) + return; + if (FlexContainer.ALIGN_ITEMS.indexOf(v) === -1) { + throw new Error("Unknown alignItems, options: " + FlexContainer.ALIGN_ITEMS.join(",")); + } + this._alignItems = v; + this._changedContents(); + } + get alignContent() { + return this._alignContent; + } + set alignContent(v) { + if (this._alignContent === v) + return; + if (FlexContainer.ALIGN_CONTENT.indexOf(v) === -1) { + throw new Error("Unknown alignContent, options: " + FlexContainer.ALIGN_CONTENT.join(",")); + } + this._alignContent = v; + this._changedContents(); + } + get justifyContent() { + return this._justifyContent; + } + set justifyContent(v) { + if (this._justifyContent === v) + return; + if (FlexContainer.JUSTIFY_CONTENT.indexOf(v) === -1) { + throw new Error("Unknown justifyContent, options: " + FlexContainer.JUSTIFY_CONTENT.join(",")); + } + this._justifyContent = v; + this._changedContents(); + } + set padding(v) { + this.paddingLeft = v; + this.paddingTop = v; + this.paddingRight = v; + this.paddingBottom = v; + } + get padding() { + return this.paddingLeft; + } + set paddingLeft(v) { + this._paddingLeft = v; + this._changedDimensions(); + } + get paddingLeft() { + return this._paddingLeft; + } + set paddingTop(v) { + this._paddingTop = v; + this._changedDimensions(); + } + get paddingTop() { + return this._paddingTop; + } + set paddingRight(v) { + this._paddingRight = v; + this._changedDimensions(); + } + get paddingRight() { + return this._paddingRight; + } + set paddingBottom(v) { + this._paddingBottom = v; + this._changedDimensions(); + } + get paddingBottom() { + return this._paddingBottom; + } + patch(settings) { + Base.patchObject(this, settings); + } +} +FlexContainer.ALIGN_ITEMS = ["flex-start", "flex-end", "center", "stretch"]; +FlexContainer.ALIGN_CONTENT = ["flex-start", "flex-end", "center", "space-between", "space-around", "space-evenly", "stretch"]; +FlexContainer.JUSTIFY_CONTENT = ["flex-start", "flex-end", "center", "space-between", "space-around", "space-evenly"]; +class FlexItem { + constructor(item) { + this._ctr = null; + this._item = item; + this._grow = 0; + this._shrink = FlexItem.SHRINK_AUTO; + this._alignSelf = void 0; + this._minWidth = 0; + this._minHeight = 0; + this._maxWidth = 0; + this._maxHeight = 0; + this._marginLeft = 0; + this._marginTop = 0; + this._marginRight = 0; + this._marginBottom = 0; + } + get item() { + return this._item; + } + get grow() { + return this._grow; + } + set grow(v) { + if (this._grow === v) + return; + this._grow = parseInt(v) || 0; + this._changed(); + } + get shrink() { + if (this._shrink === FlexItem.SHRINK_AUTO) { + return this._getDefaultShrink(); + } + return this._shrink; + } + _getDefaultShrink() { + if (this.item.isFlexEnabled()) { + return 1; + } else { + return 0; + } + } + set shrink(v) { + if (this._shrink === v) + return; + this._shrink = parseInt(v) || 0; + this._changed(); + } + get alignSelf() { + return this._alignSelf; + } + set alignSelf(v) { + if (this._alignSelf === v) + return; + if (v === void 0) { + this._alignSelf = void 0; + } else { + if (FlexContainer.ALIGN_ITEMS.indexOf(v) === -1) { + throw new Error("Unknown alignSelf, options: " + FlexContainer.ALIGN_ITEMS.join(",")); + } + this._alignSelf = v; + } + this._changed(); + } + get minWidth() { + return this._minWidth; + } + set minWidth(v) { + this._minWidth = Math.max(0, v); + this._item.changedDimensions(true, false); + } + get minHeight() { + return this._minHeight; + } + set minHeight(v) { + this._minHeight = Math.max(0, v); + this._item.changedDimensions(false, true); + } + get maxWidth() { + return this._maxWidth; + } + set maxWidth(v) { + this._maxWidth = Math.max(0, v); + this._item.changedDimensions(true, false); + } + get maxHeight() { + return this._maxHeight; + } + set maxHeight(v) { + this._maxHeight = Math.max(0, v); + this._item.changedDimensions(false, true); + } + set margin(v) { + this.marginLeft = v; + this.marginTop = v; + this.marginRight = v; + this.marginBottom = v; + } + get margin() { + return this.marginLeft; + } + set marginLeft(v) { + this._marginLeft = v; + this._changed(); + } + get marginLeft() { + return this._marginLeft; + } + set marginTop(v) { + this._marginTop = v; + this._changed(); + } + get marginTop() { + return this._marginTop; + } + set marginRight(v) { + this._marginRight = v; + this._changed(); + } + get marginRight() { + return this._marginRight; + } + set marginBottom(v) { + this._marginBottom = v; + this._changed(); + } + get marginBottom() { + return this._marginBottom; + } + _changed() { + if (this.ctr) + this.ctr._changedContents(); + } + set ctr(v) { + this._ctr = v; + } + get ctr() { + return this._ctr; + } + patch(settings) { + Base.patchObject(this, settings); + } + _resetLayoutSize() { + this._resetHorizontalAxisLayoutSize(); + this._resetVerticalAxisLayoutSize(); + } + _resetCrossAxisLayoutSize() { + if (this.ctr._horizontal) { + this._resetVerticalAxisLayoutSize(); + } else { + this._resetHorizontalAxisLayoutSize(); + } + } + _resetHorizontalAxisLayoutSize() { + let w = FlexUtils.getRelAxisSize(this.item, true); + if (this._minWidth) { + w = Math.max(this._minWidth, w); + } + if (this._maxWidth) { + w = Math.min(this._maxWidth, w); + } + FlexUtils.setAxisLayoutSize(this.item, true, w); + } + _resetVerticalAxisLayoutSize() { + let h = FlexUtils.getRelAxisSize(this.item, false); + if (this._minHeight) { + h = Math.max(this._minHeight, h); + } + if (this._maxHeight) { + h = Math.min(this._maxHeight, h); + } + FlexUtils.setAxisLayoutSize(this.item, false, h); + } + _getCrossAxisMinSizeSetting() { + return this._getMinSizeSetting(!this.ctr._horizontal); + } + _getCrossAxisMaxSizeSetting() { + return this._getMaxSizeSetting(!this.ctr._horizontal); + } + _getMainAxisMaxSizeSetting() { + return this._getMaxSizeSetting(this.ctr._horizontal); + } + _getMinSizeSetting(horizontal) { + if (horizontal) { + return this._minWidth; + } else { + return this._minHeight; + } + } + _getMaxSizeSetting(horizontal) { + if (horizontal) { + return this._maxWidth; + } else { + return this._maxHeight; + } + } + _getMainAxisMinSize() { + return FlexUtils.getAxisMinSize(this.item, this.ctr._horizontal); + } + _getCrossAxisMinSize() { + return FlexUtils.getAxisMinSize(this.item, !this.ctr._horizontal); + } + _getMainAxisLayoutSize() { + return FlexUtils.getAxisLayoutSize(this.item, this.ctr._horizontal); + } + _getMainAxisLayoutPos() { + return FlexUtils.getAxisLayoutPos(this.item, this.ctr._horizontal); + } + _setMainAxisLayoutPos(pos) { + return FlexUtils.setAxisLayoutPos(this.item, this.ctr._horizontal, pos); + } + _setCrossAxisLayoutPos(pos) { + return FlexUtils.setAxisLayoutPos(this.item, !this.ctr._horizontal, pos); + } + _getCrossAxisLayoutSize() { + return FlexUtils.getAxisLayoutSize(this.item, !this.ctr._horizontal); + } + _resizeCrossAxis(size) { + return FlexUtils.resizeAxis(this.item, !this.ctr._horizontal, size); + } + _resizeMainAxis(size) { + return FlexUtils.resizeAxis(this.item, this.ctr._horizontal, size); + } + _getMainAxisPadding() { + return FlexUtils.getTotalPadding(this.item, this.ctr._horizontal); + } + _getCrossAxisPadding() { + return FlexUtils.getTotalPadding(this.item, !this.ctr._horizontal); + } + _getMainAxisMargin() { + return FlexUtils.getTotalMargin(this.item, this.ctr._horizontal); + } + _getCrossAxisMargin() { + return FlexUtils.getTotalMargin(this.item, !this.ctr._horizontal); + } + _getHorizontalMarginOffset() { + return FlexUtils.getMarginOffset(this.item, true); + } + _getVerticalMarginOffset() { + return FlexUtils.getMarginOffset(this.item, false); + } + _getMainAxisMinSizeWithPaddingAndMargin() { + return this._getMainAxisMinSize() + this._getMainAxisPadding() + this._getMainAxisMargin(); + } + _getCrossAxisMinSizeWithPaddingAndMargin() { + return this._getCrossAxisMinSize() + this._getCrossAxisPadding() + this._getCrossAxisMargin(); + } + _getMainAxisLayoutSizeWithPaddingAndMargin() { + return this._getMainAxisLayoutSize() + this._getMainAxisPadding() + this._getMainAxisMargin(); + } + _getCrossAxisLayoutSizeWithPaddingAndMargin() { + return this._getCrossAxisLayoutSize() + this._getCrossAxisPadding() + this._getCrossAxisMargin(); + } + _hasFixedCrossAxisSize() { + return !FlexUtils.isZeroAxisSize(this.item, !this.ctr._horizontal); + } + _hasRelCrossAxisSize() { + return !!(this.ctr._horizontal ? this.item.funcH : this.item.funcW); + } +} +FlexItem.SHRINK_AUTO = -1; +class FlexTarget { + constructor(target) { + this._target = target; + this._recalc = 0; + this._enabled = false; + this.x = 0; + this.y = 0; + this.w = 0; + this.h = 0; + this._originalX = 0; + this._originalY = 0; + this._originalWidth = 0; + this._originalHeight = 0; + this._flex = null; + this._flexItem = null; + this._flexItemDisabled = false; + this._items = null; + } + get flexLayout() { + return this.flex ? this.flex._layout : null; + } + layoutFlexTree() { + if (this.isFlexEnabled() && this.isChanged()) { + this.flexLayout.layoutTree(); + } + } + get target() { + return this._target; + } + get flex() { + return this._flex; + } + set flex(v) { + if (!v) { + if (this.isFlexEnabled()) { + this._disableFlex(); + } + } else { + if (!this.isFlexEnabled()) { + this._enableFlex(); + } + this._flex.patch(v); + } + } + get flexItem() { + if (this._flexItemDisabled) { + return false; + } + this._ensureFlexItem(); + return this._flexItem; + } + set flexItem(v) { + if (v === false) { + if (!this._flexItemDisabled) { + const parent = this.flexParent; + this._flexItemDisabled = true; + this._checkEnabled(); + if (parent) { + parent._clearFlexItemsCache(); + parent.changedContents(); + } + } + } else { + this._ensureFlexItem(); + this._flexItem.patch(v); + if (this._flexItemDisabled) { + this._flexItemDisabled = false; + this._checkEnabled(); + const parent = this.flexParent; + if (parent) { + parent._clearFlexItemsCache(); + parent.changedContents(); + } + } + } + } + _enableFlex() { + this._flex = new FlexContainer(this); + this._checkEnabled(); + this.changedDimensions(); + this._enableChildrenAsFlexItems(); + } + _disableFlex() { + this.changedDimensions(); + this._flex = null; + this._checkEnabled(); + this._disableChildrenAsFlexItems(); + } + _enableChildrenAsFlexItems() { + const children = this._target._children; + if (children) { + for (let i = 0, n = children.length; i < n; i++) { + const child = children[i]; + child.layout._enableFlexItem(); + } + } + } + _disableChildrenAsFlexItems() { + const children = this._target._children; + if (children) { + for (let i = 0, n = children.length; i < n; i++) { + const child = children[i]; + child.layout._disableFlexItem(); + } + } + } + _enableFlexItem() { + this._ensureFlexItem(); + const flexParent = this._target._parent._layout; + this._flexItem.ctr = flexParent._flex; + flexParent.changedContents(); + this._checkEnabled(); + } + _disableFlexItem() { + if (this._flexItem) { + this._flexItem.ctr = null; + } + this._checkEnabled(); + this._resetOffsets(); + } + _resetOffsets() { + this.x = 0; + this.y = 0; + } + _ensureFlexItem() { + if (!this._flexItem) { + this._flexItem = new FlexItem(this); + } + } + _checkEnabled() { + const enabled = this.isEnabled(); + if (this._enabled !== enabled) { + if (enabled) { + this._enable(); + } else { + this._disable(); + } + this._enabled = enabled; + } + } + _enable() { + this._setupTargetForFlex(); + this._target.enableFlexLayout(); + } + _disable() { + this._restoreTargetToNonFlex(); + this._target.disableFlexLayout(); + } + isEnabled() { + return this.isFlexEnabled() || this.isFlexItemEnabled(); + } + isFlexEnabled() { + return this._flex !== null; + } + isFlexItemEnabled() { + return this.flexParent !== null; + } + _restoreTargetToNonFlex() { + const target = this._target; + target.x = this._originalX; + target.y = this._originalY; + target.setDimensions(this._originalWidth, this._originalHeight); + } + _setupTargetForFlex() { + const target = this._target; + this._originalX = target._x; + this._originalY = target._y; + this._originalWidth = target._w; + this._originalHeight = target._h; + } + setParent(from, to) { + if (from && from.isFlexContainer()) { + from._layout._changedChildren(); + } + if (to && to.isFlexContainer()) { + this._enableFlexItem(); + to._layout._changedChildren(); + } + this._checkEnabled(); + } + get flexParent() { + if (this._flexItemDisabled) { + return null; + } + const parent = this._target._parent; + if (parent && parent.isFlexContainer()) { + return parent._layout; + } + return null; + } + setVisible(v) { + const parent = this.flexParent; + if (parent) { + parent._changedChildren(); + } + } + get items() { + if (!this._items) { + this._items = this._getFlexItems(); + } + return this._items; + } + _getFlexItems() { + const items = []; + const children = this._target._children; + if (children) { + for (let i = 0, n = children.length; i < n; i++) { + const item = children[i]; + if (item.visible) { + if (item.isFlexItem()) { + items.push(item.layout); + } + } + } + } + return items; + } + _changedChildren() { + this._clearFlexItemsCache(); + this.changedContents(); + } + _clearFlexItemsCache() { + this._items = null; + } + setLayout(x, y, w, h) { + let originalX = this._originalX; + let originalY = this._originalY; + if (this.funcX) { + originalX = this.funcX(FlexUtils.getParentAxisSizeWithPadding(this, true)); + } + if (this.funcY) { + originalY = this.funcY(FlexUtils.getParentAxisSizeWithPadding(this, false)); + } + if (this.isFlexItemEnabled()) { + this.target.setLayout(x + originalX, y + originalY, w, h); + } else { + this.target.setLayout(originalX, originalY, w, h); + } + } + changedDimensions(changeWidth = true, changeHeight = true) { + this._updateRecalc(changeWidth, changeHeight); + } + changedContents() { + this._updateRecalc(); + } + forceLayout() { + this._updateRecalc(); + } + isChanged() { + return this._recalc > 0; + } + _updateRecalc(changeExternalWidth = false, changeExternalHeight = false) { + if (this.isFlexEnabled()) { + const layout = this._flex._layout; + changeExternalWidth = changeExternalWidth || layout.isAxisFitToContents(true); + changeExternalHeight = changeExternalHeight || layout.isAxisFitToContents(false); + } + const recalc = 1 + (changeExternalWidth ? 2 : 0) + (changeExternalHeight ? 4 : 0); + const newRecalcFlags = this.getNewRecalcFlags(recalc); + this._recalc |= recalc; + if (newRecalcFlags > 1) { + if (this.flexParent) { + this.flexParent._updateRecalcBottomUp(recalc); + } else { + this._target.triggerLayout(); + } + } else { + this._target.triggerLayout(); + } + } + getNewRecalcFlags(flags) { + return 7 - this._recalc & flags; + } + _updateRecalcBottomUp(childRecalc) { + const newRecalc = this._getRecalcFromChangedChildRecalc(childRecalc); + const newRecalcFlags = this.getNewRecalcFlags(newRecalc); + this._recalc |= newRecalc; + if (newRecalcFlags > 1) { + const flexParent = this.flexParent; + if (flexParent) { + flexParent._updateRecalcBottomUp(newRecalc); + } else { + this._target.triggerLayout(); + } + } else { + this._target.triggerLayout(); + } + } + _getRecalcFromChangedChildRecalc(childRecalc) { + const layout = this._flex._layout; + const mainAxisRecalcFlag = layout._horizontal ? 1 : 2; + const crossAxisRecalcFlag = layout._horizontal ? 2 : 1; + const crossAxisDimensionsChangedInChild = childRecalc & crossAxisRecalcFlag; + if (!crossAxisDimensionsChangedInChild) { + const mainAxisDimensionsChangedInChild = childRecalc & mainAxisRecalcFlag; + if (mainAxisDimensionsChangedInChild) { + const mainAxisIsWrapping = layout.isWrapping(); + if (mainAxisIsWrapping) { + const crossAxisIsFitToContents = layout.isCrossAxisFitToContents(); + if (crossAxisIsFitToContents) { + childRecalc += crossAxisRecalcFlag; + } + } + } + } + let isWidthDynamic = layout.isAxisFitToContents(true); + let isHeightDynamic = layout.isAxisFitToContents(false); + if (layout.shrunk) { + if (layout._horizontal) { + isWidthDynamic = true; + } else { + isHeightDynamic = true; + } + } + const localRecalc = 1 + (isWidthDynamic ? 2 : 0) + (isHeightDynamic ? 4 : 0); + const combinedRecalc = childRecalc & localRecalc; + return combinedRecalc; + } + get recalc() { + return this._recalc; + } + clearRecalcFlag() { + this._recalc = 0; + } + enableLocalRecalcFlag() { + this._recalc = 1; + } + get originalX() { + return this._originalX; + } + setOriginalXWithoutUpdatingLayout(v) { + this._originalX = v; + } + get originalY() { + return this._originalY; + } + setOriginalYWithoutUpdatingLayout(v) { + this._originalY = v; + } + get originalWidth() { + return this._originalWidth; + } + set originalWidth(v) { + if (this._originalWidth !== v) { + this._originalWidth = v; + this.changedDimensions(true, false); + } + } + get originalHeight() { + return this._originalHeight; + } + set originalHeight(v) { + if (this._originalHeight !== v) { + this._originalHeight = v; + this.changedDimensions(false, true); + } + } + get funcX() { + return this._target.funcX; + } + get funcY() { + return this._target.funcY; + } + get funcW() { + return this._target.funcW; + } + get funcH() { + return this._target.funcH; + } +} +class TextureSource { + constructor(manager, loader = null) { + this.id = TextureSource.id++; + this.manager = manager; + this.stage = manager.stage; + this.textures = /* @__PURE__ */ new Set(); + this._activeTextureCount = 0; + this.loader = loader; + this.lookupId = null; + this._cancelCb = null; + this.loadingSince = 0; + this.w = 0; + this.h = 0; + this._nativeTexture = null; + this.permanent = false; + this.renderInfo = null; + this._isResultTexture = !this.loader; + this._loadError = null; + this._imageRef = null; + this._hasAlpha = false; + } + get hasAlpha() { + return this._hasAlpha; + } + get loadError() { + return this._loadError; + } + addTexture(v) { + if (!this.textures.has(v)) { + this.textures.add(v); + } + } + removeTexture(v) { + this.textures.delete(v); + } + incActiveTextureCount() { + this._activeTextureCount++; + if (this._activeTextureCount === 1) { + this.becomesUsed(); + } + } + decActiveTextureCount() { + this._activeTextureCount--; + if (this._activeTextureCount === 0) { + this.becomesUnused(); + } + } + get isResultTexture() { + return this._isResultTexture; + } + set isResultTexture(v) { + this._isResultTexture = v; + } + forEachEnabledElement(cb) { + this.textures.forEach((texture) => { + texture.elements.forEach(cb); + }); + } + hasEnabledElements() { + return this.textures.size > 0; + } + forEachActiveElement(cb) { + this.textures.forEach((texture) => { + texture.elements.forEach((element) => { + if (element.active) { + cb(element); + } + }); + }); + } + getRenderWidth() { + return this.w; + } + getRenderHeight() { + return this.h; + } + allowCleanup() { + return !this.permanent && !this.isUsed(); + } + becomesUsed() { + this.load(); + } + becomesUnused() { + this.cancel(); + } + cancel() { + if (this.isLoading()) { + if (this._cancelCb) { + this._cancelCb(this); + this._cancelCb = null; + } + this.loadingSince = 0; + } + } + isLoaded() { + return !!this._nativeTexture; + } + isLoading() { + return this.loadingSince > 0; + } + isError() { + return !!this._loadError; + } + reload() { + this.free(); + if (this.isUsed()) { + this.load(); + } + } + load(forceSync = false) { + if (this.isResultTexture) { + return; + } + if (!this._nativeTexture && !this.isLoading()) { + this.loadingSince = new Date().getTime(); + this._cancelCb = this.loader((err, options) => { + if (this.isLoading()) { + this._cancelCb = null; + if (this.manager.stage.destroyed) { + return; + } + if (err) { + this.onError(err); + } else if (options && options.source) { + if (!this.stage.isUpdatingFrame() && !forceSync && options.throttle !== false) { + const textureThrottler = this.stage.textureThrottler; + this._cancelCb = textureThrottler.genericCancelCb; + textureThrottler.add(this, options); + } else { + this.processLoadedSource(options); + } + } + } + }, this); + } + } + processLoadedSource(options) { + this.loadingSince = 0; + this.setSource(options); + } + setSource(options) { + const source = options.source; + this._hasAlpha = options ? options.hasAlpha || false : false; + this.w = source.width || options && options.w || 0; + this.h = source.height || options && options.h || 0; + if (options && options.renderInfo) { + this.renderInfo = options.renderInfo; + } + this.permanent = !!options.permanent; + if (options && options.imageRef) + this._imageRef = options.imageRef; + if (options && options.flipTextureY) { + this._flipTextureY = options.flipTextureY; + } else { + this._flipTextureY = false; + } + if (this._isNativeTexture(source)) { + this._nativeTexture = source; + this.w = this.w || source.w; + this.h = this.h || source.h; + this.permanent = options.hasOwnProperty("permanent") ? options.permanent : true; + } else { + this.manager.uploadTextureSource(this, options); + } + this._loadError = null; + this.onLoad(); + } + isUsed() { + return this._activeTextureCount > 0; + } + onLoad() { + if (this.isUsed()) { + this.textures.forEach((texture) => { + texture.onLoad(); + }); + } + } + forceRenderUpdate() { + if (this._nativeTexture) { + this._nativeTexture.update = this.stage.frameCounter; + } + this.forEachActiveElement(function(element) { + element.forceRenderUpdate(); + }); + } + forceUpdateRenderCoords() { + this.forEachActiveElement(function(element) { + element._updateTextureCoords(); + }); + } + get nativeTexture() { + return this._nativeTexture; + } + clearNativeTexture() { + this._nativeTexture = null; + this._imageRef = null; + } + replaceNativeTexture(newNativeTexture, w, h) { + let prevNativeTexture = this._nativeTexture; + this._nativeTexture = newNativeTexture; + this.w = w; + this.h = h; + if (!prevNativeTexture && this._nativeTexture) { + this.forEachActiveElement((element) => element.onTextureSourceLoaded()); + } + if (!this._nativeTexture) { + this.forEachActiveElement((element) => element._setDisplayedTexture(null)); + } + this.forEachEnabledElement((element) => element._updateDimensions()); + } + onError(e) { + this._loadError = e; + this.loadingSince = 0; + console.error("[Lightning] texture load error", e, this.lookupId); + this.forEachActiveElement((element) => element.onTextureSourceLoadError(e)); + } + free() { + if (this.isLoaded()) { + this.manager.freeTextureSource(this); + } + } + _isNativeTexture(source) { + if (Utils$1.isNode) { + return source.constructor.name === "WebGLTexture"; + } + if ("WebGLTexture" in window) { + return source instanceof WebGLTexture; + } + return false; + } +} +TextureSource.prototype.isTextureSource = true; +TextureSource.id = 1; +class ElementTexturizer { + constructor(elementCore) { + this._element = elementCore.element; + this._core = elementCore; + this.ctx = this._core.ctx; + this._enabled = false; + this.lazy = false; + this._colorize = false; + this._renderTexture = null; + this._renderTextureReused = false; + this._resultTextureSource = null; + this._renderOffscreen = false; + this.empty = false; + } + get enabled() { + return this._enabled; + } + set enabled(v) { + this._enabled = v; + this._core.updateRenderToTextureEnabled(); + } + get renderOffscreen() { + return this._renderOffscreen; + } + set renderOffscreen(v) { + this._renderOffscreen = v; + this._core.setHasRenderUpdates(1); + this._core._setRecalc(6); + } + get colorize() { + return this._colorize; + } + set colorize(v) { + if (this._colorize !== v) { + this._colorize = v; + this._core.setHasRenderUpdates(1); + } + } + _getTextureSource() { + if (!this._resultTextureSource) { + this._resultTextureSource = new TextureSource(this._element.stage.textureManager); + this.updateResultTexture(); + } + return this._resultTextureSource; + } + hasResultTexture() { + return !!this._resultTextureSource; + } + resultTextureInUse() { + return this._resultTextureSource && this._resultTextureSource.hasEnabledElements(); + } + updateResultTexture() { + let resultTexture = this.getResultTexture(); + if (this._resultTextureSource) { + if (this._resultTextureSource.nativeTexture !== resultTexture) { + let w = resultTexture ? resultTexture.w : 0; + let h = resultTexture ? resultTexture.h : 0; + this._resultTextureSource.replaceNativeTexture(resultTexture, w, h); + } + this._resultTextureSource.forEachEnabledElement((element) => { + element._updateDimensions(); + element.core.setHasRenderUpdates(3); + }); + } + } + mustRenderToTexture() { + if (this._enabled && !this.lazy) { + return true; + } else if (this._enabled && this.lazy && this._core._hasRenderUpdates < 3) { + return true; + } + return false; + } + deactivate() { + this.release(); + } + get renderTextureReused() { + return this._renderTextureReused; + } + release() { + this.releaseRenderTexture(); + } + releaseRenderTexture() { + if (this._renderTexture) { + if (!this._renderTextureReused) { + this.ctx.releaseRenderTexture(this._renderTexture); + } + this._renderTexture = null; + this._renderTextureReused = false; + this.updateResultTexture(); + } + } + reuseTextureAsRenderTexture(nativeTexture) { + if (this._renderTexture !== nativeTexture) { + this.releaseRenderTexture(); + this._renderTexture = nativeTexture; + this._renderTextureReused = true; + } + } + hasRenderTexture() { + return !!this._renderTexture; + } + getRenderTexture() { + if (!this._renderTexture) { + this._renderTexture = this.ctx.allocateRenderTexture(this._core._w, this._core._h); + this._renderTextureReused = false; + } + return this._renderTexture; + } + getResultTexture() { + return this._renderTexture; + } +} +class ElementCore { + constructor(element) { + this._element = element; + this.ctx = element.stage.ctx; + this._recalc = 0; + this._parent = null; + this._onUpdate = null; + this._pRecalc = 0; + this._worldContext = new ElementCoreContext(); + this._hasUpdates = false; + this._localAlpha = 1; + this._onAfterCalcs = null; + this._onAfterUpdate = null; + this._localPx = 0; + this._localPy = 0; + this._localTa = 1; + this._localTb = 0; + this._localTc = 0; + this._localTd = 1; + this._isComplex = false; + this._dimsUnknown = false; + this._clipping = false; + this._zSort = false; + this._outOfBounds = 0; + this._displayedTextureSource = null; + this._zContextUsage = 0; + this._children = null; + this._hasRenderUpdates = 0; + this._zIndexedChildren = null; + this._renderContext = this._worldContext; + this.renderState = this.ctx.renderState; + this._scissor = null; + this._shaderOwner = null; + this._updateTreeOrder = 0; + this._colorUl = this._colorUr = this._colorBl = this._colorBr = 4294967295; + this._x = 0; + this._y = 0; + this._w = 0; + this._h = 0; + this._optFlags = 0; + this._funcX = null; + this._funcY = null; + this._funcW = null; + this._funcH = null; + this._scaleX = 1; + this._scaleY = 1; + this._pivotX = 0.5; + this._pivotY = 0.5; + this._mountX = 0; + this._mountY = 0; + this._rotation = 0; + this._alpha = 1; + this._visible = true; + this._ulx = 0; + this._uly = 0; + this._brx = 1; + this._bry = 1; + this._zIndex = 0; + this._forceZIndexContext = false; + this._zParent = null; + this._isRoot = false; + this._zIndexResort = false; + this._shader = null; + this._renderToTextureEnabled = false; + this._texturizer = null; + this._useRenderToTexture = false; + this._boundsMargin = null; + this._recBoundsMargin = null; + this._withinBoundsMargin = false; + this._viewport = null; + this._clipbox = true; + this.render = this._renderSimple; + this._layout = null; + } + get offsetX() { + if (this._funcX) { + return this._funcX; + } else { + if (this.hasFlexLayout()) { + return this._layout.originalX; + } else { + return this._x; + } + } + } + set offsetX(v) { + if (Utils$1.isFunction(v)) { + this.funcX = v; + } else { + this._disableFuncX(); + if (this.hasFlexLayout()) { + this.x += v - this._layout.originalX; + this._layout.setOriginalXWithoutUpdatingLayout(v); + } else { + this.x = v; + } + } + } + get x() { + return this._x; + } + set x(v) { + if (v !== this._x) { + this._updateLocalTranslateDelta(v - this._x, 0); + this._x = v; + } + } + get funcX() { + return this._optFlags & 1 ? this._funcX : null; + } + set funcX(v) { + if (this._funcX !== v) { + this._optFlags |= 1; + this._funcX = v; + if (this.hasFlexLayout()) { + this._layout.setOriginalXWithoutUpdatingLayout(0); + this.layout.forceLayout(); + } else { + this._x = 0; + this._triggerRecalcTranslate(); + } + } + } + _disableFuncX() { + this._optFlags = this._optFlags & 65535 - 1; + this._funcX = null; + } + get offsetY() { + if (this._funcY) { + return this._funcY; + } else { + if (this.hasFlexLayout()) { + return this._layout.originalY; + } else { + return this._y; + } + } + } + set offsetY(v) { + if (Utils$1.isFunction(v)) { + this.funcY = v; + } else { + this._disableFuncY(); + if (this.hasFlexLayout()) { + this.y += v - this._layout.originalY; + this._layout.setOriginalYWithoutUpdatingLayout(v); + } else { + this.y = v; + } + } + } + get y() { + return this._y; + } + set y(v) { + if (v !== this._y) { + this._updateLocalTranslateDelta(0, v - this._y); + this._y = v; + } + } + get funcY() { + return this._optFlags & 2 ? this._funcY : null; + } + set funcY(v) { + if (this._funcY !== v) { + this._optFlags |= 2; + this._funcY = v; + if (this.hasFlexLayout()) { + this._layout.setOriginalYWithoutUpdatingLayout(0); + this.layout.forceLayout(); + } else { + this._y = 0; + this._triggerRecalcTranslate(); + } + } + } + _disableFuncY() { + this._optFlags = this._optFlags & 65535 - 2; + this._funcY = null; + } + get funcW() { + return this._optFlags & 4 ? this._funcW : null; + } + set funcW(v) { + if (this._funcW !== v) { + this._optFlags |= 4; + this._funcW = v; + if (this.hasFlexLayout()) { + this._layout._originalWidth = 0; + this.layout.changedDimensions(true, false); + } else { + this._w = 0; + this._triggerRecalcTranslate(); + } + } + } + disableFuncW() { + this._optFlags = this._optFlags & 65535 - 4; + this._funcW = null; + } + get funcH() { + return this._optFlags & 8 ? this._funcH : null; + } + set funcH(v) { + if (this._funcH !== v) { + this._optFlags |= 8; + this._funcH = v; + if (this.hasFlexLayout()) { + this._layout._originalHeight = 0; + this.layout.changedDimensions(false, true); + } else { + this._h = 0; + this._triggerRecalcTranslate(); + } + } + } + disableFuncH() { + this._optFlags = this._optFlags & 65535 - 8; + this._funcH = null; + } + get w() { + return this._w; + } + getRenderWidth() { + if (this.hasFlexLayout()) { + return this._layout.originalWidth; + } else { + return this._w; + } + } + get h() { + return this._h; + } + getRenderHeight() { + if (this.hasFlexLayout()) { + return this._layout.originalHeight; + } else { + return this._h; + } + } + get scaleX() { + return this._scaleX; + } + set scaleX(v) { + if (this._scaleX !== v) { + this._scaleX = v; + this._updateLocalTransform(); + } + } + get scaleY() { + return this._scaleY; + } + set scaleY(v) { + if (this._scaleY !== v) { + this._scaleY = v; + this._updateLocalTransform(); + } + } + get scale() { + return this.scaleX; + } + set scale(v) { + if (this._scaleX !== v || this._scaleY !== v) { + this._scaleX = v; + this._scaleY = v; + this._updateLocalTransform(); + } + } + get pivotX() { + return this._pivotX; + } + set pivotX(v) { + if (this._pivotX !== v) { + this._pivotX = v; + this._updateLocalTranslate(); + } + } + get pivotY() { + return this._pivotY; + } + set pivotY(v) { + if (this._pivotY !== v) { + this._pivotY = v; + this._updateLocalTranslate(); + } + } + get pivot() { + return this._pivotX; + } + set pivot(v) { + if (this._pivotX !== v || this._pivotY !== v) { + this._pivotX = v; + this._pivotY = v; + this._updateLocalTranslate(); + } + } + get mountX() { + return this._mountX; + } + set mountX(v) { + if (this._mountX !== v) { + this._mountX = v; + this._updateLocalTranslate(); + } + } + get mountY() { + return this._mountY; + } + set mountY(v) { + if (this._mountY !== v) { + this._mountY = v; + this._updateLocalTranslate(); + } + } + get mount() { + return this._mountX; + } + set mount(v) { + if (this._mountX !== v || this._mountY !== v) { + this._mountX = v; + this._mountY = v; + this._updateLocalTranslate(); + } + } + get rotation() { + return this._rotation; + } + set rotation(v) { + if (this._rotation !== v) { + this._rotation = v; + this._updateLocalTransform(); + } + } + get alpha() { + return this._alpha; + } + set alpha(v) { + v = v > 1 ? 1 : v < 1e-14 ? 0 : v; + if (this._alpha !== v) { + let prev = this._alpha; + this._alpha = v; + this._updateLocalAlpha(); + if (prev === 0 !== (v === 0)) { + this._element._updateEnabledFlag(); + } + } + } + get visible() { + return this._visible; + } + set visible(v) { + if (this._visible !== v) { + this._visible = v; + this._updateLocalAlpha(); + this._element._updateEnabledFlag(); + if (this.hasFlexLayout()) { + this.layout.setVisible(v); + } + } + } + _updateLocalTransform() { + if (this._rotation !== 0 && this._rotation % (2 * Math.PI)) { + let _sr = Math.sin(this._rotation); + let _cr = Math.cos(this._rotation); + this._setLocalTransform( + _cr * this._scaleX, + -_sr * this._scaleY, + _sr * this._scaleX, + _cr * this._scaleY + ); + } else { + this._setLocalTransform( + this._scaleX, + 0, + 0, + this._scaleY + ); + } + this._updateLocalTranslate(); + } + _updateLocalTranslate() { + this._recalcLocalTranslate(); + this._triggerRecalcTranslate(); + } + _recalcLocalTranslate() { + let pivotXMul = this._pivotX * this._w; + let pivotYMul = this._pivotY * this._h; + let px = this._x - (pivotXMul * this._localTa + pivotYMul * this._localTb) + pivotXMul; + let py = this._y - (pivotXMul * this._localTc + pivotYMul * this._localTd) + pivotYMul; + px -= this._mountX * this._w; + py -= this._mountY * this._h; + this._localPx = px; + this._localPy = py; + } + _updateLocalTranslateDelta(dx, dy) { + this._addLocalTranslate(dx, dy); + } + _updateLocalAlpha() { + this._setLocalAlpha(this._visible ? this._alpha : 0); + } + setHasRenderUpdates(type) { + if (this._worldContext.alpha) { + let p = this; + p._hasRenderUpdates = Math.max(type, p._hasRenderUpdates); + while ((p = p._parent) && p._hasRenderUpdates !== 3) { + p._hasRenderUpdates = 3; + } + } + } + _setRecalc(type) { + this._recalc |= type; + this._setHasUpdates(); + if (this._parent) { + this._parent.setHasRenderUpdates(3); + } + } + _setHasUpdates() { + let p = this; + while (p && !p._hasUpdates) { + p._hasUpdates = true; + p = p._parent; + } + } + getParent() { + return this._parent; + } + setParent(parent) { + if (parent !== this._parent) { + let prevIsZContext = this.isZContext(); + let prevParent = this._parent; + this._parent = parent; + if (this._layout || parent && parent.isFlexContainer()) { + this.layout.setParent(prevParent, parent); + } + if (prevParent) { + prevParent.setHasRenderUpdates(3); + } + this._setRecalc(1 + 2 + 4); + if (this._parent) { + this._parent._setHasUpdates(); + } + if (this._zIndex === 0) { + this.setZParent(parent); + } else { + this.setZParent(parent ? parent.findZContext() : null); + } + if (prevIsZContext !== this.isZContext()) { + if (!this.isZContext()) { + this.disableZContext(); + } else { + this.enableZContext(prevParent.findZContext()); + } + } + this._zIndexResort = true; + if (this._zParent) { + this._zParent.enableZSort(); + } + if (!this._shader) { + let newShaderOwner = parent && !parent._renderToTextureEnabled ? parent._shaderOwner : null; + if (newShaderOwner !== this._shaderOwner) { + this.setHasRenderUpdates(1); + this._setShaderOwnerRecursive(newShaderOwner); + } + } + } + } + enableZSort(force = false) { + if (!this._zSort && this._zContextUsage > 0) { + this._zSort = true; + if (force) { + this.ctx.forceZSort(this); + } + } + } + addChildAt(index, child) { + if (!this._children) + this._children = []; + this._children.splice(index, 0, child); + child.setParent(this); + } + setChildAt(index, child) { + if (!this._children) + this._children = []; + this._children[index].setParent(null); + this._children[index] = child; + child.setParent(this); + } + removeChildAt(index) { + let child = this._children[index]; + this._children.splice(index, 1); + child.setParent(null); + } + removeChildren() { + if (this._children) { + for (let i = 0, n = this._children.length; i < n; i++) { + this._children[i].setParent(null); + } + this._children.splice(0); + if (this._zIndexedChildren) { + this._zIndexedChildren.splice(0); + } + } + } + syncChildren(removed, added, order) { + this._children = order; + for (let i = 0, n = removed.length; i < n; i++) { + removed[i].setParent(null); + } + for (let i = 0, n = added.length; i < n; i++) { + added[i].setParent(this); + } + } + moveChild(fromIndex, toIndex) { + let c = this._children[fromIndex]; + this._children.splice(fromIndex, 1); + this._children.splice(toIndex, 0, c); + this._zIndexResort = true; + if (this._zParent) { + this._zParent.enableZSort(); + } + } + _setLocalTransform(a, b, c, d) { + this._setRecalc(4); + this._localTa = a; + this._localTb = b; + this._localTc = c; + this._localTd = d; + this._isComplex = b !== 0 || c !== 0 || a < 0 || d < 0; + } + _addLocalTranslate(dx, dy) { + this._localPx += dx; + this._localPy += dy; + this._triggerRecalcTranslate(); + } + _setLocalAlpha(a) { + if (!this._worldContext.alpha && (this._parent && this._parent._worldContext.alpha && a)) { + this._setRecalc(1 + 128); + } else { + this._setRecalc(1); + } + if (a < 1e-14) { + a = 0; + } + this._localAlpha = a; + } + setDimensions(w, h, isEstimate = this._dimsUnknown) { + this._dimsUnknown = isEstimate; + if (this.hasFlexLayout()) { + this._layout.originalWidth = w; + this._layout.originalHeight = h; + } else { + if (this._w !== w || this._h !== h) { + this._updateDimensions(w, h); + return true; + } + } + return false; + } + _updateDimensions(w, h) { + if (this._w !== w || this._h !== h) { + this._w = w; + this._h = h; + this._triggerRecalcTranslate(); + if (this._texturizer) { + this._texturizer.releaseRenderTexture(); + this._texturizer.updateResultTexture(); + } + this._updateLocalTranslate(); + } + } + setTextureCoords(ulx, uly, brx, bry) { + this.setHasRenderUpdates(3); + this._ulx = ulx; + this._uly = uly; + this._brx = brx; + this._bry = bry; + } + get displayedTextureSource() { + return this._displayedTextureSource; + } + setDisplayedTextureSource(textureSource) { + this.setHasRenderUpdates(3); + this._displayedTextureSource = textureSource; + } + get isRoot() { + return this._isRoot; + } + setAsRoot() { + this._parent = new ElementCore(this._element); + this._parent._hasRenderUpdates = 3; + this._parent._hasUpdates = true; + this._isRoot = true; + this.ctx.root = this; + this._parent._viewport = [0, 0, this.ctx.stage.coordsWidth, this.ctx.stage.coordsHeight]; + this._parent._scissor = this._parent._viewport; + this._parent._recBoundsMargin = null; + this._setRecalc(1 + 2 + 4); + } + isAncestorOf(c) { + let p = c; + while (p = p._parent) { + if (this === p) { + return true; + } + } + return false; + } + isZContext() { + return this._forceZIndexContext || this._renderToTextureEnabled || this._zIndex !== 0 || this._isRoot || !this._parent; + } + findZContext() { + if (this.isZContext()) { + return this; + } else { + return this._parent.findZContext(); + } + } + setZParent(newZParent) { + if (this._zParent !== newZParent) { + if (this._zParent !== null) { + if (this._zIndex !== 0) { + this._zParent.decZContextUsage(); + } + this._zParent.enableZSort(); + } + if (newZParent !== null) { + let hadZContextUsage = newZParent._zContextUsage > 0; + if (this._zIndex !== 0) { + newZParent.incZContextUsage(); + } + if (newZParent._zContextUsage > 0) { + if (!hadZContextUsage && this._parent === newZParent) + ; + else { + newZParent._zIndexedChildren.push(this); + } + newZParent.enableZSort(); + } + } + this._zParent = newZParent; + this._zIndexResort = true; + } + } + incZContextUsage() { + this._zContextUsage++; + if (this._zContextUsage === 1) { + if (!this._zIndexedChildren) { + this._zIndexedChildren = []; + } + if (this._children) { + for (let i = 0, n = this._children.length; i < n; i++) { + this._zIndexedChildren.push(this._children[i]); + } + this._zSort = false; + } + } + } + decZContextUsage() { + this._zContextUsage--; + if (this._zContextUsage === 0) { + this._zSort = false; + this._zIndexedChildren.splice(0); + } + } + get zIndex() { + return this._zIndex; + } + set zIndex(zIndex) { + if (this._zIndex !== zIndex) { + this.setHasRenderUpdates(1); + let newZParent = this._zParent; + let prevIsZContext = this.isZContext(); + if (zIndex === 0 && this._zIndex !== 0) { + if (this._parent === this._zParent) { + if (this._zParent) { + this._zParent.decZContextUsage(); + } + } else { + newZParent = this._parent; + } + } else if (zIndex !== 0 && this._zIndex === 0) { + newZParent = this._parent ? this._parent.findZContext() : null; + if (newZParent === this._zParent) { + if (this._zParent) { + this._zParent.incZContextUsage(); + this._zParent.enableZSort(); + } + } + } else if (zIndex !== this._zIndex) { + if (this._zParent && this._zParent._zContextUsage) { + this._zParent.enableZSort(); + } + } + if (newZParent !== this._zParent) { + this.setZParent(null); + } + this._zIndex = zIndex; + if (newZParent !== this._zParent) { + this.setZParent(newZParent); + } + if (prevIsZContext !== this.isZContext()) { + if (!this.isZContext()) { + this.disableZContext(); + } else { + this.enableZContext(this._parent.findZContext()); + } + } + this._zIndexResort = true; + if (this._zParent) { + this._zParent.enableZSort(); + } + } + } + get forceZIndexContext() { + return this._forceZIndexContext; + } + set forceZIndexContext(v) { + this.setHasRenderUpdates(1); + let prevIsZContext = this.isZContext(); + this._forceZIndexContext = v; + if (prevIsZContext !== this.isZContext()) { + if (!this.isZContext()) { + this.disableZContext(); + } else { + this.enableZContext(this._parent.findZContext()); + } + } + } + enableZContext(prevZContext) { + if (prevZContext && prevZContext._zContextUsage > 0) { + const results = this._getZIndexedDescs(); + results.forEach((c) => { + if (this.isAncestorOf(c) && c._zIndex !== 0) { + c.setZParent(this); + } + }); + } + } + _getZIndexedDescs() { + const results = []; + if (this._children) { + for (let i = 0, n = this._children.length; i < n; i++) { + this._children[i]._getZIndexedDescsRec(results); + } + } + return results; + } + _getZIndexedDescsRec(results) { + if (this._zIndex) { + results.push(this); + } else if (this._children && !this.isZContext()) { + for (let i = 0, n = this._children.length; i < n; i++) { + this._children[i]._getZIndexedDescsRec(results); + } + } + } + disableZContext() { + if (this._zContextUsage > 0) { + let newZParent = this._parent.findZContext(); + if (this._zSort) { + this.sortZIndexedChildren(); + } + this._zIndexedChildren.slice().forEach(function(c) { + if (c._zIndex !== 0) { + c.setZParent(newZParent); + } + }); + } + } + get colorUl() { + return this._colorUl; + } + set colorUl(color) { + if (this._colorUl !== color) { + this.setHasRenderUpdates(this._displayedTextureSource ? 3 : 1); + this._colorUl = color; + } + } + get colorUr() { + return this._colorUr; + } + set colorUr(color) { + if (this._colorUr !== color) { + this.setHasRenderUpdates(this._displayedTextureSource ? 3 : 1); + this._colorUr = color; + } + } + get colorBl() { + return this._colorBl; + } + set colorBl(color) { + if (this._colorBl !== color) { + this.setHasRenderUpdates(this._displayedTextureSource ? 3 : 1); + this._colorBl = color; + } + } + get colorBr() { + return this._colorBr; + } + set colorBr(color) { + if (this._colorBr !== color) { + this.setHasRenderUpdates(this._displayedTextureSource ? 3 : 1); + this._colorBr = color; + } + } + set onUpdate(f) { + this._onUpdate = f; + this._setRecalc(7); + } + set onAfterUpdate(f) { + this._onAfterUpdate = f; + this._setRecalc(7); + } + set onAfterCalcs(f) { + this._onAfterCalcs = f; + this._setRecalc(7); + } + get shader() { + return this._shader; + } + set shader(v) { + this.setHasRenderUpdates(1); + let prevShader = this._shader; + this._shader = v; + if (!v && prevShader) { + let newShaderOwner = this._parent && !this._parent._renderToTextureEnabled ? this._parent._shaderOwner : null; + this._setShaderOwnerRecursive(newShaderOwner); + } else if (v) { + this._setShaderOwnerRecursive(this); + } + } + get activeShader() { + return this._shaderOwner ? this._shaderOwner.shader : this.renderState.defaultShader; + } + get activeShaderOwner() { + return this._shaderOwner; + } + get clipping() { + return this._clipping; + } + set clipping(v) { + if (this._clipping !== v) { + this._clipping = v; + this._setRecalc(1 + 2); + } + } + get clipbox() { + return this._clipbox; + } + set clipbox(v) { + this._clipbox = v; + } + _setShaderOwnerRecursive(elementCore) { + this._shaderOwner = elementCore; + if (this._children && !this._renderToTextureEnabled) { + for (let i = 0, n = this._children.length; i < n; i++) { + let c = this._children[i]; + if (!c._shader) { + c._setShaderOwnerRecursive(elementCore); + c._hasRenderUpdates = 3; + } + } + } + } + _setShaderOwnerChildrenRecursive(elementCore) { + if (this._children) { + for (let i = 0, n = this._children.length; i < n; i++) { + let c = this._children[i]; + if (!c._shader) { + c._setShaderOwnerRecursive(elementCore); + c._hasRenderUpdates = 3; + } + } + } + } + _hasRenderContext() { + return this._renderContext !== this._worldContext; + } + get renderContext() { + return this._renderContext; + } + updateRenderToTextureEnabled() { + let v = this.texturizer._enabled; + if (v) { + this._enableRenderToTexture(); + } else { + this._disableRenderToTexture(); + this._texturizer.releaseRenderTexture(); + } + } + _enableRenderToTexture() { + if (!this._renderToTextureEnabled) { + let prevIsZContext = this.isZContext(); + this._renderToTextureEnabled = true; + this._renderContext = new ElementCoreContext(); + this._setShaderOwnerChildrenRecursive(null); + if (!prevIsZContext) { + this.enableZContext(this._parent ? this._parent.findZContext() : null); + } + this.setHasRenderUpdates(3); + this._setRecalc(7); + this.render = this._renderAdvanced; + } + } + _disableRenderToTexture() { + if (this._renderToTextureEnabled) { + this._renderToTextureEnabled = false; + this._setShaderOwnerChildrenRecursive(this._shaderOwner); + this._renderContext = this._worldContext; + if (!this.isZContext()) { + this.disableZContext(); + } + this._setRecalc(7); + this.setHasRenderUpdates(3); + this.render = this._renderSimple; + } + } + isWhite() { + return this._colorUl === 4294967295 && this._colorUr === 4294967295 && this._colorBl === 4294967295 && this._colorBr === 4294967295; + } + hasSimpleTexCoords() { + return this._ulx === 0 && this._uly === 0 && this._brx === 1 && this._bry === 1; + } + _stashTexCoords() { + this._stashedTexCoords = [this._ulx, this._uly, this._brx, this._bry]; + this._ulx = 0; + this._uly = 0; + this._brx = 1; + this._bry = 1; + } + _unstashTexCoords() { + this._ulx = this._stashedTexCoords[0]; + this._uly = this._stashedTexCoords[1]; + this._brx = this._stashedTexCoords[2]; + this._bry = this._stashedTexCoords[3]; + this._stashedTexCoords = null; + } + _stashColors() { + this._stashedColors = [this._colorUl, this._colorUr, this._colorBr, this._colorBl]; + this._colorUl = 4294967295; + this._colorUr = 4294967295; + this._colorBr = 4294967295; + this._colorBl = 4294967295; + } + _unstashColors() { + this._colorUl = this._stashedColors[0]; + this._colorUr = this._stashedColors[1]; + this._colorBr = this._stashedColors[2]; + this._colorBl = this._stashedColors[3]; + this._stashedColors = null; + } + isVisible() { + return this._localAlpha > 1e-14; + } + get outOfBounds() { + return this._outOfBounds; + } + set boundsMargin(v) { + this._boundsMargin = v ? v.slice() : null; + this._triggerRecalcTranslate(); + } + get boundsMargin() { + return this._boundsMargin; + } + update() { + this._recalc |= this._parent._pRecalc; + if (this._layout && this._layout.isEnabled()) { + if (this._recalc & 256) { + this._layout.layoutFlexTree(); + } + } else if (this._recalc & 2 && this._optFlags) { + this._applyRelativeDimFuncs(); + } + if (this._onUpdate) { + this._hasUpdates = true; + this._onUpdate(this.element, this); + } + const pw = this._parent._worldContext; + let w = this._worldContext; + const visible = pw.alpha && this._localAlpha; + if (this._hasUpdates || this._recalc && visible || w.alpha && !visible) { + let recalc = this._recalc; + if (recalc & 1) { + if (!w.alpha && visible) { + this._hasRenderUpdates = 3; + } + w.alpha = pw.alpha * this._localAlpha; + if (w.alpha < 1e-14) { + w.alpha = 0; + } + } + if (recalc & 6) { + w.px = pw.px + this._localPx * pw.ta; + w.py = pw.py + this._localPy * pw.td; + if (pw.tb !== 0) + w.px += this._localPy * pw.tb; + if (pw.tc !== 0) + w.py += this._localPx * pw.tc; + } + if (recalc & 4) { + w.ta = this._localTa * pw.ta; + w.tb = this._localTd * pw.tb; + w.tc = this._localTa * pw.tc; + w.td = this._localTd * pw.td; + if (this._isComplex) { + w.ta += this._localTc * pw.tb; + w.tb += this._localTb * pw.ta; + w.tc += this._localTc * pw.td; + w.td += this._localTb * pw.tc; + } + } + const pr = this._parent._renderContext; + if (this._parent._hasRenderContext()) { + const init = this._renderContext === this._worldContext; + if (init) { + this._renderContext = new ElementCoreContext(); + } + const r2 = this._renderContext; + if (init || recalc & 1) { + r2.alpha = pr.alpha * this._localAlpha; + if (r2.alpha < 1e-14) { + r2.alpha = 0; + } + } + if (init || recalc & 6) { + r2.px = pr.px + this._localPx * pr.ta; + r2.py = pr.py + this._localPy * pr.td; + if (pr.tb !== 0) + r2.px += this._localPy * pr.tb; + if (pr.tc !== 0) + r2.py += this._localPx * pr.tc; + } + if (init) { + recalc |= 2; + } + if (init || recalc & 4) { + r2.ta = this._localTa * pr.ta; + r2.tb = this._localTd * pr.tb; + r2.tc = this._localTa * pr.tc; + r2.td = this._localTd * pr.td; + if (this._isComplex) { + r2.ta += this._localTc * pr.tb; + r2.tb += this._localTb * pr.ta; + r2.tc += this._localTc * pr.td; + r2.td += this._localTb * pr.tc; + } + } + } else { + this._renderContext = this._worldContext; + } + if (this.ctx.updateTreeOrder === -1) { + this.ctx.updateTreeOrder = this._updateTreeOrder + 1; + } else { + this._updateTreeOrder = this.ctx.updateTreeOrder++; + } + const useRenderToTexture = this._renderToTextureEnabled && this._texturizer.mustRenderToTexture(); + if (this._useRenderToTexture !== useRenderToTexture) { + this._recalc |= 2 + 4; + recalc |= 2; + if (!this._useRenderToTexture) { + this._texturizer.release(); + } + } + this._useRenderToTexture = useRenderToTexture; + const r = this._renderContext; + const bboxW = this._dimsUnknown ? 2048 : this._w; + const bboxH = this._dimsUnknown ? 2048 : this._h; + let sx, sy, ex, ey; + const rComplex = r.tb !== 0 || r.tc !== 0 || r.ta < 0 || r.td < 0; + if (rComplex) { + sx = Math.min(0, bboxW * r.ta, bboxW * r.ta + bboxH * r.tb, bboxH * r.tb) + r.px; + ex = Math.max(0, bboxW * r.ta, bboxW * r.ta + bboxH * r.tb, bboxH * r.tb) + r.px; + sy = Math.min(0, bboxW * r.tc, bboxW * r.tc + bboxH * r.td, bboxH * r.td) + r.py; + ey = Math.max(0, bboxW * r.tc, bboxW * r.tc + bboxH * r.td, bboxH * r.td) + r.py; + } else { + sx = r.px; + ex = r.px + r.ta * bboxW; + sy = r.py; + ey = r.py + r.td * bboxH; + } + if (this._dimsUnknown && (rComplex || this._localTa < 1 || this._localTb < 1)) { + const nx = this._x * pr.ta + this._y * pr.tb + pr.px; + const ny = this._x * pr.tc + this._y * pr.td + pr.py; + if (nx < sx) + sx = nx; + if (ny < sy) + sy = ny; + if (nx > ex) + ex = nx; + if (ny > ey) + ey = ny; + } + if (recalc & 6 || !this._scissor) { + if (this._clipping && r.isSquare()) { + const area = this._parent._useRenderToTexture ? this._parent._viewport : this._parent._scissor; + if (area) { + const lx = Math.max(area[0], sx); + const ly = Math.max(area[1], sy); + this._scissor = [ + lx, + ly, + Math.min(area[2] + area[0], ex) - lx, + Math.min(area[3] + area[1], ey) - ly + ]; + } else { + this._scissor = [sx, sy, ex - sx, ey - sy]; + } + } else { + this._scissor = this._parent._useRenderToTexture ? this._parent._viewport : this._parent._scissor; + } + } + if (this._boundsMargin) { + this._recBoundsMargin = this._boundsMargin; + } else { + this._recBoundsMargin = this._parent._recBoundsMargin; + } + if (this._onAfterCalcs) { + if (this._onAfterCalcs(this.element)) { + if (rComplex) { + sx = Math.min(0, bboxW * r.ta, bboxW * r.ta + bboxH * r.tb, bboxH * r.tb) + r.px; + ex = Math.max(0, bboxW * r.ta, bboxW * r.ta + bboxH * r.tb, bboxH * r.tb) + r.px; + sy = Math.min(0, bboxW * r.tc, bboxW * r.tc + bboxH * r.td, bboxH * r.td) + r.py; + ey = Math.max(0, bboxW * r.tc, bboxW * r.tc + bboxH * r.td, bboxH * r.td) + r.py; + } else { + sx = r.px; + ex = r.px + r.ta * bboxW; + sy = r.py; + ey = r.py + r.td * bboxH; + } + if (this._dimsUnknown && (rComplex || this._localTa < 1 || this._localTb < 1)) { + const nx = this._x * pr.ta + this._y * pr.tb + pr.px; + const ny = this._x * pr.tc + this._y * pr.td + pr.py; + if (nx < sx) + sx = nx; + if (ny < sy) + sy = ny; + if (nx > ex) + ex = nx; + if (ny > ey) + ey = ny; + } + } + } + if (this._parent._outOfBounds === 2) { + this._outOfBounds = 2; + if (this._withinBoundsMargin) { + this._withinBoundsMargin = false; + this.element._disableWithinBoundsMargin(); + } + } else { + if (recalc & 6) { + this._outOfBounds = 0; + let withinMargin = true; + if (!this._renderToTextureEnabled || !this._texturizer || !this._texturizer.renderOffscreen) { + if (this._scissor && (this._scissor[2] <= 0 || this._scissor[3] <= 0)) { + this._outOfBounds = 2; + } else { + if (this._scissor[0] > ex || this._scissor[1] > ey || sx > this._scissor[0] + this._scissor[2] || sy > this._scissor[1] + this._scissor[3]) { + this._outOfBounds = 1; + } + if (this._outOfBounds) { + if (this._clipping || this._useRenderToTexture || this._clipbox && (bboxW && bboxH)) { + this._outOfBounds = 2; + } + } + } + withinMargin = this._outOfBounds === 0; + if (!withinMargin) { + if (this._recBoundsMargin) { + withinMargin = !(ex < this._scissor[0] - this._recBoundsMargin[2] || ey < this._scissor[1] - this._recBoundsMargin[3] || sx > this._scissor[0] + this._scissor[2] + this._recBoundsMargin[0] || sy > this._scissor[1] + this._scissor[3] + this._recBoundsMargin[1]); + } else { + withinMargin = !(ex < this._scissor[0] - 100 || ey < this._scissor[1] - 100 || sx > this._scissor[0] + this._scissor[2] + 100 || sy > this._scissor[1] + this._scissor[3] + 100); + } + if (withinMargin && this._outOfBounds === 2) { + this._outOfBounds = 1; + } + } + } + if (this._withinBoundsMargin !== withinMargin) { + this._withinBoundsMargin = withinMargin; + if (this._withinBoundsMargin) { + this._hasUpdates = true; + const recalc2 = this._recalc; + this._recalc = 0; + this.element._enableWithinBoundsMargin(); + if (this._recalc) { + return this.update(); + } + this._recalc = recalc2; + } else { + this.element._disableWithinBoundsMargin(); + } + } + } + } + if (this._useRenderToTexture) { + if (this._viewport) { + this._viewport[2] = bboxW; + this._viewport[3] = bboxH; + } else { + this._viewport = [0, 0, bboxW, bboxH]; + } + } + this._pRecalc = this._recalc & 135; + this._recalc = 0; + this._hasUpdates = false; + if (this._outOfBounds < 2) { + if (this._useRenderToTexture) { + if (this._worldContext.isIdentity()) { + this._renderContext = this._worldContext; + } else { + this._renderContext = ElementCoreContext.IDENTITY; + } + } + if (this._children) { + for (let i = 0, n = this._children.length; i < n; i++) { + this._children[i].update(); + } + } + if (this._useRenderToTexture) { + this._renderContext = r; + } + } else { + if (this._children) { + for (let i = 0, n = this._children.length; i < n; i++) { + if (this._children[i]._hasUpdates) { + this._children[i].update(); + } else { + this._children[i]._recalc |= this._pRecalc; + this._children[i].updateOutOfBounds(); + } + } + } + } + if (this._onAfterUpdate) { + this._onAfterUpdate(this.element); + } + } else { + if (this.ctx.updateTreeOrder === -1 || this._updateTreeOrder >= this.ctx.updateTreeOrder) { + this.ctx.updateTreeOrder = -1; + } else { + this.updateTreeOrder(); + } + } + } + _applyRelativeDimFuncs() { + if (this._optFlags & 1) { + const x = this._funcX(this._parent.w); + if (x !== this._x) { + this._localPx += x - this._x; + this._x = x; + } + } + if (this._optFlags & 2) { + const y = this._funcY(this._parent.h); + if (y !== this._y) { + this._localPy += y - this._y; + this._y = y; + } + } + let changedDims = false; + if (this._optFlags & 4) { + const w = this._funcW(this._parent.w); + if (w !== this._w) { + this._w = w; + changedDims = true; + } + } + if (this._optFlags & 8) { + const h = this._funcH(this._parent.h); + if (h !== this._h) { + this._h = h; + changedDims = true; + } + } + if (changedDims) { + this._recalcLocalTranslate(); + this.element.onDimensionsChanged(this._w, this._h); + } + } + updateOutOfBounds() { + if (this._outOfBounds !== 2 && this._renderContext.alpha > 0) { + this._outOfBounds = 2; + if (this._withinBoundsMargin) { + this._withinBoundsMargin = false; + this.element._disableWithinBoundsMargin(); + } + if (this._children) { + for (let i = 0, n = this._children.length; i < n; i++) { + this._children[i].updateOutOfBounds(); + } + } + } + } + updateTreeOrder() { + if (this._localAlpha && this._outOfBounds !== 2) { + this._updateTreeOrder = this.ctx.updateTreeOrder++; + if (this._children) { + for (let i = 0, n = this._children.length; i < n; i++) { + this._children[i].updateTreeOrder(); + } + } + } + } + _renderSimple() { + this._hasRenderUpdates = 0; + if (this._zSort) { + this.sortZIndexedChildren(); + } + if (this._outOfBounds < 2 && this._renderContext.alpha) { + let renderState = this.renderState; + if (this._outOfBounds === 0 && this._displayedTextureSource) { + renderState.setShader(this.activeShader, this._shaderOwner); + renderState.setScissor(this._scissor); + this.renderState.addQuad(this); + } + if (this._children) { + if (this._zContextUsage) { + for (let i = 0, n = this._zIndexedChildren.length; i < n; i++) { + this._zIndexedChildren[i].render(); + } + } else { + for (let i = 0, n = this._children.length; i < n; i++) { + if (this._children[i]._zIndex === 0) { + this._children[i].render(); + } + } + } + } + } + } + _renderAdvanced() { + const hasRenderUpdates = this._hasRenderUpdates; + this._hasRenderUpdates = 0; + if (this._zSort) { + this.sortZIndexedChildren(); + } + if (this._outOfBounds < 2 && this._renderContext.alpha) { + let renderState = this.renderState; + let mustRenderChildren = true; + let renderTextureInfo; + let prevRenderTextureInfo; + if (this._useRenderToTexture) { + if (this._w === 0 || this._h === 0) { + return; + } else if (!this._texturizer.hasRenderTexture() || hasRenderUpdates >= 3) { + this.ctx.renderToTextureCount++; + renderState.setShader(renderState.defaultShader, this); + prevRenderTextureInfo = renderState.renderTextureInfo; + renderTextureInfo = { + nativeTexture: null, + offset: 0, + w: this._w, + h: this._h, + empty: true, + cleared: false, + ignore: false, + cache: false + }; + if (this._texturizer.hasResultTexture() || !renderState.isCachingTexturizer && hasRenderUpdates < 3) { + renderTextureInfo.cache = true; + renderState.isCachingTexturizer = true; + } + if (!this._texturizer.hasResultTexture()) { + this._texturizer.releaseRenderTexture(); + } + renderState.setRenderTextureInfo(renderTextureInfo); + renderState.setScissor(null); + if (this._displayedTextureSource) { + let r = this._renderContext; + this._renderContext = ElementCoreContext.IDENTITY; + this.renderState.addQuad(this); + this._renderContext = r; + } + } else { + mustRenderChildren = false; + } + } else { + if (this._outOfBounds === 0 && this._displayedTextureSource) { + renderState.setShader(this.activeShader, this._shaderOwner); + renderState.setScissor(this._scissor); + this.renderState.addQuad(this); + } + } + if (mustRenderChildren && this._children) { + if (this._zContextUsage) { + for (let i = 0, n = this._zIndexedChildren.length; i < n; i++) { + this._zIndexedChildren[i].render(); + } + } else { + for (let i = 0, n = this._children.length; i < n; i++) { + if (this._children[i]._zIndex === 0) { + this._children[i].render(); + } + } + } + } + if (this._useRenderToTexture) { + let updateResultTexture = false; + if (mustRenderChildren) { + renderState.finishedRenderTexture(); + this._texturizer.empty = renderTextureInfo.empty; + if (renderTextureInfo.empty) { + this._texturizer.releaseRenderTexture(); + } else if (renderTextureInfo.nativeTexture) { + this._texturizer.reuseTextureAsRenderTexture(renderTextureInfo.nativeTexture); + renderTextureInfo.ignore = true; + } else { + if (this._texturizer.renderTextureReused) { + this._texturizer.releaseRenderTexture(); + } + renderTextureInfo.nativeTexture = this._texturizer.getRenderTexture(); + } + renderState.setRenderTextureInfo(prevRenderTextureInfo); + updateResultTexture = true; + } + if (!this._texturizer.empty) { + let resultTexture = this._texturizer.getResultTexture(); + if (updateResultTexture) { + if (resultTexture) { + resultTexture.update = renderState.stage.frameCounter; + } + this._texturizer.updateResultTexture(); + } + if (!this._texturizer.renderOffscreen) { + renderState.setShader(this.activeShader, this._shaderOwner); + renderState.setScissor(this._scissor); + const cache = !renderTextureInfo || renderTextureInfo.cache; + renderState.setTexturizer(this._texturizer, cache); + this._stashTexCoords(); + if (!this._texturizer.colorize) + this._stashColors(); + this.renderState.addQuad(this, true); + if (!this._texturizer.colorize) + this._unstashColors(); + this._unstashTexCoords(); + renderState.setTexturizer(null); + } + } + } + if (renderTextureInfo && renderTextureInfo.cache) { + renderState.isCachingTexturizer = false; + } + } + } + get zSort() { + return this._zSort; + } + sortZIndexedChildren() { + const n = this._zIndexedChildren.length; + let ptr = 0; + const a = this._zIndexedChildren; + const b = []; + for (let i = 0; i < n; i++) { + if (a[i]._zParent === this) { + if (a[i]._zIndexResort) { + b.push(a[i]); + } else { + if (ptr !== i) { + a[ptr] = a[i]; + } + ptr++; + } + } + } + const m = b.length; + if (m) { + for (let j = 0; j < m; j++) { + b[j]._zIndexResort = false; + } + b.sort(ElementCore.sortZIndexedChildren); + const n2 = ptr; + if (!n2) { + ptr = 0; + let j = 0; + do { + a[ptr++] = b[j++]; + } while (j < m); + if (a.length > ptr) { + a.splice(ptr); + } + } else { + ptr = 0; + let i = 0; + let j = 0; + const mergeResult = []; + do { + const v = a[i]._zIndex === b[j]._zIndex ? a[i]._updateTreeOrder - b[j]._updateTreeOrder : a[i]._zIndex - b[j]._zIndex; + const add = v > 0 ? b[j++] : a[i++]; + if (ptr === 0 || mergeResult[ptr - 1] !== add) { + mergeResult[ptr++] = add; + } + if (i >= n2) { + do { + const add2 = b[j++]; + if (ptr === 0 || mergeResult[ptr - 1] !== add2) { + mergeResult[ptr++] = add2; + } + } while (j < m); + break; + } else if (j >= m) { + do { + const add2 = a[i++]; + if (ptr === 0 || mergeResult[ptr - 1] !== add2) { + mergeResult[ptr++] = add2; + } + } while (i < n2); + break; + } + } while (true); + this._zIndexedChildren = mergeResult; + } + } else { + if (a.length > ptr) { + a.splice(ptr); + } + } + this._zSort = false; + } + get localTa() { + return this._localTa; + } + get localTb() { + return this._localTb; + } + get localTc() { + return this._localTc; + } + get localTd() { + return this._localTd; + } + get element() { + return this._element; + } + get renderUpdates() { + return this._hasRenderUpdates; + } + get texturizer() { + if (!this._texturizer) { + this._texturizer = new ElementTexturizer(this); + } + return this._texturizer; + } + getCornerPoints() { + let w = this._worldContext; + return [ + w.px, + w.py, + w.px + this._w * w.ta, + w.py + this._w * w.tc, + w.px + this._w * w.ta + this._h * w.tb, + w.py + this._w * w.tc + this._h * w.td, + w.px + this._h * w.tb, + w.py + this._h * w.td + ]; + } + getRenderTextureCoords(relX, relY) { + let r = this._renderContext; + return [ + r.px + r.ta * relX + r.tb * relY, + r.py + r.tc * relX + r.td * relY + ]; + } + getAbsoluteCoords(relX, relY) { + let w = this._renderContext; + return [ + w.px + w.ta * relX + w.tb * relY, + w.py + w.tc * relX + w.td * relY + ]; + } + collectAtCoord(x, y, children) { + if (this._renderContext.alpha === 0) { + return; + } + if (this.inBound(x, y)) { + if (this._scissor) { + if (this.inScissor()) { + children.push(this); + } + } else { + children.push(this); + } + } + if (this._children) { + const j = this._children.length; + for (let i = 0; i < j; i++) { + this._children[i].collectAtCoord(x, y, children); + } + } + return children.sort(ElementCore.sortZIndexedChildren); + } + inBound(tx, ty) { + const c = this.getCornerPoints(); + return tx > c[0] && tx < c[2] && ty > c[1] && ty < c[7]; + } + inScissor() { + const sc = this._scissor; + const c = this.getCornerPoints(); + return c[2] >= sc[0] && c[0] <= sc[0] + sc[2] && c[7] >= sc[1] && c[1] <= sc[1] + sc[3]; + } + get layout() { + this._ensureLayout(); + return this._layout; + } + get flex() { + return this._layout ? this._layout.flex : null; + } + set flex(v) { + this.layout.flex = v; + } + get flexItem() { + return this._layout ? this._layout.flexItem : null; + } + set flexItem(v) { + this.layout.flexItem = v; + } + isFlexItem() { + return !!this._layout && this._layout.isFlexItemEnabled(); + } + isFlexContainer() { + return !!this._layout && this._layout.isFlexEnabled(); + } + enableFlexLayout() { + this._ensureLayout(); + } + _ensureLayout() { + if (!this._layout) { + this._layout = new FlexTarget(this); + } + } + disableFlexLayout() { + this._triggerRecalcTranslate(); + } + hasFlexLayout() { + return this._layout && this._layout.isEnabled(); + } + setLayout(x, y, w, h) { + this.x = x; + this.y = y; + this._updateDimensions(w, h); + } + triggerLayout() { + this._setRecalc(256); + } + _triggerRecalcTranslate() { + this._setRecalc(2); + } +} +class ElementCoreContext { + constructor() { + this.alpha = 1; + this.px = 0; + this.py = 0; + this.ta = 1; + this.tb = 0; + this.tc = 0; + this.td = 1; + } + isIdentity() { + return this.alpha === 1 && this.px === 0 && this.py === 0 && this.ta === 1 && this.tb === 0 && this.tc === 0 && this.td === 1; + } + isSquare() { + return this.tb === 0 && this.tc === 0; + } +} +ElementCoreContext.IDENTITY = new ElementCoreContext(); +ElementCore.sortZIndexedChildren = function(a, b) { + return a._zIndex === b._zIndex ? a._updateTreeOrder - b._updateTreeOrder : a._zIndex - b._zIndex; +}; +class EventEmitter { + constructor() { + this._hasEventListeners = false; + } + on(name, listener) { + if (!this._hasEventListeners) { + this._eventFunction = {}; + this._eventListeners = {}; + this._hasEventListeners = true; + } + const current = this._eventFunction[name]; + if (!current) { + this._eventFunction[name] = listener; + } else { + if (this._eventFunction[name] !== EventEmitter.combiner) { + this._eventListeners[name] = [this._eventFunction[name], listener]; + this._eventFunction[name] = EventEmitter.combiner; + } else { + this._eventListeners[name].push(listener); + } + } + } + once(name, listener) { + const wrapper = (arg1, arg2, arg3) => { + listener(arg1, arg2, arg3); + this.off(name, wrapper); + }; + wrapper.__originalFunc = listener; + this.on(name, wrapper); + } + has(name, listener) { + if (this._hasEventListeners) { + const current = this._eventFunction[name]; + if (current) { + if (current === EventEmitter.combiner) { + const listeners = this._eventListeners[name]; + for (const l of listeners) { + if (l === listener || l.__originalFunc == listener) { + return true; + } + } + } else if (this._eventFunction[name] === listener || this._eventFunction[name].__originalFunc === listener) { + return true; + } + } + } + return false; + } + off(name, listener) { + if (this._hasEventListeners) { + const current = this._eventFunction[name]; + if (current) { + if (current === EventEmitter.combiner) { + const listeners = this._eventListeners[name]; + let index = listeners.indexOf(listener); + if (index >= 0) { + listeners.splice(index, 1); + } + index = listeners.map((l) => l.__originalFunc).indexOf(listener); + if (index >= 0) { + listeners.splice(index, 1); + } + if (listeners.length === 1) { + this._eventFunction[name] = listeners[0]; + this._eventListeners[name] = void 0; + } + } else if (this._eventFunction[name] === listener || this._eventFunction[name].__originalFunc === listener) { + this._eventFunction[name] = void 0; + } + } + } + } + removeListener(name, listener) { + this.off(name, listener); + } + emit(name, arg1, arg2, arg3) { + if (this._hasEventListeners) { + const func = this._eventFunction[name]; + if (func) { + if (func === EventEmitter.combiner) { + func(this, name, arg1, arg2, arg3); + } else { + func(arg1, arg2, arg3); + } + } + } + } + listenerCount(name) { + if (this._hasEventListeners) { + const func = this._eventFunction[name]; + if (func) { + if (func === EventEmitter.combiner) { + return this._eventListeners[name].length; + } else { + return 1; + } + } + } + return 0; + } + removeAllListeners(name) { + if (this._hasEventListeners) { + delete this._eventFunction[name]; + delete this._eventListeners[name]; + } + } +} +EventEmitter.combiner = function(object, name, arg1, arg2, arg3) { + const listeners = object._eventListeners[name]; + if (listeners) { + for (const listener of [...listeners]) { + listener(arg1, arg2, arg3); + } + } +}; +EventEmitter.addAsMixin = function(cls) { + cls.prototype.on = EventEmitter.prototype.on; + cls.prototype.once = EventEmitter.prototype.once; + cls.prototype.has = EventEmitter.prototype.has; + cls.prototype.off = EventEmitter.prototype.off; + cls.prototype.removeListener = EventEmitter.prototype.removeListener; + cls.prototype.emit = EventEmitter.prototype.emit; + cls.prototype.listenerCount = EventEmitter.prototype.listenerCount; + cls.prototype.removeAllListeners = EventEmitter.prototype.removeAllListeners; +}; +class Shader { + constructor(coreContext) { + this._initialized = false; + this.ctx = coreContext; + this._elements = /* @__PURE__ */ new Set(); + } + static create(stage, v) { + let shader; + if (Utils$1.isObjectLiteral(v)) { + if (v.type) { + shader = stage.renderer.createShader(stage.ctx, v); + } else { + shader = this.shader; + } + if (shader) { + Base.patchObject(shader, v); + } + } else if (v === null) { + shader = stage.ctx.renderState.defaultShader; + } else if (v === void 0) { + shader = null; + } else { + if (v.isShader) { + if (!stage.renderer.isValidShaderType(v.constructor)) { + console.error("[Lightning] Invalid shader type"); + v = null; + } + shader = v; + } else { + console.error("[Lightning] Please specify a shader type."); + return; + } + } + return shader; + } + static getWebGL() { + return void 0; + } + static getC2d() { + return void 0; + } + addElement(elementCore) { + this._elements.add(elementCore); + } + removeElement(elementCore) { + this._elements.delete(elementCore); + if (!this._elements) { + this.cleanup(); + } + } + redraw() { + this._elements.forEach((elementCore) => { + elementCore.setHasRenderUpdates(2); + }); + } + patch(settings) { + Base.patchObject(this, settings); + } + useDefault() { + return false; + } + addEmpty() { + return false; + } + cleanup() { + } + get isShader() { + return true; + } +} +class Texture { + constructor(stage) { + this.stage = stage; + this.manager = this.stage.textureManager; + this.id = Texture.id++; + this.elements = /* @__PURE__ */ new Set(); + this._activeCount = 0; + this._source = null; + this._resizeMode = null; + this._x = 0; + this._y = 0; + this._w = 0; + this._h = 0; + this._precision = 1; + this.mw = 0; + this.mh = 0; + this.clipping = false; + this._mustUpdate = true; + } + get source() { + if (this._mustUpdate || this.stage.hasUpdateSourceTexture(this)) { + this._performUpdateSource(true); + this.stage.removeUpdateSourceTexture(this); + } + return this._source; + } + addElement(v) { + if (!this.elements.has(v)) { + this.elements.add(v); + if (this.elements.size === 1) { + if (this._source) { + this._source.addTexture(this); + } + } + if (v.active) { + this.incActiveCount(); + } + } + } + removeElement(v) { + if (this.elements.delete(v)) { + if (this.elements.size === 0) { + if (this._source) { + this._source.removeTexture(this); + } + } + if (v.active) { + this.decActiveCount(); + } + } + } + incActiveCount() { + const source = this.source; + if (source) { + this._checkForNewerReusableTextureSource(); + } + this._activeCount++; + if (this._activeCount === 1) { + this.becomesUsed(); + } + } + decActiveCount() { + this.source; + this._activeCount--; + if (!this._activeCount) { + this.becomesUnused(); + } + } + becomesUsed() { + if (this.source) { + this.source.incActiveTextureCount(); + } + } + onLoad() { + if (this._resizeMode) { + this._applyResizeMode(); + } + this.elements.forEach((element) => { + if (element.active) { + element.onTextureSourceLoaded(); + } + }); + } + _checkForNewerReusableTextureSource() { + const source = this.source; + if (!source.isLoaded()) { + const reusable = this._getReusableTextureSource(); + if (reusable && reusable.isLoaded() && reusable !== source) { + this._replaceTextureSource(reusable); + } + } else { + if (this._resizeMode) { + this._applyResizeMode(); + } + } + } + becomesUnused() { + if (this.source) { + this.source.decActiveTextureCount(); + } + } + isUsed() { + return this._activeCount > 0; + } + _getLookupId() { + return null; + } + _getSourceLoader() { + throw new Error("Texture.generate must be implemented."); + } + get isValid() { + return this._getIsValid(); + } + _getIsValid() { + return true; + } + _changed() { + if (this.isUsed()) { + this._updateSource(); + } else { + this._mustUpdate = true; + } + } + _updateSource() { + this.stage.addUpdateSourceTexture(this); + } + _performUpdateSource(force = false) { + if (force || this.isUsed()) { + this._mustUpdate = false; + let source = this._getTextureSource(); + this._replaceTextureSource(source); + } + } + _getTextureSource() { + let source = null; + if (this._getIsValid()) { + const lookupId = this._getLookupId(); + source = this._getReusableTextureSource(lookupId); + if (!source) { + source = this.manager.getTextureSource(this._getSourceLoader(), lookupId); + } + } + return source; + } + _getReusableTextureSource(lookupId = this._getLookupId()) { + if (this._getIsValid()) { + if (lookupId) { + return this.manager.getReusableTextureSource(lookupId); + } + } + return null; + } + _replaceTextureSource(newSource = null) { + let oldSource = this._source; + this._source = newSource; + if (this.elements.size) { + if (oldSource) { + if (this._activeCount) { + oldSource.decActiveTextureCount(); + } + oldSource.removeTexture(this); + if (this["text"] && !oldSource.isUsed()) { + this.manager.freeTextureSource(oldSource); + } + } + if (newSource) { + newSource.addTexture(this); + if (this._activeCount) { + newSource.incActiveTextureCount(); + } + } + } + if (this.isUsed()) { + if (newSource) { + if (newSource.isLoaded()) { + if (this._resizeMode) { + this._applyResizeMode(); + } + this.elements.forEach((element) => { + if (element.active) { + element._setDisplayedTexture(this); + } + }); + } else { + const loadError = newSource.loadError; + if (loadError) { + this.elements.forEach((element) => { + if (element.active) { + element.onTextureSourceLoadError(loadError); + } + }); + } + } + } else { + this.elements.forEach((element) => { + if (element.active) { + element._setDisplayedTexture(null); + } + }); + } + } + } + load() { + if (this.source) { + if (!this.isLoaded()) { + this.source.load(true); + } + } + } + isLoaded() { + return this._source && this._source.isLoaded(); + } + get loadError() { + return this._source && this._source.loadError; + } + free() { + if (this._source) { + this._source.free(); + } + } + set resizeMode({ type = "cover", w = 0, h = 0, clipX = 0.5, clipY = 0.5 }) { + this._resizeMode = { type, w, h, clipX, clipY }; + if (this.isLoaded()) { + this._applyResizeMode(); + } + } + get resizeMode() { + return this._resizeMode; + } + _clearResizeMode() { + this._resizeMode = null; + } + _applyResizeMode() { + if (this._resizeMode.type === "cover") { + this._applyResizeCover(); + } else if (this._resizeMode.type === "contain") { + this._applyResizeContain(); + } + this._updatePrecision(); + this._updateClipping(); + } + _applyResizeCover() { + const scaleX = this._resizeMode.w / this._source.w; + const scaleY = this._resizeMode.h / this._source.h; + let scale = Math.max(scaleX, scaleY); + if (!scale) + return; + this._precision = 1 / scale; + if (scaleX && scaleX < scale) { + const desiredSize = this._precision * this._resizeMode.w; + const choppedOffPixels = this._source.w - desiredSize; + this._x = choppedOffPixels * this._resizeMode.clipX; + this._w = this._source.w - choppedOffPixels; + } + if (scaleY && scaleY < scale) { + const desiredSize = this._precision * this._resizeMode.h; + const choppedOffPixels = this._source.h - desiredSize; + this._y = choppedOffPixels * this._resizeMode.clipY; + this._h = this._source.h - choppedOffPixels; + } + } + _applyResizeContain() { + const scaleX = this._resizeMode.w / this._source.w; + const scaleY = this._resizeMode.h / this._source.h; + let scale = scaleX; + if (!scale || scaleY < scale) { + scale = scaleY; + } + if (!scale) + return; + this._precision = 1 / scale; + } + enableClipping(x, y, w, h) { + this._clearResizeMode(); + x *= this._precision; + y *= this._precision; + w *= this._precision; + h *= this._precision; + if (this._x !== x || this._y !== y || this._w !== w || this._h !== h) { + this._x = x; + this._y = y; + this._w = w; + this._h = h; + this._updateClipping(true); + } + } + disableClipping() { + this._clearResizeMode(); + if (this._x || this._y || this._w || this._h) { + this._x = 0; + this._y = 0; + this._w = 0; + this._h = 0; + this._updateClipping(); + } + } + _updateClipping() { + this.clipping = !!(this._x || this._y || this._w || this._h); + let self = this; + this.elements.forEach(function(element) { + if (element.displayedTexture === self) { + element.onDisplayedTextureClippingChanged(); + } + }); + } + _updatePrecision() { + let self = this; + this.elements.forEach(function(element) { + if (element.displayedTexture === self) { + element.onPrecisionChanged(); + } + }); + } + getNonDefaults() { + let nonDefaults = {}; + nonDefaults["type"] = this.constructor.name; + if (this.x !== 0) + nonDefaults["x"] = this.x; + if (this.y !== 0) + nonDefaults["y"] = this.y; + if (this.w !== 0) + nonDefaults["w"] = this.w; + if (this.h !== 0) + nonDefaults["h"] = this.h; + if (this.precision !== 1) + nonDefaults["precision"] = this.precision; + return nonDefaults; + } + get px() { + return this._x; + } + get py() { + return this._y; + } + get pw() { + return this._w; + } + get ph() { + return this._h; + } + get x() { + return this._x / this._precision; + } + set x(v) { + this._clearResizeMode(); + v = v * this._precision; + if (this._x !== v) { + this._x = v; + this._updateClipping(); + } + } + get y() { + return this._y / this._precision; + } + set y(v) { + this._clearResizeMode(); + v = v * this._precision; + if (this._y !== v) { + this._y = v; + this._updateClipping(); + } + } + get w() { + return this._w / this._precision; + } + set w(v) { + this._clearResizeMode(); + v = v * this._precision; + if (this._w !== v) { + this._w = v; + this._updateClipping(); + } + } + get h() { + return this._h / this._precision; + } + set h(v) { + this._clearResizeMode(); + v = v * this._precision; + if (this._h !== v) { + this._h = v; + this._updateClipping(); + } + } + get precision() { + return this._precision; + } + set precision(v) { + this._clearResizeMode(); + if (this._precision !== v) { + this._precision = v; + this._updatePrecision(); + } + } + isAutosizeTexture() { + return true; + } + getRenderWidth() { + if (!this.isAutosizeTexture()) { + return 0; + } + return (this._w || (this._source ? this._source.getRenderWidth() - this._x : 0)) / this._precision; + } + getRenderHeight() { + if (!this.isAutosizeTexture()) { + return 0; + } + return (this._h || (this._source ? this._source.getRenderHeight() - this._y : 0)) / this._precision; + } + patch(settings) { + Base.patchObject(this, settings); + } +} +Texture.prototype.isTexture = true; +Texture.id = 0; +class ImageTexture extends Texture { + constructor(stage) { + super(stage); + this._src = void 0; + this._hasAlpha = false; + } + get src() { + return this._src; + } + set src(v) { + if (this._src !== v) { + this._src = v; + this._changed(); + } + } + get hasAlpha() { + return this._hasAlpha; + } + set hasAlpha(v) { + if (this._hasAlpha !== v) { + this._hasAlpha = v; + this._changed(); + } + } + _getIsValid() { + return !!this._src; + } + _getLookupId() { + return this._src; + } + _getSourceLoader() { + let src = this._src; + let hasAlpha = this._hasAlpha; + if (this.stage.getOption("srcBasePath")) { + var fc = src.charCodeAt(0); + if (src.indexOf("//") === -1 && (fc >= 65 && fc <= 90 || fc >= 97 && fc <= 122 || fc == 46)) { + src = this.stage.getOption("srcBasePath") + src; + } + } + return (cb) => { + return this.stage.platform.loadSrcTexture({ src, hasAlpha }, cb); + }; + } + getNonDefaults() { + const obj = super.getNonDefaults(); + if (this._src) { + obj.src = this._src; + } + return obj; + } +} +function getFontSetting(fontFace, fontStyle, fontSize, precision, defaultFontFace) { + let ff = fontFace; + if (!Array.isArray(ff)) { + ff = [ff]; + } + let ffs = []; + for (let i = 0, n = ff.length; i < n; i++) { + let curFf = ff[i]; + if (curFf === null) { + curFf = defaultFontFace; + } + if (curFf === "serif" || curFf === "sans-serif") { + ffs.push(curFf); + } else { + ffs.push(`"${curFf}"`); + } + } + return `${fontStyle} ${fontSize * precision}px ${ffs.join(",")}`; +} +function isZeroWidthSpace(space) { + return space === "" || space === "​"; +} +function isSpace(space) { + return isZeroWidthSpace(space) || space === " "; +} +function tokenizeString(tokenRegex, text) { + const delimeters = text.match(tokenRegex) || []; + const words = text.split(tokenRegex) || []; + let final = []; + for (let i = 0; i < words.length; i++) { + final.push(words[i], delimeters[i]); + } + final.pop(); + return final.filter((word) => word != ""); +} +function measureText(context, word, space = 0) { + if (!space) { + return context.measureText(word).width; + } + return word.split("").reduce((acc, char) => { + if (isZeroWidthSpace(char)) { + return acc; + } + return acc + context.measureText(char).width + space; + }, 0); +} +function wrapText(context, text, wordWrapWidth, letterSpacing, indent) { + const spaceRegex = / |\u200B/g; + let lines = text.split(/\r?\n/g); + let allLines = []; + let realNewlines = []; + for (let i = 0; i < lines.length; i++) { + let resultLines = []; + let result = ""; + let spaceLeft = wordWrapWidth - indent; + let words = lines[i].split(spaceRegex); + let spaces = lines[i].match(spaceRegex) || []; + for (let j = 0; j < words.length; j++) { + const space = spaces[j - 1] || ""; + const word = words[j]; + const wordWidth = measureText(context, word, letterSpacing); + const wordWidthWithSpace = wordWidth + measureText(context, space, letterSpacing); + if (j === 0 || wordWidthWithSpace > spaceLeft) { + if (j > 0) { + resultLines.push(result); + result = ""; + } + result += word; + spaceLeft = wordWrapWidth - wordWidth - (j === 0 ? indent : 0); + } else { + spaceLeft -= wordWidthWithSpace; + result += space + word; + } + } + resultLines.push(result); + result = ""; + allLines = allLines.concat(resultLines); + if (i < lines.length - 1) { + realNewlines.push(allLines.length); + } + } + return { l: allLines, n: realNewlines }; +} +class TextTextureRenderer { + constructor(stage, canvas, settings) { + this._stage = stage; + this._canvas = canvas; + this._context = this._canvas.getContext("2d"); + this._settings = settings; + } + getPrecision() { + return this._settings.precision; + } + setFontProperties() { + this._context.font = getFontSetting( + this._settings.fontFace, + this._settings.fontStyle, + this._settings.fontSize, + this.getPrecision(), + this._stage.getOption("defaultFontFace") + ); + this._context.textBaseline = this._settings.textBaseline; + } + _load() { + if (Utils$1.isWeb && document.fonts) { + const fontSetting = getFontSetting( + this._settings.fontFace, + this._settings.fontStyle, + this._settings.fontSize, + this.getPrecision(), + this._stage.getOption("defaultFontFace") + ); + try { + if (!document.fonts.check(fontSetting, this._settings.text)) { + return document.fonts.load(fontSetting, this._settings.text).catch((err) => { + console.warn("[Lightning] Font load error", err, fontSetting); + }).then(() => { + if (!document.fonts.check(fontSetting, this._settings.text)) { + console.warn("[Lightning] Font not found", fontSetting); + } + }); + } + } catch (e) { + console.warn("[Lightning] Can't check font loading for " + fontSetting); + } + } + } + draw() { + const loadPromise = this._load(); + if (!loadPromise) { + return Utils$1.isSpark ? this._stage.platform.drawText(this) : this._draw(); + } else { + return loadPromise.then(() => { + return Utils$1.isSpark ? this._stage.platform.drawText(this) : this._draw(); + }); + } + } + _calculateRenderInfo() { + let renderInfo = {}; + const precision = this.getPrecision(); + const paddingLeft = this._settings.paddingLeft * precision; + const paddingRight = this._settings.paddingRight * precision; + const fontSize = this._settings.fontSize * precision; + let offsetY = this._settings.offsetY === null ? null : this._settings.offsetY * precision; + let lineHeight = this._settings.lineHeight * precision; + const w = this._settings.w * precision; + const h = this._settings.h * precision; + let wordWrapWidth = this._settings.wordWrapWidth * precision; + const cutSx = this._settings.cutSx * precision; + const cutEx = this._settings.cutEx * precision; + const cutSy = this._settings.cutSy * precision; + const cutEy = this._settings.cutEy * precision; + const letterSpacing = (this._settings.letterSpacing || 0) * precision; + const textIndent = this._settings.textIndent * precision; + this.setFontProperties(); + let width = w || this._stage.getOption("w"); + let innerWidth = width - paddingLeft; + if (innerWidth < 10) { + width += 10 - innerWidth; + innerWidth = 10; + } + if (!wordWrapWidth) { + wordWrapWidth = innerWidth; + } + if (this._settings.textOverflow && !this._settings.wordWrap) { + let suffix; + switch (this._settings.textOverflow) { + case "clip": + suffix = ""; + break; + case "ellipsis": + suffix = this._settings.maxLinesSuffix; + break; + default: + suffix = this._settings.textOverflow; + } + this._settings.text = this.wrapWord(this._settings.text, wordWrapWidth - textIndent, suffix); + } + let linesInfo; + if (this._settings.wordWrap) { + linesInfo = this.wrapText(this._settings.text, wordWrapWidth, letterSpacing, textIndent); + } else { + linesInfo = { l: this._settings.text.split(/(?:\r\n|\r|\n)/), n: [] }; + let n = linesInfo.l.length; + for (let i = 0; i < n - 1; i++) { + linesInfo.n.push(i); + } + } + let lines = linesInfo.l; + if (this._settings.maxLines && lines.length > this._settings.maxLines) { + let usedLines = lines.slice(0, this._settings.maxLines); + let otherLines = null; + if (this._settings.maxLinesSuffix) { + let w2 = this._settings.maxLinesSuffix ? this.measureText(this._settings.maxLinesSuffix) : 0; + let al = this.wrapText(usedLines[usedLines.length - 1], wordWrapWidth - w2, letterSpacing, textIndent); + usedLines[usedLines.length - 1] = al.l[0] + this._settings.maxLinesSuffix; + otherLines = [al.l.length > 1 ? al.l[1] : ""]; + } else { + otherLines = [""]; + } + let i, n = lines.length; + let j = 0; + let m = linesInfo.n.length; + for (i = this._settings.maxLines; i < n; i++) { + otherLines[j] += (otherLines[j] ? " " : "") + lines[i]; + if (i + 1 < m && linesInfo.n[i + 1]) { + j++; + } + } + renderInfo.remainingText = otherLines.join("\n"); + renderInfo.moreTextLines = true; + lines = usedLines; + } else { + renderInfo.moreTextLines = false; + renderInfo.remainingText = ""; + } + let maxLineWidth = 0; + let lineWidths = []; + for (let i = 0; i < lines.length; i++) { + let lineWidth = this.measureText(lines[i], letterSpacing) + (i === 0 ? textIndent : 0); + lineWidths.push(lineWidth); + maxLineWidth = Math.max(maxLineWidth, lineWidth); + } + renderInfo.lineWidths = lineWidths; + if (!w) { + width = maxLineWidth + paddingLeft + paddingRight; + innerWidth = maxLineWidth; + } + lineHeight = lineHeight || fontSize; + let height; + if (h) { + height = h; + } else { + const baselineOffset = this._settings.textBaseline != "bottom" ? 0.5 * fontSize : 0; + height = lineHeight * (lines.length - 1) + baselineOffset + Math.max(lineHeight, fontSize) + offsetY; + } + if (offsetY === null) { + offsetY = fontSize; + } + renderInfo.w = width; + renderInfo.h = height; + renderInfo.lines = lines; + renderInfo.precision = precision; + if (!width) { + width = 1; + } + if (!height) { + height = 1; + } + if (cutSx || cutEx) { + width = Math.min(width, cutEx - cutSx); + } + if (cutSy || cutEy) { + height = Math.min(height, cutEy - cutSy); + } + renderInfo.width = width; + renderInfo.innerWidth = innerWidth; + renderInfo.height = height; + renderInfo.fontSize = fontSize; + renderInfo.cutSx = cutSx; + renderInfo.cutSy = cutSy; + renderInfo.cutEx = cutEx; + renderInfo.cutEy = cutEy; + renderInfo.lineHeight = lineHeight; + renderInfo.lineWidths = lineWidths; + renderInfo.offsetY = offsetY; + renderInfo.paddingLeft = paddingLeft; + renderInfo.paddingRight = paddingRight; + renderInfo.letterSpacing = letterSpacing; + renderInfo.textIndent = textIndent; + return renderInfo; + } + _draw() { + const renderInfo = this._calculateRenderInfo(); + const precision = this.getPrecision(); + this._canvas.width = Math.ceil(renderInfo.width + this._stage.getOption("textRenderIssueMargin")); + this._canvas.height = Math.ceil(renderInfo.height); + this.setFontProperties(); + if (renderInfo.fontSize >= 128) { + this._context.globalAlpha = 0.01; + this._context.fillRect(0, 0, 0.01, 0.01); + this._context.globalAlpha = 1; + } + if (renderInfo.cutSx || renderInfo.cutSy) { + this._context.translate(-renderInfo.cutSx, -renderInfo.cutSy); + } + let linePositionX; + let linePositionY; + let drawLines = []; + for (let i = 0, n = renderInfo.lines.length; i < n; i++) { + linePositionX = i === 0 ? renderInfo.textIndent : 0; + linePositionY = i * renderInfo.lineHeight + renderInfo.offsetY; + if (this._settings.verticalAlign == "middle") { + linePositionY += (renderInfo.lineHeight - renderInfo.fontSize) / 2; + } else if (this._settings.verticalAlign == "bottom") { + linePositionY += renderInfo.lineHeight - renderInfo.fontSize; + } + if (this._settings.textAlign === "right") { + linePositionX += renderInfo.innerWidth - renderInfo.lineWidths[i]; + } else if (this._settings.textAlign === "center") { + linePositionX += (renderInfo.innerWidth - renderInfo.lineWidths[i]) / 2; + } + linePositionX += renderInfo.paddingLeft; + drawLines.push({ text: renderInfo.lines[i], x: linePositionX, y: linePositionY, w: renderInfo.lineWidths[i] }); + } + if (this._settings.highlight) { + let color = this._settings.highlightColor || 0; + let hlHeight = this._settings.highlightHeight * precision || renderInfo.fontSize * 1.5; + const offset = this._settings.highlightOffset * precision; + const hlPaddingLeft = this._settings.highlightPaddingLeft !== null ? this._settings.highlightPaddingLeft * precision : renderInfo.paddingLeft; + const hlPaddingRight = this._settings.highlightPaddingRight !== null ? this._settings.highlightPaddingRight * precision : renderInfo.paddingRight; + this._context.fillStyle = StageUtils.getRgbaString(color); + for (let i = 0; i < drawLines.length; i++) { + let drawLine = drawLines[i]; + this._context.fillRect(drawLine.x - hlPaddingLeft, drawLine.y - renderInfo.offsetY + offset, drawLine.w + hlPaddingRight + hlPaddingLeft, hlHeight); + } + } + let prevShadowSettings = null; + if (this._settings.shadow) { + prevShadowSettings = [this._context.shadowColor, this._context.shadowOffsetX, this._context.shadowOffsetY, this._context.shadowBlur]; + this._context.shadowColor = StageUtils.getRgbaString(this._settings.shadowColor); + this._context.shadowOffsetX = this._settings.shadowOffsetX * precision; + this._context.shadowOffsetY = this._settings.shadowOffsetY * precision; + this._context.shadowBlur = this._settings.shadowBlur * precision; + } + this._context.fillStyle = StageUtils.getRgbaString(this._settings.textColor); + for (let i = 0, n = drawLines.length; i < n; i++) { + let drawLine = drawLines[i]; + if (renderInfo.letterSpacing === 0) { + this._context.fillText(drawLine.text, drawLine.x, drawLine.y); + } else { + const textSplit = drawLine.text.split(""); + let x = drawLine.x; + for (let i2 = 0, j = textSplit.length; i2 < j; i2++) { + this._context.fillText(textSplit[i2], x, drawLine.y); + x += this.measureText(textSplit[i2], renderInfo.letterSpacing); + } + } + } + if (prevShadowSettings) { + this._context.shadowColor = prevShadowSettings[0]; + this._context.shadowOffsetX = prevShadowSettings[1]; + this._context.shadowOffsetY = prevShadowSettings[2]; + this._context.shadowBlur = prevShadowSettings[3]; + } + if (renderInfo.cutSx || renderInfo.cutSy) { + this._context.translate(renderInfo.cutSx, renderInfo.cutSy); + } + this.renderInfo = renderInfo; + } + wrapWord(word, wordWrapWidth, suffix) { + const suffixWidth = this.measureText(suffix); + const wordLen = word.length; + const wordWidth = this.measureText(word); + if (wordWidth <= wordWrapWidth) { + return word; + } + let cutoffIndex = Math.floor(wordWrapWidth * wordLen / wordWidth); + let truncWordWidth = this.measureText(word.substring(0, cutoffIndex)) + suffixWidth; + if (truncWordWidth > wordWrapWidth) { + while (cutoffIndex > 0) { + truncWordWidth = this.measureText(word.substring(0, cutoffIndex)) + suffixWidth; + if (truncWordWidth > wordWrapWidth) { + cutoffIndex -= 1; + } else { + break; + } + } + } else { + while (cutoffIndex < wordLen) { + truncWordWidth = this.measureText(word.substring(0, cutoffIndex)) + suffixWidth; + if (truncWordWidth < wordWrapWidth) { + cutoffIndex += 1; + } else { + cutoffIndex -= 1; + break; + } + } + } + return word.substring(0, cutoffIndex) + (wordWrapWidth >= suffixWidth ? suffix : ""); + } + wrapText(text, wordWrapWidth, letterSpacing, indent = 0) { + return wrapText(this._context, text, wordWrapWidth, letterSpacing, indent); + } + measureText(word, space = 0) { + return measureText(this._context, word, space); + } +} +class TextTextureRendererAdvanced { + constructor(stage, canvas, settings) { + this._stage = stage; + this._canvas = canvas; + this._context = this._canvas.getContext("2d"); + this._settings = settings; + } + getPrecision() { + return this._settings.precision; + } + setFontProperties() { + const font = getFontSetting( + this._settings.fontFace, + this._settings.fontStyle, + this._settings.fontSize, + this.getPrecision(), + this._stage.getOption("defaultFontFace") + ); + this._context.font = font; + this._context.textBaseline = this._settings.textBaseline; + return font; + } + _load() { + if (Utils$1.isWeb && document.fonts) { + const fontSetting = getFontSetting( + this._settings.fontFace, + this._settings.fontStyle, + this._settings.fontSize, + this.getPrecision(), + this._stage.getOption("defaultFontFace") + ); + try { + if (!document.fonts.check(fontSetting, this._settings.text)) { + return document.fonts.load(fontSetting, this._settings.text).catch((err) => { + console.warn("Font load error", err, fontSetting); + }).then(() => { + if (!document.fonts.check(fontSetting, this._settings.text)) { + console.warn("Font not found", fontSetting); + } + }); + } + } catch (e) { + console.warn("Can't check font loading for " + fontSetting); + } + } + } + draw() { + const loadPromise = this._load(); + if (!loadPromise) { + return Utils$1.isSpark ? this._stage.platform.drawText(this) : this._draw(); + } else { + return loadPromise.then(() => { + return Utils$1.isSpark ? this._stage.platform.drawText(this) : this._draw(); + }); + } + } + _calculateRenderInfo() { + let renderInfo = {}; + const precision = this.getPrecision(); + const paddingLeft = this._settings.paddingLeft * precision; + const paddingRight = this._settings.paddingRight * precision; + const fontSize = this._settings.fontSize * precision; + const lineHeight = this._settings.lineHeight * precision || fontSize; + const w = this._settings.w != 0 ? this._settings.w * precision : this._stage.getOption("w"); + const wordWrapWidth = this._settings.wordWrapWidth * precision; + const cutSx = this._settings.cutSx * precision; + const cutEx = this._settings.cutEx * precision; + const cutSy = this._settings.cutSy * precision; + const cutEy = this._settings.cutEy * precision; + const letterSpacing = this._settings.letterSpacing || 0; + renderInfo.baseFont = this.setFontProperties(); + renderInfo.w = w; + renderInfo.width = w; + renderInfo.text = this._settings.text; + renderInfo.precision = precision; + renderInfo.fontSize = fontSize; + renderInfo.fontBaselineRatio = this._settings.fontBaselineRatio; + renderInfo.lineHeight = lineHeight; + renderInfo.letterSpacing = letterSpacing; + renderInfo.textAlign = this._settings.textAlign; + renderInfo.textColor = this._settings.textColor; + renderInfo.verticalAlign = this._settings.verticalAlign; + renderInfo.highlight = this._settings.highlight; + renderInfo.highlightColor = this._settings.highlightColor; + renderInfo.highlightHeight = this._settings.highlightHeight; + renderInfo.highlightPaddingLeft = this._settings.highlightPaddingLeft; + renderInfo.highlightPaddingRight = this._settings.highlightPaddingRight; + renderInfo.highlightOffset = this._settings.highlightOffset; + renderInfo.paddingLeft = this._settings.paddingLeft; + renderInfo.paddingRight = this._settings.paddingRight; + renderInfo.maxLines = this._settings.maxLines; + renderInfo.maxLinesSuffix = this._settings.maxLinesSuffix; + renderInfo.textOverflow = this._settings.textOverflow; + renderInfo.wordWrap = this._settings.wordWrap; + renderInfo.wordWrapWidth = wordWrapWidth; + renderInfo.shadow = this._settings.shadow; + renderInfo.shadowColor = this._settings.shadowColor; + renderInfo.shadowOffsetX = this._settings.shadowOffsetX; + renderInfo.shadowOffsetY = this._settings.shadowOffsetY; + renderInfo.shadowBlur = this._settings.shadowBlur; + renderInfo.cutSx = cutSx; + renderInfo.cutEx = cutEx; + renderInfo.cutSy = cutSy; + renderInfo.cutEy = cutEy; + renderInfo.textIndent = this._settings.textIndent * precision; + renderInfo.wordBreak = this._settings.wordBreak; + let text = renderInfo.text; + let wrapWidth = renderInfo.wordWrap ? renderInfo.wordWrapWidth || renderInfo.width : renderInfo.width; + if (renderInfo.textOverflow && !renderInfo.wordWrap) { + let suffix; + switch (this._settings.textOverflow) { + case "clip": + suffix = ""; + break; + case "ellipsis": + suffix = this._settings.maxLinesSuffix; + break; + default: + suffix = this._settings.textOverflow; + } + text = this.wrapWord(text, wordWrapWidth || renderInfo.w, suffix); + } + text = this.tokenize(text); + text = this.parse(text); + text = this.measure(text, letterSpacing, renderInfo.baseFont); + if (renderInfo.textIndent) { + text = this.indent(text, renderInfo.textIndent); + } + if (renderInfo.wordBreak) { + text = text.reduce((acc, t) => acc.concat(this.wordBreak(t, wrapWidth, renderInfo.baseFont)), []); + this.resetFontStyle(); + } + let x = paddingLeft; + let lineNo = 0; + for (const t of text) { + if (renderInfo.wordWrap && x + t.width > wrapWidth || t.text == "\n") { + x = paddingLeft; + lineNo += 1; + } + t.lineNo = lineNo; + if (t.text == "\n") { + continue; + } + t.x = x; + x += t.width; + } + renderInfo.lineNum = lineNo + 1; + if (this._settings.h) { + renderInfo.h = this._settings.h; + } else if (renderInfo.maxLines && renderInfo.maxLines < renderInfo.lineNum) { + renderInfo.h = renderInfo.maxLines * renderInfo.lineHeight + fontSize / 2; + } else { + renderInfo.h = renderInfo.lineNum * renderInfo.lineHeight + fontSize / 2; + } + const baselineOffsetInPx = renderInfo.fontBaselineRatio * renderInfo.fontSize; + let vaOffset = 0; + if (renderInfo.verticalAlign == "top" && this._context.textBaseline == "alphabetic") { + vaOffset = -baselineOffsetInPx; + } else if (renderInfo.verticalAlign == "middle") { + vaOffset = (renderInfo.lineHeight - renderInfo.fontSize - baselineOffsetInPx) / 2; + } else if (this._settings.verticalAlign == "bottom") { + vaOffset = renderInfo.lineHeight - renderInfo.fontSize; + } + renderInfo.lines = []; + for (let i = 0; i < renderInfo.lineNum; i++) { + renderInfo.lines[i] = { + width: 0, + x: 0, + y: renderInfo.lineHeight * i + vaOffset, + text: [] + }; + } + for (let t of text) { + renderInfo.lines[t.lineNo].text.push(t); + } + for (const l of renderInfo.lines) { + if (l.text.length == 0) { + continue; + } + const firstWord = l.text[0].text; + const lastWord = l.text[l.text.length - 1].text; + if (firstWord == "\n") { + l.text.shift(); + } + if (isSpace(lastWord) || lastWord == "\n") { + l.text.pop(); + } + } + for (let l of renderInfo.lines) { + l.width = l.text.reduce((acc, t) => acc + t.width, 0); + } + renderInfo.width = this._settings.w != 0 ? this._settings.w * precision : Math.max(...renderInfo.lines.map((l) => l.width)) + paddingRight; + renderInfo.w = renderInfo.width; + if (renderInfo.maxLines && renderInfo.lineNum > renderInfo.maxLines && renderInfo.maxLinesSuffix) { + const index = renderInfo.maxLines - 1; + let lastLineText = text.filter((t) => t.lineNo == index); + let suffix = renderInfo.maxLinesSuffix; + suffix = this.tokenize(suffix); + suffix = this.parse(suffix); + suffix = this.measure(suffix, renderInfo.letterSpacing, renderInfo.baseFont); + for (const s of suffix) { + s.lineNo = index; + s.x = 0; + lastLineText.push(s); + } + const spl = suffix.length + 1; + let _w = lastLineText.reduce((acc, t) => acc + t.width, 0); + while (_w > renderInfo.width || isSpace(lastLineText[lastLineText.length - spl].text)) { + lastLineText.splice(lastLineText.length - spl, 1); + _w = lastLineText.reduce((acc, t) => acc + t.width, 0); + if (lastLineText.length < spl) { + break; + } + } + this.alignLine(lastLineText, lastLineText[0].x); + renderInfo.lines[index].text = lastLineText; + renderInfo.lines[index].width = _w; + } + if (renderInfo.textAlign == "center") { + for (let l of renderInfo.lines) { + l.x = (renderInfo.width - l.width - paddingLeft) / 2; + } + } else if (renderInfo.textAlign == "right") { + for (let l of renderInfo.lines) { + l.x = renderInfo.width - l.width - paddingLeft; + } + } + return renderInfo; + } + _draw() { + const renderInfo = this._calculateRenderInfo(); + const precision = this.getPrecision(); + const paddingLeft = renderInfo.paddingLeft * precision; + let canvasWidth = renderInfo.w || renderInfo.width; + if (renderInfo.cutSx || renderInfo.cutEx) { + canvasWidth = Math.min(renderInfo.w, renderInfo.cutEx - renderInfo.cutSx); + } + let canvasHeight = renderInfo.h; + if (renderInfo.cutSy || renderInfo.cutEy) { + canvasHeight = Math.min(renderInfo.h, renderInfo.cutEy - renderInfo.cutSy); + } + this._canvas.width = Math.ceil(canvasWidth + this._stage.getOption("textRenderIssueMargin")); + this._canvas.height = Math.ceil(canvasHeight); + this.setFontProperties(); + if (renderInfo.fontSize >= 128) { + this._context.globalAlpha = 0.01; + this._context.fillRect(0, 0, 0.01, 0.01); + this._context.globalAlpha = 1; + } + if (renderInfo.cutSx || renderInfo.cutSy) { + this._context.translate(-renderInfo.cutSx, -renderInfo.cutSy); + } + if (renderInfo.highlight) { + const hlColor = renderInfo.highlightColor || 0; + const hlHeight = renderInfo.highlightHeight ? renderInfo.highlightHeight * precision : renderInfo.fontSize * 1.5; + const hlOffset = renderInfo.highlightOffset ? renderInfo.highlightOffset * precision : 0; + const hlPaddingLeft = renderInfo.highlightPaddingLeft !== null ? renderInfo.highlightPaddingLeft * precision : renderInfo.paddingLeft; + const hlPaddingRight = renderInfo.highlightPaddingRight !== null ? renderInfo.highlightPaddingRight * precision : renderInfo.paddingRight; + this._context.fillStyle = StageUtils.getRgbaString(hlColor); + const lineNum = renderInfo.maxLines ? Math.min(renderInfo.maxLines, renderInfo.lineNum) : renderInfo.lineNum; + for (let i = 0; i < lineNum; i++) { + const l = renderInfo.lines[i]; + this._context.fillRect(l.x - hlPaddingLeft + paddingLeft, l.y + hlOffset, l.width + hlPaddingLeft + hlPaddingRight, hlHeight); + } + } + let prevShadowSettings = null; + if (this._settings.shadow) { + prevShadowSettings = [this._context.shadowColor, this._context.shadowOffsetX, this._context.shadowOffsetY, this._context.shadowBlur]; + this._context.shadowColor = StageUtils.getRgbaString(this._settings.shadowColor); + this._context.shadowOffsetX = this._settings.shadowOffsetX * precision; + this._context.shadowOffsetY = this._settings.shadowOffsetY * precision; + this._context.shadowBlur = this._settings.shadowBlur * precision; + } + const defaultColor = StageUtils.getRgbaString(this._settings.textColor); + let currentColor = defaultColor; + this._context.fillStyle = defaultColor; + for (const line of renderInfo.lines) { + for (const t of line.text) { + let lx = 0; + if (t.text == "\n") { + continue; + } + if (renderInfo.maxLines && t.lineNo >= renderInfo.maxLines) { + continue; + } + if (t.color != currentColor) { + currentColor = t.color; + this._context.fillStyle = currentColor; + } + this._context.font = t.fontStyle; + if (t.letters) { + for (let l of t.letters) { + const _x = renderInfo.lines[t.lineNo].x + t.x + lx; + this._context.fillText(l.text, _x, renderInfo.lines[t.lineNo].y + renderInfo.fontSize); + lx += l.width; + } + } else { + const _x = renderInfo.lines[t.lineNo].x + t.x; + this._context.fillText(t.text, _x, renderInfo.lines[t.lineNo].y + renderInfo.fontSize); + } + } + } + if (prevShadowSettings) { + this._context.shadowColor = prevShadowSettings[0]; + this._context.shadowOffsetX = prevShadowSettings[1]; + this._context.shadowOffsetY = prevShadowSettings[2]; + this._context.shadowBlur = prevShadowSettings[3]; + } + if (renderInfo.cutSx || renderInfo.cutSy) { + this._context.translate(renderInfo.cutSx, renderInfo.cutSy); + } + renderInfo.lines = renderInfo.lines.map((l) => l.text.reduce((acc, v) => acc + v.text, "")); + if (renderInfo.maxLines) { + renderInfo.lines = renderInfo.lines.slice(0, renderInfo.maxLines); + } + this.renderInfo = renderInfo; + } + measureText(word, space = 0) { + return measureText(this._context, word, space); + } + tokenize(text) { + return tokenizeString(/ |\u200B|\n||<\/i>||<\/b>||<\/color>/g, text); + } + parse(tokens) { + let italic = 0; + let bold = 0; + let colorStack = [StageUtils.getRgbaString(this._settings.textColor)]; + let color = 0; + const colorRegexp = //; + return tokens.map((t) => { + if (t == "") { + italic += 1; + t = ""; + } else if (t == "" && italic > 0) { + italic -= 1; + t = ""; + } else if (t == "") { + bold += 1; + t = ""; + } else if (t == "" && bold > 0) { + bold -= 1; + t = ""; + } else if (t == "") { + if (colorStack.length > 1) { + color -= 1; + colorStack.pop(); + } + t = ""; + } else if (colorRegexp.test(t)) { + const matched = colorRegexp.exec(t); + colorStack.push( + StageUtils.getRgbaString(parseInt(matched[1])) + ); + color += 1; + t = ""; + } + return { + text: t, + italic, + bold, + color: colorStack[color] + }; + }).filter((o) => o.text != ""); + } + applyFontStyle(word, baseFont) { + let font = baseFont; + if (word.bold) { + font = "bold " + font; + } + if (word.italic) { + font = "italic " + font; + } + this._context.font = font; + word.fontStyle = font; + } + resetFontStyle(baseFont) { + this._context.font = baseFont; + } + measure(parsed, letterSpacing = 0, baseFont) { + for (const p of parsed) { + this.applyFontStyle(p, baseFont); + p.width = this.measureText(p.text, letterSpacing); + if (letterSpacing > 0) { + p.letters = p.text.split("").map((l) => { + return { text: l }; + }); + for (let l of p.letters) { + l.width = this.measureText(l.text, letterSpacing); + } + } + } + this.resetFontStyle(baseFont); + return parsed; + } + indent(parsed, textIndent) { + parsed.splice(0, 0, { text: "", width: textIndent }); + return parsed; + } + wrapWord(word, wordWrapWidth, suffix) { + const suffixWidth = this.measureText(suffix); + const wordLen = word.length; + const wordWidth = this.measureText(word); + if (wordWidth <= wordWrapWidth) { + return word; + } + let cutoffIndex = Math.floor(wordWrapWidth * wordLen / wordWidth); + let truncWordWidth = this.measureText(word.substring(0, cutoffIndex)) + suffixWidth; + if (truncWordWidth > wordWrapWidth) { + while (cutoffIndex > 0) { + truncWordWidth = this.measureText(word.substring(0, cutoffIndex)) + suffixWidth; + if (truncWordWidth > wordWrapWidth) { + cutoffIndex -= 1; + } else { + break; + } + } + } else { + while (cutoffIndex < wordLen) { + truncWordWidth = this.measureText(word.substring(0, cutoffIndex)) + suffixWidth; + if (truncWordWidth < wordWrapWidth) { + cutoffIndex += 1; + } else { + cutoffIndex -= 1; + break; + } + } + } + return word.substring(0, cutoffIndex) + (wordWrapWidth >= suffixWidth ? suffix : ""); + } + _getBreakIndex(word, width) { + const wordLen = word.length; + const wordWidth = this.measureText(word); + if (wordWidth <= width) { + return { breakIndex: word.length, truncWordWidth: wordWidth }; + } + let breakIndex = Math.floor(width * wordLen / wordWidth); + let truncWordWidth = this.measureText(word.substring(0, breakIndex)); + if (truncWordWidth > width) { + while (breakIndex > 0) { + truncWordWidth = this.measureText(word.substring(0, breakIndex)); + if (truncWordWidth > width) { + breakIndex -= 1; + } else { + break; + } + } + } else { + while (breakIndex < wordLen) { + truncWordWidth = this.measureText(word.substring(0, breakIndex)); + if (truncWordWidth < width) { + breakIndex += 1; + } else { + breakIndex -= 1; + truncWordWidth = this.measureText(word.substring(0, breakIndex)); + break; + } + } + } + return { breakIndex, truncWordWidth }; + } + wordBreak(word, width, baseFont) { + if (!word.text) { + return word; + } + this.applyFontStyle(word, baseFont); + const parts = []; + let text = word.text; + if (!word.letters) { + while (true) { + const { breakIndex, truncWordWidth } = this._getBreakIndex(text, width); + parts.push({ ...word }); + parts[parts.length - 1].text = text.slice(0, breakIndex); + parts[parts.length - 1].width = truncWordWidth; + if (breakIndex === text.length) { + break; + } + text = text.slice(breakIndex); + } + } else { + let totalWidth = 0; + let letters = []; + let breakIndex = 0; + for (const l of word.letters) { + if (totalWidth + l.width >= width) { + parts.push({ ...word }); + parts[parts.length - 1].text = text.slice(0, breakIndex); + parts[parts.length - 1].width = totalWidth; + parts[parts.length - 1].letters = letters; + text = text.slice(breakIndex); + totalWidth = 0; + letters = []; + breakIndex = 0; + } else { + breakIndex += 1; + letters.push(l); + totalWidth += l.width; + } + } + if (totalWidth > 0) { + parts.push({ ...word }); + parts[parts.length - 1].text = text.slice(0, breakIndex); + parts[parts.length - 1].width = totalWidth; + parts[parts.length - 1].letters = letters; + } + } + return parts; + } + alignLine(parsed, initialX = 0) { + let prevWidth = 0; + let prevX = initialX; + for (const word of parsed) { + if (word.text == "\n") { + continue; + } + word.x = prevX + prevWidth; + prevX = word.x; + prevWidth = word.width; + } + } +} +class TextTexture extends Texture { + constructor(stage) { + super(stage); + this._precision = this.stage.getOption("precision"); + } + static renderer(stage, canvas, settings) { + if (this.advancedRenderer) { + return new TextTextureRendererAdvanced(stage, canvas, settings); + } else { + return new TextTextureRenderer(stage, canvas, settings); + } + } + get text() { + return this._text; + } + set text(v) { + if (this._text !== v) { + this._text = "" + v; + this._changed(); + } + } + get w() { + return this._w; + } + set w(v) { + if (this._w !== v) { + this._w = v; + this._changed(); + } + } + get h() { + return this._h; + } + set h(v) { + if (this._h !== v) { + this._h = v; + this._changed(); + } + } + get fontStyle() { + return this._fontStyle; + } + set fontStyle(v) { + if (this._fontStyle !== v) { + this._fontStyle = v; + this._changed(); + } + } + get fontBaselineRatio() { + return this._fontBaselineRatio; + } + set fontBaselineRatio(v) { + if (this._fontBaselineRatio !== v) { + this._fontBaselineRatio = v; + this._changed(); + } + } + get fontSize() { + return this._fontSize; + } + set fontSize(v) { + if (this._fontSize !== v) { + this._fontSize = v; + this._changed(); + } + } + get fontFace() { + return this._fontFace; + } + set fontFace(v) { + if (this._fontFace !== v) { + this._fontFace = v; + this._changed(); + } + } + get wordWrap() { + return this._wordWrap; + } + set wordWrap(v) { + if (this._wordWrap !== v) { + this._wordWrap = v; + this._changed(); + } + } + get wordWrapWidth() { + return this._wordWrapWidth; + } + set wordWrapWidth(v) { + if (this._wordWrapWidth !== v) { + this._wordWrapWidth = v; + this._changed(); + } + } + get wordBreak() { + return this._wordBreak; + } + set wordBreak(v) { + if (this._wordBreak !== v) { + this._wordBreak = v; + this._changed(); + } + } + get textOverflow() { + return this._textOverflow; + } + set textOverflow(v) { + if (v != this._textOverflow) { + this._textOverflow = v; + this._changed(); + } + } + get lineHeight() { + return this._lineHeight; + } + set lineHeight(v) { + if (this._lineHeight !== v) { + this._lineHeight = v; + this._changed(); + } + } + get textBaseline() { + return this._textBaseline; + } + set textBaseline(v) { + if (this._textBaseline !== v) { + this._textBaseline = v; + this._changed(); + } + } + get textAlign() { + return this._textAlign; + } + set textAlign(v) { + if (this._textAlign !== v) { + this._textAlign = v; + this._changed(); + } + } + get verticalAlign() { + return this._verticalAlign; + } + set verticalAlign(v) { + if (this._verticalAlign !== v) { + this._verticalAlign = v; + this._changed(); + } + } + get offsetY() { + return this._offsetY; + } + set offsetY(v) { + if (this._offsetY !== v) { + this._offsetY = v; + this._changed(); + } + } + get maxLines() { + return this._maxLines; + } + set maxLines(v) { + if (this._maxLines !== v) { + this._maxLines = v; + this._changed(); + } + } + get maxLinesSuffix() { + return this._maxLinesSuffix; + } + set maxLinesSuffix(v) { + if (this._maxLinesSuffix !== v) { + this._maxLinesSuffix = v; + this._changed(); + } + } + get textColor() { + return this._textColor; + } + set textColor(v) { + if (this._textColor !== v) { + this._textColor = v; + this._changed(); + } + } + get paddingLeft() { + return this._paddingLeft; + } + set paddingLeft(v) { + if (this._paddingLeft !== v) { + this._paddingLeft = v; + this._changed(); + } + } + get paddingRight() { + return this._paddingRight; + } + set paddingRight(v) { + if (this._paddingRight !== v) { + this._paddingRight = v; + this._changed(); + } + } + get shadow() { + return this._shadow; + } + set shadow(v) { + if (this._shadow !== v) { + this._shadow = v; + this._changed(); + } + } + get shadowColor() { + return this._shadowColor; + } + set shadowColor(v) { + if (this._shadowColor !== v) { + this._shadowColor = v; + this._changed(); + } + } + get shadowOffsetX() { + return this._shadowOffsetX; + } + set shadowOffsetX(v) { + if (this._shadowOffsetX !== v) { + this._shadowOffsetX = v; + this._changed(); + } + } + get shadowOffsetY() { + return this._shadowOffsetY; + } + set shadowOffsetY(v) { + if (this._shadowOffsetY !== v) { + this._shadowOffsetY = v; + this._changed(); + } + } + get shadowBlur() { + return this._shadowBlur; + } + set shadowBlur(v) { + if (this._shadowBlur !== v) { + this._shadowBlur = v; + this._changed(); + } + } + get highlight() { + return this._highlight; + } + set highlight(v) { + if (this._highlight !== v) { + this._highlight = v; + this._changed(); + } + } + get highlightHeight() { + return this._highlightHeight; + } + set highlightHeight(v) { + if (this._highlightHeight !== v) { + this._highlightHeight = v; + this._changed(); + } + } + get highlightColor() { + return this._highlightColor; + } + set highlightColor(v) { + if (this._highlightColor !== v) { + this._highlightColor = v; + this._changed(); + } + } + get highlightOffset() { + return this._highlightOffset; + } + set highlightOffset(v) { + if (this._highlightOffset !== v) { + this._highlightOffset = v; + this._changed(); + } + } + get highlightPaddingLeft() { + return this._highlightPaddingLeft; + } + set highlightPaddingLeft(v) { + if (this._highlightPaddingLeft !== v) { + this._highlightPaddingLeft = v; + this._changed(); + } + } + get highlightPaddingRight() { + return this._highlightPaddingRight; + } + set highlightPaddingRight(v) { + if (this._highlightPaddingRight !== v) { + this._highlightPaddingRight = v; + this._changed(); + } + } + get cutSx() { + return this._cutSx; + } + set cutSx(v) { + if (this._cutSx !== v) { + this._cutSx = v; + this._changed(); + } + } + get cutEx() { + return this._cutEx; + } + set cutEx(v) { + if (this._cutEx !== v) { + this._cutEx = v; + this._changed(); + } + } + get cutSy() { + return this._cutSy; + } + set cutSy(v) { + if (this._cutSy !== v) { + this._cutSy = v; + this._changed(); + } + } + get cutEy() { + return this._cutEy; + } + set cutEy(v) { + if (this._cutEy !== v) { + this._cutEy = v; + this._changed(); + } + } + get advancedRenderer() { + return this._advancedRenderer; + } + set advancedRenderer(v) { + if (this._advancedRenderer !== v) { + this._advancedRenderer = v; + this._changed(); + } + } + set letterSpacing(v) { + if (this._letterSpacing !== v) { + this._letterSpacing = v; + this._changed(); + } + } + get letterSpacing() { + return this._letterSpacing; + } + set textIndent(v) { + if (this._textIndent !== v) { + this._textIndent = v; + this._changed(); + } + } + get textIndent() { + return this._textIndent; + } + get precision() { + return super.precision; + } + set precision(v) { + if (this.precision !== v) { + super.precision = v; + this._changed(); + } + } + _getIsValid() { + return !!this.text; + } + _getLookupId() { + let parts = []; + if (this.w !== 0) + parts.push("w " + this.w); + if (this.h !== 0) + parts.push("h " + this.h); + if (this.fontStyle !== "normal") + parts.push("fS" + this.fontStyle); + if (this.fontSize !== 40) + parts.push("fs" + this.fontSize); + if (this.fontBaselineRatio !== 0) + parts.push("fb" + this.fontBaselineRatio); + if (this.fontFace !== null) + parts.push("ff" + (Array.isArray(this.fontFace) ? this.fontFace.join(",") : this.fontFace)); + if (this.wordWrap !== true) + parts.push("wr" + (this.wordWrap ? 1 : 0)); + if (this.wordWrapWidth !== 0) + parts.push("ww" + this.wordWrapWidth); + if (this.wordBreak !== false) + parts.push( true ? 1 : undefined); + if (this.textOverflow != "") + parts.push("to" + this.textOverflow); + if (this.lineHeight !== null) + parts.push("lh" + this.lineHeight); + if (this.textBaseline !== "alphabetic") + parts.push("tb" + this.textBaseline); + if (this.textAlign !== "left") + parts.push("ta" + this.textAlign); + if (this.verticalAlign !== "top") + parts.push("va" + this.verticalAlign); + if (this.offsetY !== null) + parts.push("oy" + this.offsetY); + if (this.maxLines !== 0) + parts.push("ml" + this.maxLines); + if (this.maxLinesSuffix !== "..") + parts.push("ms" + this.maxLinesSuffix); + parts.push("pc" + this.precision); + if (this.textColor !== 4294967295) + parts.push("co" + this.textColor.toString(16)); + if (this.paddingLeft !== 0) + parts.push("pl" + this.paddingLeft); + if (this.paddingRight !== 0) + parts.push("pr" + this.paddingRight); + if (this.shadow !== false) + parts.push("sh" + (this.shadow ? 1 : 0)); + if (this.shadowColor !== 4278190080) + parts.push("sc" + this.shadowColor.toString(16)); + if (this.shadowOffsetX !== 0) + parts.push("sx" + this.shadowOffsetX); + if (this.shadowOffsetY !== 0) + parts.push("sy" + this.shadowOffsetY); + if (this.shadowBlur !== 5) + parts.push("sb" + this.shadowBlur); + if (this.highlight !== false) + parts.push("hL" + (this.highlight ? 1 : 0)); + if (this.highlightHeight !== 0) + parts.push("hh" + this.highlightHeight); + if (this.highlightColor !== 4278190080) + parts.push("hc" + this.highlightColor.toString(16)); + if (this.highlightOffset !== null) + parts.push("ho" + this.highlightOffset); + if (this.highlightPaddingLeft !== null) + parts.push("hl" + this.highlightPaddingLeft); + if (this.highlightPaddingRight !== null) + parts.push("hr" + this.highlightPaddingRight); + if (this.letterSpacing !== null) + parts.push("ls" + this.letterSpacing); + if (this.textIndent !== null) + parts.push("ti" + this.textIndent); + if (this.cutSx) + parts.push("csx" + this.cutSx); + if (this.cutEx) + parts.push("cex" + this.cutEx); + if (this.cutSy) + parts.push("csy" + this.cutSy); + if (this.cutEy) + parts.push("cey" + this.cutEy); + if (this.advancedRenderer) + parts.push( true ? 1 : undefined); + let id = "TX$" + parts.join("|") + ":" + this.text; + return id; + } + _getSourceLoader() { + const args = this.cloneArgs(); + const gl = this.stage.gl; + return function(cb) { + const canvas = this.stage.platform.getDrawingCanvas(); + const renderer = args.advancedRenderer ? new TextTextureRendererAdvanced(this.stage, canvas, args) : new TextTextureRenderer(this.stage, canvas, args); + const p = renderer.draw(); + const texParams = {}; + const sharpCfg = this.stage.getOption("fontSharp"); + let sharpen = false; + if (Utils$1.isBoolean(sharpCfg)) { + sharpen = sharpCfg; + } else if (Utils$1.isObject(sharpCfg)) { + const precision = this.stage.getRenderPrecision(); + sharpen = precision <= sharpCfg.precision && args.fontSize <= sharpCfg.fontSize; + } + if (gl && sharpen) { + texParams[gl.TEXTURE_MAG_FILTER] = gl.NEAREST; + } + if (p) { + p.then(() => { + cb(null, Object.assign({ + renderInfo: renderer.renderInfo, + throttle: false, + texParams + }, this.stage.platform.getTextureOptionsForDrawingCanvas(canvas))); + }).catch((err) => { + cb(err); + }); + } else { + cb(null, Object.assign({ + renderInfo: renderer.renderInfo, + throttle: false, + texParams + }, this.stage.platform.getTextureOptionsForDrawingCanvas(canvas))); + } + }; + } + getNonDefaults() { + const nonDefaults = super.getNonDefaults(); + if (this.text !== "") + nonDefaults["text"] = this.text; + if (this.w !== 0) + nonDefaults["w"] = this.w; + if (this.h !== 0) + nonDefaults["h"] = this.h; + if (this.fontStyle !== "normal") + nonDefaults["fontStyle"] = this.fontStyle; + if (this.fontSize !== 40) + nonDefaults["fontSize"] = this.fontSize; + if (this.fontBaselineRatio !== 0) + nonDefaults["fontBaselineRatio"] = this.fontBaselineRatio; + if (this.fontFace !== null) + nonDefaults["fontFace"] = this.fontFace; + if (this.wordWrap !== true) + nonDefaults["wordWrap"] = this.wordWrap; + if (this.wordWrapWidth !== 0) + nonDefaults["wordWrapWidth"] = this.wordWrapWidth; + if (this.wordBreak !== false) + nonDefaults["wordBreak"] = this.wordBreak; + if (this.textOverflow != "") + nonDefaults["textOverflow"] = this.textOverflow; + if (this.lineHeight !== null) + nonDefaults["lineHeight"] = this.lineHeight; + if (this.textBaseline !== "alphabetic") + nonDefaults["textBaseline"] = this.textBaseline; + if (this.textAlign !== "left") + nonDefaults["textAlign"] = this.textAlign; + if (this.verticalAlign !== "top") + nonDefaults["verticalAlign"] = this.verticalAlign; + if (this.offsetY !== null) + nonDefaults["offsetY"] = this.offsetY; + if (this.maxLines !== 0) + nonDefaults["maxLines"] = this.maxLines; + if (this.maxLinesSuffix !== "..") + nonDefaults["maxLinesSuffix"] = this.maxLinesSuffix; + if (this.precision !== this.stage.getOption("precision")) + nonDefaults["precision"] = this.precision; + if (this.textColor !== 4294967295) + nonDefaults["textColor"] = this.textColor; + if (this.paddingLeft !== 0) + nonDefaults["paddingLeft"] = this.paddingLeft; + if (this.paddingRight !== 0) + nonDefaults["paddingRight"] = this.paddingRight; + if (this.shadow !== false) + nonDefaults["shadow"] = this.shadow; + if (this.shadowColor !== 4278190080) + nonDefaults["shadowColor"] = this.shadowColor; + if (this.shadowOffsetX !== 0) + nonDefaults["shadowOffsetX"] = this.shadowOffsetX; + if (this.shadowOffsetY !== 0) + nonDefaults["shadowOffsetY"] = this.shadowOffsetY; + if (this.shadowBlur !== 5) + nonDefaults["shadowBlur"] = this.shadowBlur; + if (this.highlight !== false) + nonDefaults["highlight"] = this.highlight; + if (this.highlightHeight !== 0) + nonDefaults["highlightHeight"] = this.highlightHeight; + if (this.highlightColor !== 4278190080) + nonDefaults["highlightColor"] = this.highlightColor; + if (this.highlightOffset !== 0) + nonDefaults["highlightOffset"] = this.highlightOffset; + if (this.highlightPaddingLeft !== 0) + nonDefaults["highlightPaddingLeft"] = this.highlightPaddingLeft; + if (this.highlightPaddingRight !== 0) + nonDefaults["highlightPaddingRight"] = this.highlightPaddingRight; + if (this.letterSpacing !== 0) + nonDefaults["letterSpacing"] = this.letterSpacing; + if (this.textIndent !== 0) + nonDefaults["textIndent"] = this.textIndent; + if (this.cutSx) + nonDefaults["cutSx"] = this.cutSx; + if (this.cutEx) + nonDefaults["cutEx"] = this.cutEx; + if (this.cutSy) + nonDefaults["cutSy"] = this.cutSy; + if (this.cutEy) + nonDefaults["cutEy"] = this.cutEy; + if (this.advancedRenderer) + nonDefaults["renderer"] = this.advancedRenderer; + return nonDefaults; + } + cloneArgs() { + let obj = {}; + obj.text = this._text; + obj.w = this._w; + obj.h = this._h; + obj.fontStyle = this._fontStyle; + obj.fontSize = this._fontSize; + obj.fontBaselineRatio = this._fontBaselineRatio; + obj.fontFace = this._fontFace; + obj.wordWrap = this._wordWrap; + obj.wordWrapWidth = this._wordWrapWidth; + obj.wordBreak = this._wordBreak; + obj.textOverflow = this._textOverflow; + obj.lineHeight = this._lineHeight; + obj.textBaseline = this._textBaseline; + obj.textAlign = this._textAlign; + obj.verticalAlign = this._verticalAlign; + obj.offsetY = this._offsetY; + obj.maxLines = this._maxLines; + obj.maxLinesSuffix = this._maxLinesSuffix; + obj.precision = this._precision; + obj.textColor = this._textColor; + obj.paddingLeft = this._paddingLeft; + obj.paddingRight = this._paddingRight; + obj.shadow = this._shadow; + obj.shadowColor = this._shadowColor; + obj.shadowOffsetX = this._shadowOffsetX; + obj.shadowOffsetY = this._shadowOffsetY; + obj.shadowBlur = this._shadowBlur; + obj.highlight = this._highlight; + obj.highlightHeight = this._highlightHeight; + obj.highlightColor = this._highlightColor; + obj.highlightOffset = this._highlightOffset; + obj.highlightPaddingLeft = this._highlightPaddingLeft; + obj.highlightPaddingRight = this._highlightPaddingRight; + obj.letterSpacing = this._letterSpacing; + obj.textIndent = this._textIndent; + obj.cutSx = this._cutSx; + obj.cutEx = this._cutEx; + obj.cutSy = this._cutSy; + obj.cutEy = this._cutEy; + obj.advancedRenderer = this._advancedRenderer; + return obj; + } +} +let proto = TextTexture.prototype; +proto._text = ""; +proto._w = 0; +proto._h = 0; +proto._fontStyle = "normal"; +proto._fontSize = 40; +proto._fontFace = null; +proto._wordWrap = true; +proto._wordWrapWidth = 0; +proto._wordBreak = false; +proto._textOverflow = ""; +proto._lineHeight = null; +proto._textBaseline = "alphabetic"; +proto._textAlign = "left"; +proto._verticalAlign = "top"; +proto._offsetY = null; +proto._maxLines = 0; +proto._maxLinesSuffix = ".."; +proto._textColor = 4294967295; +proto._paddingLeft = 0; +proto._paddingRight = 0; +proto._shadow = false; +proto._shadowColor = 4278190080; +proto._shadowOffsetX = 0; +proto._shadowOffsetY = 0; +proto._shadowBlur = 5; +proto._highlight = false; +proto._highlightHeight = 0; +proto._highlightColor = 4278190080; +proto._highlightOffset = 0; +proto._highlightPaddingLeft = 0; +proto._highlightPaddingRight = 0; +proto._letterSpacing = 0; +proto._textIndent = 0; +proto._cutSx = 0; +proto._cutEx = 0; +proto._cutSy = 0; +proto._cutEy = 0; +proto._advancedRenderer = false; +proto._fontBaselineRatio = 0; +class SourceTexture extends Texture { + constructor(stage) { + super(stage); + this._textureSource = void 0; + } + get textureSource() { + return this._textureSource; + } + set textureSource(v) { + if (v !== this._textureSource) { + if (v.isResultTexture) { + this._precision = this.stage.getRenderPrecision(); + } + this._textureSource = v; + this._changed(); + } + } + _getTextureSource() { + return this._textureSource; + } +} +class Transition extends EventEmitter { + constructor(manager, settings, element, property) { + super(); + this.manager = manager; + this._settings = settings; + this._element = element; + this._getter = element.constructor.getGetter(property); + this._setter = element.constructor.getSetter(property); + this._merger = settings.merger; + if (!this._merger) { + this._merger = element.constructor.getMerger(property); + } + this._startValue = this._getter(this._element); + this._targetValue = this._startValue; + this._p = 1; + this._delayLeft = 0; + } + start(targetValue) { + this._startValue = this._getter(this._element); + if (!this.isAttached()) { + this._targetValue = targetValue; + this._p = 1; + this._updateDrawValue(); + } else { + if (targetValue === this._startValue) { + this.reset(targetValue, 1); + } else { + this._targetValue = targetValue; + this._p = 0; + this._delayLeft = this._settings.delay; + this.emit("start"); + this.add(); + } + } + } + finish() { + if (this._p < 1) { + this._p = 1; + } + } + stop() { + this.emit("stop"); + this.manager.removeActive(this); + } + pause() { + this.stop(); + } + play() { + this.manager.addActive(this); + } + reset(targetValue, p) { + if (!this.isAttached()) { + this._startValue = this._getter(this._element); + this._targetValue = targetValue; + this._p = 1; + this._updateDrawValue(); + } else { + this._startValue = this._getter(this._element); + this._targetValue = targetValue; + this._p = p; + this.add(); + } + } + _updateDrawValue() { + this._setter(this._element, this.getDrawValue()); + } + add() { + this.manager.addActive(this); + } + isAttached() { + return this._element.attached; + } + isRunning() { + return this._p < 1; + } + progress(dt) { + if (!this.isAttached()) { + this._p = 1; + } + if (this.p < 1) { + if (this.delayLeft > 0) { + this._delayLeft -= dt; + if (this.delayLeft < 0) { + dt = -this.delayLeft; + this._delayLeft = 0; + this.emit("delayEnd"); + } else { + return; + } + } + if (this._settings.duration == 0) { + this._p = 1; + } else { + this._p += dt / this._settings.duration; + } + if (this._p >= 1) { + this._p = 1; + } + } + this._updateDrawValue(); + this.invokeListeners(); + } + invokeListeners() { + this.emit("progress", this.p); + if (this.p === 1) { + this.emit("finish"); + } + } + updateTargetValue(targetValue) { + let t = this._settings.timingFunctionImpl(this.p); + if (t === 1) { + this._targetValue = targetValue; + } else if (t === 0) { + this._startValue = this._targetValue; + this._targetValue = targetValue; + } else { + this._startValue = targetValue - (targetValue - this._targetValue) / (1 - t); + this._targetValue = targetValue; + } + } + getDrawValue() { + if (this.p >= 1) { + return this.targetValue; + } else { + let v = this._settings._timingFunctionImpl(this.p); + return this._merger(this.targetValue, this.startValue, v); + } + } + skipDelay() { + this._delayLeft = 0; + } + get startValue() { + return this._startValue; + } + get targetValue() { + return this._targetValue; + } + get p() { + return this._p; + } + get delayLeft() { + return this._delayLeft; + } + get element() { + return this._element; + } + get settings() { + return this._settings; + } + set settings(v) { + this._settings = v; + } +} +Transition.prototype.isTransition = true; +class ObjectList { + constructor() { + this._items = []; + this._refs = {}; + } + get() { + return this._items; + } + get first() { + return this._items[0]; + } + get last() { + return this._items.length ? this._items[this._items.length - 1] : void 0; + } + add(item) { + this.addAt(item, this._items.length); + } + addAt(item, index) { + if (index >= 0 && index <= this._items.length) { + let currentIndex = this._items.indexOf(item); + if (currentIndex === index) { + return item; + } + if (Utils$1.isObjectLiteral(item)) { + const o = item; + item = this.createItem(o); + item.patch(o); + } + if (currentIndex != -1) { + this.setAt(item, index); + } else { + if (item.ref) { + this._refs[item.ref] = item; + } + this._items.splice(index, 0, item); + this.onAdd(item, index); + } + } else { + throw new Error("addAt: The index " + index + " is out of bounds " + this._items.length); + } + } + replaceByRef(item) { + if (item.ref) { + const existingItem = this.getByRef(item.ref); + if (!existingItem) { + throw new Error("replaceByRef: no item found with reference: " + item.ref); + } + this.replace(item, existingItem); + } else { + throw new Error("replaceByRef: no ref specified in item"); + } + this.addAt(item, this._items.length); + } + replace(item, prevItem) { + const index = this.getIndex(prevItem); + if (index === -1) { + throw new Error("replace: The previous item does not exist"); + } + this.setAt(item, index); + } + setAt(item, index) { + if (index >= 0 && index < this._items.length) { + if (Utils$1.isObjectLiteral(item)) { + const o = item; + item = this.createItem(o); + item.patch(o); + } + let currentIndex = this._items.indexOf(item); + if (currentIndex != -1) { + if (currentIndex !== index) { + const fromIndex = currentIndex; + if (fromIndex !== index) { + this._items.splice(fromIndex, 1); + this._items.splice(index, 0, item); + this.onMove(item, fromIndex, index); + } + } + } else { + if (index < this._items.length) { + if (this._items[index].ref) { + this._refs[this._items[index].ref] = void 0; + } + } + const prevItem = this._items[index]; + this._items[index] = item; + if (item.ref) { + this._refs[item.ref] = item; + } + this.onSet(item, index, prevItem); + } + } else { + throw new Error("setAt: The index " + index + " is out of bounds " + this._items.length); + } + } + getAt(index) { + return this._items[index]; + } + getIndex(item) { + return this._items.indexOf(item); + } + remove(item) { + let index = this._items.indexOf(item); + if (index !== -1) { + this.removeAt(index); + } + } + removeAt(index) { + if (index >= 0 && index < this._items.length) { + const item = this._items[index]; + if (item.ref) { + this._refs[item.ref] = void 0; + } + this._items.splice(index, 1); + this.onRemove(item, index); + return item; + } else { + throw new Error(`removeAt: The index ${index} is out of bounds ${this._items.length - 1}`); + } + } + clear() { + let n = this._items.length; + if (n) { + let prev = this._items; + this._items = []; + this._refs = {}; + this.onSync(prev, [], []); + } + } + a(o) { + if (Utils$1.isObjectLiteral(o)) { + let c = this.createItem(o); + c.patch(o); + this.add(c); + return c; + } else if (Array.isArray(o)) { + for (let i = 0, n = o.length; i < n; i++) { + this.a(o[i]); + } + return null; + } else if (this.isItem(o)) { + this.add(o); + return o; + } + } + get length() { + return this._items.length; + } + _getRefs() { + return this._refs; + } + getByRef(ref) { + return this._refs[ref]; + } + clearRef(ref) { + delete this._refs[ref]; + } + setRef(ref, child) { + this._refs[ref] = child; + } + patch(settings) { + if (Utils$1.isObjectLiteral(settings)) { + this._setByObject(settings); + } else if (Array.isArray(settings)) { + this._setByArray(settings); + } + } + _setByObject(settings) { + let refs = this._getRefs(); + let crefs = Object.keys(settings); + for (let i = 0, n = crefs.length; i < n; i++) { + let cref = crefs[i]; + let s = settings[cref]; + let c = refs[cref]; + if (!c) { + if (this.isItem(s)) { + s.ref = cref; + this.add(s); + } else { + c = this.createItem(s); + c.ref = cref; + c.patch(s); + this.add(c); + } + } else { + if (this.isItem(s)) { + if (c !== s) { + let idx = this.getIndex(c); + s.ref = cref; + this.setAt(s, idx); + } + } else { + c.patch(s); + } + } + } + } + _equalsArray(array) { + let same = true; + if (array.length === this._items.length) { + for (let i = 0, n = this._items.length; i < n && same; i++) { + same = same && this._items[i] === array[i]; + } + } else { + same = false; + } + return same; + } + _setByArray(array) { + if (this._equalsArray(array)) { + return; + } + for (let i = 0, n = this._items.length; i < n; i++) { + this._items[i].marker = true; + } + let refs; + let newItems = []; + for (let i = 0, n = array.length; i < n; i++) { + let s = array[i]; + if (this.isItem(s)) { + s.marker = false; + newItems.push(s); + } else { + let cref = s.ref; + let c; + if (cref) { + if (!refs) + refs = this._getRefs(); + c = refs[cref]; + } + if (!c) { + c = this.createItem(s); + } else { + c.marker = false; + } + if (Utils$1.isObjectLiteral(s)) { + c.patch(s); + } + newItems.push(c); + } + } + this._setItems(newItems); + } + _setItems(newItems) { + let prevItems = this._items; + this._items = newItems; + let removed = prevItems.filter((item) => { + let m = item.marker; + delete item.marker; + return m; + }); + let added = newItems.filter((item) => prevItems.indexOf(item) === -1); + if (removed.length || added.length) { + this._refs = {}; + for (let i = 0, n = this._items.length; i < n; i++) { + let ref = this._items[i].ref; + if (ref) { + this._refs[ref] = this._items[i]; + } + } + } + this.onSync(removed, added, newItems); + } + sort(f) { + const items = this._items.slice(); + items.sort(f); + this._setByArray(items); + } + onAdd(item, index) { + } + onRemove(item, index) { + } + onSync(removed, added, order) { + } + onSet(item, index, prevItem) { + } + onMove(item, fromIndex, toIndex) { + } + createItem(object) { + throw new Error("ObjectList.createItem must create and return a new object"); + } + isItem(object) { + return false; + } + forEach(f) { + this.get().forEach(f); + } +} +class ElementChildList extends ObjectList { + constructor(element) { + super(); + this._element = element; + } + _connectParent(item) { + const prevParent = item.parent; + if (prevParent && prevParent !== this._element) { + const prevChildList = item.parent.childList; + const index = prevChildList.getIndex(item); + if (item.ref) { + prevChildList._refs[item.ref] = void 0; + } + prevChildList._items.splice(index, 1); + prevParent.core.removeChildAt(index); + } + item._setParent(this._element); + } + onAdd(item, index) { + this._connectParent(item); + this._element.core.addChildAt(index, item.core); + } + onRemove(item, index) { + item._setParent(null); + this._element.core.removeChildAt(index); + } + onSync(removed, added, order) { + for (let i = 0, n = removed.length; i < n; i++) { + removed[i]._setParent(null); + } + for (let i = 0, n = added.length; i < n; i++) { + this._connectParent(added[i]); + } + let gc = (i) => i.core; + this._element.core.syncChildren(removed.map(gc), added.map(gc), order.map(gc)); + } + onSet(item, index, prevItem) { + prevItem._setParent(null); + this._connectParent(item); + this._element.core.setChildAt(index, item.core); + } + onMove(item, fromIndex, toIndex) { + this._element.core.moveChild(fromIndex, toIndex); + } + createItem(object) { + if (object.type) { + return new object.type(this._element.stage); + } else { + return this._element.stage.createElement(); + } + } + isItem(object) { + return object.isElement; + } +} +class Element { + constructor(stage) { + this.stage = stage; + this.__id = Element.id++; + this.__start(); + this._hasEventListeners = false; + this.__core = new ElementCore(this); + this.__ref = null; + this.__attached = false; + this.__enabled = false; + this.__active = false; + this.__parent = null; + this.__texture = null; + this.__displayedTexture = null; + this.__tags = null; + this.__treeTags = null; + this.__tagRoot = false; + this.__childList = null; + this._w = 0; + this._h = 0; + } + __start() { + } + get id() { + return this.__id; + } + set ref(ref) { + if (this.__ref !== ref) { + const charcode = ref.charCodeAt(0); + if (!Utils$1.isUcChar(charcode)) { + this._throwError("Ref must start with an upper case character: " + ref); + } + if (this.__ref !== null) { + this.removeTag(this.__ref); + if (this.__parent) { + this.__parent.__childList.clearRef(this.__ref); + } + } + this.__ref = ref; + if (this.__ref) { + this._addTag(this.__ref); + if (this.__parent) { + this.__parent.__childList.setRef(this.__ref, this); + } + } + } + } + get ref() { + return this.__ref; + } + get core() { + return this.__core; + } + setAsRoot() { + this.__core.setAsRoot(); + this._updateAttachedFlag(); + this._updateEnabledFlag(); + } + get isRoot() { + return this.__core.isRoot; + } + _setParent(parent) { + if (this.__parent === parent) + return; + if (this.__parent) { + this._unsetTagsParent(); + } + this.__parent = parent; + if (parent) { + this._setTagsParent(); + } + this._updateAttachedFlag(); + this._updateEnabledFlag(); + this._updateCollision(); + if (this.isRoot && parent) { + this._throwError("Root should not be added as a child! Results are unspecified!"); + } + } + getDepth() { + let depth = 0; + let p = this.__parent; + while (p) { + depth++; + p = p.__parent; + } + return depth; + } + getAncestor(l) { + let p = this; + while (l > 0 && p.__parent) { + p = p.__parent; + l--; + } + return p; + } + getAncestors() { + const a = []; + let p = this; + while (p) { + a.push(p); + p = p.__parent; + } + return a; + } + getAncestorAtDepth(depth) { + let levels = this.getDepth() - depth; + if (levels < 0) { + return null; + } + return this.getAncestor(levels); + } + isAncestorOf(c) { + let p = c; + while (p = p.parent) { + if (this === p) { + return true; + } + } + return false; + } + getSharedAncestor(c) { + let o1 = this; + let o2 = c; + let l1 = o1.getDepth(); + let l2 = o2.getDepth(); + if (l1 > l2) { + o1 = o1.getAncestor(l1 - l2); + } else if (l2 > l1) { + o2 = o2.getAncestor(l2 - l1); + } + do { + if (o1 === o2) { + return o1; + } + o1 = o1.__parent; + o2 = o2.__parent; + } while (o1 && o2); + return null; + } + get attached() { + return this.__attached; + } + get enabled() { + return this.__enabled; + } + get active() { + return this.__active; + } + _isAttached() { + return this.__parent ? this.__parent.__attached : this.stage.root === this; + } + _isEnabled() { + return this.__core.visible && this.__core.alpha > 0 && (this.__parent ? this.__parent.__enabled : this.stage.root === this); + } + _isActive() { + return this._isEnabled() && this.withinBoundsMargin; + } + _updateAttachedFlag() { + let newAttached = this._isAttached(); + if (this.__attached !== newAttached) { + this.__attached = newAttached; + if (newAttached) { + this._onSetup(); + } + let children = this._children.get(); + if (children) { + let m = children.length; + if (m > 0) { + for (let i = 0; i < m; i++) { + children[i]._updateAttachedFlag(); + } + } + } + if (newAttached) { + this._onAttach(); + } else { + this._onDetach(); + } + } + } + _updateEnabledFlag() { + let newEnabled = this._isEnabled(); + if (this.__enabled !== newEnabled) { + if (newEnabled) { + this._onEnabled(); + this._setEnabledFlag(); + } else { + this._onDisabled(); + this._unsetEnabledFlag(); + } + let children = this._children.get(); + if (children) { + let m = children.length; + if (m > 0) { + for (let i = 0; i < m; i++) { + children[i]._updateEnabledFlag(); + } + } + } + } + } + _setEnabledFlag() { + this.__enabled = true; + this._updateDimensions(); + this._updateTextureCoords(); + if (this.__texture) { + this.__texture.addElement(this); + } + if (this.withinBoundsMargin) { + this._setActiveFlag(); + } + if (this.__core.shader) { + this.__core.shader.addElement(this.__core); + } + } + _unsetEnabledFlag() { + if (this.__active) { + this._unsetActiveFlag(); + } + if (this.__texture) { + this.__texture.removeElement(this); + } + if (this.__core.shader) { + this.__core.shader.removeElement(this.__core); + } + if (this._texturizer) { + this.texturizer.filters.forEach((filter) => filter.removeElement(this.__core)); + } + this.__enabled = false; + } + _setActiveFlag() { + this.__active = true; + if (this.__texture) { + this.__texture.incActiveCount(); + } + if (this.__texture) { + this._enableTexture(); + } + this._onActive(); + } + _unsetActiveFlag() { + if (this.__texture) { + this.__texture.decActiveCount(); + } + this.__active = false; + if (this.__texture) { + this._disableTexture(); + } + if (this._hasTexturizer()) { + this.texturizer.deactivate(); + } + this._onInactive(); + } + _onSetup() { + } + _onAttach() { + } + _onDetach() { + } + _onEnabled() { + } + _onDisabled() { + } + _onActive() { + } + _onInactive() { + } + _onResize() { + } + _getRenderWidth() { + if (this._w) { + return this._w; + } else if (this.__displayedTexture) { + return this.__displayedTexture.getRenderWidth(); + } else if (this.__texture) { + return this.__texture.getRenderWidth(); + } else { + return 0; + } + } + _getRenderHeight() { + if (this._h) { + return this._h; + } else if (this.__displayedTexture) { + return this.__displayedTexture.getRenderHeight(); + } else if (this.__texture) { + return this.__texture.getRenderHeight(); + } else { + return 0; + } + } + get renderWidth() { + if (this.__enabled) { + return this.__core.getRenderWidth(); + } else { + return this._getRenderWidth(); + } + } + get renderHeight() { + if (this.__enabled) { + return this.__core.getRenderHeight(); + } else { + return this._getRenderHeight(); + } + } + get finalX() { + return this.__core.x; + } + get finalY() { + return this.__core.y; + } + get finalW() { + return this.__core.w; + } + get finalH() { + return this.__core.h; + } + textureIsLoaded() { + return this.__texture && this.__texture.isLoaded(); + } + loadTexture() { + if (this.__texture) { + this.__texture.load(); + if (!this.__texture.isUsed() || !this._isEnabled()) { + this._updateDimensions(); + } + } + } + _enableTextureError() { + const loadError = this.__texture.loadError; + if (loadError) { + this.emit("txError", loadError, this.__texture._source); + } + } + _enableTexture() { + if (this.__texture.isLoaded()) { + this._setDisplayedTexture(this.__texture); + } else { + this._setDisplayedTexture(null); + this._enableTextureError(); + } + } + _disableTexture() { + this._setDisplayedTexture(null); + } + get texture() { + return this.__texture; + } + set texture(v) { + let texture; + if (Utils$1.isObjectLiteral(v)) { + if (v.type) { + texture = new v.type(this.stage); + } else { + texture = this.texture; + } + if (texture) { + Base.patchObject(texture, v); + } + } else if (!v) { + texture = null; + } else { + if (v.isTexture) { + texture = v; + } else if (v.isTextureSource) { + texture = new SourceTexture(this.stage); + texture.textureSource = v; + } else { + console.error("[Lightning] Please specify a texture type."); + return; + } + } + const prevTexture = this.__texture; + if (texture !== prevTexture) { + this.__texture = texture; + if (this.__texture) { + if (this.__enabled) { + this.__texture.addElement(this); + if (this.withinBoundsMargin) { + if (this.__texture.isLoaded()) { + this._setDisplayedTexture(this.__texture); + } else { + this._enableTextureError(); + } + } + } + } else { + this._setDisplayedTexture(null); + } + if (prevTexture && prevTexture !== this.__displayedTexture) { + prevTexture.removeElement(this); + } + this._updateDimensions(); + } + } + get displayedTexture() { + return this.__displayedTexture; + } + _setDisplayedTexture(v) { + let prevTexture = this.__displayedTexture; + if (prevTexture && v !== prevTexture) { + if (this.__texture !== prevTexture) { + prevTexture.removeElement(this); + } + } + const prevSource = this.__core.displayedTextureSource ? this.__core.displayedTextureSource._source : null; + const sourceChanged = (v ? v._source : null) !== prevSource; + this.__displayedTexture = v; + this._updateDimensions(); + if (this.__displayedTexture) { + if (sourceChanged) { + this._updateTextureCoords(); + this.__core.setDisplayedTextureSource(this.__displayedTexture._source); + } + } else { + this.__core.setDisplayedTextureSource(null); + } + if (sourceChanged) { + if (this.__displayedTexture) { + this.emit("txLoaded", this.__displayedTexture); + } else { + this.emit("txUnloaded", this.__displayedTexture); + } + } + } + onTextureSourceLoaded() { + if (this.active) { + this._setDisplayedTexture(this.__texture); + } + } + onTextureSourceLoadError(e) { + this.emit("txError", e, this.__texture._source); + } + forceRenderUpdate() { + this.__core.setHasRenderUpdates(3); + } + onDisplayedTextureClippingChanged() { + this._updateDimensions(); + this._updateTextureCoords(); + } + onPrecisionChanged() { + this._updateDimensions(); + } + onDimensionsChanged(w, h) { + if (this.texture instanceof TextTexture) { + this.texture.w = w; + this.texture.h = h; + this.w = w; + this.h = h; + } + } + _updateDimensions() { + let w = this._getRenderWidth(); + let h = this._getRenderHeight(); + let unknownSize = false; + if (!w || !h) { + if (!this.__displayedTexture && this.__texture) { + w = w || this.__texture.mw; + h = h || this.__texture.mh; + if ((!w || !h) && this.__texture.isAutosizeTexture()) { + unknownSize = true; + } + } + } + if (this.__core.setDimensions(w, h, unknownSize)) { + this._onResize(); + } + } + _updateTextureCoords() { + if (this.displayedTexture && this.displayedTexture._source) { + let displayedTexture = this.displayedTexture; + let displayedTextureSource = this.displayedTexture._source; + let tx1 = 0, ty1 = 0, tx2 = 1, ty2 = 1; + if (displayedTexture.clipping) { + let w = displayedTextureSource.getRenderWidth(); + let h = displayedTextureSource.getRenderHeight(); + let iw, ih, rw, rh; + iw = 1 / w; + ih = 1 / h; + if (displayedTexture.pw) { + rw = displayedTexture.pw * iw; + } else { + rw = (w - displayedTexture.px) * iw; + } + if (displayedTexture.ph) { + rh = displayedTexture.ph * ih; + } else { + rh = (h - displayedTexture.py) * ih; + } + iw *= displayedTexture.px; + ih *= displayedTexture.py; + tx1 = iw; + ty1 = ih; + tx2 = tx2 * rw + iw; + ty2 = ty2 * rh + ih; + tx1 = Math.max(0, tx1); + ty1 = Math.max(0, ty1); + tx2 = Math.min(1, tx2); + ty2 = Math.min(1, ty2); + } + if (displayedTextureSource._flipTextureY) { + let tempty = ty2; + ty2 = ty1; + ty1 = tempty; + } + this.__core.setTextureCoords(tx1, ty1, tx2, ty2); + } + } + getCornerPoints() { + return this.__core.getCornerPoints(); + } + _unsetTagsParent() { + if (this.__tags) { + this.__tags.forEach((tag) => { + let p = this; + while (p = p.__parent) { + let parentTreeTags = p.__treeTags.get(tag); + parentTreeTags.delete(this); + if (p.__tagRoot) { + break; + } + } + }); + } + let tags = null; + let n = 0; + if (this.__treeTags) { + if (!this.__tagRoot) { + tags = Utils$1.iteratorToArray(this.__treeTags.keys()); + n = tags.length; + if (n > 0) { + for (let i = 0; i < n; i++) { + let tagSet = this.__treeTags.get(tags[i]); + let p = this; + while (p = p.__parent) { + let parentTreeTags = p.__treeTags.get(tags[i]); + tagSet.forEach(function(comp) { + parentTreeTags.delete(comp); + }); + if (p.__tagRoot) { + break; + } + } + } + } + } + } + } + _setTagsParent() { + if (this.__tags) { + this.__tags.forEach((tag) => { + let p = this; + while (p = p.__parent) { + if (!p.__treeTags) { + p.__treeTags = /* @__PURE__ */ new Map(); + } + let s = p.__treeTags.get(tag); + if (!s) { + s = /* @__PURE__ */ new Set(); + p.__treeTags.set(tag, s); + } + s.add(this); + if (p.__tagRoot) { + break; + } + } + }); + } + if (this.__treeTags && this.__treeTags.size) { + if (!this.__tagRoot) { + this.__treeTags.forEach((tagSet, tag) => { + let p = this; + while (!p.__tagRoot && (p = p.__parent)) { + if (p.__tagRoot) + ; + if (!p.__treeTags) { + p.__treeTags = /* @__PURE__ */ new Map(); + } + let s = p.__treeTags.get(tag); + if (!s) { + s = /* @__PURE__ */ new Set(); + p.__treeTags.set(tag, s); + } + tagSet.forEach(function(comp) { + s.add(comp); + }); + } + }); + } + } + } + _getByTag(tag) { + if (!this.__treeTags) { + return []; + } + let t = this.__treeTags.get(tag); + return t ? Utils$1.setToArray(t) : []; + } + getTags() { + return this.__tags ? this.__tags : []; + } + setTags(tags) { + tags = tags.reduce((acc, tag) => { + return acc.concat(tag.split(" ")); + }, []); + if (this.__ref) { + tags.push(this.__ref); + } + let i, n = tags.length; + let removes = []; + let adds = []; + for (i = 0; i < n; i++) { + if (!this.hasTag(tags[i])) { + adds.push(tags[i]); + } + } + let currentTags = this.tags || []; + n = currentTags.length; + for (i = 0; i < n; i++) { + if (tags.indexOf(currentTags[i]) == -1) { + removes.push(currentTags[i]); + } + } + for (i = 0; i < removes.length; i++) { + this.removeTag(removes[i]); + } + for (i = 0; i < adds.length; i++) { + this.addTag(adds[i]); + } + } + addTag(tag) { + if (tag.indexOf(" ") === -1) { + if (Utils$1.isUcChar(tag.charCodeAt(0))) { + this._throwError("Tag may not start with an upper case character."); + } + this._addTag(tag); + } else { + const tags = tag.split(" "); + for (let i = 0, m = tags.length; i < m; i++) { + const tag2 = tags[i]; + if (Utils$1.isUcChar(tag2.charCodeAt(0))) { + this._throwError("Tag may not start with an upper case character."); + } + this._addTag(tag2); + } + } + } + _addTag(tag) { + if (!this.__tags) { + this.__tags = []; + } + if (this.__tags.indexOf(tag) === -1) { + this.__tags.push(tag); + let p = this.__parent; + if (p) { + do { + if (!p.__treeTags) { + p.__treeTags = /* @__PURE__ */ new Map(); + } + let s = p.__treeTags.get(tag); + if (!s) { + s = /* @__PURE__ */ new Set(); + p.__treeTags.set(tag, s); + } + s.add(this); + } while (!p.__tagRoot && (p = p.__parent)); + } + } + } + removeTag(tag) { + let i = this.__tags.indexOf(tag); + if (i !== -1) { + this.__tags.splice(i, 1); + let p = this.__parent; + if (p) { + do { + let list = p.__treeTags.get(tag); + if (list) { + list.delete(this); + } + } while (!p.__tagRoot && (p = p.__parent)); + } + } + } + hasTag(tag) { + return this.__tags && this.__tags.indexOf(tag) !== -1; + } + _tag(tag) { + if (tag.indexOf(".") !== -1) { + return this.mtag(tag)[0]; + } else { + if (this.__treeTags) { + let t = this.__treeTags.get(tag); + if (t) { + const item = t.values().next(); + return item ? item.value : void 0; + } + } + } + } + get tag() { + return this._tag; + } + set tag(t) { + this.tags = t; + } + mtag(tag) { + let idx = tag.indexOf("."); + if (idx >= 0) { + let parts = tag.split("."); + let res = this._getByTag(parts[0]); + let level = 1; + let c = parts.length; + while (res.length && level < c) { + let resn = []; + for (let j = 0, n = res.length; j < n; j++) { + resn = resn.concat(res[j]._getByTag(parts[level])); + } + res = resn; + level++; + } + return res; + } else { + return this._getByTag(tag); + } + } + stag(tag, settings) { + let t = this.mtag(tag); + let n = t.length; + for (let i = 0; i < n; i++) { + Base.patchObject(t[i], settings); + } + } + get tagRoot() { + return this.__tagRoot; + } + set tagRoot(v) { + if (this.__tagRoot !== v) { + if (!v) { + this._setTagsParent(); + } else { + this._unsetTagsParent(); + } + this.__tagRoot = v; + } + } + sel(path) { + const results = this.select(path); + if (results.length) { + return results[0]; + } else { + return void 0; + } + } + select(path) { + if (path.indexOf(",") !== -1) { + let selectors = path.split(","); + let res = []; + for (let i = 0; i < selectors.length; i++) { + res = res.concat(this._select(selectors[i])); + } + return res; + } else { + return this._select(path); + } + } + _select(path) { + if (path === "") + return [this]; + let pointIdx = path.indexOf("."); + let arrowIdx = path.indexOf(">"); + if (pointIdx === -1 && arrowIdx === -1) { + return this.mtag(path); + } + let isRef; + if (arrowIdx === 0) { + isRef = true; + path = path.substr(1); + } else if (pointIdx === 0) { + isRef = false; + path = path.substr(1); + } else { + isRef = false; + } + return this._selectChilds(path, isRef); + } + _selectChilds(path, isRef) { + const pointIdx = path.indexOf("."); + const arrowIdx = path.indexOf(">"); + if (pointIdx === -1 && arrowIdx === -1) { + if (isRef) { + const ref = this.getByRef(path); + return ref ? [ref] : []; + } else { + return this.mtag(path); + } + } + if (arrowIdx === -1 || pointIdx !== -1 && pointIdx < arrowIdx) { + let next; + const str = path.substr(0, pointIdx); + if (isRef) { + const ref = this.getByRef(str); + next = ref ? [ref] : []; + } else { + next = this.mtag(str); + } + let total = []; + const subPath = path.substr(pointIdx + 1); + for (let i = 0, n = next.length; i < n; i++) { + total = total.concat(next[i]._selectChilds(subPath, false)); + } + return total; + } else { + let next; + const str = path.substr(0, arrowIdx); + if (isRef) { + const ref = this.getByRef(str); + next = ref ? [ref] : []; + } else { + next = this.mtag(str); + } + let total = []; + const subPath = path.substr(arrowIdx + 1); + for (let i = 0, n = next.length; i < n; i++) { + total = total.concat(next[i]._selectChilds(subPath, true)); + } + return total; + } + } + getByRef(ref) { + return this.childList.getByRef(ref); + } + getLocationString() { + let i; + i = this.__parent ? this.__parent._children.getIndex(this) : "R"; + let localTags = this.getTags(); + let str = this.__parent ? this.__parent.getLocationString() : ""; + if (this.ref) { + str += ":[" + i + "]" + this.ref; + } else if (localTags.length) { + str += ":[" + i + "]" + localTags.join(","); + } else { + str += ":[" + i + "]#" + this.id; + } + return str; + } + toString() { + let obj = this.getSettings(); + return Element.getPrettyString(obj, ""); + } + static getPrettyString(obj, indent) { + let children = obj.children; + delete obj.children; + let colorKeys = ["color", "colorUl", "colorUr", "colorBl", "colorBr"]; + let str = JSON.stringify(obj, function(k, v) { + if (colorKeys.indexOf(k) !== -1) { + return "COLOR[" + v.toString(16) + "]"; + } + return v; + }); + str = str.replace(/"COLOR\[([a-f0-9]{1,8})\]"/g, "0x$1"); + if (children) { + let childStr = ""; + if (Utils$1.isObjectLiteral(children)) { + let refs = Object.keys(children); + childStr = ""; + for (let i = 0, n = refs.length; i < n; i++) { + childStr += ` +${indent} "${refs[i]}":`; + delete children[refs[i]].ref; + childStr += Element.getPrettyString(children[refs[i]], indent + " ") + (i < n - 1 ? "," : ""); + } + let isEmpty = str === "{}"; + str = str.substr(0, str.length - 1) + (isEmpty ? "" : ",") + childStr + "\n" + indent + "}"; + } else { + let n = children.length; + childStr = "["; + for (let i = 0; i < n; i++) { + childStr += Element.getPrettyString(children[i], indent + " ") + (i < n - 1 ? "," : "") + "\n"; + } + childStr += indent + "]}"; + let isEmpty = str === "{}"; + str = str.substr(0, str.length - 1) + (isEmpty ? "" : ",") + '"children":\n' + indent + childStr + "}"; + } + } + return str; + } + getSettings() { + let settings = this.getNonDefaults(); + let children = this._children.get(); + if (children) { + let n = children.length; + if (n) { + const childArray = []; + let missing = false; + for (let i = 0; i < n; i++) { + childArray.push(children[i].getSettings()); + missing = missing || !children[i].ref; + } + if (!missing) { + settings.children = {}; + childArray.forEach((child) => { + settings.children[child.ref] = child; + }); + } else { + settings.children = childArray; + } + } + } + settings.id = this.id; + return settings; + } + getNonDefaults() { + let settings = {}; + if (this.constructor !== Element) { + settings.type = this.constructor.name; + } + if (this.__ref) { + settings.ref = this.__ref; + } + if (this.__tags && this.__tags.length) { + settings.tags = this.__tags; + } + if (this.x !== 0) + settings.x = this.x; + if (this.y !== 0) + settings.y = this.y; + if (this.w !== 0) + settings.w = this.w; + if (this.h !== 0) + settings.h = this.h; + if (this.scaleX === this.scaleY) { + if (this.scaleX !== 1) + settings.scale = this.scaleX; + } else { + if (this.scaleX !== 1) + settings.scaleX = this.scaleX; + if (this.scaleY !== 1) + settings.scaleY = this.scaleY; + } + if (this.pivotX === this.pivotY) { + if (this.pivotX !== 0.5) + settings.pivot = this.pivotX; + } else { + if (this.pivotX !== 0.5) + settings.pivotX = this.pivotX; + if (this.pivotY !== 0.5) + settings.pivotY = this.pivotY; + } + if (this.mountX === this.mountY) { + if (this.mountX !== 0) + settings.mount = this.mountX; + } else { + if (this.mountX !== 0) + settings.mountX = this.mountX; + if (this.mountY !== 0) + settings.mountY = this.mountY; + } + if (this.alpha !== 1) + settings.alpha = this.alpha; + if (!this.visible) + settings.visible = false; + if (this.rotation !== 0) + settings.rotation = this.rotation; + if (this.colorUl === this.colorUr && this.colorBl === this.colorBr && this.colorUl === this.colorBl) { + if (this.colorUl !== 4294967295) + settings.color = this.colorUl.toString(16); + } else { + if (this.colorUl !== 4294967295) + settings.colorUl = this.colorUl.toString(16); + if (this.colorUr !== 4294967295) + settings.colorUr = this.colorUr.toString(16); + if (this.colorBl !== 4294967295) + settings.colorBl = this.colorBl.toString(16); + if (this.colorBr !== 4294967295) + settings.colorBr = this.colorBr.toString(16); + } + if (this.zIndex) + settings.zIndex = this.zIndex; + if (this.forceZIndexContext) + settings.forceZIndexContext = true; + if (this.clipping) + settings.clipping = this.clipping; + if (!this.clipbox) + settings.clipbox = this.clipbox; + if (this.__texture) { + let tnd = this.__texture.getNonDefaults(); + if (Object.keys(tnd).length) { + settings.texture = tnd; + } + } + if (this.shader && Utils$1.isFunction(this.shader.getNonDefaults)) { + let tnd = this.shader.getNonDefaults(); + if (Object.keys(tnd).length) { + settings.shader = tnd; + } + } + if (this._hasTexturizer()) { + if (this.texturizer.enabled) { + settings.renderToTexture = this.texturizer.enabled; + } + if (this.texturizer.lazy) { + settings.renderToTextureLazy = this.texturizer.lazy; + } + if (this.texturizer.colorize) { + settings.colorizeResultTexture = this.texturizer.colorize; + } + if (this.texturizer.renderOffscreen) { + settings.renderOffscreen = this.texturizer.renderOffscreen; + } + } + return settings; + } + static getGetter(propertyPath) { + let getter = Element.PROP_GETTERS.get(propertyPath); + if (!getter) { + getter = new Function("obj", "return obj." + propertyPath); + Element.PROP_GETTERS.set(propertyPath, getter); + } + return getter; + } + static getSetter(propertyPath) { + let setter = Element.PROP_SETTERS.get(propertyPath); + if (!setter) { + setter = new Function("obj", "v", "obj." + propertyPath + " = v"); + Element.PROP_SETTERS.set(propertyPath, setter); + } + return setter; + } + get withinBoundsMargin() { + return this.__core._withinBoundsMargin; + } + _enableWithinBoundsMargin() { + if (this.__enabled) { + this._setActiveFlag(); + } + } + _disableWithinBoundsMargin() { + if (this.__active) { + this._unsetActiveFlag(); + } + } + set boundsMargin(v) { + if (!Array.isArray(v) && v !== null) { + throw new Error("boundsMargin should be an array of left-top-right-bottom values or null (inherit margin)"); + } + this.__core.boundsMargin = v; + } + get boundsMargin() { + return this.__core.boundsMargin; + } + get x() { + return this.__core.offsetX; + } + set x(v) { + this.__core.offsetX = v; + } + get y() { + return this.__core.offsetY; + } + set y(v) { + this.__core.offsetY = v; + } + get w() { + return this._w; + } + set w(v) { + if (Utils$1.isFunction(v)) { + this._w = 0; + this.__core.funcW = v; + } else { + v = Math.max(v, 0); + if (this._w !== v) { + this.__core.disableFuncW(); + this._w = v; + this._updateDimensions(); + } + } + } + get h() { + return this._h; + } + set h(v) { + if (Utils$1.isFunction(v)) { + this._h = 0; + this.__core.funcH = v; + } else { + v = Math.max(v, 0); + if (this._h !== v) { + this.__core.disableFuncH(); + this._h = v; + this._updateDimensions(); + } + } + } + get collision() { + return this._collision; + } + set collision(v) { + this._collision = v; + } + _updateCollision() { + if (this.collision && this.__parent && this.__parent.collision === void 0) { + this.__parent.collision = 2; + } + } + get scaleX() { + return this.__core.scaleX; + } + set scaleX(v) { + this.__core.scaleX = v; + } + get scaleY() { + return this.__core.scaleY; + } + set scaleY(v) { + this.__core.scaleY = v; + } + get scale() { + return this.__core.scale; + } + set scale(v) { + this.__core.scale = v; + } + get pivotX() { + return this.__core.pivotX; + } + set pivotX(v) { + this.__core.pivotX = v; + } + get pivotY() { + return this.__core.pivotY; + } + set pivotY(v) { + this.__core.pivotY = v; + } + get pivot() { + return this.__core.pivot; + } + set pivot(v) { + this.__core.pivot = v; + } + get mountX() { + return this.__core.mountX; + } + set mountX(v) { + this.__core.mountX = v; + } + get mountY() { + return this.__core.mountY; + } + set mountY(v) { + this.__core.mountY = v; + } + get mount() { + return this.__core.mount; + } + set mount(v) { + this.__core.mount = v; + } + get rotation() { + return this.__core.rotation; + } + set rotation(v) { + this.__core.rotation = v; + } + get alpha() { + return this.__core.alpha; + } + set alpha(v) { + this.__core.alpha = v; + } + get visible() { + return this.__core.visible; + } + set visible(v) { + this.__core.visible = v; + } + get colorUl() { + return this.__core.colorUl; + } + set colorUl(v) { + this.__core.colorUl = v; + } + get colorUr() { + return this.__core.colorUr; + } + set colorUr(v) { + this.__core.colorUr = v; + } + get colorBl() { + return this.__core.colorBl; + } + set colorBl(v) { + this.__core.colorBl = v; + } + get colorBr() { + return this.__core.colorBr; + } + set colorBr(v) { + this.__core.colorBr = v; + } + get color() { + return this.__core.colorUl; + } + set color(v) { + if (this.colorUl !== v || this.colorUr !== v || this.colorBl !== v || this.colorBr !== v) { + this.colorUl = v; + this.colorUr = v; + this.colorBl = v; + this.colorBr = v; + } + } + get colorTop() { + return this.colorUl; + } + set colorTop(v) { + if (this.colorUl !== v || this.colorUr !== v) { + this.colorUl = v; + this.colorUr = v; + } + } + get colorBottom() { + return this.colorBl; + } + set colorBottom(v) { + if (this.colorBl !== v || this.colorBr !== v) { + this.colorBl = v; + this.colorBr = v; + } + } + get colorLeft() { + return this.colorUl; + } + set colorLeft(v) { + if (this.colorUl !== v || this.colorBl !== v) { + this.colorUl = v; + this.colorBl = v; + } + } + get colorRight() { + return this.colorUr; + } + set colorRight(v) { + if (this.colorUr !== v || this.colorBr !== v) { + this.colorUr = v; + this.colorBr = v; + } + } + get zIndex() { + return this.__core.zIndex; + } + set zIndex(v) { + this.__core.zIndex = v; + } + get forceZIndexContext() { + return this.__core.forceZIndexContext; + } + set forceZIndexContext(v) { + this.__core.forceZIndexContext = v; + } + get clipping() { + return this.__core.clipping; + } + set clipping(v) { + this.__core.clipping = v; + } + get clipbox() { + return this.__core.clipbox; + } + set clipbox(v) { + this.__core.clipbox = v; + } + get tags() { + return this.getTags(); + } + set tags(v) { + if (!Array.isArray(v)) + v = [v]; + this.setTags(v); + } + set t(v) { + this.tags = v; + } + get _children() { + if (!this.__childList) { + this.__childList = new ElementChildList(this, false); + } + return this.__childList; + } + get childList() { + if (!this._allowChildrenAccess()) { + this._throwError("Direct access to children is not allowed in " + this.getLocationString()); + } + return this._children; + } + hasChildren() { + return this._allowChildrenAccess() && this.__childList && this.__childList.length > 0; + } + _allowChildrenAccess() { + return true; + } + get children() { + return this.childList.get(); + } + set children(children) { + this.childList.patch(children); + } + add(o) { + return this.childList.a(o); + } + get p() { + return this.__parent; + } + get parent() { + return this.__parent; + } + get src() { + if (this.texture && this.texture instanceof ImageTexture) { + return this.texture._src; + } else { + return void 0; + } + } + set src(v) { + const texture = new ImageTexture(this.stage); + texture.src = v; + this.texture = texture; + } + set mw(v) { + if (this.texture) { + this.texture.mw = v; + this._updateDimensions(); + } else { + this._throwError("Please set mw after setting a texture."); + } + } + set mh(v) { + if (this.texture) { + this.texture.mh = v; + this._updateDimensions(); + } else { + this._throwError("Please set mh after setting a texture."); + } + } + get rect() { + return this.texture === this.stage.rectangleTexture; + } + set rect(v) { + if (v) { + this.texture = this.stage.rectangleTexture; + } else { + this.texture = null; + } + } + enableTextTexture() { + if (!this.texture || !(this.texture instanceof TextTexture)) { + this.texture = new TextTexture(this.stage); + if (!this.texture.w && !this.texture.h) { + this.texture.w = this.w; + this.texture.h = this.h; + } + } + return this.texture; + } + get text() { + if (this.texture && this.texture instanceof TextTexture) { + return this.texture; + } else { + return null; + } + } + set text(v) { + if (!this.texture || !(this.texture instanceof TextTexture)) { + this.enableTextTexture(); + } + if (Utils$1.isString(v)) { + this.texture.text = v; + } else { + this.texture.patch(v); + } + } + set onUpdate(f) { + this.__core.onUpdate = f; + } + set onAfterCalcs(f) { + this.__core.onAfterCalcs = f; + } + set onAfterUpdate(f) { + this.__core.onAfterUpdate = f; + } + forceUpdate() { + this.__core._setHasUpdates(); + } + get shader() { + return this.__core.shader; + } + set shader(v) { + if (Utils$1.isObjectLiteral(v) && !v.type) { + if (this.shader) { + this.shader.patch(v); + } + } else { + const shader = Shader.create(this.stage, v); + if (this.__enabled && this.__core.shader) { + this.__core.shader.removeElement(this.__core); + } + this.__core.shader = shader; + if (this.__enabled && this.__core.shader) { + this.__core.shader.addElement(this.__core); + } + } + } + _hasTexturizer() { + return !!this.__core._texturizer; + } + get renderToTexture() { + return this.rtt; + } + set renderToTexture(v) { + this.rtt = v; + } + get rtt() { + return this._hasTexturizer() && this.texturizer.enabled; + } + set rtt(v) { + this.texturizer.enabled = v; + } + get rttLazy() { + return this._hasTexturizer() && this.texturizer.lazy; + } + set rttLazy(v) { + this.texturizer.lazy = v; + } + get renderOffscreen() { + return this._hasTexturizer() && this.texturizer.renderOffscreen; + } + set renderOffscreen(v) { + this.texturizer.renderOffscreen = v; + } + get colorizeResultTexture() { + return this._hasTexturizer() && this.texturizer.colorize; + } + set colorizeResultTexture(v) { + this.texturizer.colorize = v; + } + getTexture() { + return this.texturizer._getTextureSource(); + } + get texturizer() { + return this.__core.texturizer; + } + patch(settings) { + let paths = Object.keys(settings); + for (let i = 0, n = paths.length; i < n; i++) { + let path = paths[i]; + const v = settings[path]; + const firstCharCode = path.charCodeAt(0); + if (Utils$1.isUcChar(firstCharCode)) { + const child = this.getByRef(path); + if (!child) { + if (v !== void 0) { + let c; + if (Utils$1.isObjectLiteral(v)) { + c = this.childList.createItem(v); + c.patch(v); + } else if (Utils$1.isObject(v)) { + c = v; + } + if (c.isElement) { + c.ref = path; + } + this.childList.a(c); + } + } else { + if (v === void 0) { + if (child.parent) { + child.parent.childList.remove(child); + } + } else if (Utils$1.isObjectLiteral(v)) { + child.patch(v); + } else if (v.isElement) { + v.ref = path; + this.childList.replace(v, child); + } else { + this._throwError("Unexpected value for path: " + path); + } + } + } else { + Base.patchObjectProperty(this, path, v); + } + } + } + _throwError(message) { + throw new Error(this.constructor.name + " (" + this.getLocationString() + "): " + message); + } + animation(settings) { + return this.stage.animations.createAnimation(this, settings); + } + transition(property, settings = null) { + if (settings === null) { + return this._getTransition(property); + } else { + this._setTransition(property, settings); + return null; + } + } + set transitions(object) { + let keys = Object.keys(object); + keys.forEach((property) => { + this.transition(property, object[property]); + }); + } + set smooth(object) { + let keys = Object.keys(object); + keys.forEach((property) => { + let value = object[property]; + if (Array.isArray(value)) { + this.setSmooth(property, value[0], value[1]); + } else { + this.setSmooth(property, value); + } + }); + } + fastForward(property) { + if (this._transitions) { + let t = this._transitions[property]; + if (t && t.isTransition) { + t.finish(); + } + } + } + _getTransition(property) { + if (!this._transitions) { + this._transitions = {}; + } + let t = this._transitions[property]; + if (!t) { + t = new Transition(this.stage.transitions, this.stage.transitions.defaultTransitionSettings, this, property); + } else if (t.isTransitionSettings) { + t = new Transition( + this.stage.transitions, + t, + this, + property + ); + } + this._transitions[property] = t; + return t; + } + _setTransition(property, settings) { + if (!settings) { + this._removeTransition(property); + } else { + if (Utils$1.isObjectLiteral(settings)) { + settings = this.stage.transitions.createSettings(settings); + } + if (!this._transitions) { + this._transitions = {}; + } + let current = this._transitions[property]; + if (current && current.isTransition) { + current.settings = settings; + return current; + } else { + this._transitions[property] = settings; + } + } + } + _removeTransition(property) { + if (this._transitions) { + delete this._transitions[property]; + } + } + getSmooth(property, v) { + let t = this._getTransition(property); + if (t && t.isAttached()) { + return t.targetValue; + } else { + return v; + } + } + setSmooth(property, v, settings) { + if (settings) { + this._setTransition(property, settings); + } + let t = this._getTransition(property); + t.start(v); + return t; + } + get flex() { + return this.__core.flex; + } + set flex(v) { + this.__core.flex = v; + } + get flexItem() { + return this.__core.flexItem; + } + set flexItem(v) { + this.__core.flexItem = v; + } + static isColorProperty(property) { + return property.toLowerCase().indexOf("color") >= 0; + } + static getMerger(property) { + if (Element.isColorProperty(property)) { + return StageUtils.mergeColors; + } else { + return StageUtils.mergeNumbers; + } + } + toJSON() { + const ref = [`${this.constructor.name}`]; + const tree = {}; + tree[ref] = {}; + if (this.hasChildren()) { + Element.collectChildren(tree[ref], this.__childList); + } else { + tree[ref] = { ...Element.getProperties(this) }; + } + return tree; + } + static collectChildren(tree, children) { + const childList = children; + for (let i = 0, j = childList.length; i < j; i++) { + const element = childList.getAt(i); + const ref = `${element.__ref || `Element-${element.id}`}`; + const properties = this.getProperties(element); + tree[ref] = { ...properties }; + if (element.hasChildren()) { + tree[ref].children = {}; + this.collectChildren( + tree[ref].children, + element.__childList + ); + } + } + } + static getProperties(element) { + const props = {}; + const list = [ + "alpha", + "active", + "attached", + "boundsMargin", + "color", + "clipping", + "enabled", + "h", + "id", + "isComponent", + "mount", + "mountY", + "mountX", + "pivot", + "pivotX", + "pivotY", + "ref", + "renderOffscreen", + "renderToTexture", + "scale", + "scaleX", + "scaleY", + "state", + "tag", + "visible", + "w", + "x", + "y", + "zIndex", + "!!flex", + "!!flexItem", + "hasFocus()", + "hasFinalFocus()" + ]; + let n = list.length; + while (n--) { + let key = list[n]; + const getBoolean = /^!{2}/; + const isFunction = /\(\)$/; + if (getBoolean.test(key)) { + key = key.substring(2, key.length); + props[key] = !!element[key]; + } else if (isFunction.test(key)) { + key = key.substring(0, key.length - 2); + if (typeof element[key] === "function") { + props[key] = element[key](); + } + } else { + props[key] = element[key]; + } + } + return { ...props, ...element.getNonDefaults() }; + } +} +EventEmitter.addAsMixin(Element); +Element.prototype.isElement = 1; +Element.id = 1; +Element.PROP_GETTERS = /* @__PURE__ */ new Map(); +Element.PROP_SETTERS = /* @__PURE__ */ new Map(); +class StateMachine { + constructor() { + StateMachine.setupStateMachine(this); + } + static setupStateMachine(target) { + const targetConstructor = target.constructor; + const router = StateMachine.create(targetConstructor); + Object.setPrototypeOf(target, router.prototype); + target.constructor = targetConstructor; + target._initStateMachine(); + } + static create(type) { + if (!type.hasOwnProperty("_sm")) { + const stateMachineType = new StateMachineType(type); + type._sm = stateMachineType; + } + return type._sm.router; + } + fire(event, ...args) { + if (this._hasMethod(event)) { + return this[event](...args); + } + } + _getState() { + return this._state.__path; + } + _inState(statePath, currentStatePath = this._state.__path) { + const state = this._sm.getStateByPath(statePath); + const currentState = this._sm.getStateByPath(currentStatePath); + const level = state.__level; + const stateAtLevel = StateMachine._getStateAtLevel(currentState, level); + return stateAtLevel === state; + } + _hasMember(name) { + return !!this.constructor.prototype[name]; + } + _hasMethod(name) { + const member = this.constructor.prototype[name]; + return !!member && typeof member === "function"; + } + _setState(statePath, args) { + const setStateId = ++this._setStateCounter; + this._setStateId = setStateId; + if (this._state.__path !== statePath) { + let newState = this._sm._stateMap[statePath]; + if (!newState) { + newState = this._sm.getStateByPath(statePath); + } + const prevState = this._state; + const hasDifferentEnterMethod = newState.prototype.$enter !== this._state.prototype.$enter; + const hasDifferentExitMethod = newState.prototype.$exit !== this._state.prototype.$exit; + if (hasDifferentEnterMethod || hasDifferentExitMethod) { + const sharedState = StateMachine._getSharedState(this._state, newState); + const context = { + newState: newState.__path, + prevState: prevState.__path, + sharedState: sharedState.__path + }; + const sharedLevel = sharedState.__level; + if (hasDifferentExitMethod) { + const exitStates = StateMachine._getStatesUntilLevel(this._state, sharedLevel); + for (let i = 0, n = exitStates.length; i < n; i++) { + this.__setState(exitStates[i]); + this._callExit(this._state, args, context); + const stateChangeOverridden = this._setStateId !== setStateId; + if (stateChangeOverridden) { + return; + } + } + } + if (hasDifferentEnterMethod) { + const enterStates = StateMachine._getStatesUntilLevel(newState, sharedLevel).reverse(); + for (let i = 0, n = enterStates.length; i < n; i++) { + this.__setState(enterStates[i]); + this._callEnter(this._state, args, context); + const stateChangeOverridden = this._setStateId !== setStateId; + if (stateChangeOverridden) { + return; + } + } + } + } + this.__setState(newState); + if (this._changedState) { + const context = { + newState: newState.__path, + prevState: prevState.__path + }; + if (args) { + this._changedState(context, ...args); + } else { + this._changedState(context); + } + } + if (this._onStateChange) { + const context = { + newState: newState.__path, + prevState: prevState.__path + }; + this._onStateChange(context); + } + } + } + _callEnter(state, args = [], context) { + const hasParent = !!state.__parent; + if (state.prototype.$enter) { + if (!hasParent || state.__parent.prototype.$enter !== state.prototype.$enter) { + state.prototype.$enter.apply(this, [context, ...args]); + } + } + } + _callExit(state, args = [], context) { + const hasParent = !!state.__parent; + if (state.prototype.$exit) { + if (!hasParent || state.__parent.prototype.$exit !== state.prototype.$exit) { + state.prototype.$exit.apply(this, [context, ...args]); + } + } + } + __setState(state) { + this._state = state; + this._stateIndex = state.__index; + this.constructor = state; + } + _initStateMachine() { + this._state = null; + this._stateIndex = 0; + this._setStateCounter = 0; + this._sm = this._routedType._sm; + this.__setState(this._sm.getStateByPath("")); + const context = { newState: "", prevState: void 0, sharedState: void 0 }; + this._callEnter(this._state, [], context); + this._onStateChange = void 0; + } + _getMostSpecificHandledMember(memberNames) { + let cur = this._state; + do { + for (let i = 0, n = memberNames.length; i < n; i++) { + const memberName = memberNames[i]; + if (!cur.__parent) { + if (cur.prototype[memberName]) { + return memberName; + } + } else { + const alias = StateMachineType.getStateMemberAlias(cur.__path, memberName); + if (this[alias]) { + return memberName; + } + } + } + cur = cur.__parent; + } while (cur); + } + static _getStatesUntilLevel(state, level) { + const states = []; + while (state.__level > level) { + states.push(state); + state = state.__parent; + } + return states; + } + static _getSharedState(state1, state2) { + const state1Array = StateMachine._getAncestorStates(state1); + const state2Array = StateMachine._getAncestorStates(state2); + const n = Math.min(state1Array.length, state2Array.length); + for (let i = 0; i < n; i++) { + if (state1Array[i] !== state2Array[i]) { + return state1Array[i - 1]; + } + } + return state1Array[n - 1]; + } + static _getAncestorStates(state) { + const result = []; + do { + result.push(state); + } while (state = state.__parent); + return result.reverse(); + } + static _getStateAtLevel(state, level) { + if (level > state.__level) { + return void 0; + } + while (level < state.__level) { + state = state.__parent; + } + return state; + } +} +class StateMachineType { + constructor(type) { + this._type = type; + this._router = null; + this.init(); + } + get router() { + return this._router; + } + init() { + this._router = this._createRouter(); + this._stateMap = this._getStateMap(); + this._addStateMemberDelegatorsToRouter(); + } + _createRouter() { + const type = this._type; + const router = class StateMachineRouter extends type { + constructor() { + super(...arguments); + if (!this.constructor.hasOwnProperty("_isRouter")) { + throw new Error(`You need to extend ${type.name}.original instead of ${type.name}.`); + } + } + }; + router._isRouter = true; + router.prototype._routedType = type; + router.original = type; + this._mixinStateMachineMethods(router); + return router; + } + _mixinStateMachineMethods(router) { + const names = Object.getOwnPropertyNames(StateMachine.prototype); + for (let i = 0, n = names.length; i < n; i++) { + const name = names[i]; + if (name !== "constructor") { + const descriptor = Object.getOwnPropertyDescriptor(StateMachine.prototype, name); + Object.defineProperty(router.prototype, name, descriptor); + } + } + } + _addStateMemberDelegatorsToRouter() { + const members = this._getAllMemberNames(); + members.forEach((member) => { + this._addMemberRouter(member); + }); + } + _addMemberRouter(member) { + const statePaths = Object.keys(this._stateMap); + const descriptors = []; + const aliases = []; + statePaths.forEach((statePath, index) => { + const state = this._stateMap[statePath]; + const descriptor = this._getDescriptor(state, member); + if (descriptor) { + descriptors[index] = descriptor; + const alias = StateMachineType.getStateMemberAlias(descriptor._source.__path, member); + aliases[index] = alias; + if (!this._router.prototype.hasOwnProperty(alias)) { + Object.defineProperty(this._router.prototype, alias, descriptor); + } + } else { + descriptors[index] = null; + aliases[index] = null; + } + }); + let type = void 0; + descriptors.forEach((descriptor) => { + if (descriptor) { + const descType = this._getDescriptorType(descriptor); + if (type && type !== descType) { + console.warn(`[Lightning] Member ${member} in ${this._type.name} has inconsistent types.`); + return; + } + type = descType; + } + }); + switch (type) { + case "method": + this._addMethodRouter(member, descriptors, aliases); + break; + case "getter": + this._addGetterSetterRouters(member); + break; + case "property": + console.warn("[Lightning] Fixed properties are not supported; please use a getter instead!"); + break; + } + } + _getDescriptor(state, member, isValid = () => true) { + let type = state; + let curState = state; + do { + const descriptor = Object.getOwnPropertyDescriptor(type.prototype, member); + if (descriptor) { + if (isValid(descriptor)) { + descriptor._source = curState; + return descriptor; + } + } + type = Object.getPrototypeOf(type); + if (type && type.hasOwnProperty("__state")) { + curState = type; + } + } while (type && type.prototype); + return void 0; + } + _getDescriptorType(descriptor) { + if (descriptor.get || descriptor.set) { + return "getter"; + } else { + if (typeof descriptor.value === "function") { + return "method"; + } else { + return "property"; + } + } + } + static _supportsSpread() { + if (this.__supportsSpread === void 0) { + this.__supportsSpread = false; + try { + const func = new Function("return [].concat(...arguments);"); + func(); + this.__supportsSpread = true; + } catch (e) { + } + } + return this.__supportsSpread; + } + _addMethodRouter(member, descriptors, aliases) { + const code = [ + "//@ sourceURL=StateMachineRouter.js", + "var i = this._stateIndex;" + ]; + let cur = aliases[0]; + const supportsSpread = StateMachineType._supportsSpread(); + for (let i = 1, n = aliases.length; i < n; i++) { + const alias = aliases[i]; + if (alias !== cur) { + if (cur) { + if (supportsSpread) { + code.push(`if (i < ${i}) return this["${cur}"](...arguments); else`); + } else { + code.push(`if (i < ${i}) return this["${cur}"].apply(this, arguments); else`); + } + } else { + code.push(`if (i < ${i}) return ; else`); + } + } + cur = alias; + } + if (cur) { + if (supportsSpread) { + code.push(`return this["${cur}"](...arguments);`); + } else { + code.push(`return this["${cur}"].apply(this, arguments);`); + } + } else { + code.push(`;`); + } + const functionBody = code.join("\n"); + const router = new Function([], functionBody); + const descriptor = { value: router }; + Object.defineProperty(this._router.prototype, member, descriptor); + } + _addGetterSetterRouters(member) { + const getter = this._getGetterRouter(member); + const setter = this._getSetterRouter(member); + const descriptor = { + get: getter, + set: setter + }; + Object.defineProperty(this._router.prototype, member, descriptor); + } + _getGetterRouter(member) { + const statePaths = Object.keys(this._stateMap); + const aliases = []; + statePaths.forEach((statePath, index) => { + const state = this._stateMap[statePath]; + const descriptor = this._getDescriptor(state, member, (descriptor2) => descriptor2.get); + if (descriptor) { + const alias = StateMachineType.getStateMemberAlias(descriptor._source.__path, member); + aliases[index] = alias; + if (!this._router.prototype.hasOwnProperty(alias)) { + Object.defineProperty(this._router.prototype, alias, descriptor); + } + } else { + aliases[index] = null; + } + }); + const code = [ + "//@ sourceURL=StateMachineRouter.js", + "var i = this._stateIndex;" + ]; + let cur = aliases[0]; + for (let i = 1, n = aliases.length; i < n; i++) { + const alias = aliases[i]; + if (alias !== cur) { + if (cur) { + code.push(`if (i < ${i}) return this["${cur}"]; else`); + } else { + code.push(`if (i < ${i}) return ; else`); + } + } + cur = alias; + } + if (cur) { + code.push(`return this["${cur}"];`); + } else { + code.push(`;`); + } + const functionBody = code.join("\n"); + const router = new Function([], functionBody); + return router; + } + _getSetterRouter(member) { + const statePaths = Object.keys(this._stateMap); + const aliases = []; + statePaths.forEach((statePath, index) => { + const state = this._stateMap[statePath]; + const descriptor = this._getDescriptor(state, member, (descriptor2) => descriptor2.set); + if (descriptor) { + const alias = StateMachineType.getStateMemberAlias(descriptor._source.__path, member); + aliases[index] = alias; + if (!this._router.prototype.hasOwnProperty(alias)) { + Object.defineProperty(this._router.prototype, alias, descriptor); + } + } else { + aliases[index] = null; + } + }); + const code = [ + "//@ sourceURL=StateMachineRouter.js", + "var i = this._stateIndex;" + ]; + let cur = aliases[0]; + for (let i = 1, n = aliases.length; i < n; i++) { + const alias = aliases[i]; + if (alias !== cur) { + if (cur) { + code.push(`if (i < ${i}) this["${cur}"] = arg; else`); + } else { + code.push(`if (i < ${i}) ; else`); + } + } + cur = alias; + } + if (cur) { + code.push(`this["${cur}"] = arg;`); + } else { + code.push(`;`); + } + const functionBody = code.join("\n"); + const router = new Function(["arg"], functionBody); + return router; + } + static getStateMemberAlias(path, member) { + return "$" + (path ? path + "." : "") + member; + } + _getAllMemberNames() { + const stateMap = this._stateMap; + const map = Object.keys(stateMap); + let members = /* @__PURE__ */ new Set(); + map.forEach((statePath) => { + if (statePath === "") { + return; + } + const state = stateMap[statePath]; + const names = this._getStateMemberNames(state); + names.forEach((name) => { + members.add(name); + }); + }); + return [...members]; + } + _getStateMemberNames(state) { + let type = state; + let members = /* @__PURE__ */ new Set(); + const isRoot = this._type === state; + do { + const names = this._getStateMemberNamesForType(type); + names.forEach((name) => { + members.add(name); + }); + type = Object.getPrototypeOf(type); + } while (type && type.prototype && (!type.hasOwnProperty("__state") || isRoot)); + return members; + } + _getStateMemberNamesForType(type) { + const memberNames = Object.getOwnPropertyNames(type.prototype); + return memberNames.filter((memberName) => { + return memberName !== "constructor" && !StateMachineType._isStateLocalMember(memberName); + }); + } + static _isStateLocalMember(memberName) { + return memberName === "$enter" || memberName === "$exit"; + } + getStateByPath(statePath) { + if (this._stateMap[statePath]) { + return this._stateMap[statePath]; + } + const parts = statePath.split("."); + while (parts.pop()) { + const statePath2 = parts.join("."); + if (this._stateMap[statePath2]) { + return this._stateMap[statePath2]; + } + } + } + _getStateMap() { + if (!this._stateMap) { + this._stateMap = this._createStateMap(); + } + return this._stateMap; + } + _createStateMap() { + const stateMap = {}; + this._addState(this._type, null, "", stateMap); + return stateMap; + } + _addState(state, parentState, name, stateMap) { + state.__state = true; + state.__name = name; + this._addStaticStateProperty(state, parentState); + const parentPath = parentState ? parentState.__path : ""; + let path = (parentPath ? parentPath + "." : "") + name; + state.__path = path; + state.__level = parentState ? parentState.__level + 1 : 0; + state.__parent = parentState; + state.__index = Object.keys(stateMap).length; + stateMap[path] = state; + const states = state._states; + if (states) { + const isInheritedFromParent = parentState && parentState._states === states; + if (!isInheritedFromParent) { + const subStates = state._states(); + subStates.forEach((subState) => { + const stateName = StateMachineType._getStateName(subState); + this._addState(subState, state, stateName, stateMap); + }); + } + } + } + static _getStateName(state) { + const name = state.name; + const index = name.indexOf("$"); + if (index > 0) { + return name.substr(0, index); + } + return name; + } + _addStaticStateProperty(state, parentState) { + if (parentState) { + const isClassStateLevel = parentState && !parentState.__parent; + if (isClassStateLevel) { + this._router[state.__name] = state; + } else { + parentState[state.__name] = state; + } + } + } +} +class Component extends Element { + constructor(stage, properties) { + super(stage); + this.tagRoot = true; + if (Utils$1.isObjectLiteral(properties)) { + Object.assign(this, properties); + } + this.__initialized = false; + this.__firstActive = false; + this.__firstEnable = false; + this.__signals = void 0; + this.__passSignals = void 0; + this.__construct(); + const func = this.constructor.getTemplateFunc(this); + func.f(this, func.a); + this._build(); + } + __start() { + StateMachine.setupStateMachine(this); + this._onStateChange = Component.prototype.__onStateChange; + } + get state() { + return this._getState(); + } + __onStateChange() { + if (this.application) { + this.application.updateFocusPath(); + } + } + _refocus() { + if (this.application) { + this.application.updateFocusPath(); + } + } + static bindProp(name, func = null) { + return { __propertyBinding: true, __name: name, __func: func }; + } + __bindProperty(propObj, targetObj, targetProp) { + const obj = targetObj; + const prop = targetProp; + const propDependencies = Array.isArray(propObj.__name) ? propObj.__name : [propObj.__name]; + for (let i = 0; i < propDependencies.length; i++) { + const propName = propDependencies[i]; + const func = propObj.__func ? propObj.__func : (context) => context[propName]; + if (!this.hasOwnProperty(propName)) { + this[`__prop_bindings_${propName}`] = [{ __obj: obj, __prop: prop, __func: func }]; + Object.defineProperty(this, propName, { + set: (value) => { + this[`__prop_${propName}`] = value; + for (const { __obj, __prop, __func } of this[`__prop_bindings_${propName}`]) { + __obj[__prop] = __func(this); + } + }, + get: () => this[`__prop_${propName}`] + }); + } else { + this[`__prop_bindings_${propName}`].push({ __obj: obj, __prop: prop, __func: func }); + } + } + } + static getTemplateFunc(ctx) { + const name = "_templateFunc"; + const hasName = "__has" + name; + if (this[hasName] !== this) { + this[hasName] = this; + this[name] = this.parseTemplate(this._template(ctx)); + } + return this[name]; + } + static parseTemplate(obj) { + const context = { + loc: [], + store: [], + rid: 0 + }; + this.parseTemplateRec(obj, context, "element"); + const code = context.loc.join(";\n"); + const f = new Function("element", "store", code); + return { f, a: context.store }; + } + static parseTemplateRec(obj, context, cursor) { + const store = context.store; + const loc = context.loc; + const keys = Object.keys(obj); + keys.forEach((key) => { + let value = obj[key]; + if (Utils$1.isUcChar(key.charCodeAt(0))) { + if (Utils$1.isObjectLiteral(value)) { + const childCursor = `r${key.replace(/[^a-z0-9]/gi, "") + context.rid}`; + let type = value.type ? value.type : Element; + if (type === Element) { + loc.push(`var ${childCursor} = element.stage.createElement()`); + } else { + store.push(type); + loc.push(`var ${childCursor} = new store[${store.length - 1}](${cursor}.stage)`); + } + loc.push(`${childCursor}.ref = "${key}"`); + context.rid++; + this.parseTemplateRec(value, context, childCursor); + loc.push(`${cursor}.childList.add(${childCursor})`); + } else if (Utils$1.isObject(value)) { + store.push(value); + loc.push(`${cursor}.childList.add(store[${store.length - 1}])`); + } + } else { + if (key === "text") { + const propKey = cursor + "__text"; + loc.push(`var ${propKey} = ${cursor}.enableTextTexture()`); + if (value.__propertyBinding === true) { + store.push(value); + loc.push(`element.__bindProperty(store[${store.length - 1}], ${cursor}, "${key}")`); + } else { + this.parseTemplatePropRec(value, context, propKey); + } + } else if (key === "shader" && Utils$1.isObjectLiteral(value)) { + const shaderCursor = `${cursor}["shader"]`; + store.push(value); + loc.push(`${cursor}["${key}"] = store[${store.length - 1}]`); + this.parsePropertyBindings(value, context, shaderCursor); + } else if (key === "texture" && Utils$1.isObjectLiteral(value)) { + const propKey = cursor + "__texture"; + const type = value.type; + if (type) { + store.push(type); + loc.push(`var ${propKey} = new store[${store.length - 1}](${cursor}.stage)`); + this.parseTemplatePropRec(value, context, propKey); + loc.push(`${cursor}["${key}"] = ${propKey}`); + } else { + loc.push(`${propKey} = ${cursor}.texture`); + this.parseTemplatePropRec(value, context, propKey); + } + } else if (Utils$1.isObjectLiteral(value) && value.__propertyBinding === true) { + store.push(value); + loc.push(`element.__bindProperty(store[${store.length - 1}], ${cursor}, "${key}")`); + } else { + if (Utils$1.isNumber(value)) { + loc.push(`${cursor}["${key}"] = ${value}`); + } else if (Utils$1.isBoolean(value)) { + loc.push(`${cursor}["${key}"] = ${value ? "true" : "false"}`); + } else if (Utils$1.isObject(value) || Array.isArray(value)) { + store.push(value); + loc.push(`${cursor}["${key}"] = store[${store.length - 1}]`); + } else { + loc.push(`${cursor}["${key}"] = ${JSON.stringify(value)}`); + } + } + } + }); + } + static parseTemplatePropRec(obj, context, cursor) { + const store = context.store; + const loc = context.loc; + const keys = Object.keys(obj); + keys.forEach((key) => { + if (key !== "type") { + const value = obj[key]; + if (Utils$1.isNumber(value)) { + loc.push(`${cursor}["${key}"] = ${value}`); + } else if (Utils$1.isBoolean(value)) { + loc.push(`${cursor}["${key}"] = ${value ? "true" : "false"}`); + } else if (Utils$1.isObject(value) && value.__propertyBinding === true) { + store.push(value); + loc.push(`element.__bindProperty(store[${store.length - 1}], ${cursor}, "${key}")`); + } else if (Utils$1.isObject(value) || Array.isArray(value)) { + store.push(value); + loc.push(`${cursor}["${key}"] = store[${store.length - 1}]`); + } else { + loc.push(`${cursor}["${key}"] = ${JSON.stringify(value)}`); + } + } + }); + } + static parsePropertyBindings(obj, context, cursor) { + const store = context.store; + const loc = context.loc; + const keys = Object.keys(obj); + keys.forEach((key) => { + if (key !== "type") { + const value = obj[key]; + if (Utils$1.isObjectLiteral(value) && value.__propertyBinding === true) { + store.push(value); + loc.push(`element.__bindProperty(store[${store.length - 1}], ${cursor}, "${key}")`); + } + } + }); + } + _onSetup() { + if (!this.__initialized) { + this._setup(); + } + } + _setup() { + } + _onAttach() { + if (!this.__initialized) { + this.__init(); + this.__initialized = true; + } + this._attach(); + } + _attach() { + } + _onDetach() { + this._detach(); + } + _detach() { + } + _onEnabled() { + if (!this.__firstEnable) { + this._firstEnable(); + this.__firstEnable = true; + } + this._enable(); + } + _firstEnable() { + } + _enable() { + } + _onDisabled() { + this._disable(); + } + _disable() { + } + _onActive() { + if (!this.__firstActive) { + this._firstActive(); + this.__firstActive = true; + } + this._active(); + } + _firstActive() { + } + _active() { + } + _onInactive() { + this._inactive(); + } + _inactive() { + } + get application() { + return this.stage.application; + } + __construct() { + this._construct(); + } + _construct() { + } + _build() { + } + __init() { + this._init(); + } + _init() { + } + _focus(newTarget, prevTarget) { + } + _unfocus(newTarget) { + } + _focusChange(target, newTarget) { + } + _getFocused() { + return this; + } + _setFocusSettings(settings) { + } + _handleFocusSettings(settings) { + } + static _template() { + return {}; + } + hasFinalFocus() { + let path = this.application._focusPath; + return path && path.length && path[path.length - 1] === this; + } + hasFocus() { + let path = this.application._focusPath; + return path && path.indexOf(this) >= 0; + } + get cparent() { + return Component.getParent(this); + } + seekAncestorByType(type) { + let c = this.cparent; + while (c) { + if (c.constructor === type) { + return c; + } + c = c.cparent; + } + } + getSharedAncestorComponent(element) { + let ancestor = this.getSharedAncestor(element); + while (ancestor && !ancestor.isComponent) { + ancestor = ancestor.parent; + } + return ancestor; + } + get signals() { + return this.__signals; + } + set signals(v) { + if (!Utils$1.isObjectLiteral(v)) { + this._throwError("Signals: specify an object with signal-to-fire mappings"); + } + this.__signals = v; + } + set alterSignals(v) { + if (!Utils$1.isObjectLiteral(v)) { + this._throwError("Signals: specify an object with signal-to-fire mappings"); + } + if (!this.__signals) { + this.__signals = {}; + } + for (let key in v) { + const d = v[key]; + if (d === void 0) { + delete this.__signals[key]; + } else { + this.__signals[key] = v; + } + } + } + get passSignals() { + return this.__passSignals || {}; + } + set passSignals(v) { + this.__passSignals = Object.assign(this.__passSignals || {}, v); + } + set alterPassSignals(v) { + if (!Utils$1.isObjectLiteral(v)) { + this._throwError("Signals: specify an object with signal-to-fire mappings"); + } + if (!this.__passSignals) { + this.__passSignals = {}; + } + for (let key in v) { + const d = v[key]; + if (d === void 0) { + delete this.__passSignals[key]; + } else { + this.__passSignals[key] = v; + } + } + } + signal(event, ...args) { + return this._signal(event, args); + } + _signal(event, args) { + const signalParent = this._getParentSignalHandler(); + if (signalParent) { + if (this.__signals) { + let fireEvent = this.__signals[event]; + if (fireEvent === false) { + return; + } + if (fireEvent) { + if (fireEvent === true) { + fireEvent = event; + } + if (Utils$1.isFunction(fireEvent)) { + return fireEvent(...args); + } + if (signalParent._hasMethod(fireEvent)) { + return signalParent[fireEvent](...args); + } + } + } + let passSignal = this.__passSignals && this.__passSignals[event]; + if (passSignal) { + if (passSignal && passSignal !== true) { + event = passSignal; + } + return signalParent._signal(event, args); + } + } + } + _getParentSignalHandler() { + return this.cparent ? this.cparent._getSignalHandler() : null; + } + _getSignalHandler() { + if (this._signalProxy) { + return this.cparent ? this.cparent._getSignalHandler() : null; + } + return this; + } + get _signalProxy() { + return false; + } + fireAncestors(name, ...args) { + if (!name.startsWith("$")) { + throw new Error("Ancestor event name must be prefixed by dollar sign."); + } + const parent = this._getParentSignalHandler(); + if (parent) { + return parent._doFireAncestors(name, args); + } + } + _doFireAncestors(name, args) { + if (this._hasMethod(name)) { + return this.fire(name, ...args); + } else { + const signalParent = this._getParentSignalHandler(); + if (signalParent) { + return signalParent._doFireAncestors(name, args); + } + } + } + static collectSubComponents(subs, element) { + if (element.hasChildren()) { + const childList = element.__childList; + for (let i = 0, n = childList.length; i < n; i++) { + const child = childList.getAt(i); + if (child.isComponent) { + subs.push(child); + } else { + Component.collectSubComponents(subs, child); + } + } + } + } + static getComponent(element) { + let parent = element; + while (parent && !parent.isComponent) { + parent = parent.parent; + } + return parent; + } + static getParent(element) { + return Component.getComponent(element.parent); + } +} +Component.prototype.isComponent = true; +class CoreQuadList { + constructor(ctx) { + this.ctx = ctx; + this.quadTextures = []; + this.quadElements = []; + } + get length() { + return this.quadTextures.length; + } + reset() { + this.quadTextures = []; + this.quadElements = []; + this.dataLength = 0; + } + getElement(index) { + return this.quadElements[index]._element; + } + getElementCore(index) { + return this.quadElements[index]; + } + getTexture(index) { + return this.quadTextures[index]; + } + getTextureWidth(index) { + let nativeTexture = this.quadTextures[index]; + if (nativeTexture.w) { + return nativeTexture.w; + } else { + return this.quadElements[index]._displayedTextureSource.w; + } + } + getTextureHeight(index) { + let nativeTexture = this.quadTextures[index]; + if (nativeTexture.h) { + return nativeTexture.h; + } else { + return this.quadElements[index]._displayedTextureSource.h; + } + } +} +class WebGLCoreQuadList extends CoreQuadList { + constructor(ctx) { + super(ctx); + const byteSize = ctx.stage.getOption("bufferMemory"); + this.dataLength = 0; + this.data = new ArrayBuffer(byteSize); + this.floats = new Float32Array(this.data); + this.uints = new Uint32Array(this.data); + } + getAttribsDataByteOffset(index) { + return index * 80; + } + getQuadContents() { + let floats = this.floats; + let uints = this.uints; + let lines = []; + for (let i = 1; i <= this.length; i++) { + let str = "entry " + i + ": "; + for (let j = 0; j < 4; j++) { + let b = i * 20 + j * 4; + str += floats[b] + "," + floats[b + 1] + ":" + floats[b + 2] + "," + floats[b + 3] + "[" + uints[b + 4].toString(16) + "] "; + } + lines.push(str); + } + return lines; + } +} +class CoreQuadOperation { + constructor(ctx, shader, shaderOwner, renderTextureInfo, scissor, index) { + this.ctx = ctx; + this.shader = shader; + this.shaderOwner = shaderOwner; + this.renderTextureInfo = renderTextureInfo; + this.scissor = scissor; + this.index = index; + this.length = 0; + } + get quads() { + return this.ctx.renderState.quads; + } + getTexture(index) { + return this.quads.getTexture(this.index + index); + } + getElementCore(index) { + return this.quads.getElementCore(this.index + index); + } + getElement(index) { + return this.quads.getElement(this.index + index); + } + getElementWidth(index) { + return this.getElement(index).renderWidth; + } + getElementHeight(index) { + return this.getElement(index).renderHeight; + } + getTextureWidth(index) { + return this.quads.getTextureWidth(this.index + index); + } + getTextureHeight(index) { + return this.quads.getTextureHeight(this.index + index); + } + getRenderWidth() { + if (this.renderTextureInfo) { + return this.renderTextureInfo.w; + } else { + return this.ctx.stage.w; + } + } + getRenderHeight() { + if (this.renderTextureInfo) { + return this.renderTextureInfo.h; + } else { + return this.ctx.stage.h; + } + } +} +class WebGLCoreQuadOperation extends CoreQuadOperation { + constructor(ctx, shader, shaderOwner, renderTextureInfo, scissor, index) { + super(ctx, shader, shaderOwner, renderTextureInfo, scissor, index); + this.extraAttribsDataByteOffset = 0; + } + getAttribsDataByteOffset(index) { + return this.quads.getAttribsDataByteOffset(this.index + index); + } + getNormalRenderTextureCoords(x, y) { + let coords = this.shaderOwner.getRenderTextureCoords(x, y); + coords[0] /= this.getRenderWidth(); + coords[1] /= this.getRenderHeight(); + coords[0] = coords[0] * 2 - 1; + coords[1] = 1 - coords[1] * 2; + return coords; + } + getProjection() { + if (this.renderTextureInfo === null) { + return this.ctx.renderExec._projection; + } else { + return this.renderTextureInfo.nativeTexture.projection; + } + } +} +class CoreRenderExecutor { + constructor(ctx) { + this.ctx = ctx; + this.renderState = ctx.renderState; + this.gl = this.ctx.stage.gl; + } + destroy() { + this.ctx = null; + this.renderState = null; + this.gl = null; + delete this.ctx; + delete this.renderState; + delete this.gl; + } + _reset() { + this._bindRenderTexture(null); + this._setScissor(null); + this._clearRenderTexture(); + } + execute() { + this._reset(); + let qops = this.renderState.quadOperations; + let i = 0, n = qops.length; + while (i < n) { + this._processQuadOperation(qops[i]); + i++; + } + } + _processQuadOperation(quadOperation) { + if (quadOperation.renderTextureInfo && quadOperation.renderTextureInfo.ignore) { + return; + } + this._setupQuadOperation(quadOperation); + this._execQuadOperation(quadOperation); + } + _setupQuadOperation(quadOperation) { + } + _execQuadOperation(op) { + let nativeTexture = op.renderTextureInfo ? op.renderTextureInfo.nativeTexture : null; + if (this._renderTexture !== nativeTexture) { + this._bindRenderTexture(nativeTexture); + } + if (op.renderTextureInfo && !op.renderTextureInfo.cleared) { + this._setScissor(null); + this._clearRenderTexture(); + op.renderTextureInfo.cleared = true; + this._setScissor(op.scissor); + } else { + this._setScissor(op.scissor); + } + this._renderQuadOperation(op); + } + _renderQuadOperation(op) { + } + _bindRenderTexture(renderTexture) { + this._renderTexture = renderTexture; + } + _clearRenderTexture(renderTexture) { + } + _setScissor(area) { + } +} +class WebGLCoreRenderExecutor extends CoreRenderExecutor { + constructor(ctx) { + super(ctx); + this.gl = this.ctx.stage.gl; + this.init(); + } + init() { + let gl = this.gl; + this._attribsBuffer = gl.createBuffer(); + let maxQuads = Math.floor(this.renderState.quads.data.byteLength / 80); + let allIndices = new Uint16Array(maxQuads * 6); + for (let i = 0, j = 0; i < maxQuads; i += 6, j += 4) { + allIndices[i] = j; + allIndices[i + 1] = j + 1; + allIndices[i + 2] = j + 2; + allIndices[i + 3] = j; + allIndices[i + 4] = j + 2; + allIndices[i + 5] = j + 3; + } + this._quadsBuffer = gl.createBuffer(); + gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this._quadsBuffer); + gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, allIndices, gl.STATIC_DRAW); + this._projection = new Float32Array([2 / this.ctx.stage.coordsWidth, -2 / this.ctx.stage.coordsHeight]); + } + destroy() { + super.destroy(); + this.gl.deleteBuffer(this._attribsBuffer); + this.gl.deleteBuffer(this._quadsBuffer); + this.gl = null; + delete this.gl; + } + _reset() { + super._reset(); + let gl = this.gl; + gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA); + gl.enable(gl.BLEND); + gl.disable(gl.DEPTH_TEST); + this._stopShaderProgram(); + this._setupBuffers(); + } + _setupBuffers() { + let gl = this.gl; + gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this._quadsBuffer); + let element = new Float32Array(this.renderState.quads.data, 0, this.renderState.quads.dataLength); + gl.bindBuffer(gl.ARRAY_BUFFER, this._attribsBuffer); + gl.bufferData(gl.ARRAY_BUFFER, element, gl.DYNAMIC_DRAW); + } + _setupQuadOperation(quadOperation) { + super._setupQuadOperation(quadOperation); + this._useShaderProgram(quadOperation.shader, quadOperation); + } + _renderQuadOperation(op) { + let shader = op.shader; + if (op.length || op.shader.addEmpty()) { + shader.beforeDraw(op); + shader.draw(op); + shader.afterDraw(op); + } + } + _useShaderProgram(shader, operation) { + if (!shader.hasSameProgram(this._currentShaderProgram)) { + if (this._currentShaderProgram) { + this._currentShaderProgram.stopProgram(); + } + shader.useProgram(); + this._currentShaderProgram = shader; + } + shader.setupUniforms(operation); + } + _stopShaderProgram() { + if (this._currentShaderProgram) { + this._currentShaderProgram.stopProgram(); + this._currentShaderProgram = null; + } + } + _bindRenderTexture(renderTexture) { + super._bindRenderTexture(renderTexture); + let gl = this.gl; + if (!this._renderTexture) { + gl.bindFramebuffer(gl.FRAMEBUFFER, null); + gl.viewport(0, 0, this.ctx.stage.w, this.ctx.stage.h); + } else { + gl.bindFramebuffer(gl.FRAMEBUFFER, this._renderTexture.framebuffer); + gl.viewport(0, 0, this._renderTexture.w, this._renderTexture.h); + } + } + _clearRenderTexture() { + super._clearRenderTexture(); + let gl = this.gl; + if (!this._renderTexture) { + let glClearColor = this.ctx.stage.getClearColor(); + if (glClearColor) { + gl.clearColor(glClearColor[0] * glClearColor[3], glClearColor[1] * glClearColor[3], glClearColor[2] * glClearColor[3], glClearColor[3]); + gl.clear(gl.COLOR_BUFFER_BIT); + } + } else { + gl.clearColor(0, 0, 0, 0); + gl.clear(gl.COLOR_BUFFER_BIT); + } + } + _setScissor(area) { + super._setScissor(area); + if (this._scissor === area) { + return; + } + this._scissor = area; + let gl = this.gl; + if (!area) { + gl.disable(gl.SCISSOR_TEST); + } else { + gl.enable(gl.SCISSOR_TEST); + let precision = this.ctx.stage.getRenderPrecision(); + let y = area[1]; + if (this._renderTexture === null) { + y = this.ctx.stage.h / precision - (area[1] + area[3]); + } + gl.scissor(Math.round(area[0] * precision), Math.round(y * precision), Math.round(area[2] * precision), Math.round(area[3] * precision)); + } + } +} +class CoreRenderState { + constructor(ctx) { + this.ctx = ctx; + this.stage = ctx.stage; + this.defaultShader = this.stage.renderer.getDefaultShader(ctx); + this.renderer = ctx.stage.renderer; + this.quads = this.renderer.createCoreQuadList(ctx); + } + reset() { + this._renderTextureInfo = null; + this._scissor = null; + this._shader = null; + this._shaderOwner = null; + this._realShader = null; + this._check = false; + this.quadOperations = []; + this._texturizer = null; + this._texturizerTemporary = false; + this._quadOperation = null; + this.quads.reset(); + this._temporaryTexturizers = []; + this._isCachingTexturizer = false; + } + get length() { + return this.quads.quadTextures.length; + } + setShader(shader, owner) { + if (this._shaderOwner !== owner || this._realShader !== shader) { + this._realShader = shader; + if (shader.useDefault()) { + shader = this.defaultShader; + } + if (this._shader !== shader || this._shaderOwner !== owner) { + this._shader = shader; + this._shaderOwner = owner; + this._check = true; + } + } + } + get renderTextureInfo() { + return this._renderTextureInfo; + } + setScissor(area) { + if (this._scissor !== area) { + if (area) { + this._scissor = area; + } else { + this._scissor = null; + } + this._check = true; + } + } + getScissor() { + return this._scissor; + } + setRenderTextureInfo(renderTextureInfo) { + if (this._renderTextureInfo !== renderTextureInfo) { + this._renderTextureInfo = renderTextureInfo; + this._scissor = null; + this._check = true; + } + } + setTexturizer(texturizer, cache = false) { + this._texturizer = texturizer; + this._cacheTexturizer = cache; + } + set isCachingTexturizer(v) { + this._isCachingTexturizer = v; + } + get isCachingTexturizer() { + return this._isCachingTexturizer; + } + addQuad(elementCore) { + if (!this._quadOperation) { + this._createQuadOperation(); + } else if (this._check && this._hasChanges()) { + this._finishQuadOperation(); + this._check = false; + } + let nativeTexture = null; + if (this._texturizer) { + nativeTexture = this._texturizer.getResultTexture(); + if (!this._cacheTexturizer) { + this._temporaryTexturizers.push(this._texturizer); + } + } + if (!nativeTexture) { + nativeTexture = elementCore._displayedTextureSource.nativeTexture; + } + if (this._renderTextureInfo) { + if (this._shader === this.defaultShader && this._renderTextureInfo.empty) { + this._renderTextureInfo.nativeTexture = nativeTexture; + this._renderTextureInfo.offset = this.length; + } else { + this._renderTextureInfo.nativeTexture = null; + } + this._renderTextureInfo.empty = false; + } + this.quads.quadTextures.push(nativeTexture); + this.quads.quadElements.push(elementCore); + this._quadOperation.length++; + this.renderer.addQuad(this, this.quads, this.length - 1); + } + finishedRenderTexture() { + if (this._renderTextureInfo.nativeTexture) { + if (!this._isRenderTextureReusable()) { + this._renderTextureInfo.nativeTexture = null; + } + } + } + _isRenderTextureReusable() { + const offset = this._renderTextureInfo.offset; + return this.quads.quadTextures[offset].w === this._renderTextureInfo.w && this.quads.quadTextures[offset].h === this._renderTextureInfo.h && this.renderer.isRenderTextureReusable(this, this._renderTextureInfo); + } + _hasChanges() { + let q = this._quadOperation; + if (this._shader !== q.shader) + return true; + if (this._shaderOwner !== q.shaderOwner) + return true; + if (this._renderTextureInfo !== q.renderTextureInfo) + return true; + if (this._scissor !== q.scissor) { + if (this._scissor[0] !== q.scissor[0] || this._scissor[1] !== q.scissor[1] || this._scissor[2] !== q.scissor[2] || this._scissor[3] !== q.scissor[3]) { + return true; + } + } + return false; + } + _finishQuadOperation(create = true) { + if (this._quadOperation) { + if (this._quadOperation.length || this._shader.addEmpty()) { + if (!this._quadOperation.scissor || this._quadOperation.scissor[2] > 0 && this._quadOperation.scissor[3] > 0) { + this.quadOperations.push(this._quadOperation); + } + } + if (this._temporaryTexturizers.length) { + for (let i = 0, n = this._temporaryTexturizers.length; i < n; i++) { + this._temporaryTexturizers[i].releaseRenderTexture(); + } + this._temporaryTexturizers = []; + } + this._quadOperation = null; + } + if (create) { + this._createQuadOperation(); + } + } + _createQuadOperation() { + this._quadOperation = this.renderer.createCoreQuadOperation( + this.ctx, + this._shader, + this._shaderOwner, + this._renderTextureInfo, + this._scissor, + this.length + ); + this._check = false; + } + finish() { + if (this._quadOperation) { + this._finishQuadOperation(false); + } + this.renderer.finishRenderState(this); + } +} +class WebGLShaderProgram { + constructor(vertexShaderSource, fragmentShaderSource) { + this.vertexShaderSource = vertexShaderSource; + this.fragmentShaderSource = fragmentShaderSource; + this._program = null; + this.gl = null; + this._uniformLocations = /* @__PURE__ */ new Map(); + this._attributeLocations = /* @__PURE__ */ new Map(); + this._currentUniformValues = {}; + } + compile(gl) { + if (this._program) + return; + this.gl = gl; + this._program = gl.createProgram(); + let glVertShader = this._glCompile(gl.VERTEX_SHADER, this.vertexShaderSource); + let glFragShader = this._glCompile(gl.FRAGMENT_SHADER, this.fragmentShaderSource); + gl.attachShader(this._program, glVertShader); + gl.attachShader(this._program, glFragShader); + gl.linkProgram(this._program); + if (!gl.getProgramParameter(this._program, gl.LINK_STATUS)) { + console.error("[Lightning] Error: Could not initialize shader."); + console.error("[Lightning] gl.VALIDATE_STATUS", gl.getProgramParameter(this._program, gl.VALIDATE_STATUS)); + console.error("[Lightning] gl.getError()", gl.getError()); + if (gl.getProgramInfoLog(this._program) !== "") { + console.warn("[Lightning] Warning: gl.getProgramInfoLog()", gl.getProgramInfoLog(this._program)); + } + gl.deleteProgram(this._program); + this._program = null; + } + gl.deleteShader(glVertShader); + gl.deleteShader(glFragShader); + } + _glCompile(type, src) { + let shader = this.gl.createShader(type); + this.gl.shaderSource(shader, src); + this.gl.compileShader(shader); + if (!this.gl.getShaderParameter(shader, this.gl.COMPILE_STATUS)) { + console.error("[Lightning]", this.constructor.name, "Type: " + (type === this.gl.VERTEX_SHADER ? "vertex shader" : "fragment shader")); + console.error("[Lightning]", this.gl.getShaderInfoLog(shader)); + let idx = 0; + console.error("[Lightning]", "========== source ==========\n" + src.split("\n").map((line) => "" + ++idx + ": " + line).join("\n")); + return null; + } + return shader; + } + getUniformLocation(name) { + let location = this._uniformLocations.get(name); + if (location === void 0) { + location = this.gl.getUniformLocation(this._program, name); + this._uniformLocations.set(name, location); + } + return location; + } + getAttribLocation(name) { + let location = this._attributeLocations.get(name); + if (location === void 0) { + location = this.gl.getAttribLocation(this._program, name); + this._attributeLocations.set(name, location); + } + return location; + } + destroy() { + if (this._program) { + this.gl.deleteProgram(this._program); + } + this._attributeLocations = null; + this._currentUniformValues = null; + this.fragmentShaderSource = null; + this._program = null; + this.gl = null; + this._uniformLocations = null; + this.vertexShaderSource = null; + delete this.vertexShaderSource; + delete this._program; + delete this._currentUniformValues; + delete this.fragmentShaderSource; + delete this.gl; + delete this._uniformLocations; + delete this._attributeLocations; + } + get glProgram() { + return this._program; + } + get compiled() { + return !!this._program; + } + _valueEquals(v1, v2) { + if (v1.length && v2.length) { + for (let i = 0, n = v1.length; i < n; i++) { + if (v1[i] !== v2[i]) + return false; + } + return true; + } else { + return v1 === v2; + } + } + _valueClone(v) { + if (v.length) { + return v.slice(0); + } else { + return v; + } + } + setUniformValue(name, value, glFunction) { + let v = this._currentUniformValues[name]; + if (v === void 0 || !this._valueEquals(v, value)) { + let clonedValue = this._valueClone(value); + this._currentUniformValues[name] = clonedValue; + let loc = this.getUniformLocation(name); + if (loc) { + let isMatrix = glFunction === this.gl.uniformMatrix2fv || glFunction === this.gl.uniformMatrix3fv || glFunction === this.gl.uniformMatrix4fv; + if (isMatrix) { + glFunction.call(this.gl, loc, false, clonedValue); + } else { + glFunction.call(this.gl, loc, clonedValue); + } + } + } + } +} +class WebGLShader extends Shader { + constructor(ctx) { + super(ctx); + const stage = ctx.stage; + this._program = stage.renderer.shaderPrograms.get(this.constructor); + if (!this._program) { + this._program = new WebGLShaderProgram(this.constructor.vertexShaderSource, this.constructor.fragmentShaderSource); + stage.renderer.shaderPrograms.set(this.constructor, this._program); + } + this.gl = stage.gl; + } + get glProgram() { + return this._program.glProgram; + } + _init() { + if (!this._initialized) { + this.initialize(); + this._initialized = true; + } + } + initialize() { + this._program.compile(this.gl); + } + get initialized() { + return this._initialized; + } + _uniform(name) { + return this._program.getUniformLocation(name); + } + _attrib(name) { + return this._program.getAttribLocation(name); + } + _setUniform(name, value, glFunction) { + this._program.setUniformValue(name, value, glFunction); + } + useProgram() { + this._init(); + this.gl.useProgram(this.glProgram); + this.beforeUsage(); + this.enableAttribs(); + } + stopProgram() { + this.afterUsage(); + this.disableAttribs(); + } + hasSameProgram(other) { + return other && (other === this || other._program === this._program); + } + beforeUsage() { + } + afterUsage() { + } + enableAttribs() { + } + disableAttribs() { + } + getExtraAttribBytesPerVertex() { + return 0; + } + getVertexAttribPointerOffset(operation) { + return operation.extraAttribsDataByteOffset - operation.index * 4 * this.getExtraAttribBytesPerVertex(); + } + setExtraAttribsInBuffer(operation) { + } + setupUniforms(operation) { + } + _getProjection(operation) { + return operation.getProjection(); + } + getFlipY(operation) { + return this._getProjection(operation)[1] < 0; + } + beforeDraw(operation) { + } + draw(operation) { + } + afterDraw(operation) { + } + cleanup() { + this._initialized = false; + } +} +let DefaultShader$1 = class DefaultShader extends WebGLShader { + enableAttribs() { + let gl = this.gl; + gl.vertexAttribPointer(this._attrib("aVertexPosition"), 2, gl.FLOAT, false, 20, 0); + gl.enableVertexAttribArray(this._attrib("aVertexPosition")); + if (this._attrib("aTextureCoord") !== -1) { + gl.vertexAttribPointer(this._attrib("aTextureCoord"), 2, gl.FLOAT, false, 20, 2 * 4); + gl.enableVertexAttribArray(this._attrib("aTextureCoord")); + } + if (this._attrib("aColor") !== -1) { + gl.vertexAttribPointer(this._attrib("aColor"), 4, gl.UNSIGNED_BYTE, true, 20, 4 * 4); + gl.enableVertexAttribArray(this._attrib("aColor")); + } + } + disableAttribs() { + let gl = this.gl; + gl.disableVertexAttribArray(this._attrib("aVertexPosition")); + if (this._attrib("aTextureCoord") !== -1) { + gl.disableVertexAttribArray(this._attrib("aTextureCoord")); + } + if (this._attrib("aColor") !== -1) { + gl.disableVertexAttribArray(this._attrib("aColor")); + } + } + setupUniforms(operation) { + this._setUniform("projection", this._getProjection(operation), this.gl.uniform2fv, false); + } + draw(operation) { + let gl = this.gl; + let length = operation.length; + if (length) { + let glTexture = operation.getTexture(0); + let pos = 0; + for (let i = 0; i < length; i++) { + let tx = operation.getTexture(i); + if (glTexture !== tx) { + gl.bindTexture(gl.TEXTURE_2D, glTexture); + gl.drawElements(gl.TRIANGLES, 6 * (i - pos), gl.UNSIGNED_SHORT, (pos + operation.index) * 6 * 2); + glTexture = tx; + pos = i; + } + } + gl.bindTexture(gl.TEXTURE_2D, glTexture); + gl.drawElements(gl.TRIANGLES, 6 * (length - pos), gl.UNSIGNED_SHORT, (pos + operation.index) * 6 * 2); + } + } +}; +DefaultShader$1.vertexShaderSource = ` + #ifdef GL_ES + # ifdef GL_FRAGMENT_PRECISION_HIGH + precision highp float; + # else + precision lowp float; + # endif + #endif + attribute vec2 aVertexPosition; + attribute vec2 aTextureCoord; + attribute vec4 aColor; + uniform vec2 projection; + varying vec2 vTextureCoord; + varying vec4 vColor; + void main(void){ + gl_Position = vec4(aVertexPosition.x * projection.x - 1.0, aVertexPosition.y * -abs(projection.y) + 1.0, 0.0, 1.0); + vTextureCoord = aTextureCoord; + vColor = aColor; + gl_Position.y = -sign(projection.y) * gl_Position.y; + } +`; +DefaultShader$1.fragmentShaderSource = ` + #ifdef GL_ES + # ifdef GL_FRAGMENT_PRECISION_HIGH + precision highp float; + # else + precision lowp float; + # endif + #endif + varying vec2 vTextureCoord; + varying vec4 vColor; + uniform sampler2D uSampler; + void main(void){ + gl_FragColor = texture2D(uSampler, vTextureCoord) * vColor; + } +`; +class Renderer { + constructor(stage) { + this.stage = stage; + this._defaultShader = void 0; + } + gc(aggressive) { + } + destroy() { + } + getDefaultShader(ctx = this.stage.ctx) { + if (!this._defaultShader) { + this._defaultShader = this._createDefaultShader(ctx); + } + return this._defaultShader; + } + _createDefaultShader(ctx) { + } + isValidShaderType(shaderType) { + return shaderType.prototype instanceof this._getShaderBaseType(); + } + createShader(ctx, settings) { + const shaderType = settings.type; + if (!this.isValidShaderType(shaderType)) { + const convertedShaderType = this._getShaderAlternative(shaderType); + if (!convertedShaderType) { + console.warn("[Lightning] Shader has no implementation for render target: " + shaderType.name); + return this._createDefaultShader(ctx); + } + return new convertedShaderType(ctx); + } else { + const shader = new shaderType(ctx); + Base.patchObject(this, settings); + return shader; + } + } + _getShaderBaseType() { + } + _getShaderAlternative(shaderType) { + return this.getDefaultShader(); + } + copyRenderTexture(renderTexture, nativeTexture, options) { + console.warn("[Lightning] copyRenderTexture not supported by renderer"); + } +} +class WebGLRenderer extends Renderer { + constructor(stage) { + super(stage); + this.shaderPrograms = /* @__PURE__ */ new Map(); + this._compressedTextureExtensions = { + astc: stage.gl.getExtension("WEBGL_compressed_texture_astc"), + etc1: stage.gl.getExtension("WEBGL_compressed_texture_etc1"), + s3tc: stage.gl.getExtension("WEBGL_compressed_texture_s3tc"), + pvrtc: stage.gl.getExtension("WEBGL_compressed_texture_pvrtc") + }; + } + getCompressedTextureExtensions() { + return this._compressedTextureExtensions; + } + destroy() { + this.shaderPrograms.forEach((shaderProgram) => shaderProgram.destroy()); + this.shaderPrograms = null; + this._compressedTextureExtensions = null; + delete this.shaderPrograms; + delete this._compressedTextureExtensions; + } + _createDefaultShader(ctx) { + return new DefaultShader$1(ctx); + } + _getShaderBaseType() { + return WebGLShader; + } + _getShaderAlternative(shaderType) { + return shaderType.getWebGL && shaderType.getWebGL(); + } + createCoreQuadList(ctx) { + return new WebGLCoreQuadList(ctx); + } + createCoreQuadOperation(ctx, shader, shaderOwner, renderTextureInfo, scissor, index) { + return new WebGLCoreQuadOperation(ctx, shader, shaderOwner, renderTextureInfo, scissor, index); + } + createCoreRenderExecutor(ctx) { + return new WebGLCoreRenderExecutor(ctx); + } + createCoreRenderState(ctx) { + return new CoreRenderState(ctx); + } + createRenderTexture(w, h, pw, ph) { + const gl = this.stage.gl; + const glTexture = gl.createTexture(); + gl.bindTexture(gl.TEXTURE_2D, glTexture); + gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, pw, ph, 0, gl.RGBA, gl.UNSIGNED_BYTE, null); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); + glTexture.params = {}; + glTexture.params[gl.TEXTURE_MAG_FILTER] = gl.LINEAR; + glTexture.params[gl.TEXTURE_MIN_FILTER] = gl.LINEAR; + glTexture.params[gl.TEXTURE_WRAP_S] = gl.CLAMP_TO_EDGE; + glTexture.params[gl.TEXTURE_WRAP_T] = gl.CLAMP_TO_EDGE; + glTexture.options = { format: gl.RGBA, internalFormat: gl.RGBA, type: gl.UNSIGNED_BYTE }; + glTexture.framebuffer = gl.createFramebuffer(); + glTexture.projection = new Float32Array([2 / w, 2 / h]); + gl.bindFramebuffer(gl.FRAMEBUFFER, glTexture.framebuffer); + gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, glTexture, 0); + return glTexture; + } + freeRenderTexture(glTexture) { + let gl = this.stage.gl; + gl.deleteFramebuffer(glTexture.framebuffer); + gl.deleteTexture(glTexture); + } + _getBytesPerPixel(fmt, type) { + const gl = this.stage.gl; + if (fmt === gl.RGBA) { + switch (type) { + case gl.UNSIGNED_BYTE: + return 4; + case gl.UNSIGNED_SHORT_4_4_4_4: + return 2; + case gl.UNSIGNED_SHORT_5_5_5_1: + return 2; + default: + throw new Error("Invalid type specified for GL_RGBA format"); + } + } else if (fmt === gl.RGB) { + switch (type) { + case gl.UNSIGNED_BYTE: + return 3; + case gl.UNSIGNED_BYTE_5_6_5: + return 2; + default: + throw new Error("Invalid type specified for GL_RGB format"); + } + } else { + throw new Error("Invalid format specified in call to _getBytesPerPixel()"); + } + } + uploadTextureSource(textureSource, options) { + const gl = this.stage.gl; + const source = options.source; + let compressed = false; + if (options.renderInfo) { + compressed = options.renderInfo.compressed || false; + } + const format = { + premultiplyAlpha: true, + hasAlpha: true + }; + if (options && options.hasOwnProperty("premultiplyAlpha")) { + format.premultiplyAlpha = options.premultiplyAlpha; + } + if (options && options.hasOwnProperty("flipBlueRed")) { + format.flipBlueRed = options.flipBlueRed; + } + if (options && options.hasOwnProperty("hasAlpha")) { + format.hasAlpha = options.hasAlpha; + } + if (!format.hasAlpha) { + format.premultiplyAlpha = false; + } + format.texParams = options.texParams || {}; + format.texOptions = options.texOptions || {}; + let glTexture = gl.createTexture(); + gl.bindTexture(gl.TEXTURE_2D, glTexture); + gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, format.premultiplyAlpha); + if (Utils$1.isNode) { + gl.pixelStorei(gl.UNPACK_FLIP_BLUE_RED, !!format.flipBlueRed); + } + const texParams = format.texParams; + if (!texParams[gl.TEXTURE_MAG_FILTER]) + texParams[gl.TEXTURE_MAG_FILTER] = gl.LINEAR; + if (!texParams[gl.TEXTURE_MIN_FILTER]) + texParams[gl.TEXTURE_MIN_FILTER] = gl.LINEAR; + if (!texParams[gl.TEXTURE_WRAP_S]) + texParams[gl.TEXTURE_WRAP_S] = gl.CLAMP_TO_EDGE; + if (!texParams[gl.TEXTURE_WRAP_T]) + texParams[gl.TEXTURE_WRAP_T] = gl.CLAMP_TO_EDGE; + Object.keys(texParams).forEach((key) => { + const value = texParams[key]; + gl.texParameteri(gl.TEXTURE_2D, parseInt(key), value); + }); + if (compressed) { + this.stage.platform.uploadCompressedGlTexture(gl, textureSource, source); + return glTexture; + } + const texOptions = format.texOptions; + texOptions.format = texOptions.format || (format.hasAlpha ? gl.RGBA : gl.RGB); + texOptions.type = texOptions.type || gl.UNSIGNED_BYTE; + texOptions.internalFormat = texOptions.internalFormat || texOptions.format; + if (options && options.imageRef) { + texOptions.imageRef = options.imageRef; + } + this.stage.platform.uploadGlTexture(gl, textureSource, source, texOptions); + glTexture.params = Utils$1.cloneObjShallow(texParams); + glTexture.options = Utils$1.cloneObjShallow(texOptions); + glTexture.bytesPerPixel = this._getBytesPerPixel(texOptions.format, texOptions.type); + return glTexture; + } + freeTextureSource(textureSource) { + this.stage.gl.deleteTexture(textureSource.nativeTexture); + } + addQuad(renderState, quads, index) { + let offset = index * 20; + const elementCore = quads.quadElements[index]; + let r = elementCore._renderContext; + let floats = renderState.quads.floats; + let uints = renderState.quads.uints; + const mca = StageUtils.mergeColorAlpha; + if (r.tb !== 0 || r.tc !== 0) { + floats[offset++] = r.px; + floats[offset++] = r.py; + floats[offset++] = elementCore._ulx; + floats[offset++] = elementCore._uly; + uints[offset++] = mca(elementCore._colorUl, r.alpha); + floats[offset++] = r.px + elementCore._w * r.ta; + floats[offset++] = r.py + elementCore._w * r.tc; + floats[offset++] = elementCore._brx; + floats[offset++] = elementCore._uly; + uints[offset++] = mca(elementCore._colorUr, r.alpha); + floats[offset++] = r.px + elementCore._w * r.ta + elementCore._h * r.tb; + floats[offset++] = r.py + elementCore._w * r.tc + elementCore._h * r.td; + floats[offset++] = elementCore._brx; + floats[offset++] = elementCore._bry; + uints[offset++] = mca(elementCore._colorBr, r.alpha); + floats[offset++] = r.px + elementCore._h * r.tb; + floats[offset++] = r.py + elementCore._h * r.td; + floats[offset++] = elementCore._ulx; + floats[offset++] = elementCore._bry; + uints[offset] = mca(elementCore._colorBl, r.alpha); + } else { + let cx = r.px + elementCore._w * r.ta; + let cy = r.py + elementCore._h * r.td; + floats[offset++] = r.px; + floats[offset++] = r.py; + floats[offset++] = elementCore._ulx; + floats[offset++] = elementCore._uly; + uints[offset++] = mca(elementCore._colorUl, r.alpha); + floats[offset++] = cx; + floats[offset++] = r.py; + floats[offset++] = elementCore._brx; + floats[offset++] = elementCore._uly; + uints[offset++] = mca(elementCore._colorUr, r.alpha); + floats[offset++] = cx; + floats[offset++] = cy; + floats[offset++] = elementCore._brx; + floats[offset++] = elementCore._bry; + uints[offset++] = mca(elementCore._colorBr, r.alpha); + floats[offset++] = r.px; + floats[offset++] = cy; + floats[offset++] = elementCore._ulx; + floats[offset++] = elementCore._bry; + uints[offset] = mca(elementCore._colorBl, r.alpha); + } + } + isRenderTextureReusable(renderState, renderTextureInfo) { + let offset = renderState._renderTextureInfo.offset * 80 / 4; + let floats = renderState.quads.floats; + let uints = renderState.quads.uints; + return floats[offset] === 0 && floats[offset + 1] === 0 && floats[offset + 2] === 0 && floats[offset + 3] === 0 && uints[offset + 4] === 4294967295 && floats[offset + 5] === renderTextureInfo.w && floats[offset + 6] === 0 && floats[offset + 7] === 1 && floats[offset + 8] === 0 && uints[offset + 9] === 4294967295 && floats[offset + 10] === renderTextureInfo.w && floats[offset + 11] === renderTextureInfo.h && floats[offset + 12] === 1 && floats[offset + 13] === 1 && uints[offset + 14] === 4294967295 && floats[offset + 15] === 0 && floats[offset + 16] === renderTextureInfo.h && floats[offset + 17] === 0 && floats[offset + 18] === 1 && uints[offset + 19] === 4294967295; + } + finishRenderState(renderState) { + let offset = renderState.length * 80; + for (let i = 0, n = renderState.quadOperations.length; i < n; i++) { + renderState.quadOperations[i].extraAttribsDataByteOffset = offset; + let extra = renderState.quadOperations[i].shader.getExtraAttribBytesPerVertex() * 4 * renderState.quadOperations[i].length; + offset += extra; + if (extra) { + renderState.quadOperations[i].shader.setExtraAttribsInBuffer(renderState.quadOperations[i], renderState.quads); + } + } + renderState.quads.dataLength = offset; + } + copyRenderTexture(renderTexture, nativeTexture, options) { + const gl = this.stage.gl; + gl.bindTexture(gl.TEXTURE_2D, nativeTexture); + gl.bindFramebuffer(gl.FRAMEBUFFER, renderTexture.framebuffer); + const precision = renderTexture.precision; + gl.copyTexSubImage2D( + gl.TEXTURE_2D, + 0, + precision * (options.sx || 0), + precision * (options.sy || 0), + precision * (options.x || 0), + precision * (options.y || 0), + precision * (options.w || renderTexture.ow), + precision * (options.h || renderTexture.oh) + ); + } +} +class C2dCoreQuadList extends CoreQuadList { + constructor(ctx) { + super(ctx); + this.renderContexts = []; + this.modes = []; + } + setRenderContext(index, v) { + this.renderContexts[index] = v; + } + setSimpleTc(index, v) { + if (v) { + this.modes[index] |= 1; + } else { + this.modes[index] -= this.modes[index] & 1; + } + } + setWhite(index, v) { + if (v) { + this.modes[index] |= 2; + } else { + this.modes[index] -= this.modes[index] & 2; + } + } + getRenderContext(index) { + return this.renderContexts[index]; + } + getSimpleTc(index) { + return this.modes[index] & 1; + } + getWhite(index) { + return this.modes[index] & 2; + } +} +class C2dCoreQuadOperation extends CoreQuadOperation { + getRenderContext(index) { + return this.quads.getRenderContext(this.index + index); + } + getSimpleTc(index) { + return this.quads.getSimpleTc(this.index + index); + } + getWhite(index) { + return this.quads.getWhite(this.index + index); + } +} +class C2dCoreRenderExecutor extends CoreRenderExecutor { + init() { + this._mainRenderTexture = this.ctx.stage.getCanvas(); + } + _renderQuadOperation(op) { + let shader = op.shader; + if (op.length || op.shader.addEmpty()) { + const target = this._renderTexture || this._mainRenderTexture; + shader.beforeDraw(op, target); + shader.draw(op, target); + shader.afterDraw(op, target); + } + } + _clearRenderTexture() { + const ctx = this._getContext(); + let clearColor = [0, 0, 0, 0]; + if (this._mainRenderTexture.ctx === ctx) { + clearColor = this.ctx.stage.getClearColor(); + } + const renderTexture = ctx.canvas; + ctx.setTransform(1, 0, 0, 1, 0, 0); + if (!clearColor[0] && !clearColor[1] && !clearColor[2] && !clearColor[3]) { + ctx.clearRect(0, 0, renderTexture.width, renderTexture.height); + } else { + ctx.fillStyle = StageUtils.getRgbaStringFromArray(clearColor); + ctx.globalCompositeOperation = "copy"; + ctx.beginPath(); + ctx.rect(0, 0, renderTexture.width, renderTexture.height); + ctx.closePath(); + ctx.fill(); + ctx.globalCompositeOperation = "source-over"; + } + } + _getContext() { + if (this._renderTexture) { + return this._renderTexture.ctx; + } else { + return this._mainRenderTexture.ctx; + } + } + _restoreContext() { + const ctx = this._getContext(); + ctx.restore(); + ctx.save(); + ctx._scissor = null; + } + _setScissor(area) { + const ctx = this._getContext(); + if (!C2dCoreRenderExecutor._equalScissorAreas(ctx.canvas, ctx._scissor, area)) { + this._restoreContext(); + let precision = this.ctx.stage.getRenderPrecision(); + if (area) { + ctx.beginPath(); + ctx.rect(Math.round(area[0] * precision), Math.round(area[1] * precision), Math.round(area[2] * precision), Math.round(area[3] * precision)); + ctx.closePath(); + ctx.clip(); + } + ctx._scissor = area; + } + } + static _equalScissorAreas(canvas, area, current) { + if (!area) { + area = [0, 0, canvas.width, canvas.height]; + } + if (!current) { + current = [0, 0, canvas.width, canvas.height]; + } + return Utils$1.equalValues(area, current); + } +} +class C2dShader extends Shader { + beforeDraw(operation) { + } + draw(operation) { + } + afterDraw(operation) { + } +} +class DefaultShader2 extends C2dShader { + constructor(ctx) { + super(ctx); + this._rectangleTexture = ctx.stage.rectangleTexture.source.nativeTexture; + this._tintManager = this.ctx.stage.renderer.tintManager; + } + draw(operation, target) { + const ctx = target.ctx; + let length = operation.length; + for (let i = 0; i < length; i++) { + const tx = operation.getTexture(i); + const vc = operation.getElementCore(i); + const rc = operation.getRenderContext(i); + const white = operation.getWhite(i); + const stc = operation.getSimpleTc(i); + const precision = this.ctx.stage.getRenderPrecision(); + ctx.setTransform(rc.ta * precision, rc.tc * precision, rc.tb * precision, rc.td * precision, rc.px * precision, rc.py * precision); + const rect = tx === this._rectangleTexture; + const info = { operation, target, index: i, rect }; + if (rect) { + if (white) { + ctx.fillStyle = "white"; + } else { + this._setColorGradient(ctx, vc); + } + ctx.globalAlpha = rc.alpha; + this._beforeDrawEl(info); + ctx.fillRect(0, 0, vc.w, vc.h); + this._afterDrawEl(info); + ctx.globalAlpha = 1; + } else { + ctx.globalAlpha = rc.alpha; + this._beforeDrawEl(info); + const sourceX = stc ? 0 : vc._ulx * tx.w; + const sourceY = stc ? 0 : vc._uly * tx.h; + const sourceW = (stc ? 1 : vc._brx - vc._ulx) * tx.w; + const sourceH = (stc ? 1 : vc._bry - vc._uly) * tx.h; + let colorize = !white; + if (colorize) { + let color = vc._colorUl; + if (vc._colorUl !== vc._colorUr || vc._colorUr !== vc._colorBl || vc._colorBr !== vc._colorBl) { + color = StageUtils.mergeMultiColorsEqual([vc._colorUl, vc._colorUr, vc._colorBl, vc._colorBr]); + } + const alpha = (color / 16777216 | 0) / 255; + ctx.globalAlpha *= alpha; + const rgb = color & 16777215; + const tintTexture = this._tintManager.getTintTexture(tx, rgb); + ctx.fillStyle = "white"; + ctx.drawImage(tintTexture, sourceX, sourceY, sourceW, sourceH, 0, 0, vc.w, vc.h); + } else { + ctx.fillStyle = "white"; + ctx.drawImage(tx, sourceX, sourceY, sourceW, sourceH, 0, 0, vc.w, vc.h); + } + this._afterDrawEl(info); + ctx.globalAlpha = 1; + } + } + } + _setColorGradient(ctx, vc, w = vc.w, h = vc.h, transparency = true) { + let color = vc._colorUl; + let gradient; + if (vc._colorUl === vc._colorUr) { + if (vc._colorBl === vc._colorBr) { + if (vc._colorUl === vc.colorBl) + ; + else { + gradient = ctx.createLinearGradient(0, 0, 0, h); + if (transparency) { + gradient.addColorStop(0, StageUtils.getRgbaString(vc._colorUl)); + gradient.addColorStop(1, StageUtils.getRgbaString(vc._colorBl)); + } else { + gradient.addColorStop(0, StageUtils.getRgbString(vc._colorUl)); + gradient.addColorStop(1, StageUtils.getRgbString(vc._colorBl)); + } + } + } + } else { + if (vc._colorUl === vc._colorBl && vc._colorUr === vc._colorBr) { + gradient = ctx.createLinearGradient(0, 0, w, 0); + if (transparency) { + gradient.addColorStop(0, StageUtils.getRgbaString(vc._colorUl)); + gradient.addColorStop(1, StageUtils.getRgbaString(vc._colorBr)); + } else { + gradient.addColorStop(0, StageUtils.getRgbString(vc._colorUl)); + gradient.addColorStop(1, StageUtils.getRgbString(vc._colorBr)); + } + } + } + if (gradient) { + ctx.fillStyle = gradient; + } else { + ctx.fillStyle = transparency ? StageUtils.getRgbaString(color) : StageUtils.getRgbString(color); + } + } + _beforeDrawEl(info) { + } + _afterDrawEl(info) { + } +} +class C2dTextureTintManager { + constructor(stage) { + this.stage = stage; + this._usedMemory = 0; + this._cachedNativeTextures = /* @__PURE__ */ new Set(); + } + destroy() { + this.gc(true); + this.stage = null; + delete this.stage; + } + _addMemoryUsage(delta) { + this._usedMemory += delta; + this.stage.addMemoryUsage(delta); + } + delete(nativeTexture) { + if (this._hasCache(nativeTexture)) { + const cache = this._getCache(nativeTexture); + const prevMemUsage = cache.memoryUsage; + cache.clear(); + this._cachedNativeTextures.delete(nativeTexture); + this._addMemoryUsage(cache.memoryUsage - prevMemUsage); + } + } + getTintTexture(nativeTexture, color) { + const frame = this.stage.frameCounter; + this._cachedNativeTextures.add(nativeTexture); + const cache = this._getCache(nativeTexture); + const item = cache.get(color); + item.lf = frame; + if (item.tx) { + if (nativeTexture.update > item.u) { + this._tintTexture(item.tx, nativeTexture, color); + } + return item.tx; + } else { + const before = cache.memoryUsage; + let target = cache.reuseTexture(frame); + if (target) { + target.ctx.clearRect(0, 0, target.width, target.height); + } else { + target = document.createElement("canvas"); + target.width = nativeTexture.w; + target.height = nativeTexture.h; + target.ctx = target.getContext("2d"); + } + this._tintTexture(target, nativeTexture, color); + cache.set(color, target, frame); + const after = cache.memoryUsage; + if (after !== before) { + this._addMemoryUsage(after - before); + } + return target; + } + } + _tintTexture(target, source, color) { + let col = color.toString(16); + while (col.length < 6) { + col = "0" + col; + } + target.ctx.fillStyle = "#" + col; + target.ctx.globalCompositeOperation = "copy"; + target.ctx.fillRect(0, 0, source.w, source.h); + target.ctx.globalCompositeOperation = "multiply"; + target.ctx.drawImage(source, 0, 0, source.w, source.h, 0, 0, target.width, target.height); + target.ctx.globalCompositeOperation = "destination-in"; + target.ctx.drawImage(source, 0, 0, source.w, source.h, 0, 0, target.width, target.height); + } + _hasCache(nativeTexture) { + return !!nativeTexture._tintCache; + } + _getCache(nativeTexture) { + if (!nativeTexture._tintCache) { + nativeTexture._tintCache = new C2dTintCache(nativeTexture); + } + return nativeTexture._tintCache; + } + gc(aggressive = false) { + const frame = this.stage.frameCounter; + let delta = 0; + this._cachedNativeTextures.forEach((texture) => { + const cache = this._getCache(texture); + if (aggressive) { + delta += cache.memoryUsage; + cache.clear(); + } else { + const before = cache.memoryUsage; + cache.cleanup(frame); + cache.releaseBlancoTextures(); + delta += cache.memoryUsage - before; + } + }); + if (aggressive) { + this._cachedNativeTextures.clear(); + } + if (delta) { + this._addMemoryUsage(delta); + } + } +} +class C2dTintCache { + constructor(nativeTexture) { + this._tx = nativeTexture; + this._colors = /* @__PURE__ */ new Map(); + this._blancoTextures = null; + this._lastCleanupFrame = 0; + this._memTextures = 0; + } + get memoryUsage() { + return this._memTextures * this._tx.w * this._tx.h; + } + releaseBlancoTextures() { + this._memTextures -= this._blancoTextures.length; + this._blancoTextures = []; + } + clear() { + this._blancoTextures = null; + this._colors.clear(); + this._memTextures = 0; + } + get(color) { + let item = this._colors.get(color); + if (!item) { + item = { lf: -1, tx: void 0, u: -1 }; + this._colors.set(color, item); + } + return item; + } + set(color, texture, frame) { + const item = this.get(color); + item.lf = frame; + item.tx = texture; + item.u = frame; + this._memTextures++; + } + cleanup(frame) { + if (this._lastCleanupFrame !== frame) { + this._blancoTextures = []; + this._colors.forEach((item, color) => { + if (item.lf < frame - 1) { + if (item.tx) { + this._blancoTextures.push(item.tx); + } + this._colors.delete(color); + } + }); + this._lastCleanupFrame = frame; + } + } + reuseTexture(frame) { + this.cleanup(frame); + if (this._blancoTextures && this._blancoTextures.length) { + this._memTextures--; + return this._blancoTextures.pop(); + } + } +} +class C2dRenderer extends Renderer { + constructor(stage) { + super(stage); + this.tintManager = new C2dTextureTintManager(stage); + this.setupC2d(this.stage.c2d.canvas); + } + destroy() { + this.tintManager.destroy(); + this.tintManager = null; + delete this.tintManager; + } + _createDefaultShader(ctx) { + return new DefaultShader2(ctx); + } + _getShaderBaseType() { + return C2dShader; + } + _getShaderAlternative(shaderType) { + return shaderType.getC2d && shaderType.getC2d(); + } + createCoreQuadList(ctx) { + return new C2dCoreQuadList(ctx); + } + createCoreQuadOperation(ctx, shader, shaderOwner, renderTextureInfo, scissor, index) { + return new C2dCoreQuadOperation(ctx, shader, shaderOwner, renderTextureInfo, scissor, index); + } + createCoreRenderExecutor(ctx) { + return new C2dCoreRenderExecutor(ctx); + } + createCoreRenderState(ctx) { + return new CoreRenderState(ctx); + } + createRenderTexture(w, h, pw, ph) { + const canvas = document.createElement("canvas"); + canvas.width = pw; + canvas.height = ph; + this.setupC2d(canvas); + return canvas; + } + freeRenderTexture(nativeTexture) { + this.tintManager.delete(nativeTexture); + } + gc(aggressive) { + this.tintManager.gc(aggressive); + } + uploadTextureSource(textureSource, options) { + if (options.source.buffer) { + const canvas = document.createElement("canvas"); + canvas.width = options.w; + canvas.height = options.h; + const imageData = new ImageData(new Uint8ClampedArray(options.source.buffer), options.w, options.h); + canvas.getContext("2d").putImageData(imageData, 0, 0); + return canvas; + } + return options.source; + } + freeTextureSource(textureSource) { + this.tintManager.delete(textureSource.nativeTexture); + } + addQuad(renderState, quads, index) { + const elementCore = quads.quadElements[index]; + quads.setRenderContext(index, elementCore._renderContext); + quads.setWhite(index, elementCore.isWhite()); + quads.setSimpleTc(index, elementCore.hasSimpleTexCoords()); + } + isRenderTextureReusable(renderState, renderTextureInfo) { + return false; + } + finishRenderState(renderState) { + } + setupC2d(canvas) { + const ctx = canvas.getContext("2d"); + canvas.ctx = ctx; + ctx._scissor = null; + canvas.ctx.save(); + } +} +class SparkShader extends WebGLShader { + enableAttribs() { + let gl = this.gl; + gl.vertexAttribPointer(this._attrib("aVertexPosition"), 2, gl.FLOAT, false, 20, 0); + gl.enableVertexAttribArray(this._attrib("aVertexPosition")); + if (this._attrib("aTextureCoord") !== -1) { + gl.vertexAttribPointer(this._attrib("aTextureCoord"), 2, gl.FLOAT, false, 20, 2 * 4); + gl.enableVertexAttribArray(this._attrib("aTextureCoord")); + } + if (this._attrib("aColor") !== -1) { + gl.vertexAttribPointer(this._attrib("aColor"), 4, gl.UNSIGNED_BYTE, true, 20, 4 * 4); + gl.enableVertexAttribArray(this._attrib("aColor")); + } + } + disableAttribs() { + let gl = this.gl; + gl.disableVertexAttribArray(this._attrib("aVertexPosition")); + if (this._attrib("aTextureCoord") !== -1) { + gl.disableVertexAttribArray(this._attrib("aTextureCoord")); + } + if (this._attrib("aColor") !== -1) { + gl.disableVertexAttribArray(this._attrib("aColor")); + } + } + setupUniforms(operation) { + this._setUniform("projection", this._getProjection(operation), this.gl.uniform2fv, false); + } + draw(operation) { + let gl = this.gl; + let length = operation.length; + if (length) { + let glTexture = operation.getTexture(0); + let pos = 0; + for (let i = 0; i < length; i++) { + let tx = operation.getTexture(i); + if (glTexture !== tx) { + if (glTexture.options && glTexture.options.imageRef) { + let elementPostion = i > 0 ? i - 1 : i; + const precision = this.ctx.stage.getOption("precision"); + let vc = operation.getElementCore(elementPostion); + this.ctx.stage.platform.paint(gl, glTexture.options.imageRef, vc._worldContext.px * precision, vc._worldContext.py * precision, vc._colorUl, vc); + } else { + gl.bindTexture(gl.TEXTURE_2D, glTexture); + gl.drawElements(gl.TRIANGLES, 6 * (i - pos), gl.UNSIGNED_SHORT, (pos + operation.index) * 6 * 2); + } + glTexture = tx; + pos = i; + } + } + if (pos < length) { + if (glTexture.options && glTexture.options.imageRef) { + const precision = this.ctx.stage.getOption("precision"); + let vc = operation.getElementCore(pos); + this.ctx.stage.platform.paint(gl, glTexture.options.imageRef, vc._worldContext.px * precision, vc._worldContext.py * precision, vc._colorUl, vc); + } else { + gl.bindTexture(gl.TEXTURE_2D, glTexture); + gl.drawElements(gl.TRIANGLES, 6 * (length - pos), gl.UNSIGNED_SHORT, (pos + operation.index) * 6 * 2); + } + } + } + } +} +SparkShader.vertexShaderSource = ` + #ifdef GL_ES + # ifdef GL_FRAGMENT_PRECISION_HIGH + precision highp float; + # else + precision lowp float; + # endif + #endif + attribute vec2 aVertexPosition; + attribute vec2 aTextureCoord; + attribute vec4 aColor; + uniform vec2 projection; + varying vec2 vTextureCoord; + varying vec4 vColor; + void main(void){ + gl_Position = vec4(aVertexPosition.x * projection.x - 1.0, aVertexPosition.y * -abs(projection.y) + 1.0, 0.0, 1.0); + vTextureCoord = aTextureCoord; + vColor = aColor; + gl_Position.y = -sign(projection.y) * gl_Position.y; + } +`; +SparkShader.fragmentShaderSource = ` + #ifdef GL_ES + # ifdef GL_FRAGMENT_PRECISION_HIGH + precision highp float; + # else + precision lowp float; + # endif + #endif + varying vec2 vTextureCoord; + varying vec4 vColor; + uniform sampler2D uSampler; + void main(void){ + gl_FragColor = texture2D(uSampler, vTextureCoord) * vColor; + } +`; +class SparkRenderer extends WebGLRenderer { + constructor(stage) { + super(stage); + } + _createDefaultShader(ctx) { + return new SparkShader(ctx); + } + createCoreRenderExecutor(ctx) { + global.beginDrawing(); + let ret = super.createCoreRenderExecutor(ctx); + global.endDrawing(); + return ret; + } +} +class ImageWorker { + constructor(options = {}) { + this._items = /* @__PURE__ */ new Map(); + this._id = 0; + this._initWorker(); + } + destroy() { + if (this._worker) { + this._worker.terminate(); + } + this._items = null; + this._worker = null; + delete this._items; + delete this._worker; + } + _initWorker() { + const code = `(${createWorker.toString()})()`; + const blob = new Blob([code.replace('"use strict";', "")]); + const blobURL = (window.URL ? URL : webkitURL).createObjectURL(blob, { + type: "application/javascript; charset=utf-8" + }); + this._worker = new Worker(blobURL); + this._worker.postMessage({ type: "config", config: { path: window.location.href, protocol: window.location.protocol } }); + this._worker.onmessage = (e) => { + if (e.data && e.data.id) { + const id = e.data.id; + const item = this._items.get(id); + if (item) { + if (e.data.type == "data") { + this.finish(item, e.data.info); + } else { + this.error(item, e.data.info); + } + } + } + }; + } + create(src) { + const id = ++this._id; + const item = new ImageWorkerImage(this, id, src); + this._items.set(id, item); + this._worker.postMessage({ type: "add", id, src }); + return item; + } + cancel(image) { + this._worker.postMessage({ type: "cancel", id: image.id }); + this._items.delete(image.id); + } + error(image, info) { + image.error(info); + this._items.delete(image.id); + } + finish(image, info) { + image.load(info); + this._items.delete(image.id); + } +} +class ImageWorkerImage { + constructor(manager, id, src) { + this._manager = manager; + this._id = id; + this._src = src; + this._onError = null; + this._onLoad = null; + } + get id() { + return this._id; + } + get src() { + return this._src; + } + set onError(f) { + this._onError = f; + } + set onLoad(f) { + this._onLoad = f; + } + cancel() { + this._manager.cancel(this); + } + load(info) { + if (this._onLoad) { + this._onLoad(info); + } + } + error(info) { + if (this._onError) { + this._onError(info); + } + } +} +const createWorker = function() { + function ImageWorkerServer() { + this.items = /* @__PURE__ */ new Map(); + var t = this; + onmessage = function(e) { + t._receiveMessage(e); + }; + } + ImageWorkerServer.isPathAbsolute = function(path) { + return /^(?:\/|[a-z]+:\/\/)/.test(path) || path.substr(0, 5) == "data:"; + }; + ImageWorkerServer.prototype._receiveMessage = function(e) { + if (e.data.type === "config") { + this.config = e.data.config; + var base = this.config.path; + var hasHashPath = /#.*?\//; + if (hasHashPath.test(base)) { + base = base.replace(/#.*$/, ""); + } + var parts = base.split("/"); + parts.pop(); + this._relativeBase = parts.join("/") + "/"; + } else if (e.data.type === "add") { + this.add(e.data.id, e.data.src); + } else if (e.data.type === "cancel") { + this.cancel(e.data.id); + } + }; + ImageWorkerServer.prototype.add = function(id, src) { + if (!ImageWorkerServer.isPathAbsolute(src)) { + src = this._relativeBase + src; + } + if (src.substr(0, 2) === "//") { + src = this.config.protocol + src; + } + var item = new ImageWorkerServerItem(id, src); + var t = this; + item.onFinish = function(result) { + t.finish(item, result); + }; + item.onError = function(info) { + t.error(item, info); + }; + this.items.set(id, item); + item.start(); + }; + ImageWorkerServer.prototype.cancel = function(id) { + var item = this.items.get(id); + if (item) { + item.cancel(); + this.items.delete(id); + } + }; + ImageWorkerServer.prototype.finish = function(item, { imageBitmap, hasAlphaChannel }) { + postMessage({ + type: "data", + id: item.id, + info: { + imageBitmap, + hasAlphaChannel + } + }, [imageBitmap]); + this.items.delete(item.id); + }; + ImageWorkerServer.prototype.error = function(item, { type, message }) { + postMessage({ + type: "error", + id: item.id, + info: { + type, + message + } + }); + this.items.delete(item.id); + }; + ImageWorkerServer.isWPEBrowser = function() { + return navigator.userAgent.indexOf("WPE") !== -1; + }; + function ImageWorkerServerItem(id, src) { + this._onError = void 0; + this._onFinish = void 0; + this._id = id; + this._src = src; + this._xhr = void 0; + this._mimeType = void 0; + this._canceled = false; + } + Object.defineProperty(ImageWorkerServerItem.prototype, "id", { + get: function() { + return this._id; + } + }); + Object.defineProperty(ImageWorkerServerItem.prototype, "onFinish", { + get: function() { + return this._onFinish; + }, + set: function(f) { + this._onFinish = f; + } + }); + Object.defineProperty(ImageWorkerServerItem.prototype, "onError", { + get: function() { + return this._onError; + }, + set: function(f) { + this._onError = f; + } + }); + ImageWorkerServerItem.prototype.start = function() { + this._xhr = new XMLHttpRequest(); + this._xhr.open("GET", this._src, true); + this._xhr.responseType = "blob"; + var t = this; + this._xhr.onerror = function(oEvent) { + t.error({ type: "connection", message: "Connection error" }); + }; + this._xhr.onload = function(oEvent) { + var blob = t._xhr.response; + t._mimeType = blob.type; + t._createImageBitmap(blob); + }; + this._xhr.send(); + }; + ImageWorkerServerItem.prototype._createImageBitmap = function(blob) { + var t = this; + createImageBitmap(blob, { premultiplyAlpha: "premultiply", colorSpaceConversion: "none", imageOrientation: "none" }).then(function(imageBitmap) { + t.finish({ + imageBitmap, + hasAlphaChannel: t._hasAlphaChannel() + }); + }).catch(function(e) { + t.error({ type: "parse", message: "Error parsing image data" }); + }); + }; + ImageWorkerServerItem.prototype._hasAlphaChannel = function() { + if (ImageWorkerServer.isWPEBrowser()) { + return true; + } else { + return this._mimeType.indexOf("image/png") !== -1; + } + }; + ImageWorkerServerItem.prototype.cancel = function() { + if (this._canceled) + return; + if (this._xhr) { + this._xhr.abort(); + } + this._canceled = true; + }; + ImageWorkerServerItem.prototype.error = function(type, message) { + if (!this._canceled && this._onError) { + this._onError({ type, message }); + } + }; + ImageWorkerServerItem.prototype.finish = function(info) { + if (!this._canceled && this._onFinish) { + this._onFinish(info); + } + }; + new ImageWorkerServer(); +}; +class WebPlatform { + init(stage) { + this.stage = stage; + this._looping = false; + this._awaitingLoop = false; + this._loopHandler = null; + this._idleLoopCounter = 0; + this._idleLoopDelay = 60; + if (this.stage.getOption("useImageWorker")) { + if (!window.createImageBitmap || !window.Worker) { + console.warn("[Lightning] Can't use image worker because browser does not have createImageBitmap and Web Worker support"); + } else { + this._imageWorker = new ImageWorker(); + } + } + this._registerVisibilityChangeHandler(); + } + destroy() { + if (this._imageWorker) { + this._imageWorker.destroy(); + } + clearInterval(this._loopHandler); + this._removeKeyHandler(); + this._removeClickHandler(); + this._removeHoverHandler(); + this._removeScrollWheelHandler(); + this._removeVisibilityChangeHandler(); + this.stage = null; + delete this.stage; + } + startLoop() { + this._looping = true; + if (!this._awaitingLoop) { + this.loop(); + } + } + stopLoop() { + this._looping = false; + } + switchLoop() { + if (this._idleLoopCounter < this._idleLoopDelay) { + this._idleLoopCounter++; + return; + } + if (!this.stage.ctx.hasRenderUpdates()) { + this.stopLoop(); + this._loopHandler = setInterval(() => { + this.stage.updateFrame(); + this.stage.idleFrame(); + if (this.stage.ctx.hasRenderUpdates()) { + clearInterval(this._loopHandler); + this.startLoop(); + } + }, 1e3 / 60); + } else { + this._idleLoopCounter = 0; + } + } + loop() { + let self = this; + let lp = function() { + self._awaitingLoop = false; + if (self._looping) { + self.stage.updateFrame(); + if (self.stage.getOption("pauseRafLoopOnIdle")) { + self.switchLoop(); + } + self.stage.renderFrame(); + requestAnimationFrame(lp); + self._awaitingLoop = true; + } + }; + requestAnimationFrame(lp); + } + uploadCompressedGlTexture(gl, textureSource, source, options) { + const view = !source.pvr ? new DataView(source.mipmaps[0]) : source.mipmaps[0]; + gl.compressedTexImage2D( + gl.TEXTURE_2D, + 0, + source.glInternalFormat, + source.pixelWidth, + source.pixelHeight, + 0, + view + ); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR); + } + uploadGlTexture(gl, textureSource, source, options) { + if (source instanceof ImageData || source instanceof HTMLImageElement || source instanceof HTMLVideoElement || window.ImageBitmap && source instanceof ImageBitmap) { + gl.texImage2D(gl.TEXTURE_2D, 0, options.internalFormat, options.format, options.type, source); + } else if (source instanceof HTMLCanvasElement) { + if (Utils$1.isZiggo || this.stage.getOption("forceTxCanvasSource")) { + gl.texImage2D(gl.TEXTURE_2D, 0, options.internalFormat, options.format, options.type, source); + } else if (source.width > 0 && source.height > 0) { + const ctx = source.getContext("2d"); + gl.texImage2D(gl.TEXTURE_2D, 0, options.internalFormat, options.format, options.type, ctx.getImageData(0, 0, source.width, source.height)); + } + } else { + gl.texImage2D(gl.TEXTURE_2D, 0, options.internalFormat, textureSource.w, textureSource.h, 0, options.format, options.type, source); + } + } + handleKtxLoad(cb, src) { + var self = this; + return function() { + var arraybuffer = this.response; + var view = new DataView(arraybuffer); + var targetIdentifier = 3632701469; + if (targetIdentifier !== view.getUint32(0) + view.getUint32(4) + view.getUint32(8)) { + cb("Parsing failed: identifier ktx mismatch:", src); + } + var littleEndian = view.getUint32(12) === 16909060 ? true : false; + var data = { + glType: view.getUint32(16, littleEndian), + glTypeSize: view.getUint32(20, littleEndian), + glFormat: view.getUint32(24, littleEndian), + glInternalFormat: view.getUint32(28, littleEndian), + glBaseInternalFormat: view.getUint32(32, littleEndian), + pixelWidth: view.getUint32(36, littleEndian), + pixelHeight: view.getUint32(40, littleEndian), + pixelDepth: view.getUint32(44, littleEndian), + numberOfArrayElements: view.getUint32(48, littleEndian), + numberOfFaces: view.getUint32(52, littleEndian), + numberOfMipmapLevels: view.getUint32(56, littleEndian), + bytesOfKeyValueData: view.getUint32(60, littleEndian), + kvps: [], + mipmaps: [], + get width() { + return this.pixelWidth; + }, + get height() { + return this.pixelHeight; + } + }; + const props = (obj) => { + const p = []; + for (let v in obj) { + p.push(obj[v]); + } + return p; + }; + const formats = Object.values(self.stage.renderer.getCompressedTextureExtensions()).filter((obj) => obj != null).map((obj) => props(obj)).reduce((prev, current) => prev.concat(current)); + if (!formats.includes(data.glInternalFormat)) { + console.warn("[Lightning] Unrecognized texture extension format:", src, data.glInternalFormat, self.stage.renderer.getCompressedTextureExtensions()); + } + var offset = 64; + offset += data.bytesOfKeyValueData; + for (var i = 0; i < data.numberOfMipmapLevels; i++) { + var imageSize = view.getUint32(offset); + offset += 4; + data.mipmaps.push(view.buffer.slice(offset, imageSize)); + offset += imageSize; + } + cb(null, { + source: data, + renderInfo: { src, compressed: true } + }); + }; + } + handlePvrLoad(cb, src) { + return function() { + const pvrHeaderLength = 13; + const pvrFormatEtc1 = 36196; + const pvrWidth = 7; + const pvrHeight = 6; + const pvrMipmapCount = 11; + const pvrMetadata = 12; + const arrayBuffer = this.response; + const header = new Int32Array(arrayBuffer, 0, pvrHeaderLength); + const dataOffset = header[pvrMetadata] + 52; + const pvrtcData = new Uint8Array(arrayBuffer, dataOffset); + var data = { + glInternalFormat: pvrFormatEtc1, + pixelWidth: header[pvrWidth], + pixelHeight: header[pvrHeight], + numberOfMipmapLevels: header[pvrMipmapCount], + mipmaps: [], + pvr: true, + get width() { + return this.pixelWidth; + }, + get height() { + return this.pixelHeight; + } + }; + let offset = 0; + let width = data.pixelWidth; + let height = data.pixelHeight; + for (var i = 0; i < data.numberOfMipmapLevels; i++) { + const level = (width + 3 >> 2) * (height + 3 >> 2) * 8; + const view = new Uint8Array(arrayBuffer, pvrtcData.byteOffset + offset, level); + data.mipmaps.push(view); + offset += level; + width = width >> 1; + height = height >> 1; + } + cb(null, { + source: data, + renderInfo: { src, compressed: true } + }); + }; + } + loadSrcTexture({ src, hasAlpha }, cb) { + let cancelCb = void 0; + let isPng = src.toLowerCase().indexOf(".png") >= 0 || src.substr(0, 21) == "data:image/png;base64"; + let isKtx = src.indexOf(".ktx") >= 0; + let isPvr = src.indexOf(".pvr") >= 0; + if (isKtx || isPvr) { + let request = new XMLHttpRequest(); + request.addEventListener( + "load", + isKtx ? this.handleKtxLoad(cb, src) : this.handlePvrLoad(cb, src) + ); + request.open("GET", src); + request.responseType = "arraybuffer"; + request.send(); + cancelCb = function() { + request.abort(); + }; + } else if (this._imageWorker) { + const image = this._imageWorker.create(src); + image.onError = function(err) { + return cb("Image load error"); + }; + image.onLoad = function({ imageBitmap, hasAlphaChannel }) { + cb(null, { + source: imageBitmap, + renderInfo: { src, compressed: false }, + hasAlpha: hasAlphaChannel, + premultiplyAlpha: true + }); + }; + cancelCb = function() { + image.cancel(); + }; + } else { + let image = new Image(); + if (!(src.substr(0, 5) == "data:") && !Utils$1.isPS4) { + image.crossOrigin = "Anonymous"; + } + image.onerror = function(err) { + if (image.src) { + return cb("Image load error"); + } + }; + image.onload = function() { + cb(null, { + source: image, + renderInfo: { src, compressed: false }, + hasAlpha: isPng || hasAlpha + }); + }; + image.src = src; + cancelCb = function() { + image.onerror = null; + image.onload = null; + image.removeAttribute("src"); + }; + } + return cancelCb; + } + createWebGLContext(w, h) { + let canvas = this.stage.getOption("canvas") || document.createElement("canvas"); + if (w && h) { + canvas.width = w; + canvas.height = h; + } + let opts = { + alpha: true, + antialias: false, + premultipliedAlpha: true, + stencil: true, + preserveDrawingBuffer: false + }; + let gl = canvas.getContext("webgl", opts) || canvas.getContext("experimental-webgl", opts) || canvas.getContext("webgl2", opts); + if (!gl) { + throw new Error("This browser does not support webGL."); + } + return gl; + } + createCanvasContext(w, h) { + let canvas = this.stage.getOption("canvas") || document.createElement("canvas"); + if (w && h) { + canvas.width = w; + canvas.height = h; + } + let c2d = canvas.getContext("2d"); + if (!c2d) { + throw new Error("This browser does not support 2d canvas."); + } + return c2d; + } + getHrTime() { + return window.performance ? window.performance.now() : new Date().getTime(); + } + getDrawingCanvas() { + return document.createElement("canvas"); + } + getTextureOptionsForDrawingCanvas(canvas) { + let options = {}; + options.source = canvas; + return options; + } + nextFrame(changes) { + } + registerKeydownHandler(keyhandler) { + this._keydownListener = (e) => { + keyhandler(e); + }; + window.addEventListener("keydown", this._keydownListener); + } + registerKeyupHandler(keyhandler) { + this._keyupListener = (e) => { + keyhandler(e); + }; + window.addEventListener("keyup", this._keyupListener); + } + _removeKeyHandler() { + if (this._keydownListener) { + window.removeEventListener("keydown", this._keydownListener); + } + if (this._keyupListener) { + window.removeEventListener("keyup", this._keyupListener); + } + } + registerClickHandler(clickHandler) { + this._clickListener = (e) => { + clickHandler(e); + }; + window.addEventListener("mousedown", this._clickListener); + } + _removeClickHandler() { + if (this._clickListener) { + window.removeEventListener("mousedown", this._clickListener); + } + } + registerHoverHandler(hoverHandler) { + this._hoverListener = (e) => { + hoverHandler(e); + }; + window.addEventListener("mousemove", this._hoverListener); + } + _removeHoverHandler() { + if (this._hoverListener) { + window.removeEventListener("mousemove", this._hoverListener); + } + } + registerScrollWheelHandler(registerScrollWheelHandler) { + this._scrollWheelListener = (e) => { + registerScrollWheelHandler(e); + }; + window.addEventListener("wheel", this._scrollWheelListener); + } + _removeScrollWheelHandler() { + if (this._scrollWheelListener) { + window.removeEventListener("wheel", this._scrollWheelListener); + } + } + _registerVisibilityChangeHandler() { + this._visibilityChangeHandler = () => { + if (document.visibilityState === "visible") { + this.stage.root.core.setHasRenderUpdates(2); + this.stage.renderFrame(); + } + }; + document.addEventListener("visibilitychange", this._visibilityChangeHandler); + } + _removeVisibilityChangeHandler() { + if (this._visibilityChangeHandler) { + document.removeEventListener("visibilitychange", this._visibilityChangeHandler); + } + } +} +class PlatformLoader { + static load(options) { + if (options.platform) { + return options.platform; + } else { + return WebPlatform; + } + } +} +class Utils2 { + static isFunction(value) { + return typeof value === "function"; + } + static isNumber(value) { + return typeof value === "number"; + } + static isInteger(value) { + return typeof value === "number" && value % 1 === 0; + } + static isBoolean(value) { + return value === true || value === false; + } + static isString(value) { + return typeof value == "string"; + } + static isObject(value) { + let type = typeof value; + return !!value && (type == "object" || type == "function"); + } + static isPlainObject(value) { + let type = typeof value; + return !!value && type == "object"; + } + static isObjectLiteral(value) { + return typeof value === "object" && value && value.constructor === Object; + } + static getArrayIndex(index, arr) { + return Utils2.getModuloIndex(index, arr.length); + } + static equalValues(v1, v2) { + if (typeof v1 !== typeof v2) + return false; + if (Utils2.isObjectLiteral(v1)) { + return Utils2.isObjectLiteral(v2) && Utils2.equalObjectLiterals(v1, v2); + } else if (Array.isArray(v1)) { + return Array.isArray(v2) && Utils2.equalArrays(v1, v2); + } else { + return v1 === v2; + } + } + static equalObjectLiterals(obj1, obj2) { + let keys1 = Object.keys(obj1); + let keys2 = Object.keys(obj2); + if (keys1.length !== keys2.length) { + return false; + } + for (let i = 0, n = keys1.length; i < n; i++) { + const k1 = keys1[i]; + const k2 = keys2[i]; + if (k1 !== k2) { + return false; + } + const v1 = obj1[k1]; + const v2 = obj2[k2]; + if (!Utils2.equalValues(v1, v2)) { + return false; + } + } + return true; + } + static equalArrays(v1, v2) { + if (v1.length !== v2.length) { + return false; + } + for (let i = 0, n = v1.length; i < n; i++) { + if (!this.equalValues(v1[i], v2[i])) { + return false; + } + } + return true; + } +} +class WebGLState { + constructor(id, gl) { + this._id = id; + this._gl = gl; + this._program = void 0; + this._buffers = /* @__PURE__ */ new Map(); + this._framebuffers = /* @__PURE__ */ new Map(); + this._renderbuffers = /* @__PURE__ */ new Map(); + this._vertexAttribs = new Array(16); + this._nonDefaultFlags = /* @__PURE__ */ new Set(); + this._settings = /* @__PURE__ */ new Map(); + this._textures = new Array(8); + this._maxTexture = 0; + this._activeTexture = gl.TEXTURE0; + this._pixelStorei = new Array(5); + } + _getDefaultFlag(cap) { + return cap === this._gl.DITHER; + } + setFlag(cap, v) { + const def = this._getDefaultFlag(cap); + if (v === def) { + return this._nonDefaultFlags.delete(cap); + } else { + if (!this._nonDefaultFlags.has(cap)) { + this._nonDefaultFlags.add(cap); + return true; + } else { + return false; + } + } + } + setBuffer(target, buffer) { + const change = this._buffers.get(target) !== buffer; + this._buffers.set(target, buffer); + if (change && target === this._gl.ARRAY_BUFFER) { + this._vertexAttribs = []; + } + return change; + } + setFramebuffer(target, buffer) { + const change = this._framebuffers.get(target) !== buffer; + this._framebuffers.set(target, buffer); + return change; + } + setRenderbuffer(target, buffer) { + const change = this._renderbuffers.get(target) !== buffer; + this._renderbuffers.set(target, buffer); + return change; + } + setProgram(program) { + const change = this._program !== program; + this._program = program; + return change; + } + setSetting(func, v) { + const s = this._settings.get(func); + const change = !s || !Utils2.equalValues(s, v); + this._settings.set(func, v); + return change; + } + disableVertexAttribArray(index) { + const va = this._vertexAttribs[index]; + if (va && va[5]) { + va[5] = false; + return true; + } + return false; + } + enableVertexAttribArray(index) { + const va = this._vertexAttribs[index]; + if (va) { + if (!va[0]) { + va[0] = true; + return true; + } + } else { + this._vertexAttribs[index] = [0, 0, 0, 0, 0, true]; + return true; + } + return false; + } + vertexAttribPointer(index, props) { + let va = this._vertexAttribs[index]; + let equal = false; + if (va) { + equal = va[0] === props[0] && va[1] === props[1] && va[2] === props[2] && va[3] === props[3] && va[4] === props[4]; + } + if (equal) { + return false; + } else { + props[5] = va ? va[5] : false; + return true; + } + } + setActiveTexture(texture) { + const changed = this._activeTexture !== texture; + this._activeTexture = texture; + return changed; + } + bindTexture(target, texture) { + const activeIndex = WebGLState._getTextureIndex(this._activeTexture); + this._maxTexture = Math.max(this._maxTexture, activeIndex + 1); + const current = this._textures[activeIndex]; + const targetIndex = WebGLState._getTextureTargetIndex(target); + if (current) { + if (current[targetIndex] === texture) { + return false; + } + current[targetIndex] = texture; + return true; + } else { + if (texture) { + this._textures[activeIndex] = []; + this._textures[activeIndex][targetIndex] = texture; + return true; + } else { + return false; + } + } + } + setPixelStorei(pname, param) { + const i = WebGLState._getPixelStoreiIndex(pname); + const change = !Utils2.equalValues(this._pixelStorei[i], param); + this._pixelStorei[i] = param; + return change; + } + migrate(s) { + const t = this; + this._migrateFlags(t, s); + if (s._program !== t._program) { + this._gl._useProgram(s._program); + } + this._migrateFramebuffers(t, s); + this._migrateRenderbuffers(t, s); + const buffersChanged = this._migrateBuffers(t, s); + this._migrateAttributes(t, s, buffersChanged); + this._migrateFlags(t, s); + this._migrateSettings(t, s); + this._migratePixelStorei(t, s); + this._migrateTextures(t, s); + } + _migratePixelStorei(t, s) { + for (let i = 0, n = t._pixelStorei.length; i < n; i++) { + if (t._pixelStorei[i] !== s._pixelStorei[i]) { + const value = s._pixelStorei[i] !== void 0 ? s._pixelStorei[i] : WebGLState._getDefaultPixelStoreiByIndex(i); + this._gl._pixelStorei(WebGLState._getPixelStoreiByIndex(i), value); + } + } + } + _migrateTextures(t, s) { + const max = Math.max(t._maxTexture, s._maxTexture); + let activeTexture = t._activeTexture; + for (let i = 0; i < max; i++) { + const sTargets = s._textures[i]; + const tTargets = t._textures[i]; + const textureNumb = WebGLState._getTextureByIndex(i); + const targetMax = Math.max(tTargets ? tTargets.length : 0, sTargets ? sTargets.length : 0); + for (let j = 0, n = targetMax; j < n; j++) { + const target = WebGLState._getTextureTargetByIndex(j); + if (activeTexture !== textureNumb) { + this._gl._activeTexture(textureNumb); + activeTexture = textureNumb; + } + const texture = sTargets && sTargets[j] || null; + this._gl._bindTexture(target, texture); + } + } + if (s._activeTexture !== activeTexture) { + this._gl._activeTexture(s._activeTexture); + } + } + _migrateBuffers(t, s) { + s._buffers.forEach((framebuffer, target) => { + if (t._buffers.get(target) !== framebuffer) { + this._gl._bindBuffer(target, framebuffer); + } + }); + t._buffers.forEach((buffer, target) => { + const b = s._buffers.get(target); + if (b === void 0) { + this._gl._bindBuffer(target, null); + } + }); + return s._buffers.get(this._gl.ARRAY_BUFFER) !== t._buffers.get(this._gl.ARRAY_BUFFER); + } + _migrateFramebuffers(t, s) { + s._framebuffers.forEach((framebuffer, target) => { + if (t._framebuffers.get(target) !== framebuffer) { + this._gl._bindFramebuffer(target, framebuffer); + } + }); + t._framebuffers.forEach((framebuffer, target) => { + const fb = s._framebuffers.get(target); + if (fb === void 0) { + this._gl._bindFramebuffer(target, null); + } + }); + } + _migrateRenderbuffers(t, s) { + s._renderbuffers.forEach((renderbuffer, target) => { + if (t._renderbuffers.get(target) !== renderbuffer) { + this._gl._bindRenderbuffer(target, renderbuffer); + } + }); + t._renderbuffers.forEach((renderbuffer, target) => { + const fb = s._renderbuffers.get(target); + if (fb === void 0) { + this._gl._bindRenderbuffer(target, null); + } + }); + } + _migrateAttributes(t, s, buffersChanged) { + if (!buffersChanged) { + t._vertexAttribs.forEach((attrib, index) => { + if (!s._vertexAttribs[index]) { + this._gl._disableVertexAttribArray(index); + } + }); + s._vertexAttribs.forEach((attrib, index) => { + this._gl._vertexAttribPointer(index, attrib[0], attrib[1], attrib[2], attrib[4]); + if (attrib[5]) { + this._gl._enableVertexAttribArray(index); + } else { + this._gl._disableVertexAttribArray(index); + } + }); + } else { + s._vertexAttribs.forEach((attrib, index) => { + if (attrib[0]) { + this._gl._vertexAttribPointer(index, attrib[0], attrib[1], attrib[2], attrib[3], attrib[4]); + } + if (attrib[5]) { + this._gl._enableVertexAttribArray(index); + } + }); + } + } + _migrateSettings(t, s) { + const defaults = this.constructor.getDefaultSettings(); + t._settings.forEach((value, func) => { + const name = func.name || func.xname; + if (!s._settings.has(func)) { + let args = defaults.get(name); + if (Utils2.isFunction(args)) { + args = args(this._gl); + } + s._settings.set(func, args); + func.apply(this._gl, args); + } + }); + s._settings.forEach((value, func) => { + const tValue = t._settings.get(func); + if (!tValue || !Utils2.equalValues(tValue, value)) { + func.apply(this._gl, value); + } + }); + } + _migrateFlags(t, s) { + t._nonDefaultFlags.forEach((setting) => { + if (!s._nonDefaultFlags.has(setting)) { + if (this._getDefaultFlag(setting)) { + this._gl._enable(setting); + } else { + this._gl._disable(setting); + } + } + }); + s._nonDefaultFlags.forEach((setting) => { + if (!t._nonDefaultFlags.has(setting)) { + if (this._getDefaultFlag(setting)) { + this._gl._disable(setting); + } else { + this._gl._enable(setting); + } + } + }); + } + static getDefaultSettings() { + if (!this._defaultSettings) { + this._defaultSettings = /* @__PURE__ */ new Map(); + const d = this._defaultSettings; + const g = WebGLRenderingContext.prototype; + d.set("viewport", function(gl) { + return [0, 0, gl.canvas.width, gl.canvas.height]; + }); + d.set("scissor", function(gl) { + return [0, 0, gl.canvas.width, gl.canvas.height]; + }); + d.set("blendColor", [0, 0, 0, 0]); + d.set("blendEquation", [g.FUNC_ADD]); + d.set("blendEquationSeparate", [g.FUNC_ADD, g.FUNC_ADD]); + d.set("blendFunc", [g.ONE, g.ZERO]); + d.set("blendFuncSeparate", [g.ONE, g.ZERO, g.ONE, g.ZERO]); + d.set("clearColor", [0, 0, 0, 0]); + d.set("clearDepth", [1]); + d.set("clearStencil", [0]); + d.set("colorMask", [true, true, true, true]); + d.set("cullFace", [g.BACK]); + d.set("depthFunc", [g.LESS]); + d.set("depthMask", [true]); + d.set("depthRange", [0, 1]); + d.set("frontFace", [g.CCW]); + d.set("lineWidth", [1]); + d.set("polygonOffset", [0, 0]); + d.set("sampleCoverage", [1, false]); + d.set("stencilFunc", [g.ALWAYS, 0, 1]); + d.set("_stencilFuncSeparateFront", [g.ALWAYS, 0, 1]); + d.set("_stencilFuncSeparateBack", [g.ALWAYS, 0, 1]); + d.set("_stencilFuncSeparateFrontAndBack", [g.ALWAYS, 0, 1]); + d.set("stencilMask", [1]); + d.set("_stencilMaskSeparateFront", [1]); + d.set("_stencilMaskSeparateBack", [1]); + d.set("_stencilMaskSeparateFrontAndBack", [1]); + d.set("stencilOp", [g.KEEP, g.KEEP, g.KEEP]); + d.set("_stencilOpSeparateFront", [g.KEEP, g.KEEP, g.KEEP]); + d.set("_stencilOpSeparateBack", [g.KEEP, g.KEEP, g.KEEP]); + d.set("_stencilOpSeparateFrontAndBack", [g.KEEP, g.KEEP, g.KEEP]); + d.set("vertexAttrib1f", []); + d.set("vertexAttrib1fv", []); + d.set("vertexAttrib2f", []); + d.set("vertexAttrib2fv", []); + d.set("vertexAttrib3f", []); + d.set("vertexAttrib3fv", []); + d.set("vertexAttrib4f", []); + d.set("vertexAttrib4fv", []); + } + return this._defaultSettings; + } + static _getTextureTargetIndex(target) { + switch (target) { + case 3553: + return 0; + case 34067: + return 1; + default: + throw new Error("Unknown texture target: " + target); + } + } + static _getTextureTargetByIndex(index) { + if (!this._textureTargetIndices) { + this._textureTargetIndices = [3553, 34067]; + } + return this._textureTargetIndices[index]; + } + static _getTextureIndex(index) { + return index - 33984; + } + static _getTextureByIndex(index) { + return index + 33984; + } + static _getPixelStoreiIndex(pname) { + switch (pname) { + case 3333: + return 0; + case 3317: + return 1; + case 37440: + return 2; + case 37441: + return 3; + case 37443: + return 4; + case 37445: + return 5; + default: + throw new Error("Unknown pixelstorei: " + pname); + } + } + static _getPixelStoreiByIndex(index) { + if (!this._pixelStoreiIndices) { + this._pixelStoreiIndices = [3333, 3317, 37440, 37441, 37443]; + } + return this._pixelStoreiIndices[index]; + } + static _getDefaultPixelStoreiByIndex(index) { + if (!this._pixelStoreiDefaults) { + this._pixelStoreiDefaults = [4, 4, false, false, WebGLRenderingContext.prototype.BROWSER_DEFAULT_WEBGL]; + } + return this._pixelStoreiDefaults[index]; + } +} +class WebGLStateManager { + _initStateManager(id = "default") { + this._states = {}; + this._state = this._getState(id); + } + _getState(id) { + if (!this._states[id]) { + this._states[id] = new WebGLState(id, this); + } + return this._states[id]; + } + switchState(id = "default") { + if (this._state._id !== id) { + const newState = this._getState(id); + this._state.migrate(newState); + this._state = newState; + } + } + $useProgram(program) { + if (this._state.setProgram(program)) + this._useProgram(program); + } + $bindBuffer(target, fb) { + if (this._state.setBuffer(target, fb)) + this._bindBuffer(target, fb); + } + $bindFramebuffer(target, fb) { + if (this._state.setFramebuffer(target, fb)) + this._bindFramebuffer(target, fb); + } + $bindRenderbuffer(target, fb) { + if (this._state.setRenderbuffer(target, fb)) + this._bindRenderbuffer(target, fb); + } + $enable(cap) { + if (this._state.setFlag(cap, true)) + this._enable(cap); + } + $disable(cap) { + if (this._state.setFlag(cap, false)) + this._disable(cap); + } + $viewport(x, y, w, h) { + if (this._state.setSetting(this._viewport, [x, y, w, h])) + this._viewport(x, y, w, h); + } + $scissor(x, y, w, h) { + if (this._state.setSetting(this._scissor, [x, y, w, h])) + this._scissor(x, y, w, h); + } + $disableVertexAttribArray(index) { + if (this._state.disableVertexAttribArray(index)) + this._disableVertexAttribArray(index); + } + $enableVertexAttribArray(index) { + if (this._state.enableVertexAttribArray(index)) + this._enableVertexAttribArray(index); + } + $vertexAttribPointer(index, size, type, normalized, stride, offset) { + if (this._state.vertexAttribPointer(index, [size, type, normalized, stride, offset])) + this._vertexAttribPointer(index, size, type, normalized, stride, offset); + } + $activeTexture(texture) { + if (this._state.setActiveTexture(texture)) + this._activeTexture(texture); + } + $bindTexture(target, texture) { + if (this._state.bindTexture(target, texture)) + this._bindTexture(target, texture); + } + $pixelStorei(pname, param) { + if (this._state.setPixelStorei(pname, param)) { + this._pixelStorei(pname, param); + } + } + $stencilFuncSeparate(face, func, ref, mask) { + let f; + switch (face) { + case this.FRONT: + f = this._stencilFuncSeparateFront; + break; + case this.BACK: + f = this._stencilFuncSeparateBack; + break; + case this.FRONT_AND_BACK: + f = this._stencilFuncSeparateFrontAndBack; + break; + } + if (this._state.setSetting(f, [func, ref, mask])) + f.apply(this, [func, ref, mask]); + } + _stencilFuncSeparateFront(func, ref, mask) { + this._stencilFuncSeparate(this.FRONT, func, ref, mask); + } + _stencilFuncSeparateBack(func, ref, mask) { + this._stencilFuncSeparate(this.BACK, func, ref, mask); + } + _stencilFuncSeparateFrontAndBack(func, ref, mask) { + this._stencilFuncSeparate(this.FRONT_AND_BACK, func, ref, mask); + } + $stencilMaskSeparate(face, mask) { + let f; + switch (face) { + case this.FRONT: + f = this._stencilMaskSeparateFront; + break; + case this.BACK: + f = this._stencilMaskSeparateBack; + break; + case this.FRONT_AND_BACK: + f = this._stencilMaskSeparateFrontAndBack; + break; + } + if (this._state.setSetting(f, [mask])) + f.apply(this, [mask]); + } + _stencilMaskSeparateFront(mask) { + this._stencilMaskSeparate(this.FRONT, mask); + } + _stencilMaskSeparateBack(mask) { + this._stencilMaskSeparate(this.BACK, mask); + } + _stencilMaskSeparateFrontAndBack(mask) { + this._stencilMaskSeparate(this.FRONT_AND_BACK, mask); + } + $stencilOpSeparate(face, fail, zfail, zpass) { + let f; + switch (face) { + case this.FRONT: + f = this._stencilOpSeparateFront; + break; + case this.BACK: + f = this._stencilOpSeparateBack; + break; + case this.FRONT_AND_BACK: + f = this._stencilOpSeparateFrontAndBack; + break; + } + if (this._state.setSetting(f, [fail, zfail, zpass])) + f.apply(this, [fail, zfail, zpass]); + } + _stencilOpSeparateFront(fail, zfail, zpass) { + this._stencilOpSeparate(this.FRONT, fail, zfail, zpass); + } + _stencilOpSeparateBack(fail, zfail, zpass) { + this._stencilOpSeparate(this.BACK, fail, zfail, zpass); + } + _stencilOpSeparateFrontAndBack(fail, zfail, zpass) { + this._stencilOpSeparate(this.FRONT_AND_BACK, fail, zfail, zpass); + } + $blendColor(red, green, blue, alpha) { + if (this._state.setSetting(this._blendColor, [red, green, blue, alpha])) + this._blendColor(red, green, blue, alpha); + } + $blendEquation(mode) { + if (this._state.setSetting(this._blendEquation, [mode])) + this._blendEquation(mode); + } + $blendEquationSeparate(modeRGB, modeAlpha) { + if (this._state.setSetting(this._blendEquationSeparate, [modeRGB, modeAlpha])) + this._blendEquationSeparate(modeRGB, modeAlpha); + } + $blendFunc(sfactor, dfactor) { + if (this._state.setSetting(this._blendFunc, [sfactor, dfactor])) + this._blendFunc(sfactor, dfactor); + } + $blendFuncSeparate(srcRGB, dstRGB, srcAlpha, dstAlpha) { + if (this._state.setSetting(this._blendFuncSeparate, [srcRGB, dstRGB, srcAlpha, dstAlpha])) + this._blendFuncSeparate(srcRGB, dstRGB, srcAlpha, dstAlpha); + } + $clearColor(red, green, blue, alpha) { + if (this._state.setSetting(this._clearColor, [red, green, blue, alpha])) + this._clearColor(red, green, blue, alpha); + } + $clearDepth(depth) { + if (this._state.setSetting(this._clearDepth, [depth])) + this._clearDepth(depth); + } + $clearStencil(s) { + if (this._state.setSetting(this._clearStencil, [s])) + this._clearStencil(s); + } + $colorMask(red, green, blue, alpha) { + if (this._state.setSetting(this._colorMask, [red, green, blue, alpha])) + this._colorMask(red, green, blue, alpha); + } + $cullFace(mode) { + if (this._state.setSetting(this._cullFace, [mode])) + this._cullFace(mode); + } + $depthFunc(func) { + if (this._state.setSetting(this._depthFunc, [func])) + this._depthFunc(func); + } + $depthMask(flag) { + if (this._state.setSetting(this._depthMask, [flag])) + this._depthMask(flag); + } + $depthRange(zNear, zFar) { + if (this._state.setSetting(this._depthRange, [zNear, zFar])) + this._depthRange(zNear, zFar); + } + $frontFace(mode) { + if (this._state.setSetting(this._frontFace, [mode])) + this._frontFace(mode); + } + $lineWidth(width) { + if (this._state.setSetting(this._lineWidth, [width])) + this._lineWidth(width); + } + $polygonOffset(factor, units) { + if (this._state.setSetting(this._polygonOffset, [factor, units])) + this._polygonOffset(factor, units); + } + $sampleCoverage(value, invert) { + if (this._state.setSetting(this._sampleCoverage, [value, invert])) + this._sampleCoverage(value, invert); + } + $stencilFunc(func, ref, mask) { + if (this._state.setSetting(this._stencilFunc, [func, ref, mask])) + this._stencilFunc(func, ref, mask); + } + $stencilMask(mask) { + if (this._state.setSetting(this._stencilMask, [mask])) + this._stencilMask(mask); + } + $stencilOp(fail, zfail, zpass) { + if (this._state.setSetting(this._stencilOp, [fail, zfail, zpass])) + this._stencilOp(fail, zfail, zpass); + } + $vertexAttrib1f(indx, x) { + if (this._state.setSetting(this._vertexAttrib1f, [indx, x])) + this._vertexAttrib1f(indx, x); + } + $vertexAttrib1fv(indx, values) { + if (this._state.setSetting(this._vertexAttrib1fv, [indx, values])) + this._vertexAttrib1fv(indx, values); + } + $vertexAttrib2f(indx, x, y) { + if (this._state.setSetting(this._vertexAttrib2f, [indx, x, y])) + this._vertexAttrib2f(indx, x, y); + } + $vertexAttrib2fv(indx, values) { + if (this._state.setSetting(this._vertexAttrib2fv, [indx, values])) + this._vertexAttrib2fv(indx, values); + } + $vertexAttrib3f(indx, x, y, z) { + if (this._state.setSetting(this._vertexAttrib3f, [indx, x, y, z])) + this._vertexAttrib3f(indx, x, y, z); + } + $vertexAttrib3fv(indx, values) { + if (this._state.setSetting(this._vertexAttrib3fv, [indx, values])) + this._vertexAttrib3fv(indx, values); + } + $vertexAttrib4f(indx, x, y, z, w) { + if (this._state.setSetting(this._vertexAttrib4f, [indx, x, y, z, w])) + this._vertexAttrib4f(indx, x, y, z, w); + } + $vertexAttrib4fv(indx, values) { + if (this._state.setSetting(this._vertexAttrib4fv, [indx, values])) + this._vertexAttrib4fv(indx, values); + } + static enable(gl, id = "default") { + const names = Object.getOwnPropertyNames(WebGLStateManager.prototype); + gl.__proto__; + names.forEach((name) => { + if (name !== "constructor") { + const method = WebGLStateManager.prototype[name]; + if (name.charAt(0) === "$") { + name = name.substr(1); + } + if (gl[name] !== method) { + if (gl[name]) { + if (!gl[name].name) { + gl[name].xname = name; + } + gl["_" + name] = gl[name]; + } + gl[name] = method; + } + } + }); + WebGLStateManager.prototype._initStateManager.call(gl, id); + return gl; + } +} +class TextureManager { + constructor(stage) { + this.stage = stage; + this._usedMemory = 0; + this._uploadedTextureSources = []; + this.textureSourceHashmap = /* @__PURE__ */ new Map(); + } + get usedMemory() { + return this._usedMemory; + } + destroy() { + for (let i = 0, n = this._uploadedTextureSources.length; i < n; i++) { + this._nativeFreeTextureSource(this._uploadedTextureSources[i]); + } + this.textureSourceHashmap.clear(); + this._usedMemory = 0; + } + getReusableTextureSource(id) { + return this.textureSourceHashmap.get(id); + } + getTextureSource(func, id) { + let textureSource = id ? this.textureSourceHashmap.get(id) : null; + if (!textureSource) { + textureSource = new TextureSource(this, func); + if (id) { + textureSource.lookupId = id; + this.textureSourceHashmap.set(id, textureSource); + } + } + return textureSource; + } + uploadTextureSource(textureSource, options) { + if (textureSource.isLoaded()) + return; + this._addMemoryUsage(textureSource.w * textureSource.h); + const nativeTexture = this._nativeUploadTextureSource(textureSource, options); + textureSource._nativeTexture = nativeTexture; + nativeTexture.w = textureSource.w; + nativeTexture.h = textureSource.h; + nativeTexture.update = this.stage.frameCounter; + this._uploadedTextureSources.push(textureSource); + this.addToLookupMap(textureSource); + this._updateVramUsage(textureSource, 1); + } + _addMemoryUsage(delta) { + this._usedMemory += delta; + this.stage.addMemoryUsage(delta); + } + _updateVramUsage(textureSource, sign) { + const nativeTexture = textureSource.nativeTexture; + var usage; + if (!Stage.isWebglSupported()) + return; + if (!textureSource.isLoaded()) + return; + if (!nativeTexture.hasOwnProperty("bytesPerPixel") || isNaN(nativeTexture.bytesPerPixel)) + return; + usage = sign * (textureSource.w * textureSource.h * nativeTexture.bytesPerPixel); + this.stage.addVramUsage(usage, textureSource.hasAlpha); + } + addToLookupMap(textureSource) { + const lookupId = textureSource.lookupId; + if (lookupId) { + if (!this.textureSourceHashmap.has(lookupId)) { + this.textureSourceHashmap.set(lookupId, textureSource); + } + } + } + gc() { + this.freeUnusedTextureSources(); + this._cleanupLookupMap(); + } + freeUnusedTextureSources() { + let remainingTextureSources = []; + for (let i = 0, n = this._uploadedTextureSources.length; i < n; i++) { + let ts = this._uploadedTextureSources[i]; + if (ts.allowCleanup()) { + this._freeManagedTextureSource(ts); + } else { + remainingTextureSources.push(ts); + } + } + this._uploadedTextureSources = remainingTextureSources; + this._cleanupLookupMap(); + } + _freeManagedTextureSource(textureSource) { + if (textureSource.isLoaded()) { + this._nativeFreeTextureSource(textureSource); + this._addMemoryUsage(-textureSource.w * textureSource.h); + this._updateVramUsage(textureSource, -1); + } + textureSource.loadingSince = null; + } + _cleanupLookupMap() { + this.textureSourceHashmap.forEach((textureSource, lookupId) => { + if (!(textureSource.isLoaded() || textureSource.isLoading()) && !textureSource.isUsed()) { + this.textureSourceHashmap.delete(lookupId); + } + }); + } + freeTextureSource(textureSource) { + const index = this._uploadedTextureSources.indexOf(textureSource); + const managed = index !== -1; + if (textureSource.isLoaded()) { + if (managed) { + this._addMemoryUsage(-textureSource.w * textureSource.h); + this._uploadedTextureSources.splice(index, 1); + } + this._nativeFreeTextureSource(textureSource); + } + textureSource.loadingSince = null; + } + _nativeUploadTextureSource(textureSource, options) { + return this.stage.renderer.uploadTextureSource(textureSource, options); + } + _nativeFreeTextureSource(textureSource) { + this.stage.renderer.freeTextureSource(textureSource); + textureSource.clearNativeTexture(); + } +} +class TextureThrottler { + constructor(stage) { + this.stage = stage; + this.genericCancelCb = (textureSource) => { + this._remove(textureSource); + }; + this._sources = []; + this._data = []; + } + destroy() { + this._sources = []; + this._data = []; + this.stage = null; + delete this._sources; + delete this._data; + delete this.stage; + } + processSome() { + if (this._sources.length) { + const start = Date.now(); + do { + this._processItem(); + } while (this._sources.length && Date.now() - start < TextureThrottler.MAX_UPLOAD_TIME_PER_FRAME); + } + } + _processItem() { + const source = this._sources.pop(); + const data = this._data.pop(); + if (source.isLoading()) { + source.processLoadedSource(data); + } + } + add(textureSource, data) { + this._sources.push(textureSource); + this._data.push(data); + } + _remove(textureSource) { + const index = this._sources.indexOf(textureSource); + if (index >= 0) { + this._sources.splice(index, 1); + this._data.splice(index, 1); + } + } +} +TextureThrottler.MAX_UPLOAD_TIME_PER_FRAME = 10; +class CoreContext { + constructor(stage) { + this.stage = stage; + this.root = null; + this.updateTreeOrder = 0; + this.renderState = this.stage.renderer.createCoreRenderState(this); + this.renderExec = this.stage.renderer.createCoreRenderExecutor(this); + this.renderExec.init(); + this._usedMemory = 0; + this._renderTexturePool = []; + this._renderTextureId = 1; + this._zSorts = []; + this.renderToTextureCount = 0; + } + get usedMemory() { + return this._usedMemory; + } + destroy() { + this._renderTexturePool.forEach((texture) => this._freeRenderTexture(texture)); + this._usedMemory = 0; + this.stage = null; + this.root = null; + this.renderState = null; + this.renderExec = null; + this._renderTexturePool = null; + this._zSorts = null; + delete this.stage; + delete this.root; + delete this.renderState; + delete this.renderExec; + delete this._renderTexturePool; + delete this._zSorts; + } + hasRenderUpdates() { + return !!this.root._parent._hasRenderUpdates; + } + render() { + this.root._parent._hasRenderUpdates = 0; + this._render(); + } + update() { + this._update(); + if (this.root._hasUpdates) { + this._update(); + } + this._performForcedZSorts(); + } + _performForcedZSorts() { + const n = this._zSorts.length; + if (n) { + for (let i = 0, n2 = this._zSorts.length; i < n2; i++) { + if (this._zSorts[i].zSort) { + this._zSorts[i].sortZIndexedChildren(); + } + } + this._zSorts = []; + } + } + _update() { + this.updateTreeOrder = 0; + this.root.update(); + } + _render() { + const debugFrame = this.stage.getOption("debugFrame"); + this._fillRenderState(); + if (this.stage.getOption("readPixelsBeforeDraw")) { + this._readPixels(); + } + this._performRender(); + if (debugFrame) { + console.log(`[Lightning] RTT Renders in frame: ${this.renderToTextureCount}`); + } + if (this.stage.getOption("readPixelsAfterDraw") && this.renderToTextureCount >= this.stage.getOption("readPixelsAfterDrawThreshold")) { + if (debugFrame) { + console.log(`[Lightning] readPixelsAfterDraw behavior triggered`); + } + this._readPixels(); + } + this.renderToTextureCount = 0; + } + _readPixels() { + const pixels = new Uint8Array(4); + const gl = this.stage.gl; + gl.readPixels(0, 0, 1, 1, gl.RGBA, gl.UNSIGNED_BYTE, pixels); + } + _fillRenderState() { + this.renderState.reset(); + this.root.render(); + this.renderState.finish(); + } + _performRender() { + this.renderExec.execute(); + } + _addMemoryUsage(delta) { + this._usedMemory += delta; + this.stage.addMemoryUsage(delta); + } + allocateRenderTexture(w, h) { + let prec = this.stage.getRenderPrecision(); + let pw = Math.max(1, Math.round(w * prec)); + let ph = Math.max(1, Math.round(h * prec)); + const n = this._renderTexturePool.length; + for (let i = n - 1; i >= 0; i--) { + const texture2 = this._renderTexturePool[i]; + if (texture2.w === pw && texture2.h === ph && texture2.update !== this.stage.frameCounter) { + texture2.f = this.stage.frameCounter; + this._renderTexturePool.splice(i, 1); + return texture2; + } + } + const texture = this._createRenderTexture(w, h, pw, ph); + texture.precision = prec; + return texture; + } + releaseRenderTexture(texture) { + this._renderTexturePool.push(texture); + } + freeUnusedRenderTextures(maxAge = 60) { + let limit = this.stage.frameCounter - maxAge; + this._renderTexturePool = this._renderTexturePool.filter((texture) => { + if (texture.f <= limit) { + this._freeRenderTexture(texture); + return false; + } + return true; + }); + } + _createRenderTexture(w, h, pw, ph) { + this._addMemoryUsage(pw * ph); + const texture = this.stage.renderer.createRenderTexture(w, h, pw, ph); + texture.id = this._renderTextureId++; + texture.f = this.stage.frameCounter; + texture.ow = w; + texture.oh = h; + texture.w = pw; + texture.h = ph; + return texture; + } + _freeRenderTexture(nativeTexture) { + this.stage.renderer.freeRenderTexture(nativeTexture); + this._addMemoryUsage(-nativeTexture.w * nativeTexture.h); + } + copyRenderTexture(renderTexture, nativeTexture, options) { + this.stage.renderer.copyRenderTexture(renderTexture, nativeTexture, options); + } + forceZSort(elementCore) { + this._zSorts.push(elementCore); + } +} +class TransitionSettings { + constructor(stage) { + this.stage = stage; + this._timingFunction = "ease"; + this._timingFunctionImpl = StageUtils.getTimingFunction(this._timingFunction); + this.delay = 0; + this.duration = 0.2; + this.merger = null; + } + get timingFunction() { + return this._timingFunction; + } + set timingFunction(v) { + this._timingFunction = v; + this._timingFunctionImpl = StageUtils.getTimingFunction(v); + } + get timingFunctionImpl() { + return this._timingFunctionImpl; + } + patch(settings) { + Base.patchObject(this, settings); + } +} +TransitionSettings.prototype.isTransitionSettings = true; +class TransitionManager { + constructor(stage) { + this.stage = stage; + this.stage.on("frameStart", () => this.progress()); + this.active = /* @__PURE__ */ new Set(); + this.defaultTransitionSettings = new TransitionSettings(this.stage); + } + progress() { + if (this.active.size) { + let dt = this.stage.dt; + let filter = false; + this.active.forEach(function(a) { + a.progress(dt); + if (!a.isRunning()) { + filter = true; + } + }); + if (filter) { + this.active = new Set([...this.active].filter((t) => t.isRunning())); + } + } + } + createSettings(settings) { + const transitionSettings = new TransitionSettings(); + Base.patchObject(transitionSettings, settings); + return transitionSettings; + } + addActive(transition) { + this.active.add(transition); + } + removeActive(transition) { + this.active.delete(transition); + } +} +class MultiSpline { + constructor() { + this._clear(); + } + _clear() { + this._p = []; + this._pe = []; + this._idp = []; + this._f = []; + this._v = []; + this._lv = []; + this._sm = []; + this._s = []; + this._ve = []; + this._sme = []; + this._se = []; + this._length = 0; + } + parse(rgba, def) { + let i, n; + if (!Utils$1.isObjectLiteral(def)) { + def = { 0: def }; + } + let defaultSmoothness = 0.5; + let items = []; + for (let key in def) { + if (def.hasOwnProperty(key)) { + let obj = def[key]; + if (!Utils$1.isObjectLiteral(obj)) { + obj = { v: obj }; + } + let p = parseFloat(key); + if (key === "sm") { + defaultSmoothness = obj.v; + } else if (!isNaN(p) && p >= 0 && p <= 2) { + obj.p = p; + obj.f = Utils$1.isFunction(obj.v); + obj.lv = obj.f ? obj.v(0, 0) : obj.v; + items.push(obj); + } + } + } + items = items.sort(function(a, b) { + return a.p - b.p; + }); + n = items.length; + for (i = 0; i < n; i++) { + let last = i === n - 1; + if (!items[i].hasOwnProperty("pe")) { + items[i].pe = last ? items[i].p <= 1 ? 1 : 2 : items[i + 1].p; + } else { + const max = i < n - 1 ? items[i + 1].p : 1; + if (items[i].pe > max) { + items[i].pe = max; + } + } + if (items[i].pe === items[i].p) { + items[i].idp = 0; + } else { + items[i].idp = 1 / (items[i].pe - items[i].p); + } + } + for (i = 0; i < n; i++) { + if (!items[i].hasOwnProperty("sm")) { + items[i].sm = defaultSmoothness; + } + if (!items[i].hasOwnProperty("s")) { + if (i === 0 || i === n - 1 || items[i].p === 1) { + items[i].s = rgba ? [0, 0, 0, 0] : 0; + } else { + const pi = items[i - 1]; + const ni = items[i + 1]; + if (pi.p === ni.p) { + items[i].s = rgba ? [0, 0, 0, 0] : 0; + } else { + if (rgba) { + const nc = MultiSpline.getRgbaComponents(ni.lv); + const pc = MultiSpline.getRgbaComponents(pi.lv); + const d = 1 / (ni.p - pi.p); + items[i].s = [ + d * (nc[0] - pc[0]), + d * (nc[1] - pc[1]), + d * (nc[2] - pc[2]), + d * (nc[3] - pc[3]) + ]; + } else { + items[i].s = (ni.lv - pi.lv) / (ni.p - pi.p); + } + } + } + } + } + for (i = 0; i < n - 1; i++) { + if (!items[i].f) { + let last = i === n - 1; + if (!items[i].hasOwnProperty("ve")) { + items[i].ve = last ? items[i].lv : items[i + 1].lv; + } + if (Utils$1.isNumber(items[i].v) && Utils$1.isNumber(items[i].lv)) { + if (!items[i].hasOwnProperty("sme")) { + items[i].sme = last ? defaultSmoothness : items[i + 1].sm; + } + if (!items[i].hasOwnProperty("se")) { + items[i].se = last ? rgba ? [0, 0, 0, 0] : 0 : items[i + 1].s; + } + if (rgba) { + items[i].v = MultiSpline.getSplineRgbaValueFunction(items[i].v, items[i].ve, items[i].p, items[i].pe, items[i].sm, items[i].sme, items[i].s, items[i].se); + } else { + items[i].v = MultiSpline.getSplineValueFunction(items[i].v, items[i].ve, items[i].p, items[i].pe, items[i].sm, items[i].sme, items[i].s, items[i].se); + } + items[i].f = true; + } + } + } + if (this.length) { + this._clear(); + } + for (i = 0, n = items.length; i < n; i++) { + this._add(items[i]); + } + } + _add(item) { + this._p.push(item.p || 0); + this._pe.push(item.pe || 0); + this._idp.push(item.idp || 0); + this._f.push(item.f || false); + this._v.push(item.hasOwnProperty("v") ? item.v : 0); + this._lv.push(item.lv || 0); + this._sm.push(item.sm || 0); + this._s.push(item.s || 0); + this._ve.push(item.ve || 0); + this._sme.push(item.sme || 0); + this._se.push(item.se || 0); + this._length++; + } + _getItem(p) { + const n = this._length; + if (!n) { + return -1; + } + if (p < this._p[0]) { + return 0; + } + for (let i = 0; i < n; i++) { + if (this._p[i] <= p && p < this._pe[i]) { + return i; + } + } + return n - 1; + } + getValue(p) { + const i = this._getItem(p); + if (i === -1) { + return void 0; + } else { + if (this._f[i]) { + const o = Math.min(1, Math.max(0, (p - this._p[i]) * this._idp[i])); + return this._v[i](o); + } else { + return this._v[i]; + } + } + } + get length() { + return this._length; + } + static getRgbaComponents(argb) { + let r = (argb / 65536 | 0) % 256; + let g = (argb / 256 | 0) % 256; + let b = argb % 256; + let a = argb / 16777216 | 0; + return [r, g, b, a]; + } + static getSplineValueFunction(v1, v2, p1, p2, o1, i2, s1, s2) { + let dp = p2 - p1; + s1 *= dp; + s2 *= dp; + let helpers = MultiSpline.getSplineHelpers(v1, v2, o1, i2, s1, s2); + if (!helpers) { + return function(p) { + if (p === 0) + return v1; + if (p === 1) + return v2; + return v2 * p + v1 * (1 - p); + }; + } else { + return function(p) { + if (p === 0) + return v1; + if (p === 1) + return v2; + return MultiSpline.calculateSpline(helpers, p); + }; + } + } + static getSplineRgbaValueFunction(v1, v2, p1, p2, o1, i2, s1, s2) { + let dp = p2 - p1; + s1[0] *= dp; + s1[1] *= dp; + s1[2] *= dp; + s1[3] *= dp; + s2[0] *= dp; + s2[1] *= dp; + s2[2] *= dp; + s2[3] *= dp; + let cv1 = MultiSpline.getRgbaComponents(v1); + let cv2 = MultiSpline.getRgbaComponents(v2); + let helpers = [ + MultiSpline.getSplineHelpers(cv1[0], cv2[0], o1, i2, s1[0], s2[0]), + MultiSpline.getSplineHelpers(cv1[1], cv2[1], o1, i2, s1[1], s2[1]), + MultiSpline.getSplineHelpers(cv1[2], cv2[2], o1, i2, s1[2], s2[2]), + MultiSpline.getSplineHelpers(cv1[3], cv2[3], o1, i2, s1[3], s2[3]) + ]; + if (!helpers[0]) { + return function(p) { + if (p === 0) + return v1; + if (p === 1) + return v2; + return MultiSpline.mergeColors(v2, v1, p); + }; + } else { + return function(p) { + if (p === 0) + return v1; + if (p === 1) + return v2; + return MultiSpline.getArgbNumber([ + Math.min(255, MultiSpline.calculateSpline(helpers[0], p)), + Math.min(255, MultiSpline.calculateSpline(helpers[1], p)), + Math.min(255, MultiSpline.calculateSpline(helpers[2], p)), + Math.min(255, MultiSpline.calculateSpline(helpers[3], p)) + ]); + }; + } + } + static getSplineHelpers(v1, v2, o1, i2, s1, s2) { + if (!o1 && !i2) { + return null; + } + let csx = o1; + let csy = v1 + s1 * o1; + let cex = 1 - i2; + let cey = v2 - s2 * i2; + let xa = 3 * csx - 3 * cex + 1; + let xb = -6 * csx + 3 * cex; + let xc = 3 * csx; + let ya = 3 * csy - 3 * cey + v2 - v1; + let yb = 3 * (cey + v1) - 6 * csy; + let yc = 3 * (csy - v1); + let yd = v1; + return [xa, xb, xc, ya, yb, yc, yd]; + } + static calculateSpline(helpers, p) { + let xa = helpers[0]; + let xb = helpers[1]; + let xc = helpers[2]; + let ya = helpers[3]; + let yb = helpers[4]; + let yc = helpers[5]; + let yd = helpers[6]; + if (xa === -2 && ya === -2 && xc === 0 && yc === 0) { + return p; + } + let t = 0.5, cbx, dx; + for (let it = 0; it < 20; it++) { + cbx = t * (t * (t * xa + xb) + xc); + dx = p - cbx; + if (dx > -1e-8 && dx < 1e-8) { + return t * (t * (t * ya + yb) + yc) + yd; + } + let cbxd = t * (t * (3 * xa) + 2 * xb) + xc; + if (cbxd > 1e-10 && cbxd < 1e-10) { + break; + } + t += dx / cbxd; + } + let minT = 0; + let maxT = 1; + for (let it = 0; it < 20; it++) { + t = 0.5 * (minT + maxT); + cbx = t * (t * (t * xa + xb) + xc); + dx = p - cbx; + if (dx > -1e-8 && dx < 1e-8) { + return t * (t * (t * ya + yb) + yc) + yd; + } + if (dx < 0) { + maxT = t; + } else { + minT = t; + } + } + return t; + } + static mergeColors(c1, c2, p) { + let r1 = (c1 / 65536 | 0) % 256; + let g1 = (c1 / 256 | 0) % 256; + let b1 = c1 % 256; + let a1 = c1 / 16777216 | 0; + let r2 = (c2 / 65536 | 0) % 256; + let g2 = (c2 / 256 | 0) % 256; + let b2 = c2 % 256; + let a2 = c2 / 16777216 | 0; + let r = r1 * p + r2 * (1 - p); + let g = g1 * p + g2 * (1 - p); + let b = b1 * p + b2 * (1 - p); + let a = a1 * p + a2 * (1 - p); + return Math.round(a) * 16777216 + Math.round(r) * 65536 + Math.round(g) * 256 + Math.round(b); + } + static getArgbNumber(rgba) { + rgba[0] = Math.max(0, Math.min(255, rgba[0])); + rgba[1] = Math.max(0, Math.min(255, rgba[1])); + rgba[2] = Math.max(0, Math.min(255, rgba[2])); + rgba[3] = Math.max(0, Math.min(255, rgba[3])); + let v = ((rgba[3] | 0) << 24) + ((rgba[0] | 0) << 16) + ((rgba[1] | 0) << 8) + (rgba[2] | 0); + if (v < 0) { + v = 4294967295 + v + 1; + } + return v; + } +} +class AnimationActionSettings { + constructor(animationSettings) { + this.animationSettings = animationSettings; + this._selector = ""; + this._items = new MultiSpline(); + this._props = []; + this._propSetters = []; + this._resetValue = void 0; + this._hasResetValue = false; + this._hasColorProperty = void 0; + } + getResetValue() { + if (this._hasResetValue) { + return this._resetValue; + } else { + return this._items.getValue(0); + } + } + apply(element, p, factor) { + const elements = this.getAnimatedElements(element); + let v = this._items.getValue(p); + if (v === void 0 || !elements.length) { + return; + } + if (factor !== 1) { + let sv = this.getResetValue(); + if (Utils$1.isNumber(v) && Utils$1.isNumber(sv)) { + if (this.hasColorProperty()) { + v = StageUtils.mergeColors(v, sv, factor); + } else { + v = StageUtils.mergeNumbers(v, sv, factor); + } + } + } + const n = this._propSetters.length; + const m = elements.length; + for (let j = 0; j < m; j++) { + for (let i = 0; i < n; i++) { + this._propSetters[i](elements[j], v); + } + } + } + getAnimatedElements(element) { + return element.select(this._selector); + } + reset(element) { + const elements = this.getAnimatedElements(element); + let v = this.getResetValue(); + if (v === void 0 || !elements.length) { + return; + } + const n = this._propSetters.length; + const m = elements.length; + for (let j = 0; j < m; j++) { + for (let i = 0; i < n; i++) { + this._propSetters[i](elements[j], v); + } + } + } + set selector(v) { + this._selector = v; + } + set t(v) { + this.selector = v; + } + get resetValue() { + return this._resetValue; + } + set resetValue(v) { + this._resetValue = v; + this._hasResetValue = v !== void 0; + } + set rv(v) { + this.resetValue = v; + } + set value(v) { + this._items.parse(this.hasColorProperty(), v); + } + set v(v) { + this.value = v; + } + set properties(v) { + if (!Array.isArray(v)) { + v = [v]; + } + this._props = []; + v.forEach((prop) => { + this._props.push(prop); + this._propSetters.push(Element.getSetter(prop)); + }); + } + set property(v) { + this._hasColorProperty = void 0; + this.properties = v; + } + set p(v) { + this.properties = v; + } + patch(settings) { + Base.patchObject(this, settings); + } + hasColorProperty() { + if (this._hasColorProperty === void 0) { + this._hasColorProperty = this._props.length ? Element.isColorProperty(this._props[0]) : false; + } + return this._hasColorProperty; + } +} +AnimationActionSettings.prototype.isAnimationActionSettings = true; +class AnimationSettings { + constructor() { + this._actions = []; + this.delay = 0; + this.duration = 1; + this.repeat = 0; + this.repeatOffset = 0; + this.repeatDelay = 0; + this.autostop = false; + this.stopMethod = AnimationSettings.STOP_METHODS.FADE; + this._stopTimingFunction = "ease"; + this._stopTimingFunctionImpl = StageUtils.getTimingFunction(this._stopTimingFunction); + this.stopDuration = 0; + this.stopDelay = 0; + } + get actions() { + return this._actions; + } + set actions(v) { + this._actions = []; + for (let i = 0, n = v.length; i < n; i++) { + const e = v[i]; + if (!e.isAnimationActionSettings) { + const aas = new AnimationActionSettings(this); + aas.patch(e); + this._actions.push(aas); + } else { + this._actions.push(e); + } + } + } + apply(element, p, factor = 1) { + this._actions.forEach(function(action) { + action.apply(element, p, factor); + }); + } + reset(element) { + this._actions.forEach(function(action) { + action.reset(element); + }); + } + get stopTimingFunction() { + return this._stopTimingFunction; + } + set stopTimingFunction(v) { + this._stopTimingFunction = v; + this._stopTimingFunctionImpl = StageUtils.getTimingFunction(v); + } + get stopTimingFunctionImpl() { + return this._stopTimingFunctionImpl; + } + patch(settings) { + Base.patchObject(this, settings); + } +} +AnimationSettings.STOP_METHODS = { + FADE: "fade", + REVERSE: "reverse", + FORWARD: "forward", + IMMEDIATE: "immediate", + ONETOTWO: "onetotwo" +}; +class Animation extends EventEmitter { + constructor(manager, settings, element) { + super(); + this.manager = manager; + this._settings = settings; + this._element = element; + this._state = Animation.STATES.IDLE; + this._p = 0; + this._delayLeft = 0; + this._repeatsLeft = 0; + this._stopDelayLeft = 0; + this._stopP = 0; + } + start() { + if (this._element && this._element.attached) { + this._p = 0; + this._delayLeft = this.settings.delay; + this._repeatsLeft = this.settings.repeat; + this._state = Animation.STATES.PLAYING; + this.emit("start"); + this.checkActive(); + } else { + console.warn("[Lightning] Element must be attached before starting animation"); + } + } + play() { + if (this._state === Animation.STATES.PAUSED) { + this._state = Animation.STATES.PLAYING; + this.checkActive(); + this.emit("resume"); + } else if (this._state == Animation.STATES.STOPPING && this.settings.stopMethod == AnimationSettings.STOP_METHODS.REVERSE) { + this._state = Animation.STATES.PLAYING; + this.emit("stopContinue"); + } else if (this._state != Animation.STATES.PLAYING && this._state != Animation.STATES.FINISHED) { + this.start(); + } + } + pause() { + if (this._state === Animation.STATES.PLAYING) { + this._state = Animation.STATES.PAUSED; + this.emit("pause"); + } + } + replay() { + if (this._state == Animation.STATES.FINISHED) { + this.start(); + } else { + this.play(); + } + } + skipDelay() { + this._delayLeft = 0; + this._stopDelayLeft = 0; + } + finish() { + if (this._state === Animation.STATES.PLAYING) { + this._delayLeft = 0; + this._p = 1; + } else if (this._state === Animation.STATES.STOPPING) { + this._stopDelayLeft = 0; + this._p = 0; + } + } + stop() { + if (this._state === Animation.STATES.STOPPED || this._state === Animation.STATES.IDLE) + return; + this._stopDelayLeft = this.settings.stopDelay || 0; + if (this.settings.stopMethod === AnimationSettings.STOP_METHODS.IMMEDIATE && !this._stopDelayLeft || this._delayLeft > 0) { + this._state = Animation.STATES.STOPPING; + this.emit("stop"); + } else { + if (this.settings.stopMethod === AnimationSettings.STOP_METHODS.FADE) { + this._stopP = 0; + } + this._state = Animation.STATES.STOPPING; + this.emit("stop"); + } + this.checkActive(); + } + stopNow() { + if (this._state !== Animation.STATES.STOPPED || this._state !== Animation.STATES.IDLE) { + this._state = Animation.STATES.STOPPING; + this._p = 0; + this.emit("stop"); + this.reset(); + this._state = Animation.STATES.STOPPED; + this.emit("stopFinish"); + } + } + isPaused() { + return this._state === Animation.STATES.PAUSED; + } + isPlaying() { + return this._state === Animation.STATES.PLAYING; + } + isStopping() { + return this._state === Animation.STATES.STOPPING; + } + isFinished() { + return this._state === Animation.STATES.FINISHED; + } + checkActive() { + if (this.isActive()) { + this.manager.addActive(this); + } + } + isActive() { + return (this._state == Animation.STATES.PLAYING || this._state == Animation.STATES.STOPPING) && this._element && this._element.attached; + } + progress(dt) { + if (!this._element) + return; + this._progress(dt); + this.apply(); + } + _progress(dt) { + if (this._state == Animation.STATES.STOPPING) { + this._stopProgress(dt); + return; + } + if (this._state != Animation.STATES.PLAYING) { + return; + } + if (this._delayLeft > 0) { + this._delayLeft -= dt; + if (this._delayLeft < 0) { + dt = -this._delayLeft; + this._delayLeft = 0; + this.emit("delayEnd"); + } else { + return; + } + } + if (this.settings.duration === 0) { + this._p = 1; + } else if (this.settings.duration > 0) { + this._p += dt / this.settings.duration; + } + if (this._p >= 1) { + if (this.settings.repeat == -1 || this._repeatsLeft > 0) { + if (this._repeatsLeft > 0) { + this._repeatsLeft--; + } + this._p = this.settings.repeatOffset; + this.emit("progress", this._p); + if (this.settings.repeatDelay) { + this._delayLeft = this.settings.repeatDelay; + } + this.emit("repeat", this._repeatsLeft); + } else { + this._p = 1; + this.emit("progress", this._p); + this._state = Animation.STATES.FINISHED; + this.emit("finish"); + if (this.settings.autostop) { + this.stop(); + } + } + } else { + this.emit("progress", this._p); + } + } + _stopProgress(dt) { + let duration = this._getStopDuration(); + if (this._stopDelayLeft > 0) { + this._stopDelayLeft -= dt; + if (this._stopDelayLeft < 0) { + dt = -this._stopDelayLeft; + this._stopDelayLeft = 0; + this.emit("stopDelayEnd"); + } else { + return; + } + } + if (this.settings.stopMethod == AnimationSettings.STOP_METHODS.IMMEDIATE) { + this._state = Animation.STATES.STOPPED; + this.emit("stopFinish"); + } else if (this.settings.stopMethod == AnimationSettings.STOP_METHODS.REVERSE) { + if (duration === 0) { + this._p = 0; + } else if (duration > 0) { + this._p -= dt / duration; + } + if (this._p <= 0) { + this._p = 0; + this._state = Animation.STATES.STOPPED; + this.emit("stopFinish"); + } + } else if (this.settings.stopMethod == AnimationSettings.STOP_METHODS.FADE) { + this._progressStopTransition(dt); + if (this._stopP >= 1) { + this._p = 0; + this._state = Animation.STATES.STOPPED; + this.emit("stopFinish"); + } + } else if (this.settings.stopMethod == AnimationSettings.STOP_METHODS.ONETOTWO) { + if (this._p < 2) { + if (duration === 0) { + this._p = 2; + } else if (duration > 0) { + if (this._p < 1) { + this._p += dt / this.settings.duration; + } else { + this._p += dt / duration; + } + } + if (this._p >= 2) { + this._p = 2; + this._state = Animation.STATES.STOPPED; + this.emit("stopFinish"); + } else { + this.emit("progress", this._p); + } + } + } else if (this.settings.stopMethod == AnimationSettings.STOP_METHODS.FORWARD) { + if (this._p < 1) { + if (this.settings.duration == 0) { + this._p = 1; + } else { + this._p += dt / this.settings.duration; + } + if (this._p >= 1) { + if (this.settings.stopMethod == AnimationSettings.STOP_METHODS.FORWARD) { + this._p = 1; + this._state = Animation.STATES.STOPPED; + this.emit("stopFinish"); + } else { + if (this._repeatsLeft > 0) { + this._repeatsLeft--; + this._p = 0; + this.emit("repeat", this._repeatsLeft); + } else { + this._p = 1; + this._state = Animation.STATES.STOPPED; + this.emit("stopFinish"); + } + } + } else { + this.emit("progress", this._p); + } + } + } + } + _progressStopTransition(dt) { + if (this._stopP < 1) { + if (this._stopDelayLeft > 0) { + this._stopDelayLeft -= dt; + if (this._stopDelayLeft < 0) { + dt = -this._stopDelayLeft; + this._stopDelayLeft = 0; + this.emit("delayEnd"); + } else { + return; + } + } + const duration = this._getStopDuration(); + if (duration == 0) { + this._stopP = 1; + } else { + this._stopP += dt / duration; + } + if (this._stopP >= 1) { + this._stopP = 1; + } + } + } + _getStopDuration() { + return this.settings.stopDuration || this.settings.duration; + } + apply() { + if (this._state === Animation.STATES.STOPPED) { + this.reset(); + } else { + let factor = 1; + if (this._state === Animation.STATES.STOPPING && this.settings.stopMethod === AnimationSettings.STOP_METHODS.FADE) { + factor = 1 - this.settings.stopTimingFunctionImpl(this._stopP); + } + this._settings.apply(this._element, this._p, factor); + } + } + reset() { + this._settings.reset(this._element); + } + get state() { + return this._state; + } + get p() { + return this._p; + } + get delayLeft() { + return this._delayLeft; + } + get element() { + return this._element; + } + get frame() { + return Math.round(this._p * this._settings.duration * 60); + } + get settings() { + return this._settings; + } +} +Animation.STATES = { + IDLE: 0, + PLAYING: 1, + STOPPING: 2, + STOPPED: 3, + FINISHED: 4, + PAUSED: 5 +}; +class AnimationManager { + constructor(stage) { + this.stage = stage; + this.stage.on("frameStart", () => this.progress()); + this.active = /* @__PURE__ */ new Set(); + } + progress() { + if (this.active.size) { + let dt = this.stage.dt; + let filter = false; + this.active.forEach(function(a) { + if (a.isActive()) { + a.progress(dt); + } else { + filter = true; + } + }); + if (filter) { + this.active = new Set([...this.active].filter((t) => t.isActive())); + } + } + } + createAnimation(element, settings) { + if (Utils$1.isObjectLiteral(settings)) { + settings = this.createSettings(settings); + } + return new Animation( + this, + settings, + element + ); + } + createSettings(settings) { + const animationSettings = new AnimationSettings(); + Base.patchObject(animationSettings, settings); + return animationSettings; + } + addActive(transition) { + this.active.add(transition); + } +} +class RectangleTexture extends Texture { + _getLookupId() { + return "__whitepix"; + } + _getSourceLoader() { + return function(cb) { + var whitePixel = new Uint8Array([255, 255, 255, 255]); + cb(null, { source: whitePixel, w: 1, h: 1, permanent: true }); + }; + } + isAutosizeTexture() { + return false; + } +} +class Stage extends EventEmitter { + constructor(options = {}) { + super(); + this._setOptions(options); + this._usedMemory = 0; + this._lastGcFrame = 0; + this._usedVramAlpha = 0; + this._usedVramNonAlpha = 0; + const platformType = Stage.platform ? Stage.platform : PlatformLoader.load(options); + this.platform = new platformType(); + if (this.platform.init) { + this.platform.init(this); + } + this.gl = null; + this.c2d = null; + const context = this.getOption("context"); + if (context) { + if (context.useProgram) { + this.gl = context; + } else { + this.c2d = context; + } + } else { + if (Utils$1.isWeb && (!Stage.isWebglSupported() || this.getOption("canvas2d"))) { + this.c2d = this.platform.createCanvasContext(this.getOption("w"), this.getOption("h")); + } else { + this.gl = this.platform.createWebGLContext(this.getOption("w"), this.getOption("h")); + } + } + if (this.gl) { + WebGLStateManager.enable(this.gl, "lightning"); + } + this._mode = this.gl ? 0 : 1; + if (this.getCanvas()) { + if (this.getOption("devicePixelRatio") !== 1) { + const ratio = this.getOption("devicePixelRatio"); + this.getCanvas().style.width = this._options["w"] / ratio + "px"; + this.getCanvas().style.height = this._options["h"] / ratio + "px"; + } + this._options.w = this.getCanvas().width; + this._options.h = this.getCanvas().height; + } + if (this._mode === 0) { + if (Utils$1.isSpark) { + this._renderer = new SparkRenderer(this); + } else { + this._renderer = new WebGLRenderer(this); + } + } else { + this._renderer = new C2dRenderer(this); + } + this.setClearColor(this.getOption("clearColor")); + this.frameCounter = 0; + this.transitions = new TransitionManager(this); + this.animations = new AnimationManager(this); + this.textureManager = new TextureManager(this); + this.textureThrottler = new TextureThrottler(this); + this.startTime = 0; + this.currentTime = 0; + this.dt = 0; + this.rectangleTexture = new RectangleTexture(this); + this.rectangleTexture.load(); + this.rectangleTexture.source.permanent = true; + this.ctx = new CoreContext(this); + this._updateSourceTextures = /* @__PURE__ */ new Set(); + } + get renderer() { + return this._renderer; + } + static isWebglSupported() { + if (Utils$1.isNode) { + return true; + } + try { + return !!window.WebGLRenderingContext; + } catch (e) { + return false; + } + } + get mode() { + return this._mode; + } + isWebgl() { + return this.mode === 0; + } + isC2d() { + return this.mode === 1; + } + getOption(name) { + return this._options[name]; + } + _setOptions(o) { + this._options = {}; + let opt = (name, def) => { + let value = o[name]; + if (value === void 0) { + this._options[name] = def; + } else { + this._options[name] = value; + } + }; + opt("canvas", null); + opt("context", null); + opt("w", 1920); + opt("h", 1080); + opt("srcBasePath", null); + opt("memoryPressure", 24e6); + opt("bufferMemory", 2e6); + opt("textRenderIssueMargin", 0); + opt("fontSharp", { precision: 0.6666666667, fontSize: 24 }); + opt("clearColor", [0, 0, 0, 0]); + opt("defaultFontFace", "sans-serif"); + opt("fixedDt", 0); + opt("useImageWorker", true); + opt("autostart", true); + opt("precision", 1); + opt("canvas2d", false); + opt("platform", null); + opt("readPixelsBeforeDraw", false); + opt("devicePixelRatio", 1); + opt("readPixelsAfterDraw", false); + opt("readPixelsAfterDrawThreshold", 0); + opt("debugFrame", false); + opt("forceTxCanvasSource", false); + opt("pauseRafLoopOnIdle", false); + if (o["devicePixelRatio"] != null && o["devicePixelRatio"] !== 1) { + this._options["precision"] *= o["devicePixelRatio"]; + this._options["w"] *= o["devicePixelRatio"]; + this._options["h"] *= o["devicePixelRatio"]; + } + } + setApplication(app) { + this.application = app; + } + init() { + if (this.application.getOption("debug") && this.platform._imageWorker) { + console.log("[Lightning] Using image worker!"); + } + if (this.application.getOption("debug") && this.c2d) { + console.log("[Lightning] Using canvas2d renderer"); + } + this.application.setAsRoot(); + if (this.getOption("autostart")) { + this.platform.startLoop(); + } + } + destroy() { + this.platform.stopLoop(); + this.platform.destroy(); + this.ctx.destroy(); + this.textureManager.destroy(); + this._renderer.destroy(); + if (this.gl) { + this.gl.clearColor(0, 0, 0, 0); + this.gl.clear(this.gl.COLOR_BUFFER_BIT); + } else if (this.c2d) { + this.c2d.clearRect( + 0, + 0, + this.c2d.canvas.width, + this.c2d.canvas.height + ); + } + this.gl = null; + this.c2d = null; + this.ctx = null; + this._options = null; + this.platform = null; + this.textureManager = null; + this._renderer = null; + delete this.gl; + delete this.c2d; + delete this.ctx; + delete this._options; + delete this.platform; + delete this.textureManager; + delete this._renderer; + } + stop() { + this.platform.stopLoop(); + } + resume() { + this.platform.startLoop(); + } + get root() { + return this.application; + } + getCanvas() { + return this._mode ? this.c2d.canvas : this.gl.canvas; + } + getRenderPrecision() { + return this._options.precision; + } + addUpdateSourceTexture(texture) { + if (this._updatingFrame) { + texture._performUpdateSource(); + } else { + this._updateSourceTextures.add(texture); + } + } + removeUpdateSourceTexture(texture) { + if (this._updateSourceTextures) { + this._updateSourceTextures.delete(texture); + } + } + hasUpdateSourceTexture(texture) { + return this._updateSourceTextures && this._updateSourceTextures.has(texture); + } + _performUpdateSource() { + if (this._updateSourceTextures.size) { + this._updateSourceTextures.forEach((texture) => { + texture._performUpdateSource(); + }); + this._updateSourceTextures = /* @__PURE__ */ new Set(); + } + } + _calculateDt() { + this.startTime = this.currentTime; + this.currentTime = this.platform.getHrTime(); + if (this._options.fixedDt) { + this.dt = this._options.fixedDt; + } else { + this.dt = !this.startTime ? 0.02 : 1e-3 * (this.currentTime - this.startTime); + } + } + updateFrame() { + this._calculateDt(); + this.emit("frameStart"); + this._performUpdateSource(); + this.emit("update"); + } + idleFrame() { + this.textureThrottler.processSome(); + this.emit("frameEnd"); + this.frameCounter++; + } + renderFrame() { + const changes = this.ctx.hasRenderUpdates(); + this.textureThrottler.processSome(); + if (changes) { + this._updatingFrame = true; + this.ctx.update(); + this.ctx.render(); + this._updatingFrame = false; + } + this.platform.nextFrame(changes); + this.emit("frameEnd"); + this.frameCounter++; + } + isUpdatingFrame() { + return this._updatingFrame; + } + drawFrame() { + this.updateFrame(); + this.renderFrame(); + } + forceRenderUpdate() { + if (this.root) { + this.root.core._parent.setHasRenderUpdates(1); + } + } + setClearColor(clearColor) { + this.forceRenderUpdate(); + if (clearColor === null) { + this._clearColor = null; + } else if (Array.isArray(clearColor)) { + this._clearColor = clearColor; + } else { + this._clearColor = StageUtils.getRgbaComponentsNormalized(clearColor); + } + } + getClearColor() { + return this._clearColor; + } + createElement(settings) { + if (settings) { + return this.element(settings); + } else { + return new Element(this); + } + } + createShader(settings) { + return Shader.create(this, settings); + } + element(settings) { + if (settings.isElement) + return settings; + let element; + if (settings.type) { + element = new settings.type(this); + } else { + element = new Element(this); + } + element.patch(settings); + return element; + } + c(settings) { + return this.element(settings); + } + get w() { + return this._options.w; + } + get h() { + return this._options.h; + } + get coordsWidth() { + return this.w / this._options.precision; + } + get coordsHeight() { + return this.h / this._options.precision; + } + addMemoryUsage(delta) { + this._usedMemory += delta; + if (this._lastGcFrame !== this.frameCounter) { + if (this._usedMemory > this.getOption("memoryPressure")) { + this.gc(false); + if (this._usedMemory > this.getOption("memoryPressure") - 2e6) { + this.gc(true); + } + } + } + } + get usedMemory() { + return this._usedMemory; + } + addVramUsage(delta, alpha) { + if (alpha) { + this._usedVramAlpha += delta; + } else { + this._usedVramNonAlpha += delta; + } + } + get usedVramAlpha() { + return this._usedVramAlpha; + } + get usedVramNonAlpha() { + return this._usedVramNonAlpha; + } + get usedVram() { + return this._usedVramAlpha + this._usedVramNonAlpha; + } + gc(aggressive) { + if (this._lastGcFrame !== this.frameCounter) { + this._lastGcFrame = this.frameCounter; + const memoryUsageBefore = this._usedMemory; + this.gcTextureMemory(aggressive); + this.gcRenderTextureMemory(aggressive); + this.renderer.gc(aggressive); + if (this.application.getOption("debug")) { + console.log(`[Lightning] GC${aggressive ? "[aggressive]" : ""}! Frame ${this._lastGcFrame} Freed ${((memoryUsageBefore - this._usedMemory) / 1e6).toFixed(2)}MP from GPU memory. Remaining: ${(this._usedMemory / 1e6).toFixed(2)}MP`); + const other = this._usedMemory - this.textureManager.usedMemory - this.ctx.usedMemory; + console.log(`[Lightning] Textures: ${(this.textureManager.usedMemory / 1e6).toFixed(2)}MP, Render Textures: ${(this.ctx.usedMemory / 1e6).toFixed(2)}MP, Renderer caches: ${(other / 1e6).toFixed(2)}MP`); + } + } + } + gcTextureMemory(aggressive = false) { + if (aggressive && this.ctx.root.visible) { + this.ctx.root.visible = false; + this.textureManager.gc(); + this.ctx.root.visible = true; + } else { + this.textureManager.gc(); + } + } + gcRenderTextureMemory(aggressive = false) { + if (aggressive && this.root.visible) { + this.root.visible = false; + this.ctx.freeUnusedRenderTextures(0); + this.root.visible = true; + } else { + this.ctx.freeUnusedRenderTextures(0); + } + } + getDrawingCanvas() { + return this.platform.getDrawingCanvas(); + } + update() { + this.ctx.update(); + } + addServiceProvider(serviceprovider) { + if (Utils$1.isSpark) { + this.platform.addServiceProvider(serviceprovider); + } + } + getChildrenByPosition(x, y) { + const children = []; + this.root.core.update(); + this.root.core.collectAtCoord(x, y, children); + return children; + } +} +class Application extends Component { + constructor(options = {}, properties) { + Application._temp_options = options; + Application.booting = true; + const stage = new Stage(options.stage); + super(stage, properties); + Application.booting = false; + this.__updateFocusCounter = 0; + this.__keypressTimers = /* @__PURE__ */ new Map(); + this.__hoveredChild = null; + this.stage.init(); + this.updateFocusSettings(); + this.__keymap = this.getOption("keys"); + if (this.__keymap) { + this.stage.platform.registerKeydownHandler((e) => { + this._receiveKeydown(e); + }); + this.stage.platform.registerKeyupHandler((e) => { + this._receiveKeyup(e); + }); + } + if (this.getOption("enablePointer")) { + this.stage.platform.registerClickHandler((e) => { + this._receiveClick(e); + }); + this.stage.platform.registerHoverHandler((e) => { + this._receiveHover(e); + }); + this.stage.platform.registerScrollWheelHandler((e) => { + this._recieveScrollWheel(e); + }); + this.cursor = "default"; + } + } + getOption(name) { + return this.__options[name]; + } + _setOptions(o) { + this.__options = {}; + let opt = (name, def) => { + let value = o[name]; + if (value === void 0) { + this.__options[name] = def; + } else { + this.__options[name] = value; + } + }; + opt("debug", false); + opt("keys", { + 38: "Up", + 40: "Down", + 37: "Left", + 39: "Right", + 13: "Enter", + 8: "Back", + 27: "Exit" + }); + opt("enablePointer", false); + } + __construct() { + this.stage.setApplication(this); + this._setOptions(Application._temp_options); + delete Application._temp_options; + super.__construct(); + } + __init() { + super.__init(); + this.__updateFocus(); + } + updateFocusPath() { + this.__updateFocus(); + } + __updateFocus() { + const notOverridden = this.__updateFocusRec(); + if (!Application.booting && notOverridden) { + this.updateFocusSettings(); + } + } + __updateFocusRec() { + const updateFocusId = ++this.__updateFocusCounter; + this.__updateFocusId = updateFocusId; + const newFocusPath = this.__getFocusPath(); + const newFocusedComponent = newFocusPath[newFocusPath.length - 1]; + const prevFocusedComponent = this._focusPath ? this._focusPath[this._focusPath.length - 1] : void 0; + if (!prevFocusedComponent) { + this._focusPath = []; + for (let i = 0, n = newFocusPath.length; i < n; i++) { + this._focusPath.push(newFocusPath[i]); + this._focusPath[i]._focus(newFocusedComponent, void 0); + const focusOverridden = this.__updateFocusId !== updateFocusId; + if (focusOverridden) { + return false; + } + } + return true; + } else { + let m = Math.min(this._focusPath.length, newFocusPath.length); + let index; + for (index = 0; index < m; index++) { + if (this._focusPath[index] !== newFocusPath[index]) { + break; + } + } + if (this._focusPath.length !== newFocusPath.length || index !== newFocusPath.length) { + if (this.getOption("debug")) { + console.log("[Lightning] Focus changed: " + newFocusedComponent.getLocationString()); + } + for (let i = this._focusPath.length - 1; i >= index; i--) { + const unfocusedElement = this._focusPath.pop(); + unfocusedElement._unfocus(newFocusedComponent, prevFocusedComponent); + const focusOverridden = this.__updateFocusId !== updateFocusId; + if (focusOverridden) { + return false; + } + } + for (let i = index, n = newFocusPath.length; i < n; i++) { + this._focusPath.push(newFocusPath[i]); + this._focusPath[i]._focus(newFocusedComponent, prevFocusedComponent); + const focusOverridden = this.__updateFocusId !== updateFocusId; + if (focusOverridden) { + return false; + } + } + for (let i = 0; i < index; i++) { + this._focusPath[i]._focusChange(newFocusedComponent, prevFocusedComponent); + } + } + } + return true; + } + updateFocusSettings() { + const focusedComponent = this._focusPath[this._focusPath.length - 1]; + const focusSettings = {}; + const defaultSetFocusSettings = Component.prototype._setFocusSettings; + for (let i = 0, n = this._focusPath.length; i < n; i++) { + if (this._focusPath[i]._setFocusSettings !== defaultSetFocusSettings) { + this._focusPath[i]._setFocusSettings(focusSettings); + } + } + const defaultHandleFocusSettings = Component.prototype._handleFocusSettings; + for (let i = 0, n = this._focusPath.length; i < n; i++) { + if (this._focusPath[i]._handleFocusSettings !== defaultHandleFocusSettings) { + this._focusPath[i]._handleFocusSettings(focusSettings, this.__prevFocusSettings, focusedComponent); + } + } + this.__prevFocusSettings = focusSettings; + } + _handleFocusSettings(settings, prevSettings, focused, prevFocused) { + } + __getFocusPath() { + const path = [this]; + let current = this; + do { + const nextFocus = current._getFocused(); + if (!nextFocus || nextFocus === current) { + break; + } + let ptr = nextFocus.cparent; + if (ptr === current) { + path.push(nextFocus); + } else { + const newParts = [nextFocus]; + do { + if (!ptr) { + current._throwError("Return value for _getFocused must be an attached descendant component but its '" + nextFocus.getLocationString() + "'"); + } + newParts.push(ptr); + ptr = ptr.cparent; + } while (ptr !== current); + for (let i = 0, n = newParts.length; i < n; i++) { + path.push(newParts[n - i - 1]); + } + } + current = nextFocus; + } while (true); + return path; + } + get focusPath() { + return this._focusPath; + } + focusTopDownEvent(events, ...args) { + const path = this.focusPath; + const n = path.length; + for (let i = 0; i < n; i++) { + const event = path[i]._getMostSpecificHandledMember(events); + if (event !== void 0) { + const returnValue = path[i][event](...args); + if (returnValue !== false) { + return true; + } + } + } + return false; + } + focusBottomUpEvent(events, ...args) { + const path = this.focusPath; + const n = path.length; + for (let i = n - 1; i >= 0; i--) { + const event = path[i]._getMostSpecificHandledMember(events); + if (event !== void 0) { + const returnValue = path[i][event](...args); + if (returnValue !== false) { + return true; + } + } + } + return false; + } + _receiveKeydown(e) { + const obj = e; + const key = this.__keymap[e.keyCode]; + const path = this.focusPath; + let keys; + if (key) { + keys = Array.isArray(key) ? key : [key]; + } + if (keys) { + for (let i = 0, n = keys.length; i < n; i++) { + const hasTimer = this.__keypressTimers.has(keys[i]); + if (path[path.length - 1].longpress && hasTimer) { + return; + } + if (!this.stage.application.focusTopDownEvent([`_capture${keys[i]}`, "_captureKey"], obj)) { + this.stage.application.focusBottomUpEvent([`_handle${keys[i]}`, "_handleKey"], obj); + } + } + } else { + if (!this.stage.application.focusTopDownEvent(["_captureKey"], obj)) { + this.stage.application.focusBottomUpEvent(["_handleKey"], obj); + } + } + this.updateFocusPath(); + const consumer = path[path.length - 1]; + if (keys && consumer.longpress) { + for (let i = 0, n = keys.length; i < n; i++) { + this._startLongpressTimer(keys[i], consumer); + } + } + } + _receiveKeyup(e) { + const obj = e; + const key = this.__keymap[e.keyCode]; + let keys; + if (key) { + keys = Array.isArray(key) ? key : [key]; + } + if (keys) { + for (let i = 0, n = keys.length; i < n; i++) { + if (!this.stage.application.focusTopDownEvent([`_capture${keys[i]}Release`, "_captureKeyRelease"], obj)) { + this.stage.application.focusBottomUpEvent([`_handle${keys[i]}Release`, "_handleKeyRelease"], obj); + } + } + } else { + if (!this.stage.application.focusTopDownEvent(["_captureKeyRelease"], obj)) { + this.stage.application.focusBottomUpEvent(["_handleKeyRelease"], obj); + } + } + this.updateFocusPath(); + if (keys) { + for (let i = 0, n = keys.length; i < n; i++) { + if (this.__keypressTimers.has(keys[i])) { + clearTimeout(this.__keypressTimers.get(keys[i])); + this.__keypressTimers.delete(keys[i]); + } + } + } + } + _startLongpressTimer(key, element) { + const config = element.longpress; + const lookup = key.toLowerCase(); + if (config[lookup]) { + const timeout = config[lookup]; + if (!Utils$1.isNumber(timeout)) { + element._throwError("config value for longpress must be a number"); + } else { + this.__keypressTimers.set(key, setTimeout(() => { + if (!this.stage.application.focusTopDownEvent([`_capture${key}Long`, "_captureKey"], {})) { + this.stage.application.focusBottomUpEvent([`_handle${key}Long`, "_handleKey"], {}); + } + this.__keypressTimers.delete(key); + }, timeout || 500)); + } + } + return; + } + _recieveScrollWheel(e) { + const obj = e; + const { clientX, clientY } = obj; + if (clientX <= this.stage.w && clientY <= this.stage.h) { + if (!this.fireTopDownScrollWheelHandler("_captureScroll", obj)) { + this.fireBottomUpScrollWheelHandler("_handleScroll", obj); + } + } + } + fireTopDownScrollWheelHandler(event, obj) { + let children = this.stage.application.children; + let affected = this._findChildren([], children).reverse(); + let n = affected.length; + while (n--) { + const child = affected[n]; + if (child && child[event]) { + child._captureScroll(obj); + return true; + } + } + return false; + } + fireBottomUpScrollWheelHandler(event, obj) { + const { clientX, clientY } = obj; + const target = this._getTargetChild(clientX, clientY); + let child = target; + while (child !== null) { + if (child && child[event]) { + child._handleScroll(obj); + return true; + } + child = child.parent; + } + return false; + } + _receiveClick(e) { + const obj = e; + const { clientX, clientY } = obj; + if (clientX <= this.stage.w && clientY <= this.stage.h) { + this.stage.application.fireBottomUpClickHandler(obj); + } + } + fireBottomUpClickHandler(obj) { + const { clientX, clientY } = obj; + const target = this._getTargetChild(clientX, clientY); + const precision = this.stage.getRenderPrecision() / this.stage.getOption("devicePixelRatio"); + let child = target; + while (child !== null) { + if (child && child["_handleClick"]) { + const { px, py } = child.core._worldContext; + const cx = px * precision; + const cy = py * precision; + const localCoords = { + x: clientX - cx, + y: clientY - cy + }; + const returnValue = child._handleClick(target, localCoords); + if (returnValue !== false) { + break; + } + } + child = child.parent; + } + } + _receiveHover(e) { + const obj = e; + const { clientX, clientY } = obj; + if (clientX <= this.stage.w && clientY <= this.stage.h) { + this.stage.application.fireBottomUpHoverHandler(obj); + } + } + fireBottomUpHoverHandler(obj) { + const { clientX, clientY } = obj; + const target = this._getTargetChild(clientX, clientY); + if (target !== this.__hoveredChild) { + let hoveredBranch = /* @__PURE__ */ new Set(); + let newHoveredBranch = /* @__PURE__ */ new Set(); + if (target) { + newHoveredBranch = new Set(target.getAncestors()); + } + if (this.__hoveredChild) { + hoveredBranch = new Set(this.__hoveredChild.getAncestors()); + for (const elem of [...hoveredBranch].filter((e) => !newHoveredBranch.has(e))) { + const c = Component.getComponent(elem); + if (c["_handleUnhover"]) { + c._handleUnhover(elem); + } + if (elem.parent && elem.parent.cursor) { + this.stage.getCanvas().style.cursor = elem.parent.cursor; + } + } + } + this.__hoveredChild = target; + const diffBranch = [...newHoveredBranch].filter((e) => !hoveredBranch.has(e)); + for (const elem of diffBranch) { + const c = Component.getComponent(elem); + if (c["_handleHover"]) { + c._handleHover(elem); + } + } + const lastElement = diffBranch[0]; + if (lastElement && lastElement.cursor) { + this.stage.getCanvas().style.cursor = lastElement.cursor; + } + if (diffBranch.length === 0 && target) { + const c = Component.getComponent(target); + if (c["_handleHover"]) { + c._handleHover(target); + } + } + } + } + _getTargetChild(clientX, clientY) { + let children = this.stage.application.children; + let affected = this._findChildren([], children); + let hoverableChildren = this._withinClickableRange(affected, clientX, clientY); + hoverableChildren.sort((a, b) => { + if (a.zIndex > b.zIndex) { + return 1; + } else if (a.zIndex < b.zIndex) { + return -1; + } else { + return a.id > b.id ? 1 : -1; + } + }); + if (hoverableChildren.length) { + return hoverableChildren.slice(-1)[0]; + } else { + return null; + } + } + _findChildren(bucket, children) { + let n = children.length; + while (n--) { + const child = children[n]; + if (child.__active && child.collision) { + if (child.collision === true) { + bucket.push(child); + } + if (child.hasChildren()) { + this._findChildren(bucket, child.children); + } + } + } + return bucket; + } + _withinClickableRange(affectedChildren, cursorX, cursorY) { + let n = affectedChildren.length; + const candidates = []; + while (n--) { + const child = affectedChildren[n]; + const precision = this.stage.getRenderPrecision() / this.stage.getOption("devicePixelRatio"); + const ctx = child.core._worldContext; + const cx = ctx.px * precision; + const cy = ctx.py * precision; + const cw = child.finalW * ctx.ta * precision; + const ch = child.finalH * ctx.td * precision; + if (cx > this.stage.w || cy > this.stage.h) { + continue; + } + if (child.parent.core._scissor) { + const scissor = child.parent.core._scissor.map((v) => v * precision); + if (!this._testCollision(cursorX, cursorY, ...scissor)) + continue; + } + if (this._testCollision(cursorX, cursorY, cx, cy, cw, ch)) { + candidates.push(child); + } + } + return candidates; + } + _testCollision(px, py, cx, cy, cw, ch) { + if (px >= cx && px <= cx + cw && py >= cy && py <= cy + ch) { + return true; + } + return false; + } + destroy() { + if (!this._destroyed) { + this._destroy(); + this.stage.destroy(); + this._destroyed = true; + } + } + _destroy() { + this.stage.setApplication(void 0); + this._updateAttachedFlag(); + this._updateEnabledFlag(); + if (this.__keypressTimers.size) { + for (const timer of this.__keypressTimers.values()) { + clearTimeout(timer); + } + this.__keypressTimers.clear(); + } + } + getCanvas() { + return this.stage.getCanvas(); + } +} +class StaticCanvasTexture extends Texture { + constructor(stage) { + super(stage); + this._factory = void 0; + this._lookupId = void 0; + } + set content({ factory, lookupId = void 0 }) { + this._factory = factory; + this._lookupId = lookupId; + this._changed(); + } + _getIsValid() { + return !!this._factory; + } + _getLookupId() { + return this._lookupId; + } + _getSourceLoader() { + const f = this._factory; + return (cb) => { + return f((err, canvas) => { + if (err) { + return cb(err); + } + cb(null, this.stage.platform.getTextureOptionsForDrawingCanvas(canvas)); + }, this.stage); + }; + } +} +class Tools { + static getCanvasTexture(canvasFactory, lookupId) { + return { type: StaticCanvasTexture, content: { factory: canvasFactory, lookupId } }; + } + static getRoundRect(w, h, radius, strokeWidth, strokeColor, fill, fillColor) { + if (!Array.isArray(radius)) { + radius = [radius, radius, radius, radius]; + } + let factory = (cb, stage) => { + if (Utils$1.isSpark) { + stage.platform.createRoundRect(cb, stage, w, h, radius, strokeWidth, strokeColor, fill, fillColor); + } else { + cb(null, this.createRoundRect(stage, w, h, radius, strokeWidth, strokeColor, fill, fillColor)); + } + }; + let id = "rect" + [w, h, strokeWidth, strokeColor, fill ? 1 : 0, fillColor].concat(radius).join(","); + return Tools.getCanvasTexture(factory, id); + } + static createRoundRect(stage, w, h, radius, strokeWidth, strokeColor, fill, fillColor) { + if (fill === void 0) + fill = true; + if (strokeWidth === void 0) + strokeWidth = 0; + let canvas = stage.platform.getDrawingCanvas(); + let ctx = canvas.getContext("2d"); + ctx.imageSmoothingEnabled = true; + canvas.width = w + strokeWidth + 2; + canvas.height = h + strokeWidth + 2; + ctx.beginPath(); + let x = 0.5 * strokeWidth + 1, y = 0.5 * strokeWidth + 1; + ctx.moveTo(x + radius[0], y); + ctx.lineTo(x + w - radius[1], y); + ctx.arcTo(x + w, y, x + w, y + radius[1], radius[1]); + ctx.lineTo(x + w, y + h - radius[2]); + ctx.arcTo(x + w, y + h, x + w - radius[2], y + h, radius[2]); + ctx.lineTo(x + radius[3], y + h); + ctx.arcTo(x, y + h, x, y + h - radius[3], radius[3]); + ctx.lineTo(x, y + radius[0]); + ctx.arcTo(x, y, x + radius[0], y, radius[0]); + ctx.closePath(); + if (fill) { + if (Utils$1.isNumber(fillColor)) { + ctx.fillStyle = StageUtils.getRgbaString(fillColor); + } else { + ctx.fillStyle = "white"; + } + ctx.fill(); + } + if (strokeWidth) { + if (Utils$1.isNumber(strokeColor)) { + ctx.strokeStyle = StageUtils.getRgbaString(strokeColor); + } else { + ctx.strokeStyle = "white"; + } + ctx.lineWidth = strokeWidth; + ctx.stroke(); + } + return canvas; + } + static getShadowRect(w, h, radius = 0, blur = 5, margin = blur * 2) { + if (!Array.isArray(radius)) { + radius = [radius, radius, radius, radius]; + } + let factory = (cb, stage) => { + if (Utils$1.isSpark) { + stage.platform.createShadowRect(cb, stage, w, h, radius, blur, margin); + } else { + cb(null, this.createShadowRect(stage, w, h, radius, blur, margin)); + } + }; + let id = "shadow" + [w, h, blur, margin].concat(radius).join(","); + return Tools.getCanvasTexture(factory, id); + } + static createShadowRect(stage, w, h, radius, blur, margin) { + let canvas = stage.platform.getDrawingCanvas(); + let ctx = canvas.getContext("2d"); + ctx.imageSmoothingEnabled = true; + canvas.width = w + margin * 2; + canvas.height = h + margin * 2; + ctx.globalAlpha = 0.01; + ctx.fillRect(0, 0, 0.01, 0.01); + ctx.globalAlpha = 1; + ctx.shadowColor = StageUtils.getRgbaString(4294967295); + ctx.fillStyle = StageUtils.getRgbaString(4294967295); + ctx.shadowBlur = blur; + ctx.shadowOffsetX = w + 10 + margin; + ctx.shadowOffsetY = margin; + ctx.beginPath(); + const x = -(w + 10); + const y = 0; + ctx.moveTo(x + radius[0], y); + ctx.lineTo(x + w - radius[1], y); + ctx.arcTo(x + w, y, x + w, y + radius[1], radius[1]); + ctx.lineTo(x + w, y + h - radius[2]); + ctx.arcTo(x + w, y + h, x + w - radius[2], y + h, radius[2]); + ctx.lineTo(x + radius[3], y + h); + ctx.arcTo(x, y + h, x, y + h - radius[3], radius[3]); + ctx.lineTo(x, y + radius[0]); + ctx.arcTo(x, y, x + radius[0], y, radius[0]); + ctx.closePath(); + ctx.fill(); + return canvas; + } + static getSvgTexture(url, w, h) { + let factory = (cb, stage) => { + if (Utils$1.isSpark) { + stage.platform.createSvg(cb, stage, url, w, h); + } else { + this.createSvg(cb, stage, url, w, h); + } + }; + let id = "svg" + [w, h, url].join(","); + return Tools.getCanvasTexture(factory, id); + } + static createSvg(cb, stage, url, w, h) { + let canvas = stage.platform.getDrawingCanvas(); + let ctx = canvas.getContext("2d"); + ctx.imageSmoothingEnabled = true; + let img = new Image(); + img.onload = () => { + canvas.width = w; + canvas.height = h; + ctx.drawImage(img, 0, 0, canvas.width, canvas.height); + cb(null, canvas); + }; + img.onError = (err) => { + cb(err); + }; + if (!Utils$1.isPS4) { + img.crossOrigin = "Anonymous"; + } + img.src = url; + } +} +class ObjMerger { + static isMf(f) { + return Utils$1.isFunction(f) && f.__mf; + } + static mf(f) { + f.__mf = true; + return f; + } + static merge(a, b) { + const aks = Object.keys(a); + const bks = Object.keys(b); + if (!bks.length) { + return a; + } + const ai = {}; + const bi = {}; + for (let i = 0, n = bks.length; i < n; i++) { + const key = bks[i]; + ai[key] = -1; + bi[key] = i; + } + for (let i = 0, n = aks.length; i < n; i++) { + const key = aks[i]; + ai[key] = i; + if (bi[key] === void 0) { + bi[key] = -1; + } + } + const aksl = aks.length; + const result = {}; + for (let i = 0, n = bks.length; i < n; i++) { + const key = bks[i]; + const aIndex = ai[key]; + let curIndex2 = aIndex; + while (--curIndex2 >= 0) { + const akey = aks[curIndex2]; + if (bi[akey] !== -1) { + break; + } + } + while (++curIndex2 < aIndex) { + const akey = aks[curIndex2]; + result[akey] = a[akey]; + } + const bv = b[key]; + const av = a[key]; + let r; + if (this.isMf(bv)) { + r = bv(av); + } else { + if (!Utils$1.isObjectLiteral(av) || !Utils$1.isObjectLiteral(bv)) { + r = bv; + } else { + r = ObjMerger.merge(av, bv); + } + } + if (r !== void 0) { + result[key] = r; + } + } + let curIndex = aksl; + while (--curIndex >= 0) { + const akey = aks[curIndex]; + if (bi[akey] !== -1) { + break; + } + } + while (++curIndex < aksl) { + const akey = aks[curIndex]; + result[akey] = a[akey]; + } + return result; + } +} +class ObjectListProxy extends ObjectList { + constructor(target) { + super(); + this._target = target; + } + onAdd(item, index) { + this._target.addAt(item, index); + } + onRemove(item, index) { + this._target.removeAt(index); + } + onSync(removed, added, order) { + this._target._setByArray(order); + } + onSet(item, index) { + this._target.setAt(item, index); + } + onMove(item, fromIndex, toIndex) { + this._target.setAt(item, toIndex); + } + createItem(object) { + return this._target.createItem(object); + } + isItem(object) { + return this._target.isItem(object); + } +} +class ObjectListWrapper extends ObjectListProxy { + constructor(target, wrap) { + super(target); + this._wrap = wrap; + } + wrap(item) { + let wrapper = this._wrap(item); + item._wrapper = wrapper; + return wrapper; + } + onAdd(item, index) { + item = this.wrap(item); + super.onAdd(item, index); + } + onRemove(item, index) { + super.onRemove(item, index); + } + onSync(removed, added, order) { + added.forEach((a) => this.wrap(a)); + order = order.map((a) => a._wrapper); + super.onSync(removed, added, order); + } + onSet(item, index) { + item = this.wrap(item); + super.onSet(item, index); + } + onMove(item, fromIndex, toIndex) { + super.onMove(item, fromIndex, toIndex); + } +} +class NoiseTexture extends Texture { + _getLookupId() { + return "__noise"; + } + _getSourceLoader() { + const gl = this.stage.gl; + return function(cb) { + const noise = new Uint8Array(128 * 128 * 4); + for (let i = 0; i < 128 * 128 * 4; i += 4) { + const v = Math.floor(Math.random() * 256); + noise[i] = v; + noise[i + 1] = v; + noise[i + 2] = v; + noise[i + 3] = 255; + } + const texParams = {}; + if (gl) { + texParams[gl.TEXTURE_WRAP_S] = gl.REPEAT; + texParams[gl.TEXTURE_WRAP_T] = gl.REPEAT; + texParams[gl.TEXTURE_MIN_FILTER] = gl.NEAREST; + texParams[gl.TEXTURE_MAG_FILTER] = gl.NEAREST; + } + cb(null, { source: noise, w: 128, h: 128, texParams }); + }; + } +} +class HtmlTexture extends Texture { + constructor(stage) { + super(stage); + this._htmlElement = void 0; + this._scale = 1; + } + set htmlElement(v) { + this._htmlElement = v; + this._changed(); + } + get htmlElement() { + return this._htmlElement; + } + set scale(v) { + this._scale = v; + this._changed(); + } + get scale() { + return this._scale; + } + set html(v) { + if (!v) { + this.htmlElement = void 0; + } else { + const d = document.createElement("div"); + d.innerHTML = "
" + v + "
"; + this.htmlElement = d.firstElementChild; + } + } + get html() { + return this._htmlElement.innerHTML; + } + _getIsValid() { + return this.htmlElement; + } + _getLookupId() { + return this._scale + ":" + this._htmlElement.innerHTML; + } + _getSourceLoader() { + const htmlElement = this._htmlElement; + const scale = this._scale; + return function(cb) { + if (!window.html2canvas) { + return cb(new Error("Please include html2canvas (https://html2canvas.hertzen.com/)")); + } + const area = HtmlTexture.getPreloadArea(); + area.appendChild(htmlElement); + html2canvas(htmlElement, { backgroundColor: null, scale }).then(function(canvas) { + area.removeChild(htmlElement); + if (canvas.height === 0) { + return cb(new Error("Canvas height is 0")); + } + cb(null, { source: canvas, width: canvas.width, height: canvas.height }); + }).catch((e) => { + console.error("[Lightning]", e); + }); + }; + } + static getPreloadArea() { + if (!this._preloadArea) { + this._preloadArea = document.createElement("div"); + if (this._preloadArea.attachShadow) { + this._preloadArea.attachShadow({ mode: "closed" }); + } + this._preloadArea.style.opacity = 0; + this._preloadArea.style.pointerEvents = "none"; + this._preloadArea.style.position = "fixed"; + this._preloadArea.style.display = "block"; + this._preloadArea.style.top = "100vh"; + this._preloadArea.style.overflow = "hidden"; + document.body.appendChild(this._preloadArea); + } + return this._preloadArea; + } +} +class StaticTexture extends Texture { + constructor(stage, options) { + super(stage); + this._options = options; + } + set options(v) { + if (this._options !== v) { + this._options = v; + this._changed(); + } + } + get options() { + return this._options; + } + _getIsValid() { + return !!this._options; + } + _getSourceLoader() { + return (cb) => { + cb(null, this._options); + }; + } +} +class ListComponent extends Component { + constructor(stage) { + super(stage); + this._wrapper = super._children.a({}); + this._reloadVisibleElements = false; + this._visibleItems = /* @__PURE__ */ new Set(); + this._index = 0; + this._started = false; + this._scrollTransitionSettings = this.stage.transitions.createSettings({}); + this._itemSize = 100; + this._viewportScrollOffset = 0; + this._itemScrollOffset = 0; + this._roll = false; + this._rollMin = 0; + this._rollMax = 0; + this._progressAnimation = null; + this._invertDirection = false; + this._horizontal = true; + this.itemList = new ListItems(this); + } + _allowChildrenAccess() { + return false; + } + get items() { + return this.itemList.get(); + } + set items(children) { + this.itemList.patch(children); + } + start() { + this._wrapper.transition(this.property, this._scrollTransitionSettings); + this._scrollTransition = this._wrapper.transition(this.property); + this._scrollTransition.on("progress", (p) => this.update()); + this.setIndex(0, true, true); + this._started = true; + this.update(); + } + setIndex(index, immediate = false, closest = false) { + let nElements = this.length; + if (!nElements) + return; + this.emit("unfocus", this.getElement(this.realIndex), this._index, this.realIndex); + if (closest) { + let offset = Utils$1.getModuloIndex(index, nElements); + let o = Utils$1.getModuloIndex(this.index, nElements); + let diff = offset - o; + if (diff > 0.5 * nElements) { + diff -= nElements; + } else if (diff < -0.5 * nElements) { + diff += nElements; + } + this._index += diff; + } else { + this._index = index; + } + if (this._roll || this.viewportSize > this._itemSize * nElements) { + this._index = Utils$1.getModuloIndex(this._index, nElements); + } + let direction = this._horizontal ^ this._invertDirection ? -1 : 1; + let value = direction * this._index * this._itemSize; + if (this._roll) { + let min, max, scrollDelta; + if (direction == 1) { + max = (nElements - 1) * this._itemSize; + scrollDelta = this._viewportScrollOffset * this.viewportSize - this._itemScrollOffset * this._itemSize; + max -= scrollDelta; + min = this.viewportSize - (this._itemSize + scrollDelta); + if (this._rollMin) + min -= this._rollMin; + if (this._rollMax) + max += this._rollMax; + value = Math.max(Math.min(value, max), min); + } else { + max = nElements * this._itemSize - this.viewportSize; + scrollDelta = this._viewportScrollOffset * this.viewportSize - this._itemScrollOffset * this._itemSize; + max += scrollDelta; + let min2 = scrollDelta; + if (this._rollMin) + min2 -= this._rollMin; + if (this._rollMax) + max += this._rollMax; + value = Math.min(Math.max(-max, value), -min2); + } + } + this._scrollTransition.start(value); + if (immediate) { + this._scrollTransition.finish(); + } + this.emit("focus", this.getElement(this.realIndex), this._index, this.realIndex); + } + getAxisPosition() { + let target = -this._scrollTransition._targetValue; + let direction = this._horizontal ^ this._invertDirection ? -1 : 1; + let value = -direction * this._index * this._itemSize; + return this._viewportScrollOffset * this.viewportSize + (value - target); + } + update() { + if (!this._started) + return; + let nElements = this.length; + if (!nElements) + return; + let direction = this._horizontal ^ this._invertDirection ? -1 : 1; + let v = this._horizontal ? this._wrapper.x : this._wrapper.y; + let viewportSize = this.viewportSize; + let scrollDelta = this._viewportScrollOffset * viewportSize - this._itemScrollOffset * this._itemSize; + v += scrollDelta; + let s, e, ps, pe; + if (direction == -1) { + s = Math.floor(-v / this._itemSize); + ps = 1 - (-v / this._itemSize - s); + e = Math.floor((viewportSize - v) / this._itemSize); + pe = (viewportSize - v) / this._itemSize - e; + } else { + s = Math.ceil(v / this._itemSize); + ps = 1 + v / this._itemSize - s; + e = Math.ceil((v - viewportSize) / this._itemSize); + pe = e - (v - viewportSize) / this._itemSize; + } + if (this._roll || viewportSize > this._itemSize * nElements) { + if (e >= nElements) { + e = nElements - 1; + pe = 1; + } + if (s >= nElements) { + s = nElements - 1; + ps = 1; + } + if (e <= -1) { + e = 0; + pe = 1; + } + if (s <= -1) { + s = 0; + ps = 1; + } + } + let offset = -direction * s * this._itemSize; + let item; + for (let index = s; direction == -1 ? index <= e : index >= e; direction == -1 ? index++ : index--) { + let realIndex = Utils$1.getModuloIndex(index, nElements); + let element = this.getElement(realIndex); + item = element.parent; + this._visibleItems.delete(item); + if (this._horizontal) { + item.x = offset + scrollDelta; + } else { + item.y = offset + scrollDelta; + } + let wasVisible = item.visible; + item.visible = true; + if (!wasVisible || this._reloadVisibleElements) { + this.emit("visible", index, realIndex); + } + if (this._progressAnimation) { + let p = 1; + if (index == s) { + p = ps; + } else if (index == e) { + p = pe; + } + this._progressAnimation.apply(element, p); + } + offset += this._itemSize; + } + let self = this; + this._visibleItems.forEach(function(invisibleItem) { + invisibleItem.visible = false; + self._visibleItems.delete(invisibleItem); + }); + for (let index = s; direction == -1 ? index <= e : index >= e; direction == -1 ? index++ : index--) { + let realIndex = Utils$1.getModuloIndex(index, nElements); + this._visibleItems.add(this.getWrapper(realIndex)); + } + this._reloadVisibleElements = false; + } + setPrevious() { + this.setIndex(this._index - 1); + } + setNext() { + this.setIndex(this._index + 1); + } + getWrapper(index) { + return this._wrapper.children[index]; + } + getElement(index) { + let e = this._wrapper.children[index]; + return e ? e.children[0] : null; + } + reload() { + this._reloadVisibleElements = true; + this.update(); + } + get element() { + let e = this._wrapper.children[this.realIndex]; + return e ? e.children[0] : null; + } + get length() { + return this._wrapper.children.length; + } + get property() { + return this._horizontal ? "x" : "y"; + } + get viewportSize() { + return this._horizontal ? this.w : this.h; + } + get index() { + return this._index; + } + get realIndex() { + return Utils$1.getModuloIndex(this._index, this.length); + } + get itemSize() { + return this._itemSize; + } + set itemSize(v) { + this._itemSize = v; + this.update(); + } + get viewportScrollOffset() { + return this._viewportScrollOffset; + } + set viewportScrollOffset(v) { + this._viewportScrollOffset = v; + this.update(); + } + get itemScrollOffset() { + return this._itemScrollOffset; + } + set itemScrollOffset(v) { + this._itemScrollOffset = v; + this.update(); + } + get scrollTransitionSettings() { + return this._scrollTransitionSettings; + } + set scrollTransitionSettings(v) { + this._scrollTransitionSettings.patch(v); + } + set scrollTransition(v) { + this._scrollTransitionSettings.patch(v); + } + get scrollTransition() { + return this._scrollTransition; + } + get progressAnimation() { + return this._progressAnimation; + } + set progressAnimation(v) { + if (Utils$1.isObjectLiteral(v)) { + this._progressAnimation = this.stage.animations.createSettings(v); + } else { + this._progressAnimation = v; + } + this.update(); + } + get roll() { + return this._roll; + } + set roll(v) { + this._roll = v; + this.update(); + } + get rollMin() { + return this._rollMin; + } + set rollMin(v) { + this._rollMin = v; + this.update(); + } + get rollMax() { + return this._rollMax; + } + set rollMax(v) { + this._rollMax = v; + this.update(); + } + get invertDirection() { + return this._invertDirection; + } + set invertDirection(v) { + if (!this._started) { + this._invertDirection = v; + } + } + get horizontal() { + return this._horizontal; + } + set horizontal(v) { + if (v !== this._horizontal) { + if (!this._started) { + this._horizontal = v; + } + } + } +} +class ListItems extends ObjectListWrapper { + constructor(list) { + let wrap = (item) => { + let parent = item.stage.createElement(); + parent.add(item); + parent.visible = false; + return parent; + }; + super(list._wrapper._children, wrap); + this.list = list; + } + onAdd(item, index) { + super.onAdd(item, index); + this.checkStarted(index); + } + checkStarted(index) { + this.list._reloadVisibleElements = true; + if (!this.list._started) { + this.list.start(); + } else { + if (this.list.length === 1) { + this.list.setIndex(0, true, true); + } else { + if (this.list._index >= this.list.length) { + this.list.setIndex(0); + } + } + this.list.update(); + } + } + onRemove(item, index) { + super.onRemove(item, index); + let ri = this.list.realIndex; + if (ri === index) { + if (ri === this.list.length) { + ri--; + } + if (ri >= 0) { + this.list.setIndex(ri); + } + } else if (ri > index) { + this.list.setIndex(ri - 1); + } + this.list._reloadVisibleElements = true; + } + onSet(item, index) { + super.onSet(item, index); + this.checkStarted(index); + } + onSync(removed, added, order) { + super.onSync(removed, added, order); + this.checkStarted(0); + } + get _signalProxy() { + return true; + } +} +class LinearBlurShader extends DefaultShader$1 { + constructor(context) { + super(context); + this._direction = new Float32Array([1, 0]); + this._kernelRadius = 1; + } + get x() { + return this._direction[0]; + } + set x(v) { + this._direction[0] = v; + this.redraw(); + } + get y() { + return this._direction[1]; + } + set y(v) { + this._direction[1] = v; + this.redraw(); + } + get kernelRadius() { + return this._kernelRadius; + } + set kernelRadius(v) { + this._kernelRadius = v; + this.redraw(); + } + useDefault() { + return this._kernelRadius === 0; + } + setupUniforms(operation) { + super.setupUniforms(operation); + this._setUniform("direction", this._direction, this.gl.uniform2fv); + this._setUniform("kernelRadius", this._kernelRadius, this.gl.uniform1i); + const w = operation.getRenderWidth(); + const h = operation.getRenderHeight(); + this._setUniform("resolution", new Float32Array([w, h]), this.gl.uniform2fv); + } +} +LinearBlurShader.fragmentShaderSource = ` + #ifdef GL_ES + # ifdef GL_FRAGMENT_PRECISION_HIGH + precision highp float; + # else + precision lowp float; + # endif + #endif + uniform vec2 resolution; + varying vec2 vTextureCoord; + varying vec4 vColor; + uniform sampler2D uSampler; + uniform vec2 direction; + uniform int kernelRadius; + + vec4 blur1(sampler2D image, vec2 uv, vec2 resolution, vec2 direction) { + vec4 color = vec4(0.0); + vec2 off1 = vec2(1.3333333333333333) * direction; + color += texture2D(image, uv) * 0.29411764705882354; + color += texture2D(image, uv + (off1 / resolution)) * 0.35294117647058826; + color += texture2D(image, uv - (off1 / resolution)) * 0.35294117647058826; + return color; + } + + vec4 blur2(sampler2D image, vec2 uv, vec2 resolution, vec2 direction) { + vec4 color = vec4(0.0); + vec2 off1 = vec2(1.3846153846) * direction; + vec2 off2 = vec2(3.2307692308) * direction; + color += texture2D(image, uv) * 0.2270270270; + color += texture2D(image, uv + (off1 / resolution)) * 0.3162162162; + color += texture2D(image, uv - (off1 / resolution)) * 0.3162162162; + color += texture2D(image, uv + (off2 / resolution)) * 0.0702702703; + color += texture2D(image, uv - (off2 / resolution)) * 0.0702702703; + return color; + } + + vec4 blur3(sampler2D image, vec2 uv, vec2 resolution, vec2 direction) { + vec4 color = vec4(0.0); + vec2 off1 = vec2(1.411764705882353) * direction; + vec2 off2 = vec2(3.2941176470588234) * direction; + vec2 off3 = vec2(5.176470588235294) * direction; + color += texture2D(image, uv) * 0.1964825501511404; + color += texture2D(image, uv + (off1 / resolution)) * 0.2969069646728344; + color += texture2D(image, uv - (off1 / resolution)) * 0.2969069646728344; + color += texture2D(image, uv + (off2 / resolution)) * 0.09447039785044732; + color += texture2D(image, uv - (off2 / resolution)) * 0.09447039785044732; + color += texture2D(image, uv + (off3 / resolution)) * 0.010381362401148057; + color += texture2D(image, uv - (off3 / resolution)) * 0.010381362401148057; + return color; + } + + void main(void){ + if (kernelRadius == 1) { + gl_FragColor = blur1(uSampler, vTextureCoord, resolution, direction) * vColor; + } else if (kernelRadius == 2) { + gl_FragColor = blur2(uSampler, vTextureCoord, resolution, direction) * vColor; + } else { + gl_FragColor = blur3(uSampler, vTextureCoord, resolution, direction) * vColor; + } + } +`; +class BoxBlurShader extends DefaultShader$1 { + setupUniforms(operation) { + super.setupUniforms(operation); + const dx = 1 / operation.getTextureWidth(0); + const dy = 1 / operation.getTextureHeight(0); + this._setUniform("stepTextureCoord", new Float32Array([dx, dy]), this.gl.uniform2fv); + } +} +BoxBlurShader.vertexShaderSource = ` + #ifdef GL_ES + # ifdef GL_FRAGMENT_PRECISION_HIGH + precision highp float; + # else + precision lowp float; + # endif + #endif + uniform vec2 stepTextureCoord; + attribute vec2 aVertexPosition; + attribute vec2 aTextureCoord; + attribute vec4 aColor; + uniform vec2 projection; + varying vec4 vColor; + varying vec2 vTextureCoordUl; + varying vec2 vTextureCoordUr; + varying vec2 vTextureCoordBl; + varying vec2 vTextureCoordBr; + void main(void){ + gl_Position = vec4(aVertexPosition.x * projection.x - 1.0, aVertexPosition.y * -abs(projection.y) + 1.0, 0.0, 1.0); + vTextureCoordUl = aTextureCoord - stepTextureCoord; + vTextureCoordBr = aTextureCoord + stepTextureCoord; + vTextureCoordUr = vec2(vTextureCoordBr.x, vTextureCoordUl.y); + vTextureCoordBl = vec2(vTextureCoordUl.x, vTextureCoordBr.y); + vColor = aColor; + gl_Position.y = -sign(projection.y) * gl_Position.y; + } +`; +BoxBlurShader.fragmentShaderSource = ` + #ifdef GL_ES + # ifdef GL_FRAGMENT_PRECISION_HIGH + precision highp float; + # else + precision lowp float; + # endif + #endif + varying vec2 vTextureCoordUl; + varying vec2 vTextureCoordUr; + varying vec2 vTextureCoordBl; + varying vec2 vTextureCoordBr; + varying vec4 vColor; + uniform sampler2D uSampler; + void main(void){ + vec4 color = 0.25 * (texture2D(uSampler, vTextureCoordUl) + texture2D(uSampler, vTextureCoordUr) + texture2D(uSampler, vTextureCoordBl) + texture2D(uSampler, vTextureCoordBr)); + gl_FragColor = color * vColor; + } +`; +class BlurShader extends DefaultShader2 { + constructor(context) { + super(context); + this._kernelRadius = 1; + } + get kernelRadius() { + return this._kernelRadius; + } + set kernelRadius(v) { + this._kernelRadius = v; + this.redraw(); + } + useDefault() { + return this._amount === 0; + } + _beforeDrawEl({ target }) { + target.ctx.filter = "blur(" + this._kernelRadius + "px)"; + } + _afterDrawEl({ target }) { + target.ctx.filter = "none"; + } +} +class FastBlurComponent extends Component { + static _template() { + return {}; + } + get wrap() { + return this.tag("Wrap"); + } + set content(v) { + return this.wrap.content = v; + } + get content() { + return this.wrap.content; + } + set padding(v) { + this.wrap._paddingX = v; + this.wrap._paddingY = v; + this.wrap._updateBlurSize(); + } + set paddingX(v) { + this.wrap._paddingX = v; + this.wrap._updateBlurSize(); + } + set paddingY(v) { + this.wrap._paddingY = v; + this.wrap._updateBlurSize(); + } + set amount(v) { + return this.wrap.amount = v; + } + get amount() { + return this.wrap.amount; + } + _onResize() { + this.wrap.w = this.renderWidth; + this.wrap.h = this.renderHeight; + } + get _signalProxy() { + return true; + } + _build() { + this.patch({ + Wrap: { type: this.stage.gl ? WebGLFastBlurComponent : C2dFastBlurComponent } + }); + } +} +class C2dFastBlurComponent extends Component { + static _template() { + return { + forceZIndexContext: true, + rtt: true, + Textwrap: { shader: { type: BlurShader }, Content: {} } + }; + } + constructor(stage) { + super(stage); + this._textwrap = this.sel("Textwrap"); + this._wrapper = this.sel("Textwrap>Content"); + this._amount = 0; + this._paddingX = 0; + this._paddingY = 0; + } + static getSpline() { + if (!this._multiSpline) { + this._multiSpline = new MultiSpline(); + this._multiSpline.parse(false, { 0: 0, 0.25: 1.5, 0.5: 5.5, 0.75: 18, 1: 39 }); + } + return this._multiSpline; + } + get content() { + return this.sel("Textwrap>Content"); + } + set content(v) { + this.sel("Textwrap>Content").patch(v, true); + } + set padding(v) { + this._paddingX = v; + this._paddingY = v; + this._updateBlurSize(); + } + set paddingX(v) { + this._paddingX = v; + this._updateBlurSize(); + } + set paddingY(v) { + this._paddingY = v; + this._updateBlurSize(); + } + _updateBlurSize() { + let w = this.renderWidth; + let h = this.renderHeight; + let paddingX = this._paddingX; + let paddingY = this._paddingY; + this._wrapper.x = paddingX; + this._textwrap.x = -paddingX; + this._wrapper.y = paddingY; + this._textwrap.y = -paddingY; + this._textwrap.w = w + paddingX * 2; + this._textwrap.h = h + paddingY * 2; + } + get amount() { + return this._amount; + } + set amount(v) { + this._amount = v; + this._textwrap.shader.kernelRadius = C2dFastBlurComponent._amountToKernelRadius(v); + } + static _amountToKernelRadius(v) { + return C2dFastBlurComponent.getSpline().getValue(Math.min(1, v * 0.25)); + } + get _signalProxy() { + return true; + } +} +class WebGLFastBlurComponent extends Component { + static _template() { + const onUpdate = function(element, elementCore) { + if (elementCore._recalc & 2 + 128) { + const w = elementCore.w; + const h = elementCore.h; + let cur = elementCore; + do { + cur = cur._children[0]; + cur._element.w = w; + cur._element.h = h; + } while (cur._children); + } + }; + return { + Textwrap: { rtt: true, forceZIndexContext: true, renderOffscreen: true, Content: {} }, + Layers: { + L0: { rtt: true, onUpdate, renderOffscreen: true, visible: false, Content: { shader: { type: BoxBlurShader } } }, + L1: { rtt: true, onUpdate, renderOffscreen: true, visible: false, Content: { shader: { type: BoxBlurShader } } }, + L2: { rtt: true, onUpdate, renderOffscreen: true, visible: false, Content: { shader: { type: BoxBlurShader } } }, + L3: { rtt: true, onUpdate, renderOffscreen: true, visible: false, Content: { shader: { type: BoxBlurShader } } } + }, + Result: { shader: { type: FastBlurOutputShader }, visible: false } + }; + } + get _signalProxy() { + return true; + } + constructor(stage) { + super(stage); + this._textwrap = this.sel("Textwrap"); + this._wrapper = this.sel("Textwrap>Content"); + this._layers = this.sel("Layers"); + this._output = this.sel("Result"); + this._amount = 0; + this._paddingX = 0; + this._paddingY = 0; + } + _buildLayers() { + const filterShaderSettings = [{ x: 1, y: 0, kernelRadius: 1 }, { x: 0, y: 1, kernelRadius: 1 }, { x: 1.5, y: 0, kernelRadius: 1 }, { x: 0, y: 1.5, kernelRadius: 1 }]; + const filterShaders = filterShaderSettings.map((s) => { + const shader = Shader.create(this.stage, Object.assign({ type: LinearBlurShader }, s)); + return shader; + }); + this._setLayerTexture(this.getLayerContents(0), this._textwrap.getTexture(), []); + this._setLayerTexture(this.getLayerContents(1), this.getLayer(0).getTexture(), [filterShaders[0], filterShaders[1]]); + this._setLayerTexture(this.getLayerContents(2), this.getLayer(1).getTexture(), [filterShaders[0], filterShaders[1], filterShaders[2], filterShaders[3]]); + this._setLayerTexture(this.getLayerContents(3), this.getLayer(2).getTexture(), [filterShaders[0], filterShaders[1], filterShaders[2], filterShaders[3]]); + } + _setLayerTexture(element, texture, steps) { + if (!steps.length) { + element.texture = texture; + } else { + const step = steps.pop(); + const child = element.stage.c({ rtt: true, shader: step }); + this._setLayerTexture(child, texture, steps); + element.childList.add(child); + } + return element; + } + get content() { + return this.sel("Textwrap>Content"); + } + set content(v) { + this.sel("Textwrap>Content").patch(v, true); + } + set padding(v) { + this._paddingX = v; + this._paddingY = v; + this._updateBlurSize(); + } + set paddingX(v) { + this._paddingX = v; + this._updateBlurSize(); + } + set paddingY(v) { + this._paddingY = v; + this._updateBlurSize(); + } + getLayer(i) { + return this._layers.sel("L" + i); + } + getLayerContents(i) { + return this.getLayer(i).sel("Content"); + } + _onResize() { + this._updateBlurSize(); + } + _updateBlurSize() { + let w = this.renderWidth; + let h = this.renderHeight; + let paddingX = this._paddingX; + let paddingY = this._paddingY; + let fw = w + paddingX * 2; + let fh = h + paddingY * 2; + this._textwrap.w = fw; + this._wrapper.x = paddingX; + this.getLayer(0).w = this.getLayerContents(0).w = fw / 2; + this.getLayer(1).w = this.getLayerContents(1).w = fw / 4; + this.getLayer(2).w = this.getLayerContents(2).w = fw / 8; + this.getLayer(3).w = this.getLayerContents(3).w = fw / 16; + this._output.x = -paddingX; + this._textwrap.x = -paddingX; + this._output.w = fw; + this._textwrap.h = fh; + this._wrapper.y = paddingY; + this.getLayer(0).h = this.getLayerContents(0).h = fh / 2; + this.getLayer(1).h = this.getLayerContents(1).h = fh / 4; + this.getLayer(2).h = this.getLayerContents(2).h = fh / 8; + this.getLayer(3).h = this.getLayerContents(3).h = fh / 16; + this._output.y = -paddingY; + this._textwrap.y = -paddingY; + this._output.h = fh; + this.w = w; + this.h = h; + } + set amount(v) { + this._amount = v; + this._update(); + } + get amount() { + return this._amount; + } + _update() { + let v = Math.min(4, Math.max(0, this._amount)); + if (v === 0) { + this._textwrap.renderToTexture = false; + this._output.shader.otherTextureSource = null; + this._output.visible = false; + } else { + this._textwrap.renderToTexture = true; + this._output.visible = true; + this.getLayer(0).visible = v > 0; + this.getLayer(1).visible = v > 1; + this.getLayer(2).visible = v > 2; + this.getLayer(3).visible = v > 3; + if (v <= 1) { + this._output.texture = this._textwrap.getTexture(); + this._output.shader.otherTextureSource = this.getLayer(0).getTexture(); + this._output.shader.a = v; + } else if (v <= 2) { + this._output.texture = this.getLayer(0).getTexture(); + this._output.shader.otherTextureSource = this.getLayer(1).getTexture(); + this._output.shader.a = v - 1; + } else if (v <= 3) { + this._output.texture = this.getLayer(1).getTexture(); + this._output.shader.otherTextureSource = this.getLayer(2).getTexture(); + this._output.shader.a = v - 2; + } else if (v <= 4) { + this._output.texture = this.getLayer(2).getTexture(); + this._output.shader.otherTextureSource = this.getLayer(3).getTexture(); + this._output.shader.a = v - 3; + } + } + } + set shader(s) { + super.shader = s; + if (!this.renderToTexture) { + console.warn("[Lightning] Please enable renderToTexture to use with a shader."); + } + } + _firstActive() { + this._buildLayers(); + } +} +class FastBlurOutputShader extends DefaultShader$1 { + constructor(ctx) { + super(ctx); + this._a = 0; + this._otherTextureSource = null; + } + get a() { + return this._a; + } + set a(v) { + this._a = v; + this.redraw(); + } + set otherTextureSource(v) { + this._otherTextureSource = v; + this.redraw(); + } + setupUniforms(operation) { + super.setupUniforms(operation); + this._setUniform("a", this._a, this.gl.uniform1f); + this._setUniform("uSampler2", 1, this.gl.uniform1i); + } + beforeDraw(operation) { + let glTexture = this._otherTextureSource ? this._otherTextureSource.nativeTexture : null; + let gl = this.gl; + gl.activeTexture(gl.TEXTURE1); + gl.bindTexture(gl.TEXTURE_2D, glTexture); + gl.activeTexture(gl.TEXTURE0); + } +} +FastBlurOutputShader.fragmentShaderSource = ` + #ifdef GL_ES + # ifdef GL_FRAGMENT_PRECISION_HIGH + precision highp float; + # else + precision lowp float; + # endif + #endif + varying vec2 vTextureCoord; + varying vec4 vColor; + uniform sampler2D uSampler; + uniform sampler2D uSampler2; + uniform float a; + void main(void){ + if (a == 1.0) { + gl_FragColor = texture2D(uSampler2, vTextureCoord) * vColor; + } else { + gl_FragColor = ((1.0 - a) * texture2D(uSampler, vTextureCoord) + (a * texture2D(uSampler2, vTextureCoord))) * vColor; + } + } +`; +class BloomComponent extends Component { + static _template() { + const onUpdate = function(element, elementCore) { + if (elementCore._recalc & 2 + 128) { + const w = elementCore.w; + const h = elementCore.h; + let cur = elementCore; + do { + cur = cur._children[0]; + cur._element.w = w; + cur._element.h = h; + } while (cur._children); + } + }; + return { + Textwrap: { + rtt: true, + forceZIndexContext: true, + renderOffscreen: true, + BloomBase: { + shader: { type: BloomBaseShader }, + Content: {} + } + }, + Layers: { + L0: { rtt: true, onUpdate, scale: 2, pivot: 0, visible: false, Content: { shader: { type: BoxBlurShader } } }, + L1: { rtt: true, onUpdate, scale: 4, pivot: 0, visible: false, Content: { shader: { type: BoxBlurShader } } }, + L2: { rtt: true, onUpdate, scale: 8, pivot: 0, visible: false, Content: { shader: { type: BoxBlurShader } } }, + L3: { rtt: true, onUpdate, scale: 16, pivot: 0, visible: false, Content: { shader: { type: BoxBlurShader } } } + } + }; + } + get _signalProxy() { + return true; + } + constructor(stage) { + super(stage); + this._textwrap = this.sel("Textwrap"); + this._wrapper = this.sel("Textwrap.Content"); + this._layers = this.sel("Layers"); + this._amount = 0; + this._paddingX = 0; + this._paddingY = 0; + } + _build() { + const filterShaderSettings = [{ x: 1, y: 0, kernelRadius: 3 }, { x: 0, y: 1, kernelRadius: 3 }, { x: 1.5, y: 0, kernelRadius: 3 }, { x: 0, y: 1.5, kernelRadius: 3 }]; + const filterShaders = filterShaderSettings.map((s) => { + const shader = this.stage.createShader(Object.assign({ type: LinearBlurShader }, s)); + return shader; + }); + this._setLayerTexture(this.getLayerContents(0), this._textwrap.getTexture(), []); + this._setLayerTexture(this.getLayerContents(1), this.getLayer(0).getTexture(), [filterShaders[0], filterShaders[1]]); + this._setLayerTexture(this.getLayerContents(2), this.getLayer(1).getTexture(), [filterShaders[0], filterShaders[1], filterShaders[2], filterShaders[3]]); + this._setLayerTexture(this.getLayerContents(3), this.getLayer(2).getTexture(), [filterShaders[0], filterShaders[1], filterShaders[2], filterShaders[3]]); + } + _setLayerTexture(element, texture, steps) { + if (!steps.length) { + element.texture = texture; + } else { + const step = steps.pop(); + const child = element.stage.c({ rtt: true, shader: step }); + this._setLayerTexture(child, texture, steps); + element.childList.add(child); + } + return element; + } + get content() { + return this.sel("Textwrap.Content"); + } + set content(v) { + this.sel("Textwrap.Content").patch(v); + } + set padding(v) { + this._paddingX = v; + this._paddingY = v; + this._updateBlurSize(); + } + set paddingX(v) { + this._paddingX = v; + this._updateBlurSize(); + } + set paddingY(v) { + this._paddingY = v; + this._updateBlurSize(); + } + getLayer(i) { + return this._layers.sel("L" + i); + } + getLayerContents(i) { + return this.getLayer(i).sel("Content"); + } + _onResize() { + this._updateBlurSize(); + } + _updateBlurSize() { + let w = this.renderWidth; + let h = this.renderHeight; + let paddingX = this._paddingX; + let paddingY = this._paddingY; + let fw = w + paddingX * 2; + let fh = h + paddingY * 2; + this._textwrap.w = fw; + this._wrapper.x = paddingX; + this.getLayer(0).w = this.getLayerContents(0).w = fw / 2; + this.getLayer(1).w = this.getLayerContents(1).w = fw / 4; + this.getLayer(2).w = this.getLayerContents(2).w = fw / 8; + this.getLayer(3).w = this.getLayerContents(3).w = fw / 16; + this._textwrap.x = -paddingX; + this._textwrap.h = fh; + this._wrapper.y = paddingY; + this.getLayer(0).h = this.getLayerContents(0).h = fh / 2; + this.getLayer(1).h = this.getLayerContents(1).h = fh / 4; + this.getLayer(2).h = this.getLayerContents(2).h = fh / 8; + this.getLayer(3).h = this.getLayerContents(3).h = fh / 16; + this._textwrap.y = -paddingY; + this.w = w; + this.h = h; + } + set amount(v) { + this._amount = v; + this._update(); + } + get amount() { + return this._amount; + } + _update() { + let v = Math.min(4, Math.max(0, this._amount)); + if (v > 0) { + this.getLayer(0).visible = v > 0; + this.getLayer(1).visible = v > 1; + this.getLayer(2).visible = v > 2; + this.getLayer(3).visible = v > 3; + } + } + set shader(s) { + super.shader = s; + if (!this.renderToTexture) { + console.warn("[Lightning] Please enable renderToTexture to use with a shader."); + } + } + _firstActive() { + this._build(); + } +} +class BloomBaseShader extends DefaultShader$1 { +} +BloomBaseShader.fragmentShaderSource = ` + #ifdef GL_ES + # ifdef GL_FRAGMENT_PRECISION_HIGH + precision highp float; + # else + precision lowp float; + # endif + #endif + varying vec2 vTextureCoord; + varying vec4 vColor; + uniform sampler2D uSampler; + void main(void){ + vec4 color = texture2D(uSampler, vTextureCoord) * vColor; + float m = max(max(color.r, color.g), color.b); + float c = max(0.0, (m - 0.80)) * 5.0; + color = color * c; + gl_FragColor = color; + } +`; +class SmoothScaleComponent extends Component { + static _template() { + return { + ContentWrap: { + renderOffscreen: true, + forceZIndexContext: true, + onAfterUpdate: SmoothScaleComponent._updateDimensions, + Content: {} + }, + Scale: { visible: false } + }; + } + constructor(stage) { + super(stage); + this._smoothScale = 1; + this._iterations = 0; + } + get content() { + return this.tag("Content"); + } + set content(v) { + this.tag("Content").patch(v, true); + } + get smoothScale() { + return this._smoothScale; + } + set smoothScale(v) { + if (this._smoothScale !== v) { + let its = 0; + while (v < 0.5 && its < 12) { + its++; + v = v * 2; + } + this.scale = v; + this._setIterations(its); + this._smoothScale = v; + } + } + _setIterations(its) { + if (this._iterations !== its) { + const scalers = this.sel("Scale").childList; + const content = this.sel("ContentWrap"); + while (scalers.length < its) { + const first = scalers.length === 0; + const texture = first ? content.getTexture() : scalers.last.getTexture(); + scalers.a({ rtt: true, renderOffscreen: true, texture }); + } + SmoothScaleComponent._updateDimensions(this.tag("ContentWrap"), true); + const useScalers = its > 0; + this.patch({ + ContentWrap: { renderToTexture: useScalers }, + Scale: { visible: useScalers } + }); + for (let i = 0, n = scalers.length; i < n; i++) { + scalers.getAt(i).patch({ + visible: i < its, + renderOffscreen: i !== its - 1 + }); + } + this._iterations = its; + } + } + static _updateDimensions(contentWrap, force) { + const content = contentWrap.children[0]; + let w = content.renderWidth; + let h = content.renderHeight; + if (w !== contentWrap.w || h !== contentWrap.h || force) { + contentWrap.w = w; + contentWrap.h = h; + const scalers = contentWrap.parent.tag("Scale").children; + for (let i = 0, n = scalers.length; i < n; i++) { + w = w * 0.5; + h = h * 0.5; + scalers[i].w = w; + scalers[i].h = h; + } + } + } + get _signalProxy() { + return true; + } +} +class BorderComponent extends Component { + static _template() { + return { + Content: {}, + Borders: { + Top: { rect: true, visible: false, mountY: 1 }, + Right: { rect: true, visible: false }, + Bottom: { rect: true, visible: false }, + Left: { rect: true, visible: false, mountX: 1 } + } + }; + } + get _signalProxy() { + return true; + } + constructor(stage) { + super(stage); + this._borderTop = this.tag("Top"); + this._borderRight = this.tag("Right"); + this._borderBottom = this.tag("Bottom"); + this._borderLeft = this.tag("Left"); + this.onAfterUpdate = function(element) { + const content = element.childList.first; + let w = element.core.w || content.renderWidth; + let h = element.core.h || content.renderHeight; + element._borderTop.w = w; + element._borderBottom.y = h; + element._borderBottom.w = w; + element._borderLeft.h = h + element._borderTop.h + element._borderBottom.h; + element._borderLeft.y = -element._borderTop.h; + element._borderRight.x = w; + element._borderRight.h = h + element._borderTop.h + element._borderBottom.h; + element._borderRight.y = -element._borderTop.h; + }; + this.borderWidth = 1; + } + get content() { + return this.sel("Content"); + } + set content(v) { + this.sel("Content").patch(v, true); + } + get borderWidth() { + return this.borderWidthTop; + } + get borderWidthTop() { + return this._borderTop.h; + } + get borderWidthRight() { + return this._borderRight.w; + } + get borderWidthBottom() { + return this._borderBottom.h; + } + get borderWidthLeft() { + return this._borderLeft.w; + } + set borderWidth(v) { + this.borderWidthTop = v; + this.borderWidthRight = v; + this.borderWidthBottom = v; + this.borderWidthLeft = v; + } + set borderWidthTop(v) { + this._borderTop.h = v; + this._borderTop.visible = v > 0; + } + set borderWidthRight(v) { + this._borderRight.w = v; + this._borderRight.visible = v > 0; + } + set borderWidthBottom(v) { + this._borderBottom.h = v; + this._borderBottom.visible = v > 0; + } + set borderWidthLeft(v) { + this._borderLeft.w = v; + this._borderLeft.visible = v > 0; + } + get colorBorder() { + return this.colorBorderTop; + } + get colorBorderTop() { + return this._borderTop.color; + } + get colorBorderRight() { + return this._borderRight.color; + } + get colorBorderBottom() { + return this._borderBottom.color; + } + get colorBorderLeft() { + return this._borderLeft.color; + } + set colorBorder(v) { + this.colorBorderTop = v; + this.colorBorderRight = v; + this.colorBorderBottom = v; + this.colorBorderLeft = v; + } + set colorBorderTop(v) { + this._borderTop.color = v; + } + set colorBorderRight(v) { + this._borderRight.color = v; + } + set colorBorderBottom(v) { + this._borderBottom.color = v; + } + set colorBorderLeft(v) { + this._borderLeft.color = v; + } + get borderTop() { + return this._borderTop; + } + set borderTop(settings) { + this.borderTop.patch(settings); + } + get borderRight() { + return this._borderRight; + } + set borderRight(settings) { + this.borderRight.patch(settings); + } + get borderBottom() { + return this._borderBottom; + } + set borderBottom(settings) { + this.borderBottom.patch(settings); + } + get borderLeft() { + return this._borderLeft; + } + set borderLeft(settings) { + this.borderLeft.patch(settings); + } + set borders(settings) { + this.borderTop = settings; + this.borderLeft = settings; + this.borderBottom = settings; + this.borderRight = settings; + } +} +class WebGLGrayscaleShader extends DefaultShader$1 { + constructor(context) { + super(context); + this._amount = 1; + } + static getC2d() { + return C2dGrayscaleShader; + } + set amount(v) { + this._amount = v; + this.redraw(); + } + get amount() { + return this._amount; + } + useDefault() { + return this._amount === 0; + } + setupUniforms(operation) { + super.setupUniforms(operation); + this._setUniform("amount", this._amount, this.gl.uniform1f); + } +} +WebGLGrayscaleShader.fragmentShaderSource = ` + #ifdef GL_ES + # ifdef GL_FRAGMENT_PRECISION_HIGH + precision highp float; + # else + precision lowp float; + # endif + #endif + varying vec2 vTextureCoord; + varying vec4 vColor; + uniform sampler2D uSampler; + uniform float amount; + void main(void){ + vec4 color = texture2D(uSampler, vTextureCoord) * vColor; + float grayness = 0.2 * color.r + 0.6 * color.g + 0.2 * color.b; + gl_FragColor = vec4(amount * vec3(grayness, grayness, grayness) + (1.0 - amount) * color.rgb, color.a); + } +`; +class C2dGrayscaleShader extends DefaultShader2 { + constructor(context) { + super(context); + this._amount = 1; + } + static getWebGL() { + return WebGLGrayscaleShader; + } + set amount(v) { + this._amount = v; + this.redraw(); + } + get amount() { + return this._amount; + } + useDefault() { + return this._amount === 0; + } + _beforeDrawEl({ target }) { + target.ctx.filter = "grayscale(" + this._amount + ")"; + } + _afterDrawEl({ target }) { + target.ctx.filter = "none"; + } +} +class DitheringShader extends DefaultShader$1 { + constructor(ctx) { + super(ctx); + this._noiseTexture = new NoiseTexture(ctx.stage); + this._graining = 1 / 256; + this._random = false; + } + set graining(v) { + this._graining = v; + this.redraw(); + } + set random(v) { + this._random = v; + this.redraw(); + } + setExtraAttribsInBuffer(operation) { + this._noiseTexture.load(); + let offset = operation.extraAttribsDataByteOffset / 4; + let floats = operation.quads.floats; + let length = operation.length; + for (let i = 0; i < length; i++) { + let brx = operation.getElementWidth(i) / this._noiseTexture.getRenderWidth(); + let bry = operation.getElementHeight(i) / this._noiseTexture.getRenderHeight(); + let ulx = 0; + let uly = 0; + if (this._random) { + ulx = Math.random(); + uly = Math.random(); + brx += ulx; + bry += uly; + if (Math.random() < 0.5) { + const t = ulx; + ulx = brx; + brx = t; + } + if (Math.random() < 0.5) { + const t = uly; + uly = bry; + bry = t; + } + } + floats[offset] = ulx; + floats[offset + 1] = uly; + floats[offset + 2] = brx; + floats[offset + 3] = uly; + floats[offset + 4] = brx; + floats[offset + 5] = bry; + floats[offset + 6] = ulx; + floats[offset + 7] = bry; + offset += 8; + } + } + beforeDraw(operation) { + let gl = this.gl; + gl.vertexAttribPointer(this._attrib("aNoiseTextureCoord"), 2, gl.FLOAT, false, 8, this.getVertexAttribPointerOffset(operation)); + let glTexture = this._noiseTexture.source.nativeTexture; + gl.activeTexture(gl.TEXTURE1); + gl.bindTexture(gl.TEXTURE_2D, glTexture); + gl.activeTexture(gl.TEXTURE0); + } + getExtraAttribBytesPerVertex() { + return 8; + } + setupUniforms(operation) { + super.setupUniforms(operation); + this._setUniform("uNoiseSampler", 1, this.gl.uniform1i); + this._setUniform("graining", 2 * this._graining, this.gl.uniform1f); + } + enableAttribs() { + super.enableAttribs(); + let gl = this.gl; + gl.enableVertexAttribArray(this._attrib("aNoiseTextureCoord")); + } + disableAttribs() { + super.disableAttribs(); + let gl = this.gl; + gl.disableVertexAttribArray(this._attrib("aNoiseTextureCoord")); + } + useDefault() { + return this._graining === 0; + } + afterDraw(operation) { + if (this._random) { + this.redraw(); + } + } +} +DitheringShader.vertexShaderSource = ` + #ifdef GL_ES + # ifdef GL_FRAGMENT_PRECISION_HIGH + precision highp float; + # else + precision lowp float; + # endif + #endif + attribute vec2 aVertexPosition; + attribute vec2 aTextureCoord; + attribute vec2 aNoiseTextureCoord; + attribute vec4 aColor; + uniform vec2 projection; + varying vec2 vTextureCoord; + varying vec2 vNoiseTextureCoord; + varying vec4 vColor; + void main(void){ + gl_Position = vec4(aVertexPosition.x * projection.x - 1.0, aVertexPosition.y * -abs(projection.y) + 1.0, 0.0, 1.0); + vTextureCoord = aTextureCoord; + vNoiseTextureCoord = aNoiseTextureCoord; + vColor = aColor; + gl_Position.y = -sign(projection.y) * gl_Position.y; + } +`; +DitheringShader.fragmentShaderSource = ` + #ifdef GL_ES + # ifdef GL_FRAGMENT_PRECISION_HIGH + precision highp float; + # else + precision lowp float; + # endif + #endif + varying vec2 vTextureCoord; + varying vec2 vNoiseTextureCoord; + varying vec4 vColor; + uniform sampler2D uSampler; + uniform sampler2D uNoiseSampler; + uniform float graining; + void main(void){ + vec4 noise = texture2D(uNoiseSampler, vNoiseTextureCoord); + vec4 color = texture2D(uSampler, vTextureCoord); + gl_FragColor = (color * vColor) + graining * (noise.r - 0.5); + } +`; +class CircularPushShader extends DefaultShader$1 { + constructor(ctx) { + super(ctx); + this._inputValue = 0; + this._maxDerivative = 0.01; + this._normalizedValue = 0; + this._offset = 0; + this._amount = 0.1; + this._aspectRatio = 1; + this._offsetX = 0; + this._offsetY = 0; + this.buckets = 100; + } + get aspectRatio() { + return this._aspectRatio; + } + set aspectRatio(v) { + this._aspectRatio = v; + this.redraw(); + } + get offsetX() { + return this._offsetX; + } + set offsetX(v) { + this._offsetX = v; + this.redraw(); + } + get offsetY() { + return this._offsetY; + } + set offsetY(v) { + this._offsetY = v; + this.redraw(); + } + set amount(v) { + this._amount = v; + this.redraw(); + } + get amount() { + return this._amount; + } + set inputValue(v) { + this._inputValue = v; + } + get inputValue() { + return this._inputValue; + } + set maxDerivative(v) { + this._maxDerivative = v; + } + get maxDerivative() { + return this._maxDerivative; + } + set buckets(v) { + if (v > 100) { + console.warn("[Lightning] CircularPushShader: supports max 100 buckets"); + v = 100; + } + this._buckets = v; + this._values = new Uint8Array(this._getValues(v)); + this.redraw(); + } + get buckets() { + return this._buckets; + } + _getValues(n) { + const v = []; + for (let i = 0; i < n; i++) { + v.push(this._inputValue); + } + return v; + } + progress(o) { + this._offset += o * this._buckets; + const full = Math.floor(this._offset); + this._offset -= full; + this._shiftBuckets(full); + this.redraw(); + } + _shiftBuckets(n) { + for (let i = this._buckets - 1; i >= 0; i--) { + const targetIndex = i - n; + if (targetIndex < 0) { + this._normalizedValue = Math.min(this._normalizedValue + this._maxDerivative, Math.max(this._normalizedValue - this._maxDerivative, this._inputValue)); + this._values[i] = 255 * this._normalizedValue; + } else { + this._values[i] = this._values[targetIndex]; + } + } + } + set offset(v) { + this._offset = v; + this.redraw(); + } + setupUniforms(operation) { + super.setupUniforms(operation); + this._setUniform("aspectRatio", this._aspectRatio, this.gl.uniform1f); + this._setUniform("offsetX", this._offsetX, this.gl.uniform1f); + this._setUniform("offsetY", this._offsetY, this.gl.uniform1f); + this._setUniform("amount", this._amount, this.gl.uniform1f); + this._setUniform("offset", this._offset, this.gl.uniform1f); + this._setUniform("buckets", this._buckets, this.gl.uniform1f); + this._setUniform("uValueSampler", 1, this.gl.uniform1i); + } + useDefault() { + return this._amount === 0; + } + beforeDraw(operation) { + const gl = this.gl; + gl.activeTexture(gl.TEXTURE1); + if (!this._valuesTexture) { + this._valuesTexture = gl.createTexture(); + gl.bindTexture(gl.TEXTURE_2D, this._valuesTexture); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); + if (Utils$1.isNode) { + gl.pixelStorei(gl.UNPACK_FLIP_BLUE_RED, false); + } + gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false); + } else { + gl.bindTexture(gl.TEXTURE_2D, this._valuesTexture); + } + gl.texImage2D(gl.TEXTURE_2D, 0, gl.ALPHA, this._buckets, 1, 0, gl.ALPHA, gl.UNSIGNED_BYTE, this._values); + gl.activeTexture(gl.TEXTURE0); + } + cleanup() { + if (this._valuesTexture) { + this.gl.deleteTexture(this._valuesTexture); + } + } +} +CircularPushShader.vertexShaderSource = ` + #ifdef GL_ES + # ifdef GL_FRAGMENT_PRECISION_HIGH + precision highp float; + # else + precision lowp float; + # endif + #endif + attribute vec2 aVertexPosition; + attribute vec2 aTextureCoord; + attribute vec4 aColor; + uniform vec2 projection; + uniform float offsetX; + uniform float offsetY; + uniform float aspectRatio; + varying vec2 vTextureCoord; + varying vec2 vPos; + varying vec4 vColor; + void main(void){ + gl_Position = vec4(aVertexPosition.x * projection.x - 1.0, aVertexPosition.y * -abs(projection.y) + 1.0, 0.0, 1.0); + vTextureCoord = aTextureCoord; + vPos = vTextureCoord * 2.0 - 1.0; + vPos.y = vPos.y * aspectRatio; + vPos.y = vPos.y + offsetY; + vPos.x = vPos.x + offsetX; + vColor = aColor; + gl_Position.y = -sign(projection.y) * gl_Position.y; + } +`; +CircularPushShader.fragmentShaderSource = ` + #ifdef GL_ES + # ifdef GL_FRAGMENT_PRECISION_HIGH + precision highp float; + # else + precision lowp float; + # endif + #endif + varying vec2 vTextureCoord; + varying vec4 vColor; + varying vec2 vPos; + uniform float amount; + uniform float offset; + uniform float values[100]; + uniform float buckets; + uniform sampler2D uSampler; + uniform sampler2D uValueSampler; + void main(void){ + float l = length(vPos); + float m = (l * buckets * 0.678 - offset) / buckets; + float f = texture2D(uValueSampler, vec2(m, 0.0)).a * amount; + vec2 unit = vPos / l; + gl_FragColor = texture2D(uSampler, vTextureCoord - f * unit) * vColor; + } +`; +class InversionShader extends DefaultShader$1 { + constructor(context) { + super(context); + this._amount = 1; + } + set amount(v) { + this._amount = v; + this.redraw(); + } + get amount() { + return this._amount; + } + useDefault() { + return this._amount === 0; + } + setupUniforms(operation) { + super.setupUniforms(operation); + this._setUniform("amount", this._amount, this.gl.uniform1f); + } +} +InversionShader.fragmentShaderSource = ` + #ifdef GL_ES + # ifdef GL_FRAGMENT_PRECISION_HIGH + precision highp float; + # else + precision lowp float; + # endif + #endif + varying vec2 vTextureCoord; + varying vec4 vColor; + uniform sampler2D uSampler; + uniform float amount; + void main(void){ + vec4 color = texture2D(uSampler, vTextureCoord); + color.rgb = color.rgb * (1.0 - amount) + amount * (1.0 * color.a - color.rgb); + gl_FragColor = color * vColor; + } +`; +class OutlineShader extends DefaultShader$1 { + constructor(ctx) { + super(ctx); + this._width = 5; + this._col = 4294967295; + this._color = [1, 1, 1, 1]; + } + set width(v) { + this._width = v; + this.redraw(); + } + get color() { + return this._col; + } + set color(v) { + if (this._col !== v) { + const col = StageUtils.getRgbaComponentsNormalized(v); + col[0] = col[0] * col[3]; + col[1] = col[1] * col[3]; + col[2] = col[2] * col[3]; + this._color = col; + this.redraw(); + this._col = v; + } + } + useDefault() { + return this._width === 0 || this._col[3] === 0; + } + setupUniforms(operation) { + super.setupUniforms(operation); + let gl = this.gl; + this._setUniform("color", new Float32Array(this._color), gl.uniform4fv); + } + enableAttribs() { + super.enableAttribs(); + this.gl.enableVertexAttribArray(this._attrib("aCorner")); + } + disableAttribs() { + super.disableAttribs(); + this.gl.disableVertexAttribArray(this._attrib("aCorner")); + } + setExtraAttribsInBuffer(operation) { + let offset = operation.extraAttribsDataByteOffset / 4; + let floats = operation.quads.floats; + let length = operation.length; + for (let i = 0; i < length; i++) { + const elementCore = operation.getElementCore(i); + const ddw = this._width / elementCore.w; + const dw = ddw / (1 - 2 * ddw); + const ddh = this._width / elementCore.h; + const dh = ddh / (1 - 2 * ddh); + floats[offset] = -dw; + floats[offset + 1] = -dh; + floats[offset + 2] = 1 + dw; + floats[offset + 3] = -dh; + floats[offset + 4] = 1 + dw; + floats[offset + 5] = 1 + dh; + floats[offset + 6] = -dw; + floats[offset + 7] = 1 + dh; + offset += 8; + } + } + beforeDraw(operation) { + let gl = this.gl; + gl.vertexAttribPointer(this._attrib("aCorner"), 2, gl.FLOAT, false, 8, this.getVertexAttribPointerOffset(operation)); + } + getExtraAttribBytesPerVertex() { + return 8; + } +} +OutlineShader.vertexShaderSource = ` + #ifdef GL_ES + # ifdef GL_FRAGMENT_PRECISION_HIGH + precision highp float; + # else + precision lowp float; + # endif + #endif + attribute vec2 aVertexPosition; + attribute vec2 aTextureCoord; + attribute vec4 aColor; + attribute vec2 aCorner; + uniform vec2 projection; + varying vec2 vTextureCoord; + varying vec2 vCorner; + varying vec4 vColor; + void main(void){ + gl_Position = vec4(aVertexPosition.x * projection.x - 1.0, aVertexPosition.y * -abs(projection.y) + 1.0, 0.0, 1.0); + vTextureCoord = aTextureCoord; + vCorner = aCorner; + vColor = aColor; + gl_Position.y = -sign(projection.y) * gl_Position.y; + } +`; +OutlineShader.fragmentShaderSource = ` + #ifdef GL_ES + # ifdef GL_FRAGMENT_PRECISION_HIGH + precision highp float; + # else + precision lowp float; + # endif + #endif + varying vec2 vTextureCoord; + varying vec4 vColor; + varying vec2 vCorner; + uniform vec4 color; + uniform sampler2D uSampler; + void main(void){ + vec2 m = min(vCorner, 1.0 - vCorner); + float value = step(0.0, min(m.x, m.y)); + gl_FragColor = mix(color, texture2D(uSampler, vTextureCoord) * vColor, value); + } +`; +class PixelateShader extends DefaultShader$1 { + constructor(ctx) { + super(ctx); + this._size = new Float32Array([4, 4]); + } + get x() { + return this._size[0]; + } + set x(v) { + this._size[0] = v; + this.redraw(); + } + get y() { + return this._size[1]; + } + set y(v) { + this._size[1] = v; + this.redraw(); + } + get size() { + return this._size[0]; + } + set size(v) { + this._size[0] = v; + this._size[1] = v; + this.redraw(); + } + useDefault() { + return this._size[0] === 0 && this._size[1] === 0; + } + static getWebGLImpl() { + return WebGLPixelateShaderImpl; + } + setupUniforms(operation) { + super.setupUniforms(operation); + let gl = this.gl; + this._setUniform("size", new Float32Array(this._size), gl.uniform2fv); + } + getExtraAttribBytesPerVertex() { + return 8; + } + enableAttribs() { + super.enableAttribs(); + this.gl.enableVertexAttribArray(this._attrib("aTextureRes")); + } + disableAttribs() { + super.disableAttribs(); + this.gl.disableVertexAttribArray(this._attrib("aTextureRes")); + } + setExtraAttribsInBuffer(operation) { + let offset = operation.extraAttribsDataByteOffset / 4; + let floats = operation.quads.floats; + let length = operation.length; + for (let i = 0; i < length; i++) { + let w = operation.quads.getTextureWidth(operation.index + i); + let h = operation.quads.getTextureHeight(operation.index + i); + floats[offset] = w; + floats[offset + 1] = h; + floats[offset + 2] = w; + floats[offset + 3] = h; + floats[offset + 4] = w; + floats[offset + 5] = h; + floats[offset + 6] = w; + floats[offset + 7] = h; + offset += 8; + } + } + beforeDraw(operation) { + let gl = this.gl; + gl.vertexAttribPointer(this._attrib("aTextureRes"), 2, gl.FLOAT, false, this.getExtraAttribBytesPerVertex(), this.getVertexAttribPointerOffset(operation)); + } +} +PixelateShader.vertexShaderSource = ` + #ifdef GL_ES + # ifdef GL_FRAGMENT_PRECISION_HIGH + precision highp float; + # else + precision lowp float; + # endif + #endif + attribute vec2 aVertexPosition; + attribute vec2 aTextureCoord; + attribute vec4 aColor; + attribute vec2 aTextureRes; + uniform vec2 projection; + varying vec2 vTextureCoord; + varying vec4 vColor; + varying vec2 vTextureRes; + void main(void){ + gl_Position = vec4(aVertexPosition.x * projection.x - 1.0, aVertexPosition.y * -abs(projection.y) + 1.0, 0.0, 1.0); + vTextureCoord = aTextureCoord; + vColor = aColor; + vTextureRes = aTextureRes; + gl_Position.y = -sign(projection.y) * gl_Position.y; + } +`; +PixelateShader.fragmentShaderSource = ` + #ifdef GL_ES + # ifdef GL_FRAGMENT_PRECISION_HIGH + precision highp float; + # else + precision lowp float; + # endif + #endif + varying vec2 vTextureCoord; + varying vec4 vColor; + varying vec2 vTextureRes; + + uniform vec2 size; + uniform sampler2D uSampler; + + vec2 mapCoord( vec2 coord ) + { + coord *= vTextureRes.xy; + return coord; + } + + vec2 unmapCoord( vec2 coord ) + { + coord /= vTextureRes.xy; + return coord; + } + + vec2 pixelate(vec2 coord, vec2 size) + { + return floor( coord / size ) * size; + } + + void main(void) + { + vec2 coord = mapCoord(vTextureCoord); + coord = pixelate(coord, size); + coord = unmapCoord(coord); + gl_FragColor = texture2D(uSampler, coord) * vColor; + } +`; +class RadialFilterShader extends DefaultShader$1 { + constructor(context) { + super(context); + this._radius = 0; + this._cutoff = 1; + } + set radius(v) { + this._radius = v; + this.redraw(); + } + get radius() { + return this._radius; + } + set cutoff(v) { + this._cutoff = v; + this.redraw(); + } + get cutoff() { + return this._cutoff; + } + useDefault() { + return this._radius === 0; + } + setupUniforms(operation) { + super.setupUniforms(operation); + this._setUniform("radius", 2 * (this._radius - 0.5) / operation.getRenderWidth(), this.gl.uniform1f); + this._setUniform("cutoff", 0.5 * operation.getRenderWidth() / this._cutoff, this.gl.uniform1f); + } +} +RadialFilterShader.vertexShaderSource = ` + #ifdef GL_ES + # ifdef GL_FRAGMENT_PRECISION_HIGH + precision highp float; + # else + precision lowp float; + # endif + #endif + attribute vec2 aVertexPosition; + attribute vec2 aTextureCoord; + attribute vec4 aColor; + uniform vec2 projection; + varying vec2 pos; + varying vec2 vTextureCoord; + varying vec4 vColor; + void main(void){ + gl_Position = vec4(aVertexPosition.x * projection.x - 1.0, aVertexPosition.y * -abs(projection.y) + 1.0, 0.0, 1.0); + vTextureCoord = aTextureCoord; + vColor = aColor; + gl_Position.y = -sign(projection.y) * gl_Position.y; + pos = gl_Position.xy; + } +`; +RadialFilterShader.fragmentShaderSource = ` + #ifdef GL_ES + # ifdef GL_FRAGMENT_PRECISION_HIGH + precision highp float; + # else + precision lowp float; + # endif + #endif + varying vec2 vTextureCoord; + varying vec2 pos; + varying vec4 vColor; + uniform sampler2D uSampler; + uniform float radius; + uniform float cutoff; + void main(void){ + vec4 color = texture2D(uSampler, vTextureCoord); + float f = max(0.0, min(1.0, 1.0 - (length(pos) - radius) * cutoff)); + gl_FragColor = texture2D(uSampler, vTextureCoord) * vColor * f; + } +`; +class RoundedRectangleShader extends DefaultShader$1 { + constructor(context) { + super(context); + this._blend = 0; + this._radius = [1, 1, 1, 1]; + this._stroke = 0; + this._fc = 16777215; + this._fillColor = this._getNormalizedColor(4294967295); + this._strokeColor = this._getNormalizedColor(16777215); + } + set blend(p) { + this._blend = Math.min(Math.max(p, 0), 1); + } + set radius(v) { + if (Array.isArray(v)) { + if (v.length === 2) { + this._radius = [v[0], v[1], v[0], v[1]]; + } else if (v.length === 3) { + this._radius = [v[0], v[1], v[2], this._radius[3]]; + } else if (v.length === 4) { + this._radius = v; + } else { + this._radius = [v[0], v[0], v[0], v[0]]; + } + } else { + this._radius = [v, v, v, v]; + } + this.redraw(); + } + get radius() { + return this._radius; + } + set topLeft(num) { + this._radius[0] = num; + this.redraw(); + } + get topLeft() { + return this._radius[0]; + } + set topRight(num) { + this._radius[1] = num; + this.redraw(); + } + get topRight() { + return this._radius[1]; + } + set bottomRight(num) { + this._radius[2] = num; + this.redraw(); + } + get bottomRight() { + return this._radius[2]; + } + set bottomLeft(num) { + this._radius[3] = num; + this.redraw(); + } + get bottomLeft() { + return this._radius[4]; + } + set strokeColor(argb) { + this._sc = argb; + this._strokeColor = this._getNormalizedColor(argb); + this.redraw(); + } + get strokeColor() { + return this._sc; + } + set fillColor(argb) { + this._fc = argb; + this._fillColor = this._getNormalizedColor(argb); + this.redraw(); + } + get fillColor() { + return this._fc; + } + set stroke(num) { + this._stroke = num; + this.redraw(); + } + get stroke() { + return this._stroke; + } + _getNormalizedColor(color) { + const col = StageUtils.getRgbaComponentsNormalized(color); + col[0] *= col[3]; + col[1] *= col[3]; + col[2] *= col[3]; + return new Float32Array(col); + } + setupUniforms(operation) { + super.setupUniforms(operation); + const owner = operation.shaderOwner; + const renderPrecision = this.ctx.stage.getRenderPrecision(); + const _radius = this._radius.map((r) => (r + 0.5) * renderPrecision); + this._setUniform("radius", new Float32Array(_radius), this.gl.uniform4fv); + this._setUniform("alpha", operation.getElementCore(0).renderContext.alpha, this.gl.uniform1f); + this._setUniform("blend", this._blend, this.gl.uniform1f); + this._setUniform("strokeColor", this._strokeColor, this.gl.uniform4fv); + this._setUniform("fillColor", this._fillColor, this.gl.uniform4fv); + this._setUniform("stroke", this._stroke * renderPrecision, this.gl.uniform1f); + this._setUniform("resolution", new Float32Array([owner._w * renderPrecision, owner._h * renderPrecision]), this.gl.uniform2fv); + } +} +RoundedRectangleShader.vertexShaderSource = ` + #ifdef GL_ES + # ifdef GL_FRAGMENT_PRECISION_HIGH + precision highp float; + # else + precision lowp float; + # endif + #endif + attribute vec2 aVertexPosition; + attribute vec2 aTextureCoord; + + attribute vec4 aColor; + uniform vec2 projection; + varying vec2 vTextureCoord; + varying vec4 vColor; + + void main(void){ + gl_Position = vec4(aVertexPosition.x * projection.x - 1.0, aVertexPosition.y * -abs(projection.y) + 1.0, 0.0, 1.0); + vTextureCoord = aTextureCoord; + vColor = aColor; + gl_Position.y = -sign(projection.y) * gl_Position.y; + } +`; +RoundedRectangleShader.fragmentShaderSource = ` + #ifdef GL_ES + # ifdef GL_FRAGMENT_PRECISION_HIGH + precision highp float; + # else + precision lowp float; + # endif + #endif + + #define PI 3.14159265359 + + varying vec2 vTextureCoord; + varying vec4 vColor; + + uniform sampler2D uSampler; + uniform vec2 resolution; + uniform vec4 radius; + uniform float stroke; + uniform vec4 strokeColor; + uniform vec4 fillColor; + uniform float alpha; + uniform float fill; + uniform float blend; + + float boxDist(vec2 p, vec2 size, float radius){ + size -= vec2(radius); + vec2 d = abs(p) - size; + return min(max(d.x, d.y), 0.0) + length(max(d, 0.0)) - radius; + } + + float fillMask(float dist){ + return clamp(-dist, 0.0, 1.0); + } + + float innerBorderMask(float dist, float width){ + float alpha1 = clamp(dist + width, 0.0, 1.0); + float alpha2 = clamp(dist, 0.0, 1.0); + return alpha1 - alpha2; + } + + void main() { + vec2 halfRes = 0.5 * resolution.xy; + float r = 0.0; + if (vTextureCoord.x < 0.5 && vTextureCoord.y < 0.5) { + r = radius[0]; + } else if (vTextureCoord.x >= 0.5 && vTextureCoord.y < 0.5) { + r = radius[1]; + } else if (vTextureCoord.x >= 0.5 && vTextureCoord.y >= 0.5) { + r = radius[2]; + } else { + r = radius[3]; + } + + float b = boxDist(vTextureCoord.xy * resolution - halfRes, halfRes - 0.005, r); + vec4 tex = texture2D(uSampler, vTextureCoord) * vColor; + vec4 blend = mix(vec4(1.0) * alpha, tex, blend); + vec4 layer1 = mix(vec4(0.0), tex * fillColor, fillMask(b)); + gl_FragColor = mix(layer1, blend * strokeColor, innerBorderMask(b, stroke)); + } +`; +class FadeOutShader extends DefaultShader$1 { + constructor(context) { + super(context); + this._fade = [0, 0, 0, 0]; + } + set top(num) { + this._fade[0] = num; + this.redraw(); + } + get top() { + return this._fade[0]; + } + set right(num) { + this._fade[1] = num; + this.redraw(); + } + get right() { + return this._fade[1]; + } + set bottom(num) { + this._fade[2] = num; + this.redraw(); + } + get bottom() { + return this._fade[2]; + } + set left(num) { + this._fade[3] = num; + this.redraw(); + } + get left() { + return this._fade[3]; + } + set fade(v) { + if (Array.isArray(v)) { + if (v.length === 2) { + this._fade = [v[0], v[1], v[0], v[1]]; + } else if (v.length === 3) { + this._fade = [v[0], v[1], v[2], this._fade[3]]; + } else if (v.length === 4) { + this._fade = v; + } else { + this._fade = [v[0], v[0], v[0], v[0]]; + } + } else { + this._fade = [v, v, v, v]; + } + this.redraw(); + } + get fade() { + return this._fade; + } + setupUniforms(operation) { + super.setupUniforms(operation); + const owner = operation.shaderOwner; + const renderPrecision = this.ctx.stage.getRenderPrecision(); + const fade = this._fade.map((f) => f * renderPrecision); + this._setUniform("fade", new Float32Array(fade), this.gl.uniform4fv); + this._setUniform("resolution", new Float32Array([owner._w * renderPrecision, owner._h * renderPrecision]), this.gl.uniform2fv); + } +} +FadeOutShader.fragmentShaderSource = ` + #ifdef GL_ES + # ifdef GL_FRAGMENT_PRECISION_HIGH + precision highp float; + # else + precision lowp float; + # endif + #endif + varying vec2 vTextureCoord; + varying vec4 vColor; + uniform sampler2D uSampler; + uniform vec2 resolution; + uniform vec4 fade; + + void main() { + vec4 color = texture2D(uSampler, vTextureCoord) * vColor; + vec2 halfRes = 0.5 * resolution.xy; + vec2 point = vTextureCoord.xy * resolution.xy; + + vec2 pos1; + vec2 pos2; + vec2 d; + float c; + float t = 0.0; + + if(fade[0] > 0.0) { + pos1 = vec2(point.x, point.y); + pos2 = vec2(point.x, point.y + fade[0]); + d = pos2 - pos1; + c = dot(pos1, d) / dot(d, d); + t = smoothstep(0.0, 1.0, clamp(c, 0.0, 1.0)); + color = mix(vec4(0.0), color, t); + } + + if(fade[1] > 0.0) { + vec2 pos1 = vec2(point.x - resolution.x - fade[1], vTextureCoord.y); + vec2 pos2 = vec2(point.x - resolution.x, vTextureCoord.y); + d = pos1 - pos2; + c = dot(pos2, d) / dot(d, d); + t = smoothstep(0.0, 1.0, clamp(c, 0.0, 1.0)); + color = mix(vec4(0.0), color, t); + } + + if(fade[2] > 0.0) { + vec2 pos1 = vec2(vTextureCoord.x, point.y - resolution.y - fade[2]); + vec2 pos2 = vec2(vTextureCoord.x, point.y - resolution.y); + d = pos1 - pos2; + c = dot(pos2, d) / dot(d, d); + t = smoothstep(0.0, 1.0, clamp(c, 0.0, 1.0)); + color = mix(vec4(0.0), color, t); + } + + if(fade[3] > 0.0) { + pos1 = vec2(point.x, point.y); + pos2 = vec2(point.x + fade[3], point.y); + d = pos2 - pos1; + c = dot(pos1, d) / dot(d, d); + t = smoothstep(0.0, 1.0, clamp(c, 0.0, 1.0)); + color = mix(vec4(0.0), color, t); + } + + gl_FragColor = color; + } +`; +class VignetteShader extends DefaultShader$1 { + constructor(context) { + super(context); + this._magnitude = 1.3; + this._intensity = 0.7; + this._pivot = [0.5, 0.5]; + } + setupUniforms(operation) { + super.setupUniforms(operation); + this._setUniform("magnitude", this._magnitude, this.gl.uniform1f); + this._setUniform("intensity", this._intensity, this.gl.uniform1f); + this._setUniform("pivot", new Float32Array(this._pivot), this.gl.uniform2fv); + this.redraw(); + } + set pivot(v) { + if (Array.isArray(v)) { + this._pivot = v; + } else { + this._pivot = [v, v]; + } + this.redraw(); + } + get pivotX() { + return this._pivot[0]; + } + set pivotX(v) { + this._pivot[0] = v; + this.redraw(); + } + get pivotY() { + return this._pivot[1]; + } + set pivotY(v) { + this._pivot[1] = v; + this.redraw(); + } + get intensity() { + return this._intensity; + } + set intensity(v) { + this._intensity = v; + this.redraw(); + } + get magnitude() { + return this._magnitude; + } + set magnitude(v) { + this._magnitude = v; + this.redraw(); + } +} +VignetteShader.vertexShaderSource = DefaultShader$1.vertexShaderSource; +VignetteShader.fragmentShaderSource = ` + #ifdef GL_ES + # ifdef GL_FRAGMENT_PRECISION_HIGH + precision highp float; + # else + precision lowp float; + # endif + #endif + varying vec2 vTextureCoord; + varying vec4 vColor; + uniform sampler2D uSampler; + + uniform float magnitude; + uniform float intensity; + uniform vec2 pivot; + + void main() { + vec2 uv = vTextureCoord.xy - pivot + vec2(0.5); + uv.x = clamp(uv.x, 0.0, 1.0); + uv.y = clamp(uv.y, 0.0, 1.0); + + uv *= 1.00 - uv.yx; + float vig = uv.x * uv.y * 25.0 * intensity; + vig = pow(vig, 0.45 * magnitude); + vec4 fragColor = vec4(vig) * vColor; + gl_FragColor = texture2D(uSampler, vTextureCoord) * fragColor; + + } +`; +class SpinnerShader extends DefaultShader$1 { + constructor(ctx) { + super(ctx); + this._radius = 100; + this._width = 50; + this._period = 1; + this._angle = 0.5; + this._smooth = 5e-3; + this._color = 4294967295; + this._backgroundColor = 4278190080; + this._time = Date.now(); + } + set radius(v) { + this._radius = v; + this.redraw(); + } + set width(v) { + this._width = v; + this.redraw(); + } + set period(v) { + this._period = v; + this.redraw(); + } + set angle(v) { + this._angle = v; + this.redraw(); + } + set smooth(v) { + this._smooth = v; + this.redraw(); + } + set color(v) { + this._color = v; + this.redraw(); + } + set backgroundColor(v) { + this._backgroundColor = v; + this.redraw(); + } + setupUniforms(operation) { + super.setupUniforms(operation); + const owner = operation.shaderOwner; + this._setUniform("iTime", Date.now() - this._time, this.gl.uniform1f); + const renderPrecision = this.ctx.stage.getRenderPrecision(); + this._setUniform("radius", this._radius * renderPrecision, this.gl.uniform1f); + this._setUniform("width", this._width * renderPrecision, this.gl.uniform1f); + this._setUniform("period", this._period, this.gl.uniform1f); + this._setUniform("angle", this._angle, this.gl.uniform1f); + this._setUniform("smooth", this._smooth, this.gl.uniform1f); + this._setUniform("color", new Float32Array(StageUtils.getRgbaComponentsNormalized(this._color)), this.gl.uniform4fv); + this._setUniform("backgroundColor", new Float32Array(StageUtils.getRgbaComponentsNormalized(this._backgroundColor)), this.gl.uniform4fv); + this._setUniform("resolution", new Float32Array([owner._w * renderPrecision, owner._h * renderPrecision]), this.gl.uniform2fv); + this.redraw(); + } +} +SpinnerShader.vertexShaderSource = DefaultShader$1.vertexShaderSource; +SpinnerShader.fragmentShaderSource = ` + #ifdef GL_ES + # ifdef GL_FRAGMENT_PRECISION_HIGH + precision highp float; + # else + precision lowp float; + # endif + #endif + varying vec2 vTextureCoord; + varying vec4 vColor; + uniform sampler2D uSampler; + + uniform float iTime; + uniform float radius; + uniform float width; + uniform float period; + uniform float angle; + uniform float smooth; + uniform vec2 resolution; + + uniform vec4 color; + uniform vec4 backgroundColor; + + float ratio = resolution.y / resolution.x; + + vec2 transpose_pos(vec2 pos) { + if (ratio < 1.) { + float diff = 0.5 - pos.x; + pos.x = 0.5 - diff / ratio; + } else { + float diff = 0.5 - pos.y; + pos.y = 0.5 - diff * ratio; + } + return pos; + } + + float get_angle(vec2 pos) { + pos = transpose_pos(pos); + float a = atan(pos.y - 0.5, pos.x - 0.5); + a = (1.0+a/3.14159)/2.0; + + return a; + } + + float dist(vec2 pos1, vec2 pos2) { + pos1 = transpose_pos(pos1); + return distance(pos1, pos2); + } + + void main() + { + vec2 fragCoord = vTextureCoord; + vec4 fragColor = vColor; + + vec2 st = vTextureCoord; + float pct = dist(st, vec2(0.5)); + + float a = get_angle(st); + float t = iTime / 1000.0 / period; + + float inner = max((radius - width) / resolution.x, (radius - width) / resolution.y); + float outer = max(radius / resolution.x, radius / resolution.y); + + float x1 = mod(t, 1.0); + float x2 = mod(t + angle, 1.0); + + if (x1 < x2) { + if (a > x1 && a < x2) { + float val = (1.0 - (x2 - a) / angle) * smoothstep(0.0, 3. * smooth, (x2 - a)); + fragColor = mix(backgroundColor, color, val); + } else { + fragColor = backgroundColor; + } + } else { + if (a < x2) { + float val = (1.0 - (x2 - a) / angle) * smoothstep(0.0, 3. * smooth, (x2 - a)); + fragColor = mix(backgroundColor, color, val); + } else if (a > x1) { + float val = (1.0 - (1.0 + x2 - a) / angle) * smoothstep(0.0, 3. * smooth, (1.0 + x2 - a)); + fragColor = mix(backgroundColor, color, val); + } else { + fragColor = backgroundColor; + } + } + + float s = smoothstep(inner, inner + smooth + 0.00001, pct) * (1.0 - smoothstep(outer, outer + smooth + 0.00001, pct)); + gl_FragColor = texture2D(uSampler, fragCoord) * vColor * (1. - s * fragColor.a) + fragColor * s; + } +`; +class HoleShader extends DefaultShader$1 { + constructor(context) { + super(context); + this._x = 0; + this._y = 0; + this._w = 0; + this._h = 0; + this._radius = 0; + } + get x() { + return this._x; + } + set x(v) { + this._x = v; + this.redraw(); + } + get y() { + return this._y; + } + set y(v) { + this._y = v; + this.redraw(); + } + get w() { + return this._w; + } + set w(v) { + this._w = v; + this.redraw(); + } + get h() { + return this._h; + } + set h(v) { + this._h = v; + this.redraw(); + } + get radius() { + return this._radius; + } + set radius(v) { + this._radius = v; + this.redraw(); + } + setupUniforms(operation) { + super.setupUniforms(operation); + const owner = operation.shaderOwner; + const renderPrecision = this.ctx.stage.getRenderPrecision(); + this._setUniform("x", this._x * renderPrecision, this.gl.uniform1f); + this._setUniform("y", this._y * renderPrecision, this.gl.uniform1f); + this._setUniform("w", this._w * renderPrecision, this.gl.uniform1f); + this._setUniform("h", this._h * renderPrecision, this.gl.uniform1f); + this._setUniform("radius", (this._radius + 0.5) * renderPrecision, this.gl.uniform1f); + this._setUniform("resolution", new Float32Array([owner._w * renderPrecision, owner._h * renderPrecision]), this.gl.uniform2fv); + } + useDefault() { + return this._x === 0 && this._y === 0 && this._w === 0 && this._h === 0; + } +} +HoleShader.vertexShaderSource = DefaultShader$1.vertexShaderSource; +HoleShader.fragmentShaderSource = ` + #ifdef GL_ES + # ifdef GL_FRAGMENT_PRECISION_HIGH + precision highp float; + # else + precision lowp float; + # endif + #endif + varying vec2 vTextureCoord; + varying vec4 vColor; + uniform sampler2D uSampler; + uniform float x; + uniform float y; + uniform float w; + uniform float h; + uniform vec2 resolution; + uniform float radius; + + float roundBox(vec2 p, vec2 b, float r) { + float d = length(max(abs(p)-b+r, 0.1))-r; + return smoothstep(1.0, 0.0, d); + } + + void main(void){ + vec4 color = texture2D(uSampler, vTextureCoord); + vec2 pos = vTextureCoord.xy * resolution - vec2(x, y) - vec2(w, h) / 2.0; + vec2 size = vec2(w, h) / 2.0; + float b = roundBox(pos, size, radius); + gl_FragColor = mix(color, vec4(0.0), b) * vColor; + } +`; +class RadialGradientShader extends DefaultShader$1 { + constructor(context) { + super(context); + this._pivot = [0, 0]; + this._ic = 4294967295; + this._normalizedIC = this._getNormalizedColor(this._ic); + this._oc = 16777215; + this._normalizedOC = this._getNormalizedColor(this._oc); + this._radius = 0; + } + set radiusX(v) { + this.radius = v; + } + get radiusX() { + return this._radius; + } + set radiusY(v) { + this._radiusY = v; + this.redraw(); + } + get radiusY() { + return this._radiusY; + } + set radius(v) { + this._radius = v; + this.redraw(); + } + set innerColor(argb) { + this._ic = argb; + this._normalizedIC = this._getNormalizedColor(argb); + this.redraw(); + } + get innerColor() { + return this._ic; + } + set outerColor(argb) { + this._oc = argb; + this._normalizedOC = this._getNormalizedColor(argb); + this.redraw(); + } + set color(argb) { + this.innerColor = argb; + } + get color() { + return this.innerColor; + } + get outerColor() { + return this._ic; + } + set x(f) { + this._x = f; + this.redraw(); + } + set y(f) { + this._y = f; + this.redraw(); + } + set pivot(v) { + if (Array.isArray(v) && v.length === 2) { + this._pivot = v; + } else if (Array.isArray(v)) { + this._pivot = [v[0], v[1] || v[0]]; + } else { + this._pivot = [v, v]; + } + this.redraw(); + } + get pivot() { + return this._pivot[0]; + } + set pivotY(f) { + this._pivot[1] = f; + this.redraw(); + } + get pivotY() { + return this._pivot[1]; + } + set pivotX(f) { + this._pivot[0] = f; + this.redraw(); + } + get pivotX() { + return this._pivot[0]; + } + _getNormalizedColor(color) { + const col = StageUtils.getRgbaComponentsNormalized(color); + col[0] *= col[3]; + col[1] *= col[3]; + col[2] *= col[3]; + return new Float32Array(col); + } + setupUniforms(operation) { + super.setupUniforms(operation); + const owner = operation.shaderOwner; + if (this._x) { + this._pivot[0] = this._x / owner.w; + } + if (this._y) { + this._pivot[1] = this._y / owner.h; + } + if (this._radius === 0) { + this._radius = owner.w * 0.5; + } + this._setUniform("innerColor", this._normalizedIC, this.gl.uniform4fv); + this._setUniform("fill", StageUtils.getRgbaComponentsNormalized(this._oc)[3], this.gl.uniform1f); + this._setUniform("outerColor", this._normalizedOC, this.gl.uniform4fv); + this._setUniform("pivot", new Float32Array(this._pivot), this.gl.uniform2fv); + this._setUniform("resolution", new Float32Array([owner._w, owner._h]), this.gl.uniform2fv); + this._setUniform("alpha", operation.getElementCore(0).renderContext.alpha, this.gl.uniform1f); + this._setUniform("radius", this._radius, this.gl.uniform1f); + this._setUniform("radiusY", this._radiusY || this._radius, this.gl.uniform1f); + } +} +RadialGradientShader.fragmentShaderSource = ` + #ifdef GL_ES + # ifdef GL_FRAGMENT_PRECISION_HIGH + precision highp float; + # else + precision lowp float; + # endif + #endif + + #define PI 3.14159265359 + + varying vec2 vTextureCoord; + varying vec4 vColor; + uniform sampler2D uSampler; + uniform vec2 resolution; + uniform vec2 pivot; + uniform vec4 innerColor; + uniform vec4 outerColor; + uniform float radius; + uniform float radiusY; + uniform float alpha; + uniform float fill; + uniform float aspectRatio; + + void main() { + vec2 point = vTextureCoord.xy * resolution; + vec2 projection = vec2(pivot.x * resolution.x, pivot.y * resolution.y); + float d = length((point - projection) / vec2(radius * 2.0, radiusY * 2.0)); + vec4 color = mix(texture2D(uSampler, vTextureCoord) * vColor, outerColor * alpha, fill); + gl_FragColor = mix(innerColor * alpha, color, smoothstep(0.0, 1.0, d)); + } +`; +class Light3dShader extends DefaultShader$1 { + constructor(ctx) { + super(ctx); + this._strength = 0.5; + this._ambient = 0.5; + this._fudge = 0.4; + this._rx = 0; + this._ry = 0; + this._z = 0; + this._pivotX = NaN; + this._pivotY = NaN; + this._pivotZ = 0; + this._lightY = 0; + this._lightZ = 0; + } + setupUniforms(operation) { + super.setupUniforms(operation); + let vr = operation.shaderOwner; + let element = vr.element; + let pivotX = isNaN(this._pivotX) ? element.pivotX * vr.w : this._pivotX; + let pivotY = isNaN(this._pivotY) ? element.pivotY * vr.h : this._pivotY; + let coords = vr.getRenderTextureCoords(pivotX, pivotY); + let rz = -Math.atan2(vr._renderContext.tc, vr._renderContext.ta); + let gl = this.gl; + this._setUniform("pivot", new Float32Array([coords[0], coords[1], this._pivotZ]), gl.uniform3fv); + this._setUniform("rot", new Float32Array([this._rx, this._ry, rz]), gl.uniform3fv); + this._setUniform("z", this._z, gl.uniform1f); + this._setUniform("lightY", this.lightY, gl.uniform1f); + this._setUniform("lightZ", this.lightZ, gl.uniform1f); + this._setUniform("strength", this._strength, gl.uniform1f); + this._setUniform("ambient", this._ambient, gl.uniform1f); + this._setUniform("fudge", this._fudge, gl.uniform1f); + } + set strength(v) { + this._strength = v; + this.redraw(); + } + get strength() { + return this._strength; + } + set ambient(v) { + this._ambient = v; + this.redraw(); + } + get ambient() { + return this._ambient; + } + set fudge(v) { + this._fudge = v; + this.redraw(); + } + get fudge() { + return this._fudge; + } + get rx() { + return this._rx; + } + set rx(v) { + this._rx = v; + this.redraw(); + } + get ry() { + return this._ry; + } + set ry(v) { + this._ry = v; + this.redraw(); + } + get z() { + return this._z; + } + set z(v) { + this._z = v; + this.redraw(); + } + get pivotX() { + return this._pivotX; + } + set pivotX(v) { + this._pivotX = v + 1; + this.redraw(); + } + get pivotY() { + return this._pivotY; + } + set pivotY(v) { + this._pivotY = v + 1; + this.redraw(); + } + get lightY() { + return this._lightY; + } + set lightY(v) { + this._lightY = v; + this.redraw(); + } + get pivotZ() { + return this._pivotZ; + } + set pivotZ(v) { + this._pivotZ = v; + this.redraw(); + } + get lightZ() { + return this._lightZ; + } + set lightZ(v) { + this._lightZ = v; + this.redraw(); + } + useDefault() { + return this._rx === 0 && this._ry === 0 && this._z === 0 && this._strength === 0 && this._ambient === 1; + } +} +Light3dShader.vertexShaderSource = ` + #ifdef GL_ES + # ifdef GL_FRAGMENT_PRECISION_HIGH + precision highp float; + # else + precision lowp float; + # endif + #endif + attribute vec2 aVertexPosition; + attribute vec2 aTextureCoord; + attribute vec4 aColor; + uniform vec2 projection; + varying vec2 vTextureCoord; + varying vec4 vColor; + + uniform float fudge; + uniform float strength; + uniform float ambient; + uniform float z; + uniform float lightY; + uniform float lightZ; + uniform vec3 pivot; + uniform vec3 rot; + varying vec3 pos; + + void main(void) { + pos = vec3(aVertexPosition.xy, z); + + pos -= pivot; + + // Undo XY rotation + mat2 iRotXy = mat2( cos(rot.z), sin(rot.z), + -sin(rot.z), cos(rot.z)); + pos.xy = iRotXy * pos.xy; + + // Perform 3d rotations + gl_Position.x = cos(rot.x) * pos.x - sin(rot.x) * pos.z; + gl_Position.y = pos.y; + gl_Position.z = sin(rot.x) * pos.x + cos(rot.x) * pos.z; + + pos.x = gl_Position.x; + pos.y = cos(rot.y) * gl_Position.y - sin(rot.y) * gl_Position.z; + pos.z = sin(rot.y) * gl_Position.y + cos(rot.y) * gl_Position.z; + + // Redo XY rotation + iRotXy[0][1] = -iRotXy[0][1]; + iRotXy[1][0] = -iRotXy[1][0]; + pos.xy = iRotXy * pos.xy; + + // Undo translate to pivot position + pos.xyz += pivot; + + pos = vec3(pos.x * projection.x - 1.0, pos.y * -abs(projection.y) + 1.0, pos.z * projection.x); + + // Set depth perspective + float perspective = 1.0 + fudge * pos.z; + + pos.z += lightZ * projection.x; + + // Map coords to gl coordinate space. + // Set z to 0 because we don't want to perform z-clipping + gl_Position = vec4(pos.xy, 0.0, perspective); + + // Correct light source position. + pos.y += lightY * abs(projection.y); + + vTextureCoord = aTextureCoord; + vColor = aColor; + + gl_Position.y = -sign(projection.y) * gl_Position.y; + } +`; +Light3dShader.fragmentShaderSource = ` + #ifdef GL_ES + # ifdef GL_FRAGMENT_PRECISION_HIGH + precision highp float; + # else + precision lowp float; + # endif + #endif + varying vec2 vTextureCoord; + varying vec4 vColor; + varying vec3 pos; + uniform sampler2D uSampler; + uniform float ambient; + uniform float strength; + void main(void){ + vec4 rgba = texture2D(uSampler, vTextureCoord); + float d = length(pos); + float n = 1.0 / max(0.1, d); + rgba.rgb = rgba.rgb * (strength * n + ambient); + gl_FragColor = rgba * vColor; + } +`; +class PerspectiveShader extends DefaultShader$1 { + constructor(ctx) { + super(ctx); + this._fudge = 0.2; + this._rx = 0; + this._ry = 0; + this._z = 1; + } + setupUniforms(operation) { + super.setupUniforms(operation); + const vr = operation.shaderOwner; + const element = vr.element; + const pivotX = element.pivotX * vr.w; + const pivotY = element.pivotY * vr.h; + const coords = vr.getRenderTextureCoords(pivotX, pivotY); + const rz = -Math.atan2(vr._renderContext.tc, vr._renderContext.ta); + const gl = this.gl; + this._setUniform("pivot", new Float32Array([coords[0], coords[1], 0]), gl.uniform3fv); + this._setUniform("rot", new Float32Array([this._rx, this._ry, rz]), gl.uniform3fv); + this._setUniform("z", this._z, gl.uniform1f); + this._setUniform("fudge", this._fudge, gl.uniform1f); + } + set fudge(v) { + this._fudge = v; + this.redraw(); + } + get fudge() { + return this._fudge; + } + get rx() { + return this._rx; + } + set rx(v) { + this._rx = v; + this.redraw(); + } + get ry() { + return this._ry; + } + set ry(v) { + this._ry = v; + this.redraw(); + } + get z() { + return this._z; + } + set z(v) { + this._z = v; + this.redraw(); + } + useDefault() { + return this._rx === 0 && this._ry === 0 && this._z === 0; + } +} +PerspectiveShader.vertexShaderSource = ` + #ifdef GL_ES + # ifdef GL_FRAGMENT_PRECISION_HIGH + precision highp float; + # else + precision lowp float; + # endif + #endif + attribute vec2 aVertexPosition; + attribute vec2 aTextureCoord; + attribute vec4 aColor; + uniform vec2 projection; + varying vec2 vTextureCoord; + varying vec4 vColor; + + uniform float z; + uniform vec3 pivot; + uniform vec3 rot; + varying vec3 pos; + + void main(void) { + pos = vec3(aVertexPosition.xy, z); + + pos -= pivot; + + // Undo XY rotation + mat2 iRotXy = mat2( cos(rot.z), sin(rot.z), + -sin(rot.z), cos(rot.z)); + pos.xy = iRotXy * pos.xy; + + // Perform 3d rotations + gl_Position.x = cos(rot.x) * pos.x - sin(rot.x) * pos.z; + gl_Position.y = pos.y; + gl_Position.z = sin(rot.x) * pos.x + cos(rot.x) * pos.z; + + pos.x = gl_Position.x; + pos.y = cos(rot.y) * gl_Position.y - sin(rot.y) * gl_Position.z; + pos.z = sin(rot.y) * gl_Position.y + cos(rot.y) * gl_Position.z; + + // Redo XY rotation + iRotXy[0][1] = -iRotXy[0][1]; + iRotXy[1][0] = -iRotXy[1][0]; + pos.xy = iRotXy * pos.xy; + + // Undo translate to pivot position + pos.xyz += pivot; + + pos = vec3(pos.x * projection.x - 1.0, pos.y * -abs(projection.y) + 1.0, pos.z * projection.x); + + // Map coords to gl coordinate space. + // Set z to 0 because we don't want to perform z-clipping + gl_Position = vec4(pos.xy, 0.0, z); + + vTextureCoord = aTextureCoord; + vColor = aColor; + + gl_Position.y = -sign(projection.y) * gl_Position.y; + } +`; +PerspectiveShader.fragmentShaderSource = ` + #ifdef GL_ES + # ifdef GL_FRAGMENT_PRECISION_HIGH + precision highp float; + # else + precision lowp float; + # endif + #endif + varying vec2 vTextureCoord; + varying vec4 vColor; + uniform sampler2D uSampler; + + uniform vec3 rot; + uniform float fudge; + + void main(void) { + vec2 coords = vTextureCoord; + + coords.xy -= vec2(0.5); + coords.y = coords.y + (sign(rot[0]) * 0.5 - coords.x) * sin(rot[0]) * fudge * coords.y; + coords.x = coords.x + (sign(rot[1]) * 0.5 - coords.y) * sin(rot[1]) * fudge * coords.x; + coords.xy += vec2(0.5); + + if (coords.x < 0.0 || coords.x > 1.0 || coords.y < 0.0 || coords.y > 1.0) { + gl_FragColor = vec4(0.0); + } else { + gl_FragColor = texture2D(uSampler, coords) * vColor; + } + } +`; +class MagnifierShader extends DefaultShader$1 { + constructor(context) { + super(context); + this._x = 0; + this._y = 0; + this._w = 0; + this._h = 0; + this._radius = 0; + this._magnification = 0.6; + } + get x() { + return this._x; + } + set x(v) { + this._x = v; + this.redraw(); + } + get y() { + return this._y; + } + set y(v) { + this._y = v; + this.redraw(); + } + get w() { + return this._w; + } + set w(v) { + this._w = v; + this.redraw(); + } + get h() { + return this._h; + } + set h(v) { + this._h = v; + this.redraw(); + } + get magnification() { + return this._magnification; + } + set magnification(v) { + this._magnification = v; + this.redraw(); + } + get radius() { + return this._radius; + } + set radius(v) { + this._radius = v; + this.redraw(); + } + setupUniforms(operation) { + super.setupUniforms(operation); + const owner = operation.shaderOwner; + const renderPrecision = this.ctx.stage.getRenderPrecision(); + this._setUniform("x", this._x * renderPrecision, this.gl.uniform1f); + this._setUniform("y", this._y * renderPrecision, this.gl.uniform1f); + this._setUniform("w", this._w * renderPrecision, this.gl.uniform1f); + this._setUniform("h", this._h * renderPrecision, this.gl.uniform1f); + this._setUniform("magnification", this._magnification, this.gl.uniform1f); + this._setUniform( + "radius", + (this._radius + 0.5) * renderPrecision, + this.gl.uniform1f + ); + this._setUniform( + "resolution", + new Float32Array([ + owner._w * renderPrecision, + owner._h * renderPrecision + ]), + this.gl.uniform2fv + ); + } + useDefault() { + return this._w === 0 && this._h === 0; + } +} +MagnifierShader.vertexShaderSource = DefaultShader$1.vertexShaderSource; +MagnifierShader.fragmentShaderSource = ` + #ifdef GL_ES + # ifdef GL_FRAGMENT_PRECISION_HIGH + precision highp float; + # else + precision lowp float; + # endif + #endif + + varying vec2 vTextureCoord; + varying vec4 vColor; + uniform sampler2D uSampler; + uniform float x; + uniform float y; + uniform float w; + uniform float h; + uniform vec2 resolution; + uniform float radius; + uniform float magnification; + + float roundBox(vec2 p, vec2 b, float r) { + float d = length(max(abs(p)-b+r, 0.1))-r; + return smoothstep(1.0, 0.0, d); + } + + float inside(vec2 v) { + vec2 s = step(vec2(0.0, 0.0), v) - step(vec2(1.0, 1.0), v); + return s.x * s.y; + } + + void main(void) { + vec4 color = texture2D(uSampler, vTextureCoord); + vec2 pos = vTextureCoord.xy * resolution - vec2(x, y) - vec2(w, h) / 2.0; + vec2 size = vec2(w, h) / 2.0; + float b = roundBox(pos, size, radius); + vec2 pos2 = (vTextureCoord.xy * magnification * resolution + vec2(x, y) * magnification) / resolution; + gl_FragColor = mix(color, texture2D(uSampler, pos2) * inside(pos2), b) * vColor; + } + `; +class SpinnerShader2 extends DefaultShader$1 { + constructor(context) { + super(context); + this._period = 1; + this._stroke = 0; + this._showDot = true; + this._clockwise = true; + this._bc = 4278190080; + this._normalizedBC = this._getNormalizedColor(this._bc); + this._c = 4294967295; + this._normalizedC = this._getNormalizedColor(this._c); + } + set radius(v) { + if (v === 0) { + v = 1; + } + this._radius = v; + } + set stroke(value) { + this._stroke = Math.abs(value); + } + get stroke() { + return this._stroke; + } + set color(argb) { + this._c = argb; + this._normalizedC = this._getNormalizedColor(argb); + } + get color() { + return this._c; + } + set backgroundColor(argb) { + this._bc = argb; + this._normalizedBC = this._getNormalizedColor(argb); + } + get backgroundColor() { + return this._sc; + } + set showDot(bool) { + this._showDot = bool; + } + get showDot() { + return this._showDot; + } + set clockwise(bool) { + this._clockwise = bool; + } + get clockwise() { + return this._clockwise; + } + set period(v) { + this._period = v; + } + get period() { + return this._period; + } + _getNormalizedColor(color) { + const col = StageUtils.getRgbaComponentsNormalized(color); + col[0] *= col[3]; + col[1] *= col[3]; + col[2] *= col[3]; + return new Float32Array(col); + } + setupUniforms(operation) { + super.setupUniforms(operation); + const owner = operation.shaderOwner; + const radius = this._radius || owner._w / 2; + if (this._stroke === 0) { + this._stroke = radius * 0.33; + } + this._setUniform("resolution", new Float32Array([owner._w, owner._h]), this.gl.uniform2fv); + this._setUniform("color", this._normalizedC, this.gl.uniform4fv); + this._setUniform("backgroundColor", this._normalizedBC, this.gl.uniform4fv); + this._setUniform("stroke", this._stroke, this.gl.uniform1f); + this._setUniform("radius", radius, this.gl.uniform1f); + this._setUniform("direction", this._clockwise ? -1 : 1, this.gl.uniform1f); + this._setUniform("showDot", !!this._showDot, this.gl.uniform1f); + this._setUniform("time", Date.now() - SpinnerShader2.spinSync, this.gl.uniform1f); + this._setUniform("period", this._period, this.gl.uniform1f); + this._setUniform("alpha", operation.getElementCore(0).renderContext.alpha, this.gl.uniform1f); + if (this._sc !== this._bc || this._stroke !== radius * 0.5) { + this.redraw(); + } + } +} +SpinnerShader2.spinSync = Date.now(); +SpinnerShader2.fragmentShaderSource = ` + #ifdef GL_ES + # ifdef GL_FRAGMENT_PRECISION_HIGH + precision highp float; + # else + precision lowp float; + # endif + #endif + + #define PI 3.14159265359 + + varying vec2 vTextureCoord; + varying vec4 vColor; + + uniform sampler2D uSampler; + uniform vec2 resolution; + uniform vec4 color; + uniform vec4 backgroundColor; + uniform float direction; + uniform float radius; + uniform float time; + uniform float stroke; + uniform float showDot; + uniform float period; + uniform float alpha; + + float circleDist(vec2 p, float radius){ + return length(p) - radius; + } + + float fillMask(float dist){ + return clamp(-dist, 0.0, 1.0); + } + + void main() { + vec2 halfRes = 0.5 * resolution.xy; + vec2 center = vTextureCoord.xy * resolution - halfRes; + + float c = max(-circleDist(center, radius - stroke), circleDist(center, radius)); + float rot = -(time / 1000.0 / period) * 6.0 * direction; + center *= mat2(cos(rot), sin(rot), -sin(rot), cos(rot)); + + float a = direction * atan(center.x, center.y) * PI * 0.05 + 0.45; + + float strokeRad = stroke * 0.5; + a = mix(a, max(a, fillMask(circleDist(vec2(center.x, center.y + (radius - strokeRad)), strokeRad))), showDot); + vec4 base = mix(vec4(0.0), backgroundColor * alpha, fillMask(c)); + gl_FragColor = mix(base, color * alpha, fillMask(c) * a); + } +`; +const lightning = { + Application, + Component, + Base, + Utils: Utils$1, + StageUtils, + Element, + Tools, + Stage, + ElementCore, + ElementTexturizer, + Texture, + EventEmitter, + shaders: { + Grayscale: WebGLGrayscaleShader, + BoxBlur: BoxBlurShader, + Dithering: DitheringShader, + CircularPush: CircularPushShader, + Inversion: InversionShader, + LinearBlur: LinearBlurShader, + Outline: OutlineShader, + Pixelate: PixelateShader, + RadialFilter: RadialFilterShader, + RoundedRectangle: RoundedRectangleShader, + Spinner2: SpinnerShader2, + FadeOut: FadeOutShader, + Hole: HoleShader, + Vignette: VignetteShader, + Spinner: SpinnerShader, + RadialGradient: RadialGradientShader, + Light3d: Light3dShader, + Perspective: PerspectiveShader, + Magnifier: MagnifierShader, + WebGLShader, + WebGLDefaultShader: DefaultShader$1, + C2dShader, + C2dDefaultShader: DefaultShader2, + c2d: { + Grayscale: C2dGrayscaleShader, + Blur: BlurShader + } + }, + textures: { + RectangleTexture, + NoiseTexture, + TextTexture, + ImageTexture, + HtmlTexture, + StaticTexture, + StaticCanvasTexture, + SourceTexture + }, + components: { + FastBlurComponent, + BloomComponent, + SmoothScaleComponent, + BorderComponent, + ListComponent + }, + tools: { + ObjMerger, + ObjectListProxy, + ObjectListWrapper + } +}; +if (Utils$1.isWeb) { + window.lng = lightning; +} + +//# sourceMappingURL=lightning.esm.js.map + +/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../../../webpack/buildin/global.js */ "./node_modules/webpack/buildin/global.js"))) + +/***/ }), + +/***/ "./node_modules/@lightningjs/core/dist/lightning.js": +/*!**********************************************************!*\ + !*** ./node_modules/@lightningjs/core/dist/lightning.js ***! + \**********************************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +/* WEBPACK VAR INJECTION */(function(global) {/* + * Lightning v2.11.0 + * + * https://github.com/rdkcentral/Lightning + */ +(function(global2, factory) { + true ? module.exports = factory() : undefined; +})(this, function() { + "use strict"; + class StageUtils { + static mergeNumbers(v1, v2, p) { + return v1 * p + v2 * (1 - p); + } + static rgb(r, g, b) { + return (r << 16) + (g << 8) + b + 255 * 16777216; + } + static rgba(r, g, b, a) { + return (r << 16) + (g << 8) + b + (a * 255 | 0) * 16777216; + } + static getRgbString(color) { + let r = (color / 65536 | 0) % 256; + let g = (color / 256 | 0) % 256; + let b = color % 256; + return "rgb(" + r + "," + g + "," + b + ")"; + } + static getRgbaString(color) { + let r = (color / 65536 | 0) % 256; + let g = (color / 256 | 0) % 256; + let b = color % 256; + let a = (color / 16777216 | 0) / 255; + return "rgba(" + r + "," + g + "," + b + "," + a.toFixed(4) + ")"; + } + static getRgbaStringFromArray(color) { + let r = Math.floor(color[0] * 255); + let g = Math.floor(color[1] * 255); + let b = Math.floor(color[2] * 255); + let a = Math.floor(color[3] * 255) / 255; + return "rgba(" + r + "," + g + "," + b + "," + a.toFixed(4) + ")"; + } + static getRgbaComponentsNormalized(argb) { + let r = (argb / 65536 | 0) % 256; + let g = (argb / 256 | 0) % 256; + let b = argb % 256; + let a = argb / 16777216 | 0; + return [r / 255, g / 255, b / 255, a / 255]; + } + static getRgbComponentsNormalized(argb) { + let r = (argb / 65536 | 0) % 256; + let g = (argb / 256 | 0) % 256; + let b = argb % 256; + return [r / 255, g / 255, b / 255]; + } + static getRgbaComponents(argb) { + let r = (argb / 65536 | 0) % 256; + let g = (argb / 256 | 0) % 256; + let b = argb % 256; + let a = argb / 16777216 | 0; + return [r, g, b, a]; + } + static getArgbNumber(rgba) { + rgba[0] = Math.max(0, Math.min(255, rgba[0])); + rgba[1] = Math.max(0, Math.min(255, rgba[1])); + rgba[2] = Math.max(0, Math.min(255, rgba[2])); + rgba[3] = Math.max(0, Math.min(255, rgba[3])); + let v = ((rgba[3] | 0) << 24) + ((rgba[0] | 0) << 16) + ((rgba[1] | 0) << 8) + (rgba[2] | 0); + if (v < 0) { + v = 4294967295 + v + 1; + } + return v; + } + static mergeColors(c1, c2, p) { + let r1 = (c1 / 65536 | 0) % 256; + let g1 = (c1 / 256 | 0) % 256; + let b1 = c1 % 256; + let a1 = c1 / 16777216 | 0; + let r2 = (c2 / 65536 | 0) % 256; + let g2 = (c2 / 256 | 0) % 256; + let b2 = c2 % 256; + let a2 = c2 / 16777216 | 0; + let r = r1 * p + r2 * (1 - p); + let g = g1 * p + g2 * (1 - p); + let b = b1 * p + b2 * (1 - p); + let a = a1 * p + a2 * (1 - p); + return Math.round(a) * 16777216 + Math.round(r) * 65536 + Math.round(g) * 256 + Math.round(b); + } + static mergeMultiColors(c, p) { + let r = 0, g = 0, b = 0, a = 0, t = 0; + let n = c.length; + for (let i = 0; i < n; i++) { + let r1 = (c[i] / 65536 | 0) % 256; + let g1 = (c[i] / 256 | 0) % 256; + let b1 = c[i] % 256; + let a1 = c[i] / 16777216 | 0; + r += r1 * p[i]; + g += g1 * p[i]; + b += b1 * p[i]; + a += a1 * p[i]; + t += p[i]; + } + t = 1 / t; + return Math.round(a * t) * 16777216 + Math.round(r * t) * 65536 + Math.round(g * t) * 256 + Math.round(b * t); + } + static mergeMultiColorsEqual(c) { + let r = 0, g = 0, b = 0, a = 0, t = 0; + let n = c.length; + for (let i = 0; i < n; i++) { + let r1 = (c[i] / 65536 | 0) % 256; + let g1 = (c[i] / 256 | 0) % 256; + let b1 = c[i] % 256; + let a1 = c[i] / 16777216 | 0; + r += r1; + g += g1; + b += b1; + a += a1; + t += 1; + } + t = 1 / t; + return Math.round(a * t) * 16777216 + Math.round(r * t) * 65536 + Math.round(g * t) * 256 + Math.round(b * t); + } + static mergeColorAlpha(c, alpha) { + let a = (c / 16777216 | 0) * alpha | 0; + return ((c >> 16 & 255) * a / 255 & 255) + ((c & 65280) * a / 255 & 65280) + (((c & 255) << 16) * a / 255 & 16711680) + (a << 24); + } + static rad(deg) { + return deg * (Math.PI / 180); + } + static getTimingBezier(a, b, c, d) { + let xc = 3 * a; + let xb = 3 * (c - a) - xc; + let xa = 1 - xc - xb; + let yc = 3 * b; + let yb = 3 * (d - b) - yc; + let ya = 1 - yc - yb; + return function(time) { + if (time >= 1) { + return 1; + } + if (time <= 0) { + return 0; + } + let t = 0.5, cbx, cbxd, dx; + for (let it = 0; it < 20; it++) { + cbx = t * (t * (t * xa + xb) + xc); + dx = time - cbx; + if (dx > -1e-8 && dx < 1e-8) { + return t * (t * (t * ya + yb) + yc); + } + cbxd = t * (t * (3 * xa) + 2 * xb) + xc; + if (cbxd > 1e-10 && cbxd < 1e-10) { + break; + } + t += dx / cbxd; + } + let minT = 0; + let maxT = 1; + for (let it = 0; it < 20; it++) { + t = 0.5 * (minT + maxT); + cbx = t * (t * (t * xa + xb) + xc); + dx = time - cbx; + if (dx > -1e-8 && dx < 1e-8) { + return t * (t * (t * ya + yb) + yc); + } + if (dx < 0) { + maxT = t; + } else { + minT = t; + } + } + }; + } + static getTimingFunction(str) { + switch (str) { + case "linear": + return function(time) { + return time; + }; + case "ease": + return StageUtils.getTimingBezier(0.25, 0.1, 0.25, 1); + case "ease-in": + return StageUtils.getTimingBezier(0.42, 0, 1, 1); + case "ease-out": + return StageUtils.getTimingBezier(0, 0, 0.58, 1); + case "ease-in-out": + return StageUtils.getTimingBezier(0.42, 0, 0.58, 1); + case "step-start": + return function() { + return 1; + }; + case "step-end": + return function(time) { + return time === 1 ? 1 : 0; + }; + default: + let s = "cubic-bezier("; + if (str && str.indexOf(s) === 0) { + let parts = str.substr(s.length, str.length - s.length - 1).split(","); + if (parts.length !== 4) { + console.warn("[Lightning] Unknown timing function: " + str); + return function(time) { + return time; + }; + } + let a = parseFloat(parts[0]); + let b = parseFloat(parts[1]); + let c = parseFloat(parts[2]); + let d = parseFloat(parts[3]); + if (isNaN(a) || isNaN(b) || isNaN(c) || isNaN(d)) { + console.warn("[Lightning] Unknown timing function: " + str); + return function(time) { + return time; + }; + } + return StageUtils.getTimingBezier(a, b, c, d); + } else { + console.warn("[Lightning] Unknown timing function: " + str); + return function(time) { + return time; + }; + } + } + } + } + let Utils$1 = class Utils { + static isFunction(value) { + return typeof value === "function"; + } + static isNumber(value) { + return typeof value === "number"; + } + static isInteger(value) { + return typeof value === "number" && value % 1 === 0; + } + static isBoolean(value) { + return value === true || value === false; + } + static isString(value) { + return typeof value === "string"; + } + static clone(v) { + if (Utils$1.isObjectLiteral(v) || Array.isArray(v)) { + return Utils$1.getDeepClone(v); + } else { + return v; + } + } + static cloneObjShallow(obj) { + let keys = Object.keys(obj); + let clone = {}; + for (let i = 0; i < keys.length; i++) { + clone[keys[i]] = obj[keys[i]]; + } + return clone; + } + static merge(obj1, obj2) { + let keys = Object.keys(obj2); + for (let i = 0; i < keys.length; i++) { + obj1[keys[i]] = obj2[keys[i]]; + } + return obj1; + } + static isObject(value) { + let type = typeof value; + return !!value && (type === "object" || type === "function"); + } + static isPlainObject(value) { + let type = typeof value; + return !!value && type === "object"; + } + static isObjectLiteral(value) { + return typeof value === "object" && value && value.constructor === Object; + } + static getArrayIndex(index, arr) { + return Utils$1.getModuloIndex(index, arr.length); + } + static getModuloIndex(index, len) { + if (len === 0) + return index; + while (index < 0) { + index += Math.ceil(-index / len) * len; + } + index = index % len; + return index; + } + static getDeepClone(obj) { + let i, c; + if (Utils$1.isFunction(obj)) { + return obj; + } + if (Array.isArray(obj)) { + c = []; + let keys = Object.keys(obj); + for (i = 0; i < keys.length; i++) { + c[keys[i]] = Utils$1.getDeepClone(obj[keys[i]]); + } + return c; + } else if (Utils$1.isObject(obj)) { + c = {}; + let keys = Object.keys(obj); + for (i = 0; i < keys.length; i++) { + c[keys[i]] = Utils$1.getDeepClone(obj[keys[i]]); + } + return c; + } else { + return obj; + } + } + static equalValues(v1, v2) { + if (typeof v1 !== typeof v2) + return false; + if (Utils$1.isObjectLiteral(v1)) { + return Utils$1.isObjectLiteral(v2) && Utils$1.equalObjectLiterals(v1, v2); + } else if (Array.isArray(v1)) { + return Array.isArray(v2) && Utils$1.equalArrays(v1, v2); + } else { + return v1 === v2; + } + } + static equalObjectLiterals(obj1, obj2) { + let keys1 = Object.keys(obj1); + let keys2 = Object.keys(obj2); + if (keys1.length !== keys2.length) { + return false; + } + for (let i = 0, n = keys1.length; i < n; i++) { + const k1 = keys1[i]; + const k2 = keys2[i]; + if (k1 !== k2) { + return false; + } + const v1 = obj1[k1]; + const v2 = obj2[k2]; + if (!Utils$1.equalValues(v1, v2)) { + return false; + } + } + return true; + } + static equalArrays(v1, v2) { + if (v1.length !== v2.length) { + return false; + } + for (let i = 0, n = v1.length; i < n; i++) { + if (!this.equalValues(v1[i], v2[i])) { + return false; + } + } + return true; + } + static setToArray(s) { + let result = []; + s.forEach(function(value) { + result.push(value); + }); + return result; + } + static iteratorToArray(iterator) { + let result = []; + let iteratorResult = iterator.next(); + while (!iteratorResult.done) { + result.push(iteratorResult.value); + iteratorResult = iterator.next(); + } + return result; + } + static isUcChar(charcode) { + return charcode >= 65 && charcode <= 90; + } + }; + Utils$1.isWeb = typeof window !== "undefined" && typeof sparkscene === "undefined"; + Utils$1.isWPE = Utils$1.isWeb && navigator.userAgent.indexOf("WPE") !== -1; + Utils$1.isSpark = typeof sparkscene !== "undefined"; + Utils$1.isNode = typeof window === "undefined" || Utils$1.isSpark; + Utils$1.isPS4 = Utils$1.isWeb && navigator.userAgent.indexOf("PlayStation 4") !== -1; + Utils$1.isZiggo = Utils$1.isWeb && (navigator.userAgent.indexOf("EOSSTB") !== -1 || navigator.userAgent.indexOf("HZNSTB") !== -1); + class Base { + static defaultSetter(obj, name, value) { + obj[name] = value; + } + static patchObject(obj, settings) { + if (!Utils$1.isObjectLiteral(settings)) { + console.error("[Lightning] Settings must be object literal"); + } else { + let names = Object.keys(settings); + for (let i = 0, n = names.length; i < n; i++) { + let name = names[i]; + this.patchObjectProperty(obj, name, settings[name]); + } + } + } + static patchObjectProperty(obj, name, value) { + let setter = obj.setSetting || Base.defaultSetter; + if (name.charAt(0) === "_") { + if (name !== "__create") { + console.error("[Lightning] Patch of private property '" + name + "' is not allowed"); + } + } else if (name !== "type") { + if (Utils$1.isFunction(value) && value.__local) { + value = value.__local(obj); + } + setter(obj, name, value); + } + } + static local(func) { + func.__local = true; + } + } + class SpacingCalculator { + static getSpacing(mode, numberOfItems, remainingSpace) { + const itemGaps = numberOfItems - 1; + let spacePerGap; + let spacingBefore, spacingBetween; + switch (mode) { + case "flex-start": + spacingBefore = 0; + spacingBetween = 0; + break; + case "flex-end": + spacingBefore = remainingSpace; + spacingBetween = 0; + break; + case "center": + spacingBefore = remainingSpace / 2; + spacingBetween = 0; + break; + case "space-between": + spacingBefore = 0; + spacingBetween = Math.max(0, remainingSpace) / itemGaps; + break; + case "space-around": + if (remainingSpace < 0) { + return this.getSpacing("center", numberOfItems, remainingSpace); + } else { + spacePerGap = remainingSpace / (itemGaps + 1); + spacingBefore = 0.5 * spacePerGap; + spacingBetween = spacePerGap; + } + break; + case "space-evenly": + if (remainingSpace < 0) { + return this.getSpacing("center", numberOfItems, remainingSpace); + } else { + spacePerGap = remainingSpace / (itemGaps + 2); + spacingBefore = spacePerGap; + spacingBetween = spacePerGap; + } + break; + case "stretch": + spacingBefore = 0; + spacingBetween = 0; + break; + default: + throw new Error("Unknown mode: " + mode); + } + return { spacingBefore, spacingBetween }; + } + } + class ContentAligner { + constructor(layout) { + this._layout = layout; + this._totalCrossAxisSize = 0; + } + get _lines() { + return this._layout._lines; + } + init() { + this._totalCrossAxisSize = this._getTotalCrossAxisSize(); + } + align() { + const crossAxisSize = this._layout.crossAxisSize; + const remainingSpace = crossAxisSize - this._totalCrossAxisSize; + const { spacingBefore, spacingBetween } = this._getSpacing(remainingSpace); + const lines = this._lines; + const mode = this._layout._flexContainer.alignContent; + let growSize = 0; + if (mode === "stretch" && lines.length && remainingSpace > 0) { + growSize = remainingSpace / lines.length; + } + let currentPos = spacingBefore; + for (let i = 0, n = lines.length; i < n; i++) { + const crossAxisLayoutOffset = currentPos; + const aligner = lines[i].createItemAligner(); + let finalCrossAxisLayoutSize = lines[i].crossAxisLayoutSize + growSize; + aligner.setCrossAxisLayoutSize(finalCrossAxisLayoutSize); + aligner.setCrossAxisLayoutOffset(crossAxisLayoutOffset); + aligner.align(); + if (aligner.recursiveResizeOccured) { + lines[i].setItemPositions(); + } + currentPos += finalCrossAxisLayoutSize; + currentPos += spacingBetween; + } + } + get totalCrossAxisSize() { + return this._totalCrossAxisSize; + } + _getTotalCrossAxisSize() { + const lines = this._lines; + let total = 0; + for (let i = 0, n = lines.length; i < n; i++) { + const line = lines[i]; + total += line.crossAxisLayoutSize; + } + return total; + } + _getSpacing(remainingSpace) { + const mode = this._layout._flexContainer.alignContent; + const numberOfItems = this._lines.length; + return SpacingCalculator.getSpacing(mode, numberOfItems, remainingSpace); + } + } + class FlexUtils { + static getParentAxisSizeWithPadding(item, horizontal) { + const target = item.target; + const parent = target.getParent(); + if (!parent) { + return 0; + } else { + const flexParent = item.flexParent; + if (flexParent) { + return this.getAxisLayoutSize(flexParent, horizontal) + this.getTotalPadding(flexParent, horizontal); + } else { + return horizontal ? parent.w : parent.h; + } + } + } + static getRelAxisSize(item, horizontal) { + if (horizontal) { + if (item.funcW) { + if (this._allowRelAxisSizeFunction(item, true)) { + return item.funcW(this.getParentAxisSizeWithPadding(item, true)); + } else { + return 0; + } + } else { + return item.originalWidth; + } + } else { + if (item.funcH) { + if (this._allowRelAxisSizeFunction(item, false)) { + return item.funcH(this.getParentAxisSizeWithPadding(item, false)); + } else { + return 0; + } + } else { + return item.originalHeight; + } + } + } + static _allowRelAxisSizeFunction(item, horizontal) { + const flexParent = item.flexParent; + if (flexParent && flexParent._flex._layout.isAxisFitToContents(horizontal)) { + return false; + } + return true; + } + static isZeroAxisSize(item, horizontal) { + if (horizontal) { + return !item.originalWidth && !item.funcW; + } else { + return !item.originalHeight && !item.funcH; + } + } + static getAxisLayoutPos(item, horizontal) { + return horizontal ? item.x : item.y; + } + static getAxisLayoutSize(item, horizontal) { + return horizontal ? item.w : item.h; + } + static setAxisLayoutPos(item, horizontal, pos) { + if (horizontal) { + item.x = pos; + } else { + item.y = pos; + } + } + static setAxisLayoutSize(item, horizontal, size) { + if (horizontal) { + item.w = size; + } else { + item.h = size; + } + } + static getAxisMinSize(item, horizontal) { + let minSize = this.getPlainAxisMinSize(item, horizontal); + let flexItemMinSize = 0; + if (item.isFlexItemEnabled()) { + flexItemMinSize = item._flexItem._getMinSizeSetting(horizontal); + } + const hasLimitedMinSize = flexItemMinSize > 0; + if (hasLimitedMinSize) { + minSize = Math.max(minSize, flexItemMinSize); + } + return minSize; + } + static getPlainAxisMinSize(item, horizontal) { + if (item.isFlexEnabled()) { + return item._flex._layout.getAxisMinSize(horizontal); + } else { + const isShrinkable = item.flexItem.shrink !== 0; + if (isShrinkable) { + return 0; + } else { + return this.getRelAxisSize(item, horizontal); + } + } + } + static resizeAxis(item, horizontal, size) { + if (item.isFlexEnabled()) { + const isMainAxis = item._flex._horizontal === horizontal; + if (isMainAxis) { + item._flex._layout.resizeMainAxis(size); + } else { + item._flex._layout.resizeCrossAxis(size); + } + } else { + this.setAxisLayoutSize(item, horizontal, size); + } + } + static getPaddingOffset(item, horizontal) { + if (item.isFlexEnabled()) { + const flex = item._flex; + if (horizontal) { + return flex.paddingLeft; + } else { + return flex.paddingTop; + } + } else { + return 0; + } + } + static getTotalPadding(item, horizontal) { + if (item.isFlexEnabled()) { + const flex = item._flex; + if (horizontal) { + return flex.paddingRight + flex.paddingLeft; + } else { + return flex.paddingTop + flex.paddingBottom; + } + } else { + return 0; + } + } + static getMarginOffset(item, horizontal) { + const flexItem = item.flexItem; + if (flexItem) { + if (horizontal) { + return flexItem.marginLeft; + } else { + return flexItem.marginTop; + } + } else { + return 0; + } + } + static getTotalMargin(item, horizontal) { + const flexItem = item.flexItem; + if (flexItem) { + if (horizontal) { + return flexItem.marginRight + flexItem.marginLeft; + } else { + return flexItem.marginTop + flexItem.marginBottom; + } + } else { + return 0; + } + } + } + class SizeShrinker { + constructor(line) { + this._line = line; + this._amountRemaining = 0; + this._shrunkSize = 0; + } + shrink(amount) { + this._shrunkSize = 0; + this._amountRemaining = amount; + let totalShrinkAmount = this._getTotalShrinkAmount(); + if (totalShrinkAmount) { + const items = this._line.items; + do { + let amountPerShrink = this._amountRemaining / totalShrinkAmount; + for (let i = this._line.startIndex; i <= this._line.endIndex; i++) { + const item = items[i]; + const flexItem = item.flexItem; + const shrinkAmount = flexItem.shrink; + const isShrinkableItem = shrinkAmount > 0; + if (isShrinkableItem) { + let shrink = shrinkAmount * amountPerShrink; + const minSize = flexItem._getMainAxisMinSize(); + const size = flexItem._getMainAxisLayoutSize(); + if (size > minSize) { + const maxShrink = size - minSize; + const isFullyShrunk = shrink >= maxShrink; + if (isFullyShrunk) { + shrink = maxShrink; + totalShrinkAmount -= shrinkAmount; + } + const finalSize = size - shrink; + flexItem._resizeMainAxis(finalSize); + this._shrunkSize += shrink; + this._amountRemaining -= shrink; + if (Math.abs(this._amountRemaining) < 1e-5) { + return; + } + } + } + } + } while (totalShrinkAmount && Math.abs(this._amountRemaining) > 1e-5); + } + } + _getTotalShrinkAmount() { + let total = 0; + const items = this._line.items; + for (let i = this._line.startIndex; i <= this._line.endIndex; i++) { + const item = items[i]; + const flexItem = item.flexItem; + if (flexItem.shrink) { + const minSize = flexItem._getMainAxisMinSize(); + const size = flexItem._getMainAxisLayoutSize(); + if (size > minSize) { + total += flexItem.shrink; + } + } + } + return total; + } + getShrunkSize() { + return this._shrunkSize; + } + } + class SizeGrower { + constructor(line) { + this._line = line; + this._amountRemaining = 0; + this._grownSize = 0; + } + grow(amount) { + this._grownSize = 0; + this._amountRemaining = amount; + let totalGrowAmount = this._getTotalGrowAmount(); + if (totalGrowAmount) { + const items = this._line.items; + do { + let amountPerGrow = this._amountRemaining / totalGrowAmount; + for (let i = this._line.startIndex; i <= this._line.endIndex; i++) { + const item = items[i]; + const flexItem = item.flexItem; + const growAmount = flexItem.grow; + const isGrowableItem = growAmount > 0; + if (isGrowableItem) { + let grow = growAmount * amountPerGrow; + const maxSize = flexItem._getMainAxisMaxSizeSetting(); + const size = flexItem._getMainAxisLayoutSize(); + if (maxSize > 0) { + if (size >= maxSize) { + grow = 0; + } else { + const maxGrow = maxSize - size; + const isFullyGrown = grow >= maxGrow; + if (isFullyGrown) { + grow = maxGrow; + totalGrowAmount -= growAmount; + } + } + } + if (grow > 0) { + const finalSize = size + grow; + flexItem._resizeMainAxis(finalSize); + this._grownSize += grow; + this._amountRemaining -= grow; + if (Math.abs(this._amountRemaining) < 1e-5) { + return; + } + } + } + } + } while (totalGrowAmount && Math.abs(this._amountRemaining) > 1e-5); + } + } + _getTotalGrowAmount() { + let total = 0; + const items = this._line.items; + for (let i = this._line.startIndex; i <= this._line.endIndex; i++) { + const item = items[i]; + const flexItem = item.flexItem; + if (flexItem.grow) { + const maxSize = flexItem._getMainAxisMaxSizeSetting(); + const size = flexItem._getMainAxisLayoutSize(); + if (maxSize === 0 || size < maxSize) { + total += flexItem.grow; + } + } + } + return total; + } + getGrownSize() { + return this._grownSize; + } + } + class ItemPositioner { + constructor(lineLayout) { + this._line = lineLayout; + } + get _layout() { + return this._line._layout; + } + position() { + const { spacingBefore, spacingBetween } = this._getSpacing(); + let currentPos = spacingBefore; + const items = this._line.items; + for (let i = this._line.startIndex; i <= this._line.endIndex; i++) { + const item = items[i]; + item.flexItem._setMainAxisLayoutPos(currentPos); + currentPos += item.flexItem._getMainAxisLayoutSizeWithPaddingAndMargin(); + currentPos += spacingBetween; + } + } + _getSpacing() { + const remainingSpace = this._line._availableSpace; + let mode = this._layout._flexContainer.justifyContent; + const numberOfItems = this._line.numberOfItems; + return SpacingCalculator.getSpacing(mode, numberOfItems, remainingSpace); + } + } + class ItemAligner { + constructor(line) { + this._line = line; + this._crossAxisLayoutSize = 0; + this._crossAxisLayoutOffset = 0; + this._alignItemsSetting = null; + this._recursiveResizeOccured = false; + this._isCrossAxisFitToContents = false; + } + get _layout() { + return this._line._layout; + } + get _flexContainer() { + return this._layout._flexContainer; + } + setCrossAxisLayoutSize(size) { + this._crossAxisLayoutSize = size; + } + setCrossAxisLayoutOffset(offset) { + this._crossAxisLayoutOffset = offset; + } + align() { + this._alignItemsSetting = this._flexContainer.alignItems; + this._isCrossAxisFitToContents = this._layout.isAxisFitToContents(!this._flexContainer._horizontal); + this._recursiveResizeOccured = false; + const items = this._line.items; + for (let i = this._line.startIndex; i <= this._line.endIndex; i++) { + const item = items[i]; + this._alignItem(item); + } + } + get recursiveResizeOccured() { + return this._recursiveResizeOccured; + } + _alignItem(item) { + const flexItem = item.flexItem; + let align = flexItem.alignSelf || this._alignItemsSetting; + if (align === "stretch" && this._preventStretch(flexItem)) { + align = "flex-start"; + } + if (align !== "stretch" && !this._isCrossAxisFitToContents) { + if (flexItem._hasRelCrossAxisSize()) { + flexItem._resetCrossAxisLayoutSize(); + } + } + switch (align) { + case "flex-start": + this._alignItemFlexStart(flexItem); + break; + case "flex-end": + this._alignItemFlexEnd(flexItem); + break; + case "center": + this._alignItemFlexCenter(flexItem); + break; + case "stretch": + this._alignItemStretch(flexItem); + break; + } + } + _alignItemFlexStart(flexItem) { + flexItem._setCrossAxisLayoutPos(this._crossAxisLayoutOffset); + } + _alignItemFlexEnd(flexItem) { + const itemCrossAxisSize = flexItem._getCrossAxisLayoutSizeWithPaddingAndMargin(); + flexItem._setCrossAxisLayoutPos(this._crossAxisLayoutOffset + (this._crossAxisLayoutSize - itemCrossAxisSize)); + } + _alignItemFlexCenter(flexItem) { + const itemCrossAxisSize = flexItem._getCrossAxisLayoutSizeWithPaddingAndMargin(); + const center = (this._crossAxisLayoutSize - itemCrossAxisSize) / 2; + flexItem._setCrossAxisLayoutPos(this._crossAxisLayoutOffset + center); + } + _alignItemStretch(flexItem) { + flexItem._setCrossAxisLayoutPos(this._crossAxisLayoutOffset); + const mainAxisLayoutSizeBeforeResize = flexItem._getMainAxisLayoutSize(); + let size = this._crossAxisLayoutSize - flexItem._getCrossAxisMargin() - flexItem._getCrossAxisPadding(); + const crossAxisMinSizeSetting = flexItem._getCrossAxisMinSizeSetting(); + if (crossAxisMinSizeSetting > 0) { + size = Math.max(size, crossAxisMinSizeSetting); + } + const crossAxisMaxSizeSetting = flexItem._getCrossAxisMaxSizeSetting(); + const crossAxisMaxSizeSettingEnabled = crossAxisMaxSizeSetting > 0; + if (crossAxisMaxSizeSettingEnabled) { + size = Math.min(size, crossAxisMaxSizeSetting); + } + flexItem._resizeCrossAxis(size); + const mainAxisLayoutSizeAfterResize = flexItem._getMainAxisLayoutSize(); + const recursiveResize = mainAxisLayoutSizeAfterResize !== mainAxisLayoutSizeBeforeResize; + if (recursiveResize) { + this._recursiveResizeOccured = true; + } + } + _preventStretch(flexItem) { + const hasFixedCrossAxisSize = flexItem._hasFixedCrossAxisSize(); + const forceStretch = flexItem.alignSelf === "stretch"; + return hasFixedCrossAxisSize && !forceStretch; + } + } + class LineLayout { + constructor(layout, startIndex, endIndex, availableSpace) { + this._layout = layout; + this.items = layout.items; + this.startIndex = startIndex; + this.endIndex = endIndex; + this._availableSpace = availableSpace; + } + performLayout() { + this._setItemSizes(); + this.setItemPositions(); + this._calcLayoutInfo(); + } + _setItemSizes() { + if (this._availableSpace > 0) { + this._growItemSizes(this._availableSpace); + } else if (this._availableSpace < 0) { + this._shrinkItemSizes(-this._availableSpace); + } + } + _growItemSizes(amount) { + const grower = new SizeGrower(this); + grower.grow(amount); + this._availableSpace -= grower.getGrownSize(); + } + _shrinkItemSizes(amount) { + const shrinker = new SizeShrinker(this); + shrinker.shrink(amount); + this._availableSpace += shrinker.getShrunkSize(); + } + setItemPositions() { + const positioner = new ItemPositioner(this); + positioner.position(); + } + createItemAligner() { + return new ItemAligner(this); + } + _calcLayoutInfo() { + this._calcCrossAxisMaxLayoutSize(); + } + getMainAxisMinSize() { + let mainAxisMinSize = 0; + for (let i = this.startIndex; i <= this.endIndex; i++) { + const item = this.items[i]; + mainAxisMinSize += item.flexItem._getMainAxisMinSizeWithPaddingAndMargin(); + } + return mainAxisMinSize; + } + get numberOfItems() { + return this.endIndex - this.startIndex + 1; + } + get crossAxisLayoutSize() { + const noSpecifiedCrossAxisSize = this._layout.isCrossAxisFitToContents() && !this._layout.resizingCrossAxis; + const shouldFitToContents = this._layout.isWrapping() || noSpecifiedCrossAxisSize; + if (shouldFitToContents) { + return this._crossAxisMaxLayoutSize; + } else { + return this._layout.crossAxisSize; + } + } + _calcCrossAxisMaxLayoutSize() { + this._crossAxisMaxLayoutSize = this._getCrossAxisMaxLayoutSize(); + } + _getCrossAxisMaxLayoutSize() { + let crossAxisMaxSize = 0; + for (let i = this.startIndex; i <= this.endIndex; i++) { + const item = this.items[i]; + crossAxisMaxSize = Math.max(crossAxisMaxSize, item.flexItem._getCrossAxisLayoutSizeWithPaddingAndMargin()); + } + return crossAxisMaxSize; + } + } + class LineLayouter { + constructor(layout) { + this._layout = layout; + this._mainAxisMinSize = -1; + this._crossAxisMinSize = -1; + this._mainAxisContentSize = 0; + } + get lines() { + return this._lines; + } + get mainAxisMinSize() { + if (this._mainAxisMinSize === -1) { + this._mainAxisMinSize = this._getMainAxisMinSize(); + } + return this._mainAxisMinSize; + } + get crossAxisMinSize() { + if (this._crossAxisMinSize === -1) { + this._crossAxisMinSize = this._getCrossAxisMinSize(); + } + return this._crossAxisMinSize; + } + get mainAxisContentSize() { + return this._mainAxisContentSize; + } + layoutLines() { + this._setup(); + const items = this._layout.items; + const wrap = this._layout.isWrapping(); + let startIndex = 0; + let i; + const n = items.length; + for (i = 0; i < n; i++) { + const item = items[i]; + this._layoutFlexItem(item); + const itemMainAxisSize = item.flexItem._getMainAxisLayoutSizeWithPaddingAndMargin(); + if (wrap && i > startIndex) { + const isOverflowing = this._curMainAxisPos + itemMainAxisSize > this._mainAxisSize; + if (isOverflowing) { + this._layoutLine(startIndex, i - 1); + this._curMainAxisPos = 0; + startIndex = i; + } + } + this._addToMainAxisPos(itemMainAxisSize); + } + if (startIndex < i) { + this._layoutLine(startIndex, i - 1); + } + } + _layoutFlexItem(item) { + if (item.isFlexEnabled()) { + item.flexLayout.updateTreeLayout(); + } else { + item.flexItem._resetLayoutSize(); + } + } + _setup() { + this._mainAxisSize = this._layout.mainAxisSize; + this._curMainAxisPos = 0; + this._maxMainAxisPos = 0; + this._lines = []; + this._mainAxisMinSize = -1; + this._crossAxisMinSize = -1; + this._mainAxisContentSize = 0; + } + _addToMainAxisPos(itemMainAxisSize) { + this._curMainAxisPos += itemMainAxisSize; + if (this._curMainAxisPos > this._maxMainAxisPos) { + this._maxMainAxisPos = this._curMainAxisPos; + } + } + _layoutLine(startIndex, endIndex) { + const availableSpace = this._getAvailableMainAxisLayoutSpace(); + const line = new LineLayout(this._layout, startIndex, endIndex, availableSpace); + line.performLayout(); + this._lines.push(line); + if (this._mainAxisContentSize === 0 || this._curMainAxisPos > this._mainAxisContentSize) { + this._mainAxisContentSize = this._curMainAxisPos; + } + } + _getAvailableMainAxisLayoutSpace() { + if (!this._layout.resizingMainAxis && this._layout.isMainAxisFitToContents()) { + return 0; + } else { + return this._mainAxisSize - this._curMainAxisPos; + } + } + _getCrossAxisMinSize() { + let crossAxisMinSize = 0; + const items = this._layout.items; + for (let i = 0, n = items.length; i < n; i++) { + const item = items[i]; + const itemCrossAxisMinSize = item.flexItem._getCrossAxisMinSizeWithPaddingAndMargin(); + crossAxisMinSize = Math.max(crossAxisMinSize, itemCrossAxisMinSize); + } + return crossAxisMinSize; + } + _getMainAxisMinSize() { + if (this._lines.length === 1) { + return this._lines[0].getMainAxisMinSize(); + } else { + return this._layout.mainAxisSize; + } + } + } + class ItemCoordinatesUpdater { + constructor(layout) { + this._layout = layout; + this._isReverse = this._flexContainer._reverse; + this._horizontalPaddingOffset = this._layout._getHorizontalPaddingOffset(); + this._verticalPaddingOffset = this._layout._getVerticalPaddingOffset(); + } + get _flexContainer() { + return this._layout._flexContainer; + } + finalize() { + const parentFlex = this._layout.getParentFlexContainer(); + if (parentFlex) { + const updater = new ItemCoordinatesUpdater(parentFlex._layout); + updater._finalizeItemAndChildren(this._flexContainer.item); + } else { + this._finalizeRoot(); + this._finalizeItems(); + } + } + _finalizeRoot() { + const item = this._flexContainer.item; + let x = FlexUtils.getAxisLayoutPos(item, true); + let y = FlexUtils.getAxisLayoutPos(item, false); + let w = FlexUtils.getAxisLayoutSize(item, true); + let h = FlexUtils.getAxisLayoutSize(item, false); + w += this._layout._getHorizontalPadding(); + h += this._layout._getVerticalPadding(); + item.clearRecalcFlag(); + item.setLayout(x, y, w, h); + } + _finalizeItems() { + const items = this._layout.items; + for (let i = 0, n = items.length; i < n; i++) { + const item = items[i]; + const validCache = this._validateItemCache(item); + this._finalizeItem(item); + if (!validCache) { + this._finalizeItemChildren(item); + } + } + } + _validateItemCache(item) { + if (item.recalc === 0) { + if (item.isFlexEnabled()) { + const layout = item._flex._layout; + const dimensionsMatchPreviousResult = item.w === item.target.w && item.h === item.target.h; + if (dimensionsMatchPreviousResult) { + return true; + } else { + const crossAxisSize = layout.crossAxisSize; + layout.performResizeMainAxis(layout.mainAxisSize); + layout.performResizeCrossAxis(crossAxisSize); + } + } + } + return false; + } + _finalizeItemAndChildren(item) { + this._finalizeItem(item); + this._finalizeItemChildren(item); + } + _finalizeItem(item) { + if (this._isReverse) { + this._reverseMainAxisLayoutPos(item); + } + let x = FlexUtils.getAxisLayoutPos(item, true); + let y = FlexUtils.getAxisLayoutPos(item, false); + let w = FlexUtils.getAxisLayoutSize(item, true); + let h = FlexUtils.getAxisLayoutSize(item, false); + x += this._horizontalPaddingOffset; + y += this._verticalPaddingOffset; + const flex = item.flex; + if (flex) { + w += item._flex._layout._getHorizontalPadding(); + h += item._flex._layout._getVerticalPadding(); + } + const flexItem = item.flexItem; + if (flexItem) { + x += flexItem._getHorizontalMarginOffset(); + y += flexItem._getVerticalMarginOffset(); + } + item.clearRecalcFlag(); + item.setLayout(x, y, w, h); + } + _finalizeItemChildren(item) { + const flex = item._flex; + if (flex) { + const updater = new ItemCoordinatesUpdater(flex._layout); + updater._finalizeItems(); + } + } + _reverseMainAxisLayoutPos(item) { + const endPos = item.flexItem._getMainAxisLayoutPos() + item.flexItem._getMainAxisLayoutSizeWithPaddingAndMargin(); + const reversedPos = this._layout.mainAxisSize - endPos; + item.flexItem._setMainAxisLayoutPos(reversedPos); + } + } + class FlexLayout { + constructor(flexContainer) { + this._flexContainer = flexContainer; + this._lineLayouter = new LineLayouter(this); + this._resizingMainAxis = false; + this._resizingCrossAxis = false; + this._cachedMainAxisSizeAfterLayout = 0; + this._cachedCrossAxisSizeAfterLayout = 0; + this._shrunk = false; + } + get shrunk() { + return this._shrunk; + } + get recalc() { + return this.item.recalc; + } + layoutTree() { + const isSubTree = this.item.flexParent !== null; + if (isSubTree) { + this._updateSubTreeLayout(); + } else { + this.updateTreeLayout(); + } + this.updateItemCoords(); + } + updateTreeLayout() { + if (this.recalc) { + this._performUpdateLayoutTree(); + } else { + this._performUpdateLayoutTreeFromCache(); + } + } + _performUpdateLayoutTree() { + this._setInitialAxisSizes(); + this._layoutAxes(); + this._refreshLayoutCache(); + } + _refreshLayoutCache() { + this._cachedMainAxisSizeAfterLayout = this.mainAxisSize; + this._cachedCrossAxisSizeAfterLayout = this.crossAxisSize; + } + _performUpdateLayoutTreeFromCache() { + const sizeMightHaveChanged = this.item.funcW || this.item.funcH; + if (sizeMightHaveChanged) { + this.item.enableLocalRecalcFlag(); + this._performUpdateLayoutTree(); + } else { + this.mainAxisSize = this._cachedMainAxisSizeAfterLayout; + this.crossAxisSize = this._cachedCrossAxisSizeAfterLayout; + } + } + updateItemCoords() { + const updater = new ItemCoordinatesUpdater(this); + updater.finalize(); + } + _updateSubTreeLayout() { + const crossAxisSize = this.crossAxisSize; + this._layoutMainAxis(); + this.performResizeCrossAxis(crossAxisSize); + } + _setInitialAxisSizes() { + if (this.item.isFlexItemEnabled()) { + this.item.flexItem._resetLayoutSize(); + } else { + this.mainAxisSize = this._getMainAxisBasis(); + this.crossAxisSize = this._getCrossAxisBasis(); + } + this._resizingMainAxis = false; + this._resizingCrossAxis = false; + this._shrunk = false; + } + _layoutAxes() { + this._layoutMainAxis(); + this._layoutCrossAxis(); + } + _layoutMainAxis() { + this._layoutLines(); + this._fitMainAxisSizeToContents(); + } + _layoutLines() { + this._lineLayouter.layoutLines(); + } + get _lines() { + return this._lineLayouter.lines; + } + _fitMainAxisSizeToContents() { + if (!this._resizingMainAxis) { + if (this.isMainAxisFitToContents()) { + this.mainAxisSize = this._lineLayouter.mainAxisContentSize; + } + } + } + _layoutCrossAxis() { + const aligner = new ContentAligner(this); + aligner.init(); + this._totalCrossAxisSize = aligner.totalCrossAxisSize; + this._fitCrossAxisSizeToContents(); + aligner.align(); + } + _fitCrossAxisSizeToContents() { + if (!this._resizingCrossAxis) { + if (this.isCrossAxisFitToContents()) { + this.crossAxisSize = this._totalCrossAxisSize; + } + } + } + isWrapping() { + return this._flexContainer.wrap; + } + isAxisFitToContents(horizontal) { + if (this._horizontal === horizontal) { + return this.isMainAxisFitToContents(); + } else { + return this.isCrossAxisFitToContents(); + } + } + isMainAxisFitToContents() { + return !this.isWrapping() && !this._hasFixedMainAxisBasis(); + } + isCrossAxisFitToContents() { + return !this._hasFixedCrossAxisBasis(); + } + _hasFixedMainAxisBasis() { + return !FlexUtils.isZeroAxisSize(this.item, this._horizontal); + } + _hasFixedCrossAxisBasis() { + return !FlexUtils.isZeroAxisSize(this.item, !this._horizontal); + } + getAxisMinSize(horizontal) { + if (this._horizontal === horizontal) { + return this._getMainAxisMinSize(); + } else { + return this._getCrossAxisMinSize(); + } + } + _getMainAxisMinSize() { + return this._lineLayouter.mainAxisMinSize; + } + _getCrossAxisMinSize() { + return this._lineLayouter.crossAxisMinSize; + } + resizeMainAxis(size) { + if (this.mainAxisSize !== size) { + if (this.recalc > 0) { + this.performResizeMainAxis(size); + } else { + if (this._checkValidCacheMainAxisResize()) { + this.mainAxisSize = size; + this._fitCrossAxisSizeToContents(); + } else { + this.item.enableLocalRecalcFlag(); + this.performResizeMainAxis(size); + } + } + } + } + _checkValidCacheMainAxisResize(size) { + const isFinalMainAxisSize = size === this.targetMainAxisSize; + if (isFinalMainAxisSize) { + return true; + } + const canIgnoreCacheMiss = !this.isCrossAxisFitToContents(); + if (canIgnoreCacheMiss) { + return true; + } + return false; + } + performResizeMainAxis(size) { + const isShrinking = size < this.mainAxisSize; + this._shrunk = isShrinking; + this.mainAxisSize = size; + this._resizingMainAxis = true; + this._layoutAxes(); + this._resizingMainAxis = false; + } + resizeCrossAxis(size) { + if (this.crossAxisSize !== size) { + if (this.recalc > 0) { + this.performResizeCrossAxis(size); + } else { + this.crossAxisSize = size; + } + } + } + performResizeCrossAxis(size) { + this.crossAxisSize = size; + this._resizingCrossAxis = true; + this._layoutCrossAxis(); + this._resizingCrossAxis = false; + } + get targetMainAxisSize() { + return this._horizontal ? this.item.target.w : this.item.target.h; + } + get targetCrossAxisSize() { + return this._horizontal ? this.item.target.h : this.item.target.w; + } + getParentFlexContainer() { + return this.item.isFlexItemEnabled() ? this.item.flexItem.ctr : null; + } + _getHorizontalPadding() { + return FlexUtils.getTotalPadding(this.item, true); + } + _getVerticalPadding() { + return FlexUtils.getTotalPadding(this.item, false); + } + _getHorizontalPaddingOffset() { + return FlexUtils.getPaddingOffset(this.item, true); + } + _getVerticalPaddingOffset() { + return FlexUtils.getPaddingOffset(this.item, false); + } + _getMainAxisBasis() { + return FlexUtils.getRelAxisSize(this.item, this._horizontal); + } + _getCrossAxisBasis() { + return FlexUtils.getRelAxisSize(this.item, !this._horizontal); + } + get _horizontal() { + return this._flexContainer._horizontal; + } + get _reverse() { + return this._flexContainer._reverse; + } + get item() { + return this._flexContainer.item; + } + get items() { + return this.item.items; + } + get resizingMainAxis() { + return this._resizingMainAxis; + } + get resizingCrossAxis() { + return this._resizingCrossAxis; + } + get numberOfItems() { + return this.items.length; + } + get mainAxisSize() { + return FlexUtils.getAxisLayoutSize(this.item, this._horizontal); + } + get crossAxisSize() { + return FlexUtils.getAxisLayoutSize(this.item, !this._horizontal); + } + set mainAxisSize(v) { + FlexUtils.setAxisLayoutSize(this.item, this._horizontal, v); + } + set crossAxisSize(v) { + FlexUtils.setAxisLayoutSize(this.item, !this._horizontal, v); + } + } + class FlexContainer { + constructor(item) { + this._item = item; + this._layout = new FlexLayout(this); + this._horizontal = true; + this._reverse = false; + this._wrap = false; + this._alignItems = "stretch"; + this._justifyContent = "flex-start"; + this._alignContent = "flex-start"; + this._paddingLeft = 0; + this._paddingTop = 0; + this._paddingRight = 0; + this._paddingBottom = 0; + } + get item() { + return this._item; + } + _changedDimensions() { + this._item.changedDimensions(); + } + _changedContents() { + this._item.changedContents(); + } + get direction() { + return (this._horizontal ? "row" : "column") + (this._reverse ? "-reverse" : ""); + } + set direction(f) { + if (this.direction === f) + return; + this._horizontal = f === "row" || f === "row-reverse"; + this._reverse = f === "row-reverse" || f === "column-reverse"; + this._changedContents(); + } + set wrap(v) { + this._wrap = v; + this._changedContents(); + } + get wrap() { + return this._wrap; + } + get alignItems() { + return this._alignItems; + } + set alignItems(v) { + if (this._alignItems === v) + return; + if (FlexContainer.ALIGN_ITEMS.indexOf(v) === -1) { + throw new Error("Unknown alignItems, options: " + FlexContainer.ALIGN_ITEMS.join(",")); + } + this._alignItems = v; + this._changedContents(); + } + get alignContent() { + return this._alignContent; + } + set alignContent(v) { + if (this._alignContent === v) + return; + if (FlexContainer.ALIGN_CONTENT.indexOf(v) === -1) { + throw new Error("Unknown alignContent, options: " + FlexContainer.ALIGN_CONTENT.join(",")); + } + this._alignContent = v; + this._changedContents(); + } + get justifyContent() { + return this._justifyContent; + } + set justifyContent(v) { + if (this._justifyContent === v) + return; + if (FlexContainer.JUSTIFY_CONTENT.indexOf(v) === -1) { + throw new Error("Unknown justifyContent, options: " + FlexContainer.JUSTIFY_CONTENT.join(",")); + } + this._justifyContent = v; + this._changedContents(); + } + set padding(v) { + this.paddingLeft = v; + this.paddingTop = v; + this.paddingRight = v; + this.paddingBottom = v; + } + get padding() { + return this.paddingLeft; + } + set paddingLeft(v) { + this._paddingLeft = v; + this._changedDimensions(); + } + get paddingLeft() { + return this._paddingLeft; + } + set paddingTop(v) { + this._paddingTop = v; + this._changedDimensions(); + } + get paddingTop() { + return this._paddingTop; + } + set paddingRight(v) { + this._paddingRight = v; + this._changedDimensions(); + } + get paddingRight() { + return this._paddingRight; + } + set paddingBottom(v) { + this._paddingBottom = v; + this._changedDimensions(); + } + get paddingBottom() { + return this._paddingBottom; + } + patch(settings) { + Base.patchObject(this, settings); + } + } + FlexContainer.ALIGN_ITEMS = ["flex-start", "flex-end", "center", "stretch"]; + FlexContainer.ALIGN_CONTENT = ["flex-start", "flex-end", "center", "space-between", "space-around", "space-evenly", "stretch"]; + FlexContainer.JUSTIFY_CONTENT = ["flex-start", "flex-end", "center", "space-between", "space-around", "space-evenly"]; + class FlexItem { + constructor(item) { + this._ctr = null; + this._item = item; + this._grow = 0; + this._shrink = FlexItem.SHRINK_AUTO; + this._alignSelf = void 0; + this._minWidth = 0; + this._minHeight = 0; + this._maxWidth = 0; + this._maxHeight = 0; + this._marginLeft = 0; + this._marginTop = 0; + this._marginRight = 0; + this._marginBottom = 0; + } + get item() { + return this._item; + } + get grow() { + return this._grow; + } + set grow(v) { + if (this._grow === v) + return; + this._grow = parseInt(v) || 0; + this._changed(); + } + get shrink() { + if (this._shrink === FlexItem.SHRINK_AUTO) { + return this._getDefaultShrink(); + } + return this._shrink; + } + _getDefaultShrink() { + if (this.item.isFlexEnabled()) { + return 1; + } else { + return 0; + } + } + set shrink(v) { + if (this._shrink === v) + return; + this._shrink = parseInt(v) || 0; + this._changed(); + } + get alignSelf() { + return this._alignSelf; + } + set alignSelf(v) { + if (this._alignSelf === v) + return; + if (v === void 0) { + this._alignSelf = void 0; + } else { + if (FlexContainer.ALIGN_ITEMS.indexOf(v) === -1) { + throw new Error("Unknown alignSelf, options: " + FlexContainer.ALIGN_ITEMS.join(",")); + } + this._alignSelf = v; + } + this._changed(); + } + get minWidth() { + return this._minWidth; + } + set minWidth(v) { + this._minWidth = Math.max(0, v); + this._item.changedDimensions(true, false); + } + get minHeight() { + return this._minHeight; + } + set minHeight(v) { + this._minHeight = Math.max(0, v); + this._item.changedDimensions(false, true); + } + get maxWidth() { + return this._maxWidth; + } + set maxWidth(v) { + this._maxWidth = Math.max(0, v); + this._item.changedDimensions(true, false); + } + get maxHeight() { + return this._maxHeight; + } + set maxHeight(v) { + this._maxHeight = Math.max(0, v); + this._item.changedDimensions(false, true); + } + set margin(v) { + this.marginLeft = v; + this.marginTop = v; + this.marginRight = v; + this.marginBottom = v; + } + get margin() { + return this.marginLeft; + } + set marginLeft(v) { + this._marginLeft = v; + this._changed(); + } + get marginLeft() { + return this._marginLeft; + } + set marginTop(v) { + this._marginTop = v; + this._changed(); + } + get marginTop() { + return this._marginTop; + } + set marginRight(v) { + this._marginRight = v; + this._changed(); + } + get marginRight() { + return this._marginRight; + } + set marginBottom(v) { + this._marginBottom = v; + this._changed(); + } + get marginBottom() { + return this._marginBottom; + } + _changed() { + if (this.ctr) + this.ctr._changedContents(); + } + set ctr(v) { + this._ctr = v; + } + get ctr() { + return this._ctr; + } + patch(settings) { + Base.patchObject(this, settings); + } + _resetLayoutSize() { + this._resetHorizontalAxisLayoutSize(); + this._resetVerticalAxisLayoutSize(); + } + _resetCrossAxisLayoutSize() { + if (this.ctr._horizontal) { + this._resetVerticalAxisLayoutSize(); + } else { + this._resetHorizontalAxisLayoutSize(); + } + } + _resetHorizontalAxisLayoutSize() { + let w = FlexUtils.getRelAxisSize(this.item, true); + if (this._minWidth) { + w = Math.max(this._minWidth, w); + } + if (this._maxWidth) { + w = Math.min(this._maxWidth, w); + } + FlexUtils.setAxisLayoutSize(this.item, true, w); + } + _resetVerticalAxisLayoutSize() { + let h = FlexUtils.getRelAxisSize(this.item, false); + if (this._minHeight) { + h = Math.max(this._minHeight, h); + } + if (this._maxHeight) { + h = Math.min(this._maxHeight, h); + } + FlexUtils.setAxisLayoutSize(this.item, false, h); + } + _getCrossAxisMinSizeSetting() { + return this._getMinSizeSetting(!this.ctr._horizontal); + } + _getCrossAxisMaxSizeSetting() { + return this._getMaxSizeSetting(!this.ctr._horizontal); + } + _getMainAxisMaxSizeSetting() { + return this._getMaxSizeSetting(this.ctr._horizontal); + } + _getMinSizeSetting(horizontal) { + if (horizontal) { + return this._minWidth; + } else { + return this._minHeight; + } + } + _getMaxSizeSetting(horizontal) { + if (horizontal) { + return this._maxWidth; + } else { + return this._maxHeight; + } + } + _getMainAxisMinSize() { + return FlexUtils.getAxisMinSize(this.item, this.ctr._horizontal); + } + _getCrossAxisMinSize() { + return FlexUtils.getAxisMinSize(this.item, !this.ctr._horizontal); + } + _getMainAxisLayoutSize() { + return FlexUtils.getAxisLayoutSize(this.item, this.ctr._horizontal); + } + _getMainAxisLayoutPos() { + return FlexUtils.getAxisLayoutPos(this.item, this.ctr._horizontal); + } + _setMainAxisLayoutPos(pos) { + return FlexUtils.setAxisLayoutPos(this.item, this.ctr._horizontal, pos); + } + _setCrossAxisLayoutPos(pos) { + return FlexUtils.setAxisLayoutPos(this.item, !this.ctr._horizontal, pos); + } + _getCrossAxisLayoutSize() { + return FlexUtils.getAxisLayoutSize(this.item, !this.ctr._horizontal); + } + _resizeCrossAxis(size) { + return FlexUtils.resizeAxis(this.item, !this.ctr._horizontal, size); + } + _resizeMainAxis(size) { + return FlexUtils.resizeAxis(this.item, this.ctr._horizontal, size); + } + _getMainAxisPadding() { + return FlexUtils.getTotalPadding(this.item, this.ctr._horizontal); + } + _getCrossAxisPadding() { + return FlexUtils.getTotalPadding(this.item, !this.ctr._horizontal); + } + _getMainAxisMargin() { + return FlexUtils.getTotalMargin(this.item, this.ctr._horizontal); + } + _getCrossAxisMargin() { + return FlexUtils.getTotalMargin(this.item, !this.ctr._horizontal); + } + _getHorizontalMarginOffset() { + return FlexUtils.getMarginOffset(this.item, true); + } + _getVerticalMarginOffset() { + return FlexUtils.getMarginOffset(this.item, false); + } + _getMainAxisMinSizeWithPaddingAndMargin() { + return this._getMainAxisMinSize() + this._getMainAxisPadding() + this._getMainAxisMargin(); + } + _getCrossAxisMinSizeWithPaddingAndMargin() { + return this._getCrossAxisMinSize() + this._getCrossAxisPadding() + this._getCrossAxisMargin(); + } + _getMainAxisLayoutSizeWithPaddingAndMargin() { + return this._getMainAxisLayoutSize() + this._getMainAxisPadding() + this._getMainAxisMargin(); + } + _getCrossAxisLayoutSizeWithPaddingAndMargin() { + return this._getCrossAxisLayoutSize() + this._getCrossAxisPadding() + this._getCrossAxisMargin(); + } + _hasFixedCrossAxisSize() { + return !FlexUtils.isZeroAxisSize(this.item, !this.ctr._horizontal); + } + _hasRelCrossAxisSize() { + return !!(this.ctr._horizontal ? this.item.funcH : this.item.funcW); + } + } + FlexItem.SHRINK_AUTO = -1; + class FlexTarget { + constructor(target) { + this._target = target; + this._recalc = 0; + this._enabled = false; + this.x = 0; + this.y = 0; + this.w = 0; + this.h = 0; + this._originalX = 0; + this._originalY = 0; + this._originalWidth = 0; + this._originalHeight = 0; + this._flex = null; + this._flexItem = null; + this._flexItemDisabled = false; + this._items = null; + } + get flexLayout() { + return this.flex ? this.flex._layout : null; + } + layoutFlexTree() { + if (this.isFlexEnabled() && this.isChanged()) { + this.flexLayout.layoutTree(); + } + } + get target() { + return this._target; + } + get flex() { + return this._flex; + } + set flex(v) { + if (!v) { + if (this.isFlexEnabled()) { + this._disableFlex(); + } + } else { + if (!this.isFlexEnabled()) { + this._enableFlex(); + } + this._flex.patch(v); + } + } + get flexItem() { + if (this._flexItemDisabled) { + return false; + } + this._ensureFlexItem(); + return this._flexItem; + } + set flexItem(v) { + if (v === false) { + if (!this._flexItemDisabled) { + const parent = this.flexParent; + this._flexItemDisabled = true; + this._checkEnabled(); + if (parent) { + parent._clearFlexItemsCache(); + parent.changedContents(); + } + } + } else { + this._ensureFlexItem(); + this._flexItem.patch(v); + if (this._flexItemDisabled) { + this._flexItemDisabled = false; + this._checkEnabled(); + const parent = this.flexParent; + if (parent) { + parent._clearFlexItemsCache(); + parent.changedContents(); + } + } + } + } + _enableFlex() { + this._flex = new FlexContainer(this); + this._checkEnabled(); + this.changedDimensions(); + this._enableChildrenAsFlexItems(); + } + _disableFlex() { + this.changedDimensions(); + this._flex = null; + this._checkEnabled(); + this._disableChildrenAsFlexItems(); + } + _enableChildrenAsFlexItems() { + const children = this._target._children; + if (children) { + for (let i = 0, n = children.length; i < n; i++) { + const child = children[i]; + child.layout._enableFlexItem(); + } + } + } + _disableChildrenAsFlexItems() { + const children = this._target._children; + if (children) { + for (let i = 0, n = children.length; i < n; i++) { + const child = children[i]; + child.layout._disableFlexItem(); + } + } + } + _enableFlexItem() { + this._ensureFlexItem(); + const flexParent = this._target._parent._layout; + this._flexItem.ctr = flexParent._flex; + flexParent.changedContents(); + this._checkEnabled(); + } + _disableFlexItem() { + if (this._flexItem) { + this._flexItem.ctr = null; + } + this._checkEnabled(); + this._resetOffsets(); + } + _resetOffsets() { + this.x = 0; + this.y = 0; + } + _ensureFlexItem() { + if (!this._flexItem) { + this._flexItem = new FlexItem(this); + } + } + _checkEnabled() { + const enabled = this.isEnabled(); + if (this._enabled !== enabled) { + if (enabled) { + this._enable(); + } else { + this._disable(); + } + this._enabled = enabled; + } + } + _enable() { + this._setupTargetForFlex(); + this._target.enableFlexLayout(); + } + _disable() { + this._restoreTargetToNonFlex(); + this._target.disableFlexLayout(); + } + isEnabled() { + return this.isFlexEnabled() || this.isFlexItemEnabled(); + } + isFlexEnabled() { + return this._flex !== null; + } + isFlexItemEnabled() { + return this.flexParent !== null; + } + _restoreTargetToNonFlex() { + const target = this._target; + target.x = this._originalX; + target.y = this._originalY; + target.setDimensions(this._originalWidth, this._originalHeight); + } + _setupTargetForFlex() { + const target = this._target; + this._originalX = target._x; + this._originalY = target._y; + this._originalWidth = target._w; + this._originalHeight = target._h; + } + setParent(from, to) { + if (from && from.isFlexContainer()) { + from._layout._changedChildren(); + } + if (to && to.isFlexContainer()) { + this._enableFlexItem(); + to._layout._changedChildren(); + } + this._checkEnabled(); + } + get flexParent() { + if (this._flexItemDisabled) { + return null; + } + const parent = this._target._parent; + if (parent && parent.isFlexContainer()) { + return parent._layout; + } + return null; + } + setVisible(v) { + const parent = this.flexParent; + if (parent) { + parent._changedChildren(); + } + } + get items() { + if (!this._items) { + this._items = this._getFlexItems(); + } + return this._items; + } + _getFlexItems() { + const items = []; + const children = this._target._children; + if (children) { + for (let i = 0, n = children.length; i < n; i++) { + const item = children[i]; + if (item.visible) { + if (item.isFlexItem()) { + items.push(item.layout); + } + } + } + } + return items; + } + _changedChildren() { + this._clearFlexItemsCache(); + this.changedContents(); + } + _clearFlexItemsCache() { + this._items = null; + } + setLayout(x, y, w, h) { + let originalX = this._originalX; + let originalY = this._originalY; + if (this.funcX) { + originalX = this.funcX(FlexUtils.getParentAxisSizeWithPadding(this, true)); + } + if (this.funcY) { + originalY = this.funcY(FlexUtils.getParentAxisSizeWithPadding(this, false)); + } + if (this.isFlexItemEnabled()) { + this.target.setLayout(x + originalX, y + originalY, w, h); + } else { + this.target.setLayout(originalX, originalY, w, h); + } + } + changedDimensions(changeWidth = true, changeHeight = true) { + this._updateRecalc(changeWidth, changeHeight); + } + changedContents() { + this._updateRecalc(); + } + forceLayout() { + this._updateRecalc(); + } + isChanged() { + return this._recalc > 0; + } + _updateRecalc(changeExternalWidth = false, changeExternalHeight = false) { + if (this.isFlexEnabled()) { + const layout = this._flex._layout; + changeExternalWidth = changeExternalWidth || layout.isAxisFitToContents(true); + changeExternalHeight = changeExternalHeight || layout.isAxisFitToContents(false); + } + const recalc = 1 + (changeExternalWidth ? 2 : 0) + (changeExternalHeight ? 4 : 0); + const newRecalcFlags = this.getNewRecalcFlags(recalc); + this._recalc |= recalc; + if (newRecalcFlags > 1) { + if (this.flexParent) { + this.flexParent._updateRecalcBottomUp(recalc); + } else { + this._target.triggerLayout(); + } + } else { + this._target.triggerLayout(); + } + } + getNewRecalcFlags(flags) { + return 7 - this._recalc & flags; + } + _updateRecalcBottomUp(childRecalc) { + const newRecalc = this._getRecalcFromChangedChildRecalc(childRecalc); + const newRecalcFlags = this.getNewRecalcFlags(newRecalc); + this._recalc |= newRecalc; + if (newRecalcFlags > 1) { + const flexParent = this.flexParent; + if (flexParent) { + flexParent._updateRecalcBottomUp(newRecalc); + } else { + this._target.triggerLayout(); + } + } else { + this._target.triggerLayout(); + } + } + _getRecalcFromChangedChildRecalc(childRecalc) { + const layout = this._flex._layout; + const mainAxisRecalcFlag = layout._horizontal ? 1 : 2; + const crossAxisRecalcFlag = layout._horizontal ? 2 : 1; + const crossAxisDimensionsChangedInChild = childRecalc & crossAxisRecalcFlag; + if (!crossAxisDimensionsChangedInChild) { + const mainAxisDimensionsChangedInChild = childRecalc & mainAxisRecalcFlag; + if (mainAxisDimensionsChangedInChild) { + const mainAxisIsWrapping = layout.isWrapping(); + if (mainAxisIsWrapping) { + const crossAxisIsFitToContents = layout.isCrossAxisFitToContents(); + if (crossAxisIsFitToContents) { + childRecalc += crossAxisRecalcFlag; + } + } + } + } + let isWidthDynamic = layout.isAxisFitToContents(true); + let isHeightDynamic = layout.isAxisFitToContents(false); + if (layout.shrunk) { + if (layout._horizontal) { + isWidthDynamic = true; + } else { + isHeightDynamic = true; + } + } + const localRecalc = 1 + (isWidthDynamic ? 2 : 0) + (isHeightDynamic ? 4 : 0); + const combinedRecalc = childRecalc & localRecalc; + return combinedRecalc; + } + get recalc() { + return this._recalc; + } + clearRecalcFlag() { + this._recalc = 0; + } + enableLocalRecalcFlag() { + this._recalc = 1; + } + get originalX() { + return this._originalX; + } + setOriginalXWithoutUpdatingLayout(v) { + this._originalX = v; + } + get originalY() { + return this._originalY; + } + setOriginalYWithoutUpdatingLayout(v) { + this._originalY = v; + } + get originalWidth() { + return this._originalWidth; + } + set originalWidth(v) { + if (this._originalWidth !== v) { + this._originalWidth = v; + this.changedDimensions(true, false); + } + } + get originalHeight() { + return this._originalHeight; + } + set originalHeight(v) { + if (this._originalHeight !== v) { + this._originalHeight = v; + this.changedDimensions(false, true); + } + } + get funcX() { + return this._target.funcX; + } + get funcY() { + return this._target.funcY; + } + get funcW() { + return this._target.funcW; + } + get funcH() { + return this._target.funcH; + } + } + class TextureSource { + constructor(manager, loader = null) { + this.id = TextureSource.id++; + this.manager = manager; + this.stage = manager.stage; + this.textures = /* @__PURE__ */ new Set(); + this._activeTextureCount = 0; + this.loader = loader; + this.lookupId = null; + this._cancelCb = null; + this.loadingSince = 0; + this.w = 0; + this.h = 0; + this._nativeTexture = null; + this.permanent = false; + this.renderInfo = null; + this._isResultTexture = !this.loader; + this._loadError = null; + this._imageRef = null; + this._hasAlpha = false; + } + get hasAlpha() { + return this._hasAlpha; + } + get loadError() { + return this._loadError; + } + addTexture(v) { + if (!this.textures.has(v)) { + this.textures.add(v); + } + } + removeTexture(v) { + this.textures.delete(v); + } + incActiveTextureCount() { + this._activeTextureCount++; + if (this._activeTextureCount === 1) { + this.becomesUsed(); + } + } + decActiveTextureCount() { + this._activeTextureCount--; + if (this._activeTextureCount === 0) { + this.becomesUnused(); + } + } + get isResultTexture() { + return this._isResultTexture; + } + set isResultTexture(v) { + this._isResultTexture = v; + } + forEachEnabledElement(cb) { + this.textures.forEach((texture) => { + texture.elements.forEach(cb); + }); + } + hasEnabledElements() { + return this.textures.size > 0; + } + forEachActiveElement(cb) { + this.textures.forEach((texture) => { + texture.elements.forEach((element) => { + if (element.active) { + cb(element); + } + }); + }); + } + getRenderWidth() { + return this.w; + } + getRenderHeight() { + return this.h; + } + allowCleanup() { + return !this.permanent && !this.isUsed(); + } + becomesUsed() { + this.load(); + } + becomesUnused() { + this.cancel(); + } + cancel() { + if (this.isLoading()) { + if (this._cancelCb) { + this._cancelCb(this); + this._cancelCb = null; + } + this.loadingSince = 0; + } + } + isLoaded() { + return !!this._nativeTexture; + } + isLoading() { + return this.loadingSince > 0; + } + isError() { + return !!this._loadError; + } + reload() { + this.free(); + if (this.isUsed()) { + this.load(); + } + } + load(forceSync = false) { + if (this.isResultTexture) { + return; + } + if (!this._nativeTexture && !this.isLoading()) { + this.loadingSince = new Date().getTime(); + this._cancelCb = this.loader((err, options) => { + if (this.isLoading()) { + this._cancelCb = null; + if (this.manager.stage.destroyed) { + return; + } + if (err) { + this.onError(err); + } else if (options && options.source) { + if (!this.stage.isUpdatingFrame() && !forceSync && options.throttle !== false) { + const textureThrottler = this.stage.textureThrottler; + this._cancelCb = textureThrottler.genericCancelCb; + textureThrottler.add(this, options); + } else { + this.processLoadedSource(options); + } + } + } + }, this); + } + } + processLoadedSource(options) { + this.loadingSince = 0; + this.setSource(options); + } + setSource(options) { + const source = options.source; + this._hasAlpha = options ? options.hasAlpha || false : false; + this.w = source.width || options && options.w || 0; + this.h = source.height || options && options.h || 0; + if (options && options.renderInfo) { + this.renderInfo = options.renderInfo; + } + this.permanent = !!options.permanent; + if (options && options.imageRef) + this._imageRef = options.imageRef; + if (options && options.flipTextureY) { + this._flipTextureY = options.flipTextureY; + } else { + this._flipTextureY = false; + } + if (this._isNativeTexture(source)) { + this._nativeTexture = source; + this.w = this.w || source.w; + this.h = this.h || source.h; + this.permanent = options.hasOwnProperty("permanent") ? options.permanent : true; + } else { + this.manager.uploadTextureSource(this, options); + } + this._loadError = null; + this.onLoad(); + } + isUsed() { + return this._activeTextureCount > 0; + } + onLoad() { + if (this.isUsed()) { + this.textures.forEach((texture) => { + texture.onLoad(); + }); + } + } + forceRenderUpdate() { + if (this._nativeTexture) { + this._nativeTexture.update = this.stage.frameCounter; + } + this.forEachActiveElement(function(element) { + element.forceRenderUpdate(); + }); + } + forceUpdateRenderCoords() { + this.forEachActiveElement(function(element) { + element._updateTextureCoords(); + }); + } + get nativeTexture() { + return this._nativeTexture; + } + clearNativeTexture() { + this._nativeTexture = null; + this._imageRef = null; + } + replaceNativeTexture(newNativeTexture, w, h) { + let prevNativeTexture = this._nativeTexture; + this._nativeTexture = newNativeTexture; + this.w = w; + this.h = h; + if (!prevNativeTexture && this._nativeTexture) { + this.forEachActiveElement((element) => element.onTextureSourceLoaded()); + } + if (!this._nativeTexture) { + this.forEachActiveElement((element) => element._setDisplayedTexture(null)); + } + this.forEachEnabledElement((element) => element._updateDimensions()); + } + onError(e) { + this._loadError = e; + this.loadingSince = 0; + console.error("[Lightning] texture load error", e, this.lookupId); + this.forEachActiveElement((element) => element.onTextureSourceLoadError(e)); + } + free() { + if (this.isLoaded()) { + this.manager.freeTextureSource(this); + } + } + _isNativeTexture(source) { + if (Utils$1.isNode) { + return source.constructor.name === "WebGLTexture"; + } + if ("WebGLTexture" in window) { + return source instanceof WebGLTexture; + } + return false; + } + } + TextureSource.prototype.isTextureSource = true; + TextureSource.id = 1; + class ElementTexturizer { + constructor(elementCore) { + this._element = elementCore.element; + this._core = elementCore; + this.ctx = this._core.ctx; + this._enabled = false; + this.lazy = false; + this._colorize = false; + this._renderTexture = null; + this._renderTextureReused = false; + this._resultTextureSource = null; + this._renderOffscreen = false; + this.empty = false; + } + get enabled() { + return this._enabled; + } + set enabled(v) { + this._enabled = v; + this._core.updateRenderToTextureEnabled(); + } + get renderOffscreen() { + return this._renderOffscreen; + } + set renderOffscreen(v) { + this._renderOffscreen = v; + this._core.setHasRenderUpdates(1); + this._core._setRecalc(6); + } + get colorize() { + return this._colorize; + } + set colorize(v) { + if (this._colorize !== v) { + this._colorize = v; + this._core.setHasRenderUpdates(1); + } + } + _getTextureSource() { + if (!this._resultTextureSource) { + this._resultTextureSource = new TextureSource(this._element.stage.textureManager); + this.updateResultTexture(); + } + return this._resultTextureSource; + } + hasResultTexture() { + return !!this._resultTextureSource; + } + resultTextureInUse() { + return this._resultTextureSource && this._resultTextureSource.hasEnabledElements(); + } + updateResultTexture() { + let resultTexture = this.getResultTexture(); + if (this._resultTextureSource) { + if (this._resultTextureSource.nativeTexture !== resultTexture) { + let w = resultTexture ? resultTexture.w : 0; + let h = resultTexture ? resultTexture.h : 0; + this._resultTextureSource.replaceNativeTexture(resultTexture, w, h); + } + this._resultTextureSource.forEachEnabledElement((element) => { + element._updateDimensions(); + element.core.setHasRenderUpdates(3); + }); + } + } + mustRenderToTexture() { + if (this._enabled && !this.lazy) { + return true; + } else if (this._enabled && this.lazy && this._core._hasRenderUpdates < 3) { + return true; + } + return false; + } + deactivate() { + this.release(); + } + get renderTextureReused() { + return this._renderTextureReused; + } + release() { + this.releaseRenderTexture(); + } + releaseRenderTexture() { + if (this._renderTexture) { + if (!this._renderTextureReused) { + this.ctx.releaseRenderTexture(this._renderTexture); + } + this._renderTexture = null; + this._renderTextureReused = false; + this.updateResultTexture(); + } + } + reuseTextureAsRenderTexture(nativeTexture) { + if (this._renderTexture !== nativeTexture) { + this.releaseRenderTexture(); + this._renderTexture = nativeTexture; + this._renderTextureReused = true; + } + } + hasRenderTexture() { + return !!this._renderTexture; + } + getRenderTexture() { + if (!this._renderTexture) { + this._renderTexture = this.ctx.allocateRenderTexture(this._core._w, this._core._h); + this._renderTextureReused = false; + } + return this._renderTexture; + } + getResultTexture() { + return this._renderTexture; + } + } + class ElementCore { + constructor(element) { + this._element = element; + this.ctx = element.stage.ctx; + this._recalc = 0; + this._parent = null; + this._onUpdate = null; + this._pRecalc = 0; + this._worldContext = new ElementCoreContext(); + this._hasUpdates = false; + this._localAlpha = 1; + this._onAfterCalcs = null; + this._onAfterUpdate = null; + this._localPx = 0; + this._localPy = 0; + this._localTa = 1; + this._localTb = 0; + this._localTc = 0; + this._localTd = 1; + this._isComplex = false; + this._dimsUnknown = false; + this._clipping = false; + this._zSort = false; + this._outOfBounds = 0; + this._displayedTextureSource = null; + this._zContextUsage = 0; + this._children = null; + this._hasRenderUpdates = 0; + this._zIndexedChildren = null; + this._renderContext = this._worldContext; + this.renderState = this.ctx.renderState; + this._scissor = null; + this._shaderOwner = null; + this._updateTreeOrder = 0; + this._colorUl = this._colorUr = this._colorBl = this._colorBr = 4294967295; + this._x = 0; + this._y = 0; + this._w = 0; + this._h = 0; + this._optFlags = 0; + this._funcX = null; + this._funcY = null; + this._funcW = null; + this._funcH = null; + this._scaleX = 1; + this._scaleY = 1; + this._pivotX = 0.5; + this._pivotY = 0.5; + this._mountX = 0; + this._mountY = 0; + this._rotation = 0; + this._alpha = 1; + this._visible = true; + this._ulx = 0; + this._uly = 0; + this._brx = 1; + this._bry = 1; + this._zIndex = 0; + this._forceZIndexContext = false; + this._zParent = null; + this._isRoot = false; + this._zIndexResort = false; + this._shader = null; + this._renderToTextureEnabled = false; + this._texturizer = null; + this._useRenderToTexture = false; + this._boundsMargin = null; + this._recBoundsMargin = null; + this._withinBoundsMargin = false; + this._viewport = null; + this._clipbox = true; + this.render = this._renderSimple; + this._layout = null; + } + get offsetX() { + if (this._funcX) { + return this._funcX; + } else { + if (this.hasFlexLayout()) { + return this._layout.originalX; + } else { + return this._x; + } + } + } + set offsetX(v) { + if (Utils$1.isFunction(v)) { + this.funcX = v; + } else { + this._disableFuncX(); + if (this.hasFlexLayout()) { + this.x += v - this._layout.originalX; + this._layout.setOriginalXWithoutUpdatingLayout(v); + } else { + this.x = v; + } + } + } + get x() { + return this._x; + } + set x(v) { + if (v !== this._x) { + this._updateLocalTranslateDelta(v - this._x, 0); + this._x = v; + } + } + get funcX() { + return this._optFlags & 1 ? this._funcX : null; + } + set funcX(v) { + if (this._funcX !== v) { + this._optFlags |= 1; + this._funcX = v; + if (this.hasFlexLayout()) { + this._layout.setOriginalXWithoutUpdatingLayout(0); + this.layout.forceLayout(); + } else { + this._x = 0; + this._triggerRecalcTranslate(); + } + } + } + _disableFuncX() { + this._optFlags = this._optFlags & 65535 - 1; + this._funcX = null; + } + get offsetY() { + if (this._funcY) { + return this._funcY; + } else { + if (this.hasFlexLayout()) { + return this._layout.originalY; + } else { + return this._y; + } + } + } + set offsetY(v) { + if (Utils$1.isFunction(v)) { + this.funcY = v; + } else { + this._disableFuncY(); + if (this.hasFlexLayout()) { + this.y += v - this._layout.originalY; + this._layout.setOriginalYWithoutUpdatingLayout(v); + } else { + this.y = v; + } + } + } + get y() { + return this._y; + } + set y(v) { + if (v !== this._y) { + this._updateLocalTranslateDelta(0, v - this._y); + this._y = v; + } + } + get funcY() { + return this._optFlags & 2 ? this._funcY : null; + } + set funcY(v) { + if (this._funcY !== v) { + this._optFlags |= 2; + this._funcY = v; + if (this.hasFlexLayout()) { + this._layout.setOriginalYWithoutUpdatingLayout(0); + this.layout.forceLayout(); + } else { + this._y = 0; + this._triggerRecalcTranslate(); + } + } + } + _disableFuncY() { + this._optFlags = this._optFlags & 65535 - 2; + this._funcY = null; + } + get funcW() { + return this._optFlags & 4 ? this._funcW : null; + } + set funcW(v) { + if (this._funcW !== v) { + this._optFlags |= 4; + this._funcW = v; + if (this.hasFlexLayout()) { + this._layout._originalWidth = 0; + this.layout.changedDimensions(true, false); + } else { + this._w = 0; + this._triggerRecalcTranslate(); + } + } + } + disableFuncW() { + this._optFlags = this._optFlags & 65535 - 4; + this._funcW = null; + } + get funcH() { + return this._optFlags & 8 ? this._funcH : null; + } + set funcH(v) { + if (this._funcH !== v) { + this._optFlags |= 8; + this._funcH = v; + if (this.hasFlexLayout()) { + this._layout._originalHeight = 0; + this.layout.changedDimensions(false, true); + } else { + this._h = 0; + this._triggerRecalcTranslate(); + } + } + } + disableFuncH() { + this._optFlags = this._optFlags & 65535 - 8; + this._funcH = null; + } + get w() { + return this._w; + } + getRenderWidth() { + if (this.hasFlexLayout()) { + return this._layout.originalWidth; + } else { + return this._w; + } + } + get h() { + return this._h; + } + getRenderHeight() { + if (this.hasFlexLayout()) { + return this._layout.originalHeight; + } else { + return this._h; + } + } + get scaleX() { + return this._scaleX; + } + set scaleX(v) { + if (this._scaleX !== v) { + this._scaleX = v; + this._updateLocalTransform(); + } + } + get scaleY() { + return this._scaleY; + } + set scaleY(v) { + if (this._scaleY !== v) { + this._scaleY = v; + this._updateLocalTransform(); + } + } + get scale() { + return this.scaleX; + } + set scale(v) { + if (this._scaleX !== v || this._scaleY !== v) { + this._scaleX = v; + this._scaleY = v; + this._updateLocalTransform(); + } + } + get pivotX() { + return this._pivotX; + } + set pivotX(v) { + if (this._pivotX !== v) { + this._pivotX = v; + this._updateLocalTranslate(); + } + } + get pivotY() { + return this._pivotY; + } + set pivotY(v) { + if (this._pivotY !== v) { + this._pivotY = v; + this._updateLocalTranslate(); + } + } + get pivot() { + return this._pivotX; + } + set pivot(v) { + if (this._pivotX !== v || this._pivotY !== v) { + this._pivotX = v; + this._pivotY = v; + this._updateLocalTranslate(); + } + } + get mountX() { + return this._mountX; + } + set mountX(v) { + if (this._mountX !== v) { + this._mountX = v; + this._updateLocalTranslate(); + } + } + get mountY() { + return this._mountY; + } + set mountY(v) { + if (this._mountY !== v) { + this._mountY = v; + this._updateLocalTranslate(); + } + } + get mount() { + return this._mountX; + } + set mount(v) { + if (this._mountX !== v || this._mountY !== v) { + this._mountX = v; + this._mountY = v; + this._updateLocalTranslate(); + } + } + get rotation() { + return this._rotation; + } + set rotation(v) { + if (this._rotation !== v) { + this._rotation = v; + this._updateLocalTransform(); + } + } + get alpha() { + return this._alpha; + } + set alpha(v) { + v = v > 1 ? 1 : v < 1e-14 ? 0 : v; + if (this._alpha !== v) { + let prev = this._alpha; + this._alpha = v; + this._updateLocalAlpha(); + if (prev === 0 !== (v === 0)) { + this._element._updateEnabledFlag(); + } + } + } + get visible() { + return this._visible; + } + set visible(v) { + if (this._visible !== v) { + this._visible = v; + this._updateLocalAlpha(); + this._element._updateEnabledFlag(); + if (this.hasFlexLayout()) { + this.layout.setVisible(v); + } + } + } + _updateLocalTransform() { + if (this._rotation !== 0 && this._rotation % (2 * Math.PI)) { + let _sr = Math.sin(this._rotation); + let _cr = Math.cos(this._rotation); + this._setLocalTransform( + _cr * this._scaleX, + -_sr * this._scaleY, + _sr * this._scaleX, + _cr * this._scaleY + ); + } else { + this._setLocalTransform( + this._scaleX, + 0, + 0, + this._scaleY + ); + } + this._updateLocalTranslate(); + } + _updateLocalTranslate() { + this._recalcLocalTranslate(); + this._triggerRecalcTranslate(); + } + _recalcLocalTranslate() { + let pivotXMul = this._pivotX * this._w; + let pivotYMul = this._pivotY * this._h; + let px = this._x - (pivotXMul * this._localTa + pivotYMul * this._localTb) + pivotXMul; + let py = this._y - (pivotXMul * this._localTc + pivotYMul * this._localTd) + pivotYMul; + px -= this._mountX * this._w; + py -= this._mountY * this._h; + this._localPx = px; + this._localPy = py; + } + _updateLocalTranslateDelta(dx, dy) { + this._addLocalTranslate(dx, dy); + } + _updateLocalAlpha() { + this._setLocalAlpha(this._visible ? this._alpha : 0); + } + setHasRenderUpdates(type) { + if (this._worldContext.alpha) { + let p = this; + p._hasRenderUpdates = Math.max(type, p._hasRenderUpdates); + while ((p = p._parent) && p._hasRenderUpdates !== 3) { + p._hasRenderUpdates = 3; + } + } + } + _setRecalc(type) { + this._recalc |= type; + this._setHasUpdates(); + if (this._parent) { + this._parent.setHasRenderUpdates(3); + } + } + _setHasUpdates() { + let p = this; + while (p && !p._hasUpdates) { + p._hasUpdates = true; + p = p._parent; + } + } + getParent() { + return this._parent; + } + setParent(parent) { + if (parent !== this._parent) { + let prevIsZContext = this.isZContext(); + let prevParent = this._parent; + this._parent = parent; + if (this._layout || parent && parent.isFlexContainer()) { + this.layout.setParent(prevParent, parent); + } + if (prevParent) { + prevParent.setHasRenderUpdates(3); + } + this._setRecalc(1 + 2 + 4); + if (this._parent) { + this._parent._setHasUpdates(); + } + if (this._zIndex === 0) { + this.setZParent(parent); + } else { + this.setZParent(parent ? parent.findZContext() : null); + } + if (prevIsZContext !== this.isZContext()) { + if (!this.isZContext()) { + this.disableZContext(); + } else { + this.enableZContext(prevParent.findZContext()); + } + } + this._zIndexResort = true; + if (this._zParent) { + this._zParent.enableZSort(); + } + if (!this._shader) { + let newShaderOwner = parent && !parent._renderToTextureEnabled ? parent._shaderOwner : null; + if (newShaderOwner !== this._shaderOwner) { + this.setHasRenderUpdates(1); + this._setShaderOwnerRecursive(newShaderOwner); + } + } + } + } + enableZSort(force = false) { + if (!this._zSort && this._zContextUsage > 0) { + this._zSort = true; + if (force) { + this.ctx.forceZSort(this); + } + } + } + addChildAt(index, child) { + if (!this._children) + this._children = []; + this._children.splice(index, 0, child); + child.setParent(this); + } + setChildAt(index, child) { + if (!this._children) + this._children = []; + this._children[index].setParent(null); + this._children[index] = child; + child.setParent(this); + } + removeChildAt(index) { + let child = this._children[index]; + this._children.splice(index, 1); + child.setParent(null); + } + removeChildren() { + if (this._children) { + for (let i = 0, n = this._children.length; i < n; i++) { + this._children[i].setParent(null); + } + this._children.splice(0); + if (this._zIndexedChildren) { + this._zIndexedChildren.splice(0); + } + } + } + syncChildren(removed, added, order) { + this._children = order; + for (let i = 0, n = removed.length; i < n; i++) { + removed[i].setParent(null); + } + for (let i = 0, n = added.length; i < n; i++) { + added[i].setParent(this); + } + } + moveChild(fromIndex, toIndex) { + let c = this._children[fromIndex]; + this._children.splice(fromIndex, 1); + this._children.splice(toIndex, 0, c); + this._zIndexResort = true; + if (this._zParent) { + this._zParent.enableZSort(); + } + } + _setLocalTransform(a, b, c, d) { + this._setRecalc(4); + this._localTa = a; + this._localTb = b; + this._localTc = c; + this._localTd = d; + this._isComplex = b !== 0 || c !== 0 || a < 0 || d < 0; + } + _addLocalTranslate(dx, dy) { + this._localPx += dx; + this._localPy += dy; + this._triggerRecalcTranslate(); + } + _setLocalAlpha(a) { + if (!this._worldContext.alpha && (this._parent && this._parent._worldContext.alpha && a)) { + this._setRecalc(1 + 128); + } else { + this._setRecalc(1); + } + if (a < 1e-14) { + a = 0; + } + this._localAlpha = a; + } + setDimensions(w, h, isEstimate = this._dimsUnknown) { + this._dimsUnknown = isEstimate; + if (this.hasFlexLayout()) { + this._layout.originalWidth = w; + this._layout.originalHeight = h; + } else { + if (this._w !== w || this._h !== h) { + this._updateDimensions(w, h); + return true; + } + } + return false; + } + _updateDimensions(w, h) { + if (this._w !== w || this._h !== h) { + this._w = w; + this._h = h; + this._triggerRecalcTranslate(); + if (this._texturizer) { + this._texturizer.releaseRenderTexture(); + this._texturizer.updateResultTexture(); + } + this._updateLocalTranslate(); + } + } + setTextureCoords(ulx, uly, brx, bry) { + this.setHasRenderUpdates(3); + this._ulx = ulx; + this._uly = uly; + this._brx = brx; + this._bry = bry; + } + get displayedTextureSource() { + return this._displayedTextureSource; + } + setDisplayedTextureSource(textureSource) { + this.setHasRenderUpdates(3); + this._displayedTextureSource = textureSource; + } + get isRoot() { + return this._isRoot; + } + setAsRoot() { + this._parent = new ElementCore(this._element); + this._parent._hasRenderUpdates = 3; + this._parent._hasUpdates = true; + this._isRoot = true; + this.ctx.root = this; + this._parent._viewport = [0, 0, this.ctx.stage.coordsWidth, this.ctx.stage.coordsHeight]; + this._parent._scissor = this._parent._viewport; + this._parent._recBoundsMargin = null; + this._setRecalc(1 + 2 + 4); + } + isAncestorOf(c) { + let p = c; + while (p = p._parent) { + if (this === p) { + return true; + } + } + return false; + } + isZContext() { + return this._forceZIndexContext || this._renderToTextureEnabled || this._zIndex !== 0 || this._isRoot || !this._parent; + } + findZContext() { + if (this.isZContext()) { + return this; + } else { + return this._parent.findZContext(); + } + } + setZParent(newZParent) { + if (this._zParent !== newZParent) { + if (this._zParent !== null) { + if (this._zIndex !== 0) { + this._zParent.decZContextUsage(); + } + this._zParent.enableZSort(); + } + if (newZParent !== null) { + let hadZContextUsage = newZParent._zContextUsage > 0; + if (this._zIndex !== 0) { + newZParent.incZContextUsage(); + } + if (newZParent._zContextUsage > 0) { + if (!hadZContextUsage && this._parent === newZParent) + ; + else { + newZParent._zIndexedChildren.push(this); + } + newZParent.enableZSort(); + } + } + this._zParent = newZParent; + this._zIndexResort = true; + } + } + incZContextUsage() { + this._zContextUsage++; + if (this._zContextUsage === 1) { + if (!this._zIndexedChildren) { + this._zIndexedChildren = []; + } + if (this._children) { + for (let i = 0, n = this._children.length; i < n; i++) { + this._zIndexedChildren.push(this._children[i]); + } + this._zSort = false; + } + } + } + decZContextUsage() { + this._zContextUsage--; + if (this._zContextUsage === 0) { + this._zSort = false; + this._zIndexedChildren.splice(0); + } + } + get zIndex() { + return this._zIndex; + } + set zIndex(zIndex) { + if (this._zIndex !== zIndex) { + this.setHasRenderUpdates(1); + let newZParent = this._zParent; + let prevIsZContext = this.isZContext(); + if (zIndex === 0 && this._zIndex !== 0) { + if (this._parent === this._zParent) { + if (this._zParent) { + this._zParent.decZContextUsage(); + } + } else { + newZParent = this._parent; + } + } else if (zIndex !== 0 && this._zIndex === 0) { + newZParent = this._parent ? this._parent.findZContext() : null; + if (newZParent === this._zParent) { + if (this._zParent) { + this._zParent.incZContextUsage(); + this._zParent.enableZSort(); + } + } + } else if (zIndex !== this._zIndex) { + if (this._zParent && this._zParent._zContextUsage) { + this._zParent.enableZSort(); + } + } + if (newZParent !== this._zParent) { + this.setZParent(null); + } + this._zIndex = zIndex; + if (newZParent !== this._zParent) { + this.setZParent(newZParent); + } + if (prevIsZContext !== this.isZContext()) { + if (!this.isZContext()) { + this.disableZContext(); + } else { + this.enableZContext(this._parent.findZContext()); + } + } + this._zIndexResort = true; + if (this._zParent) { + this._zParent.enableZSort(); + } + } + } + get forceZIndexContext() { + return this._forceZIndexContext; + } + set forceZIndexContext(v) { + this.setHasRenderUpdates(1); + let prevIsZContext = this.isZContext(); + this._forceZIndexContext = v; + if (prevIsZContext !== this.isZContext()) { + if (!this.isZContext()) { + this.disableZContext(); + } else { + this.enableZContext(this._parent.findZContext()); + } + } + } + enableZContext(prevZContext) { + if (prevZContext && prevZContext._zContextUsage > 0) { + const results = this._getZIndexedDescs(); + results.forEach((c) => { + if (this.isAncestorOf(c) && c._zIndex !== 0) { + c.setZParent(this); + } + }); + } + } + _getZIndexedDescs() { + const results = []; + if (this._children) { + for (let i = 0, n = this._children.length; i < n; i++) { + this._children[i]._getZIndexedDescsRec(results); + } + } + return results; + } + _getZIndexedDescsRec(results) { + if (this._zIndex) { + results.push(this); + } else if (this._children && !this.isZContext()) { + for (let i = 0, n = this._children.length; i < n; i++) { + this._children[i]._getZIndexedDescsRec(results); + } + } + } + disableZContext() { + if (this._zContextUsage > 0) { + let newZParent = this._parent.findZContext(); + if (this._zSort) { + this.sortZIndexedChildren(); + } + this._zIndexedChildren.slice().forEach(function(c) { + if (c._zIndex !== 0) { + c.setZParent(newZParent); + } + }); + } + } + get colorUl() { + return this._colorUl; + } + set colorUl(color) { + if (this._colorUl !== color) { + this.setHasRenderUpdates(this._displayedTextureSource ? 3 : 1); + this._colorUl = color; + } + } + get colorUr() { + return this._colorUr; + } + set colorUr(color) { + if (this._colorUr !== color) { + this.setHasRenderUpdates(this._displayedTextureSource ? 3 : 1); + this._colorUr = color; + } + } + get colorBl() { + return this._colorBl; + } + set colorBl(color) { + if (this._colorBl !== color) { + this.setHasRenderUpdates(this._displayedTextureSource ? 3 : 1); + this._colorBl = color; + } + } + get colorBr() { + return this._colorBr; + } + set colorBr(color) { + if (this._colorBr !== color) { + this.setHasRenderUpdates(this._displayedTextureSource ? 3 : 1); + this._colorBr = color; + } + } + set onUpdate(f) { + this._onUpdate = f; + this._setRecalc(7); + } + set onAfterUpdate(f) { + this._onAfterUpdate = f; + this._setRecalc(7); + } + set onAfterCalcs(f) { + this._onAfterCalcs = f; + this._setRecalc(7); + } + get shader() { + return this._shader; + } + set shader(v) { + this.setHasRenderUpdates(1); + let prevShader = this._shader; + this._shader = v; + if (!v && prevShader) { + let newShaderOwner = this._parent && !this._parent._renderToTextureEnabled ? this._parent._shaderOwner : null; + this._setShaderOwnerRecursive(newShaderOwner); + } else if (v) { + this._setShaderOwnerRecursive(this); + } + } + get activeShader() { + return this._shaderOwner ? this._shaderOwner.shader : this.renderState.defaultShader; + } + get activeShaderOwner() { + return this._shaderOwner; + } + get clipping() { + return this._clipping; + } + set clipping(v) { + if (this._clipping !== v) { + this._clipping = v; + this._setRecalc(1 + 2); + } + } + get clipbox() { + return this._clipbox; + } + set clipbox(v) { + this._clipbox = v; + } + _setShaderOwnerRecursive(elementCore) { + this._shaderOwner = elementCore; + if (this._children && !this._renderToTextureEnabled) { + for (let i = 0, n = this._children.length; i < n; i++) { + let c = this._children[i]; + if (!c._shader) { + c._setShaderOwnerRecursive(elementCore); + c._hasRenderUpdates = 3; + } + } + } + } + _setShaderOwnerChildrenRecursive(elementCore) { + if (this._children) { + for (let i = 0, n = this._children.length; i < n; i++) { + let c = this._children[i]; + if (!c._shader) { + c._setShaderOwnerRecursive(elementCore); + c._hasRenderUpdates = 3; + } + } + } + } + _hasRenderContext() { + return this._renderContext !== this._worldContext; + } + get renderContext() { + return this._renderContext; + } + updateRenderToTextureEnabled() { + let v = this.texturizer._enabled; + if (v) { + this._enableRenderToTexture(); + } else { + this._disableRenderToTexture(); + this._texturizer.releaseRenderTexture(); + } + } + _enableRenderToTexture() { + if (!this._renderToTextureEnabled) { + let prevIsZContext = this.isZContext(); + this._renderToTextureEnabled = true; + this._renderContext = new ElementCoreContext(); + this._setShaderOwnerChildrenRecursive(null); + if (!prevIsZContext) { + this.enableZContext(this._parent ? this._parent.findZContext() : null); + } + this.setHasRenderUpdates(3); + this._setRecalc(7); + this.render = this._renderAdvanced; + } + } + _disableRenderToTexture() { + if (this._renderToTextureEnabled) { + this._renderToTextureEnabled = false; + this._setShaderOwnerChildrenRecursive(this._shaderOwner); + this._renderContext = this._worldContext; + if (!this.isZContext()) { + this.disableZContext(); + } + this._setRecalc(7); + this.setHasRenderUpdates(3); + this.render = this._renderSimple; + } + } + isWhite() { + return this._colorUl === 4294967295 && this._colorUr === 4294967295 && this._colorBl === 4294967295 && this._colorBr === 4294967295; + } + hasSimpleTexCoords() { + return this._ulx === 0 && this._uly === 0 && this._brx === 1 && this._bry === 1; + } + _stashTexCoords() { + this._stashedTexCoords = [this._ulx, this._uly, this._brx, this._bry]; + this._ulx = 0; + this._uly = 0; + this._brx = 1; + this._bry = 1; + } + _unstashTexCoords() { + this._ulx = this._stashedTexCoords[0]; + this._uly = this._stashedTexCoords[1]; + this._brx = this._stashedTexCoords[2]; + this._bry = this._stashedTexCoords[3]; + this._stashedTexCoords = null; + } + _stashColors() { + this._stashedColors = [this._colorUl, this._colorUr, this._colorBr, this._colorBl]; + this._colorUl = 4294967295; + this._colorUr = 4294967295; + this._colorBr = 4294967295; + this._colorBl = 4294967295; + } + _unstashColors() { + this._colorUl = this._stashedColors[0]; + this._colorUr = this._stashedColors[1]; + this._colorBr = this._stashedColors[2]; + this._colorBl = this._stashedColors[3]; + this._stashedColors = null; + } + isVisible() { + return this._localAlpha > 1e-14; + } + get outOfBounds() { + return this._outOfBounds; + } + set boundsMargin(v) { + this._boundsMargin = v ? v.slice() : null; + this._triggerRecalcTranslate(); + } + get boundsMargin() { + return this._boundsMargin; + } + update() { + this._recalc |= this._parent._pRecalc; + if (this._layout && this._layout.isEnabled()) { + if (this._recalc & 256) { + this._layout.layoutFlexTree(); + } + } else if (this._recalc & 2 && this._optFlags) { + this._applyRelativeDimFuncs(); + } + if (this._onUpdate) { + this._hasUpdates = true; + this._onUpdate(this.element, this); + } + const pw = this._parent._worldContext; + let w = this._worldContext; + const visible = pw.alpha && this._localAlpha; + if (this._hasUpdates || this._recalc && visible || w.alpha && !visible) { + let recalc = this._recalc; + if (recalc & 1) { + if (!w.alpha && visible) { + this._hasRenderUpdates = 3; + } + w.alpha = pw.alpha * this._localAlpha; + if (w.alpha < 1e-14) { + w.alpha = 0; + } + } + if (recalc & 6) { + w.px = pw.px + this._localPx * pw.ta; + w.py = pw.py + this._localPy * pw.td; + if (pw.tb !== 0) + w.px += this._localPy * pw.tb; + if (pw.tc !== 0) + w.py += this._localPx * pw.tc; + } + if (recalc & 4) { + w.ta = this._localTa * pw.ta; + w.tb = this._localTd * pw.tb; + w.tc = this._localTa * pw.tc; + w.td = this._localTd * pw.td; + if (this._isComplex) { + w.ta += this._localTc * pw.tb; + w.tb += this._localTb * pw.ta; + w.tc += this._localTc * pw.td; + w.td += this._localTb * pw.tc; + } + } + const pr = this._parent._renderContext; + if (this._parent._hasRenderContext()) { + const init = this._renderContext === this._worldContext; + if (init) { + this._renderContext = new ElementCoreContext(); + } + const r2 = this._renderContext; + if (init || recalc & 1) { + r2.alpha = pr.alpha * this._localAlpha; + if (r2.alpha < 1e-14) { + r2.alpha = 0; + } + } + if (init || recalc & 6) { + r2.px = pr.px + this._localPx * pr.ta; + r2.py = pr.py + this._localPy * pr.td; + if (pr.tb !== 0) + r2.px += this._localPy * pr.tb; + if (pr.tc !== 0) + r2.py += this._localPx * pr.tc; + } + if (init) { + recalc |= 2; + } + if (init || recalc & 4) { + r2.ta = this._localTa * pr.ta; + r2.tb = this._localTd * pr.tb; + r2.tc = this._localTa * pr.tc; + r2.td = this._localTd * pr.td; + if (this._isComplex) { + r2.ta += this._localTc * pr.tb; + r2.tb += this._localTb * pr.ta; + r2.tc += this._localTc * pr.td; + r2.td += this._localTb * pr.tc; + } + } + } else { + this._renderContext = this._worldContext; + } + if (this.ctx.updateTreeOrder === -1) { + this.ctx.updateTreeOrder = this._updateTreeOrder + 1; + } else { + this._updateTreeOrder = this.ctx.updateTreeOrder++; + } + const useRenderToTexture = this._renderToTextureEnabled && this._texturizer.mustRenderToTexture(); + if (this._useRenderToTexture !== useRenderToTexture) { + this._recalc |= 2 + 4; + recalc |= 2; + if (!this._useRenderToTexture) { + this._texturizer.release(); + } + } + this._useRenderToTexture = useRenderToTexture; + const r = this._renderContext; + const bboxW = this._dimsUnknown ? 2048 : this._w; + const bboxH = this._dimsUnknown ? 2048 : this._h; + let sx, sy, ex, ey; + const rComplex = r.tb !== 0 || r.tc !== 0 || r.ta < 0 || r.td < 0; + if (rComplex) { + sx = Math.min(0, bboxW * r.ta, bboxW * r.ta + bboxH * r.tb, bboxH * r.tb) + r.px; + ex = Math.max(0, bboxW * r.ta, bboxW * r.ta + bboxH * r.tb, bboxH * r.tb) + r.px; + sy = Math.min(0, bboxW * r.tc, bboxW * r.tc + bboxH * r.td, bboxH * r.td) + r.py; + ey = Math.max(0, bboxW * r.tc, bboxW * r.tc + bboxH * r.td, bboxH * r.td) + r.py; + } else { + sx = r.px; + ex = r.px + r.ta * bboxW; + sy = r.py; + ey = r.py + r.td * bboxH; + } + if (this._dimsUnknown && (rComplex || this._localTa < 1 || this._localTb < 1)) { + const nx = this._x * pr.ta + this._y * pr.tb + pr.px; + const ny = this._x * pr.tc + this._y * pr.td + pr.py; + if (nx < sx) + sx = nx; + if (ny < sy) + sy = ny; + if (nx > ex) + ex = nx; + if (ny > ey) + ey = ny; + } + if (recalc & 6 || !this._scissor) { + if (this._clipping && r.isSquare()) { + const area = this._parent._useRenderToTexture ? this._parent._viewport : this._parent._scissor; + if (area) { + const lx = Math.max(area[0], sx); + const ly = Math.max(area[1], sy); + this._scissor = [ + lx, + ly, + Math.min(area[2] + area[0], ex) - lx, + Math.min(area[3] + area[1], ey) - ly + ]; + } else { + this._scissor = [sx, sy, ex - sx, ey - sy]; + } + } else { + this._scissor = this._parent._useRenderToTexture ? this._parent._viewport : this._parent._scissor; + } + } + if (this._boundsMargin) { + this._recBoundsMargin = this._boundsMargin; + } else { + this._recBoundsMargin = this._parent._recBoundsMargin; + } + if (this._onAfterCalcs) { + if (this._onAfterCalcs(this.element)) { + if (rComplex) { + sx = Math.min(0, bboxW * r.ta, bboxW * r.ta + bboxH * r.tb, bboxH * r.tb) + r.px; + ex = Math.max(0, bboxW * r.ta, bboxW * r.ta + bboxH * r.tb, bboxH * r.tb) + r.px; + sy = Math.min(0, bboxW * r.tc, bboxW * r.tc + bboxH * r.td, bboxH * r.td) + r.py; + ey = Math.max(0, bboxW * r.tc, bboxW * r.tc + bboxH * r.td, bboxH * r.td) + r.py; + } else { + sx = r.px; + ex = r.px + r.ta * bboxW; + sy = r.py; + ey = r.py + r.td * bboxH; + } + if (this._dimsUnknown && (rComplex || this._localTa < 1 || this._localTb < 1)) { + const nx = this._x * pr.ta + this._y * pr.tb + pr.px; + const ny = this._x * pr.tc + this._y * pr.td + pr.py; + if (nx < sx) + sx = nx; + if (ny < sy) + sy = ny; + if (nx > ex) + ex = nx; + if (ny > ey) + ey = ny; + } + } + } + if (this._parent._outOfBounds === 2) { + this._outOfBounds = 2; + if (this._withinBoundsMargin) { + this._withinBoundsMargin = false; + this.element._disableWithinBoundsMargin(); + } + } else { + if (recalc & 6) { + this._outOfBounds = 0; + let withinMargin = true; + if (!this._renderToTextureEnabled || !this._texturizer || !this._texturizer.renderOffscreen) { + if (this._scissor && (this._scissor[2] <= 0 || this._scissor[3] <= 0)) { + this._outOfBounds = 2; + } else { + if (this._scissor[0] > ex || this._scissor[1] > ey || sx > this._scissor[0] + this._scissor[2] || sy > this._scissor[1] + this._scissor[3]) { + this._outOfBounds = 1; + } + if (this._outOfBounds) { + if (this._clipping || this._useRenderToTexture || this._clipbox && (bboxW && bboxH)) { + this._outOfBounds = 2; + } + } + } + withinMargin = this._outOfBounds === 0; + if (!withinMargin) { + if (this._recBoundsMargin) { + withinMargin = !(ex < this._scissor[0] - this._recBoundsMargin[2] || ey < this._scissor[1] - this._recBoundsMargin[3] || sx > this._scissor[0] + this._scissor[2] + this._recBoundsMargin[0] || sy > this._scissor[1] + this._scissor[3] + this._recBoundsMargin[1]); + } else { + withinMargin = !(ex < this._scissor[0] - 100 || ey < this._scissor[1] - 100 || sx > this._scissor[0] + this._scissor[2] + 100 || sy > this._scissor[1] + this._scissor[3] + 100); + } + if (withinMargin && this._outOfBounds === 2) { + this._outOfBounds = 1; + } + } + } + if (this._withinBoundsMargin !== withinMargin) { + this._withinBoundsMargin = withinMargin; + if (this._withinBoundsMargin) { + this._hasUpdates = true; + const recalc2 = this._recalc; + this._recalc = 0; + this.element._enableWithinBoundsMargin(); + if (this._recalc) { + return this.update(); + } + this._recalc = recalc2; + } else { + this.element._disableWithinBoundsMargin(); + } + } + } + } + if (this._useRenderToTexture) { + if (this._viewport) { + this._viewport[2] = bboxW; + this._viewport[3] = bboxH; + } else { + this._viewport = [0, 0, bboxW, bboxH]; + } + } + this._pRecalc = this._recalc & 135; + this._recalc = 0; + this._hasUpdates = false; + if (this._outOfBounds < 2) { + if (this._useRenderToTexture) { + if (this._worldContext.isIdentity()) { + this._renderContext = this._worldContext; + } else { + this._renderContext = ElementCoreContext.IDENTITY; + } + } + if (this._children) { + for (let i = 0, n = this._children.length; i < n; i++) { + this._children[i].update(); + } + } + if (this._useRenderToTexture) { + this._renderContext = r; + } + } else { + if (this._children) { + for (let i = 0, n = this._children.length; i < n; i++) { + if (this._children[i]._hasUpdates) { + this._children[i].update(); + } else { + this._children[i]._recalc |= this._pRecalc; + this._children[i].updateOutOfBounds(); + } + } + } + } + if (this._onAfterUpdate) { + this._onAfterUpdate(this.element); + } + } else { + if (this.ctx.updateTreeOrder === -1 || this._updateTreeOrder >= this.ctx.updateTreeOrder) { + this.ctx.updateTreeOrder = -1; + } else { + this.updateTreeOrder(); + } + } + } + _applyRelativeDimFuncs() { + if (this._optFlags & 1) { + const x = this._funcX(this._parent.w); + if (x !== this._x) { + this._localPx += x - this._x; + this._x = x; + } + } + if (this._optFlags & 2) { + const y = this._funcY(this._parent.h); + if (y !== this._y) { + this._localPy += y - this._y; + this._y = y; + } + } + let changedDims = false; + if (this._optFlags & 4) { + const w = this._funcW(this._parent.w); + if (w !== this._w) { + this._w = w; + changedDims = true; + } + } + if (this._optFlags & 8) { + const h = this._funcH(this._parent.h); + if (h !== this._h) { + this._h = h; + changedDims = true; + } + } + if (changedDims) { + this._recalcLocalTranslate(); + this.element.onDimensionsChanged(this._w, this._h); + } + } + updateOutOfBounds() { + if (this._outOfBounds !== 2 && this._renderContext.alpha > 0) { + this._outOfBounds = 2; + if (this._withinBoundsMargin) { + this._withinBoundsMargin = false; + this.element._disableWithinBoundsMargin(); + } + if (this._children) { + for (let i = 0, n = this._children.length; i < n; i++) { + this._children[i].updateOutOfBounds(); + } + } + } + } + updateTreeOrder() { + if (this._localAlpha && this._outOfBounds !== 2) { + this._updateTreeOrder = this.ctx.updateTreeOrder++; + if (this._children) { + for (let i = 0, n = this._children.length; i < n; i++) { + this._children[i].updateTreeOrder(); + } + } + } + } + _renderSimple() { + this._hasRenderUpdates = 0; + if (this._zSort) { + this.sortZIndexedChildren(); + } + if (this._outOfBounds < 2 && this._renderContext.alpha) { + let renderState = this.renderState; + if (this._outOfBounds === 0 && this._displayedTextureSource) { + renderState.setShader(this.activeShader, this._shaderOwner); + renderState.setScissor(this._scissor); + this.renderState.addQuad(this); + } + if (this._children) { + if (this._zContextUsage) { + for (let i = 0, n = this._zIndexedChildren.length; i < n; i++) { + this._zIndexedChildren[i].render(); + } + } else { + for (let i = 0, n = this._children.length; i < n; i++) { + if (this._children[i]._zIndex === 0) { + this._children[i].render(); + } + } + } + } + } + } + _renderAdvanced() { + const hasRenderUpdates = this._hasRenderUpdates; + this._hasRenderUpdates = 0; + if (this._zSort) { + this.sortZIndexedChildren(); + } + if (this._outOfBounds < 2 && this._renderContext.alpha) { + let renderState = this.renderState; + let mustRenderChildren = true; + let renderTextureInfo; + let prevRenderTextureInfo; + if (this._useRenderToTexture) { + if (this._w === 0 || this._h === 0) { + return; + } else if (!this._texturizer.hasRenderTexture() || hasRenderUpdates >= 3) { + this.ctx.renderToTextureCount++; + renderState.setShader(renderState.defaultShader, this); + prevRenderTextureInfo = renderState.renderTextureInfo; + renderTextureInfo = { + nativeTexture: null, + offset: 0, + w: this._w, + h: this._h, + empty: true, + cleared: false, + ignore: false, + cache: false + }; + if (this._texturizer.hasResultTexture() || !renderState.isCachingTexturizer && hasRenderUpdates < 3) { + renderTextureInfo.cache = true; + renderState.isCachingTexturizer = true; + } + if (!this._texturizer.hasResultTexture()) { + this._texturizer.releaseRenderTexture(); + } + renderState.setRenderTextureInfo(renderTextureInfo); + renderState.setScissor(null); + if (this._displayedTextureSource) { + let r = this._renderContext; + this._renderContext = ElementCoreContext.IDENTITY; + this.renderState.addQuad(this); + this._renderContext = r; + } + } else { + mustRenderChildren = false; + } + } else { + if (this._outOfBounds === 0 && this._displayedTextureSource) { + renderState.setShader(this.activeShader, this._shaderOwner); + renderState.setScissor(this._scissor); + this.renderState.addQuad(this); + } + } + if (mustRenderChildren && this._children) { + if (this._zContextUsage) { + for (let i = 0, n = this._zIndexedChildren.length; i < n; i++) { + this._zIndexedChildren[i].render(); + } + } else { + for (let i = 0, n = this._children.length; i < n; i++) { + if (this._children[i]._zIndex === 0) { + this._children[i].render(); + } + } + } + } + if (this._useRenderToTexture) { + let updateResultTexture = false; + if (mustRenderChildren) { + renderState.finishedRenderTexture(); + this._texturizer.empty = renderTextureInfo.empty; + if (renderTextureInfo.empty) { + this._texturizer.releaseRenderTexture(); + } else if (renderTextureInfo.nativeTexture) { + this._texturizer.reuseTextureAsRenderTexture(renderTextureInfo.nativeTexture); + renderTextureInfo.ignore = true; + } else { + if (this._texturizer.renderTextureReused) { + this._texturizer.releaseRenderTexture(); + } + renderTextureInfo.nativeTexture = this._texturizer.getRenderTexture(); + } + renderState.setRenderTextureInfo(prevRenderTextureInfo); + updateResultTexture = true; + } + if (!this._texturizer.empty) { + let resultTexture = this._texturizer.getResultTexture(); + if (updateResultTexture) { + if (resultTexture) { + resultTexture.update = renderState.stage.frameCounter; + } + this._texturizer.updateResultTexture(); + } + if (!this._texturizer.renderOffscreen) { + renderState.setShader(this.activeShader, this._shaderOwner); + renderState.setScissor(this._scissor); + const cache = !renderTextureInfo || renderTextureInfo.cache; + renderState.setTexturizer(this._texturizer, cache); + this._stashTexCoords(); + if (!this._texturizer.colorize) + this._stashColors(); + this.renderState.addQuad(this, true); + if (!this._texturizer.colorize) + this._unstashColors(); + this._unstashTexCoords(); + renderState.setTexturizer(null); + } + } + } + if (renderTextureInfo && renderTextureInfo.cache) { + renderState.isCachingTexturizer = false; + } + } + } + get zSort() { + return this._zSort; + } + sortZIndexedChildren() { + const n = this._zIndexedChildren.length; + let ptr = 0; + const a = this._zIndexedChildren; + const b = []; + for (let i = 0; i < n; i++) { + if (a[i]._zParent === this) { + if (a[i]._zIndexResort) { + b.push(a[i]); + } else { + if (ptr !== i) { + a[ptr] = a[i]; + } + ptr++; + } + } + } + const m = b.length; + if (m) { + for (let j = 0; j < m; j++) { + b[j]._zIndexResort = false; + } + b.sort(ElementCore.sortZIndexedChildren); + const n2 = ptr; + if (!n2) { + ptr = 0; + let j = 0; + do { + a[ptr++] = b[j++]; + } while (j < m); + if (a.length > ptr) { + a.splice(ptr); + } + } else { + ptr = 0; + let i = 0; + let j = 0; + const mergeResult = []; + do { + const v = a[i]._zIndex === b[j]._zIndex ? a[i]._updateTreeOrder - b[j]._updateTreeOrder : a[i]._zIndex - b[j]._zIndex; + const add = v > 0 ? b[j++] : a[i++]; + if (ptr === 0 || mergeResult[ptr - 1] !== add) { + mergeResult[ptr++] = add; + } + if (i >= n2) { + do { + const add2 = b[j++]; + if (ptr === 0 || mergeResult[ptr - 1] !== add2) { + mergeResult[ptr++] = add2; + } + } while (j < m); + break; + } else if (j >= m) { + do { + const add2 = a[i++]; + if (ptr === 0 || mergeResult[ptr - 1] !== add2) { + mergeResult[ptr++] = add2; + } + } while (i < n2); + break; + } + } while (true); + this._zIndexedChildren = mergeResult; + } + } else { + if (a.length > ptr) { + a.splice(ptr); + } + } + this._zSort = false; + } + get localTa() { + return this._localTa; + } + get localTb() { + return this._localTb; + } + get localTc() { + return this._localTc; + } + get localTd() { + return this._localTd; + } + get element() { + return this._element; + } + get renderUpdates() { + return this._hasRenderUpdates; + } + get texturizer() { + if (!this._texturizer) { + this._texturizer = new ElementTexturizer(this); + } + return this._texturizer; + } + getCornerPoints() { + let w = this._worldContext; + return [ + w.px, + w.py, + w.px + this._w * w.ta, + w.py + this._w * w.tc, + w.px + this._w * w.ta + this._h * w.tb, + w.py + this._w * w.tc + this._h * w.td, + w.px + this._h * w.tb, + w.py + this._h * w.td + ]; + } + getRenderTextureCoords(relX, relY) { + let r = this._renderContext; + return [ + r.px + r.ta * relX + r.tb * relY, + r.py + r.tc * relX + r.td * relY + ]; + } + getAbsoluteCoords(relX, relY) { + let w = this._renderContext; + return [ + w.px + w.ta * relX + w.tb * relY, + w.py + w.tc * relX + w.td * relY + ]; + } + collectAtCoord(x, y, children) { + if (this._renderContext.alpha === 0) { + return; + } + if (this.inBound(x, y)) { + if (this._scissor) { + if (this.inScissor()) { + children.push(this); + } + } else { + children.push(this); + } + } + if (this._children) { + const j = this._children.length; + for (let i = 0; i < j; i++) { + this._children[i].collectAtCoord(x, y, children); + } + } + return children.sort(ElementCore.sortZIndexedChildren); + } + inBound(tx, ty) { + const c = this.getCornerPoints(); + return tx > c[0] && tx < c[2] && ty > c[1] && ty < c[7]; + } + inScissor() { + const sc = this._scissor; + const c = this.getCornerPoints(); + return c[2] >= sc[0] && c[0] <= sc[0] + sc[2] && c[7] >= sc[1] && c[1] <= sc[1] + sc[3]; + } + get layout() { + this._ensureLayout(); + return this._layout; + } + get flex() { + return this._layout ? this._layout.flex : null; + } + set flex(v) { + this.layout.flex = v; + } + get flexItem() { + return this._layout ? this._layout.flexItem : null; + } + set flexItem(v) { + this.layout.flexItem = v; + } + isFlexItem() { + return !!this._layout && this._layout.isFlexItemEnabled(); + } + isFlexContainer() { + return !!this._layout && this._layout.isFlexEnabled(); + } + enableFlexLayout() { + this._ensureLayout(); + } + _ensureLayout() { + if (!this._layout) { + this._layout = new FlexTarget(this); + } + } + disableFlexLayout() { + this._triggerRecalcTranslate(); + } + hasFlexLayout() { + return this._layout && this._layout.isEnabled(); + } + setLayout(x, y, w, h) { + this.x = x; + this.y = y; + this._updateDimensions(w, h); + } + triggerLayout() { + this._setRecalc(256); + } + _triggerRecalcTranslate() { + this._setRecalc(2); + } + } + class ElementCoreContext { + constructor() { + this.alpha = 1; + this.px = 0; + this.py = 0; + this.ta = 1; + this.tb = 0; + this.tc = 0; + this.td = 1; + } + isIdentity() { + return this.alpha === 1 && this.px === 0 && this.py === 0 && this.ta === 1 && this.tb === 0 && this.tc === 0 && this.td === 1; + } + isSquare() { + return this.tb === 0 && this.tc === 0; + } + } + ElementCoreContext.IDENTITY = new ElementCoreContext(); + ElementCore.sortZIndexedChildren = function(a, b) { + return a._zIndex === b._zIndex ? a._updateTreeOrder - b._updateTreeOrder : a._zIndex - b._zIndex; + }; + class EventEmitter { + constructor() { + this._hasEventListeners = false; + } + on(name, listener) { + if (!this._hasEventListeners) { + this._eventFunction = {}; + this._eventListeners = {}; + this._hasEventListeners = true; + } + const current = this._eventFunction[name]; + if (!current) { + this._eventFunction[name] = listener; + } else { + if (this._eventFunction[name] !== EventEmitter.combiner) { + this._eventListeners[name] = [this._eventFunction[name], listener]; + this._eventFunction[name] = EventEmitter.combiner; + } else { + this._eventListeners[name].push(listener); + } + } + } + once(name, listener) { + const wrapper = (arg1, arg2, arg3) => { + listener(arg1, arg2, arg3); + this.off(name, wrapper); + }; + wrapper.__originalFunc = listener; + this.on(name, wrapper); + } + has(name, listener) { + if (this._hasEventListeners) { + const current = this._eventFunction[name]; + if (current) { + if (current === EventEmitter.combiner) { + const listeners = this._eventListeners[name]; + for (const l of listeners) { + if (l === listener || l.__originalFunc == listener) { + return true; + } + } + } else if (this._eventFunction[name] === listener || this._eventFunction[name].__originalFunc === listener) { + return true; + } + } + } + return false; + } + off(name, listener) { + if (this._hasEventListeners) { + const current = this._eventFunction[name]; + if (current) { + if (current === EventEmitter.combiner) { + const listeners = this._eventListeners[name]; + let index = listeners.indexOf(listener); + if (index >= 0) { + listeners.splice(index, 1); + } + index = listeners.map((l) => l.__originalFunc).indexOf(listener); + if (index >= 0) { + listeners.splice(index, 1); + } + if (listeners.length === 1) { + this._eventFunction[name] = listeners[0]; + this._eventListeners[name] = void 0; + } + } else if (this._eventFunction[name] === listener || this._eventFunction[name].__originalFunc === listener) { + this._eventFunction[name] = void 0; + } + } + } + } + removeListener(name, listener) { + this.off(name, listener); + } + emit(name, arg1, arg2, arg3) { + if (this._hasEventListeners) { + const func = this._eventFunction[name]; + if (func) { + if (func === EventEmitter.combiner) { + func(this, name, arg1, arg2, arg3); + } else { + func(arg1, arg2, arg3); + } + } + } + } + listenerCount(name) { + if (this._hasEventListeners) { + const func = this._eventFunction[name]; + if (func) { + if (func === EventEmitter.combiner) { + return this._eventListeners[name].length; + } else { + return 1; + } + } + } + return 0; + } + removeAllListeners(name) { + if (this._hasEventListeners) { + delete this._eventFunction[name]; + delete this._eventListeners[name]; + } + } + } + EventEmitter.combiner = function(object, name, arg1, arg2, arg3) { + const listeners = object._eventListeners[name]; + if (listeners) { + for (const listener of [...listeners]) { + listener(arg1, arg2, arg3); + } + } + }; + EventEmitter.addAsMixin = function(cls) { + cls.prototype.on = EventEmitter.prototype.on; + cls.prototype.once = EventEmitter.prototype.once; + cls.prototype.has = EventEmitter.prototype.has; + cls.prototype.off = EventEmitter.prototype.off; + cls.prototype.removeListener = EventEmitter.prototype.removeListener; + cls.prototype.emit = EventEmitter.prototype.emit; + cls.prototype.listenerCount = EventEmitter.prototype.listenerCount; + cls.prototype.removeAllListeners = EventEmitter.prototype.removeAllListeners; + }; + class Shader { + constructor(coreContext) { + this._initialized = false; + this.ctx = coreContext; + this._elements = /* @__PURE__ */ new Set(); + } + static create(stage, v) { + let shader; + if (Utils$1.isObjectLiteral(v)) { + if (v.type) { + shader = stage.renderer.createShader(stage.ctx, v); + } else { + shader = this.shader; + } + if (shader) { + Base.patchObject(shader, v); + } + } else if (v === null) { + shader = stage.ctx.renderState.defaultShader; + } else if (v === void 0) { + shader = null; + } else { + if (v.isShader) { + if (!stage.renderer.isValidShaderType(v.constructor)) { + console.error("[Lightning] Invalid shader type"); + v = null; + } + shader = v; + } else { + console.error("[Lightning] Please specify a shader type."); + return; + } + } + return shader; + } + static getWebGL() { + return void 0; + } + static getC2d() { + return void 0; + } + addElement(elementCore) { + this._elements.add(elementCore); + } + removeElement(elementCore) { + this._elements.delete(elementCore); + if (!this._elements) { + this.cleanup(); + } + } + redraw() { + this._elements.forEach((elementCore) => { + elementCore.setHasRenderUpdates(2); + }); + } + patch(settings) { + Base.patchObject(this, settings); + } + useDefault() { + return false; + } + addEmpty() { + return false; + } + cleanup() { + } + get isShader() { + return true; + } + } + class Texture { + constructor(stage) { + this.stage = stage; + this.manager = this.stage.textureManager; + this.id = Texture.id++; + this.elements = /* @__PURE__ */ new Set(); + this._activeCount = 0; + this._source = null; + this._resizeMode = null; + this._x = 0; + this._y = 0; + this._w = 0; + this._h = 0; + this._precision = 1; + this.mw = 0; + this.mh = 0; + this.clipping = false; + this._mustUpdate = true; + } + get source() { + if (this._mustUpdate || this.stage.hasUpdateSourceTexture(this)) { + this._performUpdateSource(true); + this.stage.removeUpdateSourceTexture(this); + } + return this._source; + } + addElement(v) { + if (!this.elements.has(v)) { + this.elements.add(v); + if (this.elements.size === 1) { + if (this._source) { + this._source.addTexture(this); + } + } + if (v.active) { + this.incActiveCount(); + } + } + } + removeElement(v) { + if (this.elements.delete(v)) { + if (this.elements.size === 0) { + if (this._source) { + this._source.removeTexture(this); + } + } + if (v.active) { + this.decActiveCount(); + } + } + } + incActiveCount() { + const source = this.source; + if (source) { + this._checkForNewerReusableTextureSource(); + } + this._activeCount++; + if (this._activeCount === 1) { + this.becomesUsed(); + } + } + decActiveCount() { + this.source; + this._activeCount--; + if (!this._activeCount) { + this.becomesUnused(); + } + } + becomesUsed() { + if (this.source) { + this.source.incActiveTextureCount(); + } + } + onLoad() { + if (this._resizeMode) { + this._applyResizeMode(); + } + this.elements.forEach((element) => { + if (element.active) { + element.onTextureSourceLoaded(); + } + }); + } + _checkForNewerReusableTextureSource() { + const source = this.source; + if (!source.isLoaded()) { + const reusable = this._getReusableTextureSource(); + if (reusable && reusable.isLoaded() && reusable !== source) { + this._replaceTextureSource(reusable); + } + } else { + if (this._resizeMode) { + this._applyResizeMode(); + } + } + } + becomesUnused() { + if (this.source) { + this.source.decActiveTextureCount(); + } + } + isUsed() { + return this._activeCount > 0; + } + _getLookupId() { + return null; + } + _getSourceLoader() { + throw new Error("Texture.generate must be implemented."); + } + get isValid() { + return this._getIsValid(); + } + _getIsValid() { + return true; + } + _changed() { + if (this.isUsed()) { + this._updateSource(); + } else { + this._mustUpdate = true; + } + } + _updateSource() { + this.stage.addUpdateSourceTexture(this); + } + _performUpdateSource(force = false) { + if (force || this.isUsed()) { + this._mustUpdate = false; + let source = this._getTextureSource(); + this._replaceTextureSource(source); + } + } + _getTextureSource() { + let source = null; + if (this._getIsValid()) { + const lookupId = this._getLookupId(); + source = this._getReusableTextureSource(lookupId); + if (!source) { + source = this.manager.getTextureSource(this._getSourceLoader(), lookupId); + } + } + return source; + } + _getReusableTextureSource(lookupId = this._getLookupId()) { + if (this._getIsValid()) { + if (lookupId) { + return this.manager.getReusableTextureSource(lookupId); + } + } + return null; + } + _replaceTextureSource(newSource = null) { + let oldSource = this._source; + this._source = newSource; + if (this.elements.size) { + if (oldSource) { + if (this._activeCount) { + oldSource.decActiveTextureCount(); + } + oldSource.removeTexture(this); + if (this["text"] && !oldSource.isUsed()) { + this.manager.freeTextureSource(oldSource); + } + } + if (newSource) { + newSource.addTexture(this); + if (this._activeCount) { + newSource.incActiveTextureCount(); + } + } + } + if (this.isUsed()) { + if (newSource) { + if (newSource.isLoaded()) { + if (this._resizeMode) { + this._applyResizeMode(); + } + this.elements.forEach((element) => { + if (element.active) { + element._setDisplayedTexture(this); + } + }); + } else { + const loadError = newSource.loadError; + if (loadError) { + this.elements.forEach((element) => { + if (element.active) { + element.onTextureSourceLoadError(loadError); + } + }); + } + } + } else { + this.elements.forEach((element) => { + if (element.active) { + element._setDisplayedTexture(null); + } + }); + } + } + } + load() { + if (this.source) { + if (!this.isLoaded()) { + this.source.load(true); + } + } + } + isLoaded() { + return this._source && this._source.isLoaded(); + } + get loadError() { + return this._source && this._source.loadError; + } + free() { + if (this._source) { + this._source.free(); + } + } + set resizeMode({ type = "cover", w = 0, h = 0, clipX = 0.5, clipY = 0.5 }) { + this._resizeMode = { type, w, h, clipX, clipY }; + if (this.isLoaded()) { + this._applyResizeMode(); + } + } + get resizeMode() { + return this._resizeMode; + } + _clearResizeMode() { + this._resizeMode = null; + } + _applyResizeMode() { + if (this._resizeMode.type === "cover") { + this._applyResizeCover(); + } else if (this._resizeMode.type === "contain") { + this._applyResizeContain(); + } + this._updatePrecision(); + this._updateClipping(); + } + _applyResizeCover() { + const scaleX = this._resizeMode.w / this._source.w; + const scaleY = this._resizeMode.h / this._source.h; + let scale = Math.max(scaleX, scaleY); + if (!scale) + return; + this._precision = 1 / scale; + if (scaleX && scaleX < scale) { + const desiredSize = this._precision * this._resizeMode.w; + const choppedOffPixels = this._source.w - desiredSize; + this._x = choppedOffPixels * this._resizeMode.clipX; + this._w = this._source.w - choppedOffPixels; + } + if (scaleY && scaleY < scale) { + const desiredSize = this._precision * this._resizeMode.h; + const choppedOffPixels = this._source.h - desiredSize; + this._y = choppedOffPixels * this._resizeMode.clipY; + this._h = this._source.h - choppedOffPixels; + } + } + _applyResizeContain() { + const scaleX = this._resizeMode.w / this._source.w; + const scaleY = this._resizeMode.h / this._source.h; + let scale = scaleX; + if (!scale || scaleY < scale) { + scale = scaleY; + } + if (!scale) + return; + this._precision = 1 / scale; + } + enableClipping(x, y, w, h) { + this._clearResizeMode(); + x *= this._precision; + y *= this._precision; + w *= this._precision; + h *= this._precision; + if (this._x !== x || this._y !== y || this._w !== w || this._h !== h) { + this._x = x; + this._y = y; + this._w = w; + this._h = h; + this._updateClipping(true); + } + } + disableClipping() { + this._clearResizeMode(); + if (this._x || this._y || this._w || this._h) { + this._x = 0; + this._y = 0; + this._w = 0; + this._h = 0; + this._updateClipping(); + } + } + _updateClipping() { + this.clipping = !!(this._x || this._y || this._w || this._h); + let self2 = this; + this.elements.forEach(function(element) { + if (element.displayedTexture === self2) { + element.onDisplayedTextureClippingChanged(); + } + }); + } + _updatePrecision() { + let self2 = this; + this.elements.forEach(function(element) { + if (element.displayedTexture === self2) { + element.onPrecisionChanged(); + } + }); + } + getNonDefaults() { + let nonDefaults = {}; + nonDefaults["type"] = this.constructor.name; + if (this.x !== 0) + nonDefaults["x"] = this.x; + if (this.y !== 0) + nonDefaults["y"] = this.y; + if (this.w !== 0) + nonDefaults["w"] = this.w; + if (this.h !== 0) + nonDefaults["h"] = this.h; + if (this.precision !== 1) + nonDefaults["precision"] = this.precision; + return nonDefaults; + } + get px() { + return this._x; + } + get py() { + return this._y; + } + get pw() { + return this._w; + } + get ph() { + return this._h; + } + get x() { + return this._x / this._precision; + } + set x(v) { + this._clearResizeMode(); + v = v * this._precision; + if (this._x !== v) { + this._x = v; + this._updateClipping(); + } + } + get y() { + return this._y / this._precision; + } + set y(v) { + this._clearResizeMode(); + v = v * this._precision; + if (this._y !== v) { + this._y = v; + this._updateClipping(); + } + } + get w() { + return this._w / this._precision; + } + set w(v) { + this._clearResizeMode(); + v = v * this._precision; + if (this._w !== v) { + this._w = v; + this._updateClipping(); + } + } + get h() { + return this._h / this._precision; + } + set h(v) { + this._clearResizeMode(); + v = v * this._precision; + if (this._h !== v) { + this._h = v; + this._updateClipping(); + } + } + get precision() { + return this._precision; + } + set precision(v) { + this._clearResizeMode(); + if (this._precision !== v) { + this._precision = v; + this._updatePrecision(); + } + } + isAutosizeTexture() { + return true; + } + getRenderWidth() { + if (!this.isAutosizeTexture()) { + return 0; + } + return (this._w || (this._source ? this._source.getRenderWidth() - this._x : 0)) / this._precision; + } + getRenderHeight() { + if (!this.isAutosizeTexture()) { + return 0; + } + return (this._h || (this._source ? this._source.getRenderHeight() - this._y : 0)) / this._precision; + } + patch(settings) { + Base.patchObject(this, settings); + } + } + Texture.prototype.isTexture = true; + Texture.id = 0; + class ImageTexture extends Texture { + constructor(stage) { + super(stage); + this._src = void 0; + this._hasAlpha = false; + } + get src() { + return this._src; + } + set src(v) { + if (this._src !== v) { + this._src = v; + this._changed(); + } + } + get hasAlpha() { + return this._hasAlpha; + } + set hasAlpha(v) { + if (this._hasAlpha !== v) { + this._hasAlpha = v; + this._changed(); + } + } + _getIsValid() { + return !!this._src; + } + _getLookupId() { + return this._src; + } + _getSourceLoader() { + let src = this._src; + let hasAlpha = this._hasAlpha; + if (this.stage.getOption("srcBasePath")) { + var fc = src.charCodeAt(0); + if (src.indexOf("//") === -1 && (fc >= 65 && fc <= 90 || fc >= 97 && fc <= 122 || fc == 46)) { + src = this.stage.getOption("srcBasePath") + src; + } + } + return (cb) => { + return this.stage.platform.loadSrcTexture({ src, hasAlpha }, cb); + }; + } + getNonDefaults() { + const obj = super.getNonDefaults(); + if (this._src) { + obj.src = this._src; + } + return obj; + } + } + function getFontSetting(fontFace, fontStyle, fontSize, precision, defaultFontFace) { + let ff = fontFace; + if (!Array.isArray(ff)) { + ff = [ff]; + } + let ffs = []; + for (let i = 0, n = ff.length; i < n; i++) { + let curFf = ff[i]; + if (curFf === null) { + curFf = defaultFontFace; + } + if (curFf === "serif" || curFf === "sans-serif") { + ffs.push(curFf); + } else { + ffs.push(`"${curFf}"`); + } + } + return `${fontStyle} ${fontSize * precision}px ${ffs.join(",")}`; + } + function isZeroWidthSpace(space) { + return space === "" || space === "​"; + } + function isSpace(space) { + return isZeroWidthSpace(space) || space === " "; + } + function tokenizeString(tokenRegex, text) { + const delimeters = text.match(tokenRegex) || []; + const words = text.split(tokenRegex) || []; + let final = []; + for (let i = 0; i < words.length; i++) { + final.push(words[i], delimeters[i]); + } + final.pop(); + return final.filter((word) => word != ""); + } + function measureText(context, word, space = 0) { + if (!space) { + return context.measureText(word).width; + } + return word.split("").reduce((acc, char) => { + if (isZeroWidthSpace(char)) { + return acc; + } + return acc + context.measureText(char).width + space; + }, 0); + } + function wrapText(context, text, wordWrapWidth, letterSpacing, indent) { + const spaceRegex = / |\u200B/g; + let lines = text.split(/\r?\n/g); + let allLines = []; + let realNewlines = []; + for (let i = 0; i < lines.length; i++) { + let resultLines = []; + let result = ""; + let spaceLeft = wordWrapWidth - indent; + let words = lines[i].split(spaceRegex); + let spaces = lines[i].match(spaceRegex) || []; + for (let j = 0; j < words.length; j++) { + const space = spaces[j - 1] || ""; + const word = words[j]; + const wordWidth = measureText(context, word, letterSpacing); + const wordWidthWithSpace = wordWidth + measureText(context, space, letterSpacing); + if (j === 0 || wordWidthWithSpace > spaceLeft) { + if (j > 0) { + resultLines.push(result); + result = ""; + } + result += word; + spaceLeft = wordWrapWidth - wordWidth - (j === 0 ? indent : 0); + } else { + spaceLeft -= wordWidthWithSpace; + result += space + word; + } + } + resultLines.push(result); + result = ""; + allLines = allLines.concat(resultLines); + if (i < lines.length - 1) { + realNewlines.push(allLines.length); + } + } + return { l: allLines, n: realNewlines }; + } + class TextTextureRenderer { + constructor(stage, canvas, settings) { + this._stage = stage; + this._canvas = canvas; + this._context = this._canvas.getContext("2d"); + this._settings = settings; + } + getPrecision() { + return this._settings.precision; + } + setFontProperties() { + this._context.font = getFontSetting( + this._settings.fontFace, + this._settings.fontStyle, + this._settings.fontSize, + this.getPrecision(), + this._stage.getOption("defaultFontFace") + ); + this._context.textBaseline = this._settings.textBaseline; + } + _load() { + if (Utils$1.isWeb && document.fonts) { + const fontSetting = getFontSetting( + this._settings.fontFace, + this._settings.fontStyle, + this._settings.fontSize, + this.getPrecision(), + this._stage.getOption("defaultFontFace") + ); + try { + if (!document.fonts.check(fontSetting, this._settings.text)) { + return document.fonts.load(fontSetting, this._settings.text).catch((err) => { + console.warn("[Lightning] Font load error", err, fontSetting); + }).then(() => { + if (!document.fonts.check(fontSetting, this._settings.text)) { + console.warn("[Lightning] Font not found", fontSetting); + } + }); + } + } catch (e) { + console.warn("[Lightning] Can't check font loading for " + fontSetting); + } + } + } + draw() { + const loadPromise = this._load(); + if (!loadPromise) { + return Utils$1.isSpark ? this._stage.platform.drawText(this) : this._draw(); + } else { + return loadPromise.then(() => { + return Utils$1.isSpark ? this._stage.platform.drawText(this) : this._draw(); + }); + } + } + _calculateRenderInfo() { + let renderInfo = {}; + const precision = this.getPrecision(); + const paddingLeft = this._settings.paddingLeft * precision; + const paddingRight = this._settings.paddingRight * precision; + const fontSize = this._settings.fontSize * precision; + let offsetY = this._settings.offsetY === null ? null : this._settings.offsetY * precision; + let lineHeight = this._settings.lineHeight * precision; + const w = this._settings.w * precision; + const h = this._settings.h * precision; + let wordWrapWidth = this._settings.wordWrapWidth * precision; + const cutSx = this._settings.cutSx * precision; + const cutEx = this._settings.cutEx * precision; + const cutSy = this._settings.cutSy * precision; + const cutEy = this._settings.cutEy * precision; + const letterSpacing = (this._settings.letterSpacing || 0) * precision; + const textIndent = this._settings.textIndent * precision; + this.setFontProperties(); + let width = w || this._stage.getOption("w"); + let innerWidth = width - paddingLeft; + if (innerWidth < 10) { + width += 10 - innerWidth; + innerWidth = 10; + } + if (!wordWrapWidth) { + wordWrapWidth = innerWidth; + } + if (this._settings.textOverflow && !this._settings.wordWrap) { + let suffix; + switch (this._settings.textOverflow) { + case "clip": + suffix = ""; + break; + case "ellipsis": + suffix = this._settings.maxLinesSuffix; + break; + default: + suffix = this._settings.textOverflow; + } + this._settings.text = this.wrapWord(this._settings.text, wordWrapWidth - textIndent, suffix); + } + let linesInfo; + if (this._settings.wordWrap) { + linesInfo = this.wrapText(this._settings.text, wordWrapWidth, letterSpacing, textIndent); + } else { + linesInfo = { l: this._settings.text.split(/(?:\r\n|\r|\n)/), n: [] }; + let n = linesInfo.l.length; + for (let i = 0; i < n - 1; i++) { + linesInfo.n.push(i); + } + } + let lines = linesInfo.l; + if (this._settings.maxLines && lines.length > this._settings.maxLines) { + let usedLines = lines.slice(0, this._settings.maxLines); + let otherLines = null; + if (this._settings.maxLinesSuffix) { + let w2 = this._settings.maxLinesSuffix ? this.measureText(this._settings.maxLinesSuffix) : 0; + let al = this.wrapText(usedLines[usedLines.length - 1], wordWrapWidth - w2, letterSpacing, textIndent); + usedLines[usedLines.length - 1] = al.l[0] + this._settings.maxLinesSuffix; + otherLines = [al.l.length > 1 ? al.l[1] : ""]; + } else { + otherLines = [""]; + } + let i, n = lines.length; + let j = 0; + let m = linesInfo.n.length; + for (i = this._settings.maxLines; i < n; i++) { + otherLines[j] += (otherLines[j] ? " " : "") + lines[i]; + if (i + 1 < m && linesInfo.n[i + 1]) { + j++; + } + } + renderInfo.remainingText = otherLines.join("\n"); + renderInfo.moreTextLines = true; + lines = usedLines; + } else { + renderInfo.moreTextLines = false; + renderInfo.remainingText = ""; + } + let maxLineWidth = 0; + let lineWidths = []; + for (let i = 0; i < lines.length; i++) { + let lineWidth = this.measureText(lines[i], letterSpacing) + (i === 0 ? textIndent : 0); + lineWidths.push(lineWidth); + maxLineWidth = Math.max(maxLineWidth, lineWidth); + } + renderInfo.lineWidths = lineWidths; + if (!w) { + width = maxLineWidth + paddingLeft + paddingRight; + innerWidth = maxLineWidth; + } + lineHeight = lineHeight || fontSize; + let height; + if (h) { + height = h; + } else { + const baselineOffset = this._settings.textBaseline != "bottom" ? 0.5 * fontSize : 0; + height = lineHeight * (lines.length - 1) + baselineOffset + Math.max(lineHeight, fontSize) + offsetY; + } + if (offsetY === null) { + offsetY = fontSize; + } + renderInfo.w = width; + renderInfo.h = height; + renderInfo.lines = lines; + renderInfo.precision = precision; + if (!width) { + width = 1; + } + if (!height) { + height = 1; + } + if (cutSx || cutEx) { + width = Math.min(width, cutEx - cutSx); + } + if (cutSy || cutEy) { + height = Math.min(height, cutEy - cutSy); + } + renderInfo.width = width; + renderInfo.innerWidth = innerWidth; + renderInfo.height = height; + renderInfo.fontSize = fontSize; + renderInfo.cutSx = cutSx; + renderInfo.cutSy = cutSy; + renderInfo.cutEx = cutEx; + renderInfo.cutEy = cutEy; + renderInfo.lineHeight = lineHeight; + renderInfo.lineWidths = lineWidths; + renderInfo.offsetY = offsetY; + renderInfo.paddingLeft = paddingLeft; + renderInfo.paddingRight = paddingRight; + renderInfo.letterSpacing = letterSpacing; + renderInfo.textIndent = textIndent; + return renderInfo; + } + _draw() { + const renderInfo = this._calculateRenderInfo(); + const precision = this.getPrecision(); + this._canvas.width = Math.ceil(renderInfo.width + this._stage.getOption("textRenderIssueMargin")); + this._canvas.height = Math.ceil(renderInfo.height); + this.setFontProperties(); + if (renderInfo.fontSize >= 128) { + this._context.globalAlpha = 0.01; + this._context.fillRect(0, 0, 0.01, 0.01); + this._context.globalAlpha = 1; + } + if (renderInfo.cutSx || renderInfo.cutSy) { + this._context.translate(-renderInfo.cutSx, -renderInfo.cutSy); + } + let linePositionX; + let linePositionY; + let drawLines = []; + for (let i = 0, n = renderInfo.lines.length; i < n; i++) { + linePositionX = i === 0 ? renderInfo.textIndent : 0; + linePositionY = i * renderInfo.lineHeight + renderInfo.offsetY; + if (this._settings.verticalAlign == "middle") { + linePositionY += (renderInfo.lineHeight - renderInfo.fontSize) / 2; + } else if (this._settings.verticalAlign == "bottom") { + linePositionY += renderInfo.lineHeight - renderInfo.fontSize; + } + if (this._settings.textAlign === "right") { + linePositionX += renderInfo.innerWidth - renderInfo.lineWidths[i]; + } else if (this._settings.textAlign === "center") { + linePositionX += (renderInfo.innerWidth - renderInfo.lineWidths[i]) / 2; + } + linePositionX += renderInfo.paddingLeft; + drawLines.push({ text: renderInfo.lines[i], x: linePositionX, y: linePositionY, w: renderInfo.lineWidths[i] }); + } + if (this._settings.highlight) { + let color = this._settings.highlightColor || 0; + let hlHeight = this._settings.highlightHeight * precision || renderInfo.fontSize * 1.5; + const offset = this._settings.highlightOffset * precision; + const hlPaddingLeft = this._settings.highlightPaddingLeft !== null ? this._settings.highlightPaddingLeft * precision : renderInfo.paddingLeft; + const hlPaddingRight = this._settings.highlightPaddingRight !== null ? this._settings.highlightPaddingRight * precision : renderInfo.paddingRight; + this._context.fillStyle = StageUtils.getRgbaString(color); + for (let i = 0; i < drawLines.length; i++) { + let drawLine = drawLines[i]; + this._context.fillRect(drawLine.x - hlPaddingLeft, drawLine.y - renderInfo.offsetY + offset, drawLine.w + hlPaddingRight + hlPaddingLeft, hlHeight); + } + } + let prevShadowSettings = null; + if (this._settings.shadow) { + prevShadowSettings = [this._context.shadowColor, this._context.shadowOffsetX, this._context.shadowOffsetY, this._context.shadowBlur]; + this._context.shadowColor = StageUtils.getRgbaString(this._settings.shadowColor); + this._context.shadowOffsetX = this._settings.shadowOffsetX * precision; + this._context.shadowOffsetY = this._settings.shadowOffsetY * precision; + this._context.shadowBlur = this._settings.shadowBlur * precision; + } + this._context.fillStyle = StageUtils.getRgbaString(this._settings.textColor); + for (let i = 0, n = drawLines.length; i < n; i++) { + let drawLine = drawLines[i]; + if (renderInfo.letterSpacing === 0) { + this._context.fillText(drawLine.text, drawLine.x, drawLine.y); + } else { + const textSplit = drawLine.text.split(""); + let x = drawLine.x; + for (let i2 = 0, j = textSplit.length; i2 < j; i2++) { + this._context.fillText(textSplit[i2], x, drawLine.y); + x += this.measureText(textSplit[i2], renderInfo.letterSpacing); + } + } + } + if (prevShadowSettings) { + this._context.shadowColor = prevShadowSettings[0]; + this._context.shadowOffsetX = prevShadowSettings[1]; + this._context.shadowOffsetY = prevShadowSettings[2]; + this._context.shadowBlur = prevShadowSettings[3]; + } + if (renderInfo.cutSx || renderInfo.cutSy) { + this._context.translate(renderInfo.cutSx, renderInfo.cutSy); + } + this.renderInfo = renderInfo; + } + wrapWord(word, wordWrapWidth, suffix) { + const suffixWidth = this.measureText(suffix); + const wordLen = word.length; + const wordWidth = this.measureText(word); + if (wordWidth <= wordWrapWidth) { + return word; + } + let cutoffIndex = Math.floor(wordWrapWidth * wordLen / wordWidth); + let truncWordWidth = this.measureText(word.substring(0, cutoffIndex)) + suffixWidth; + if (truncWordWidth > wordWrapWidth) { + while (cutoffIndex > 0) { + truncWordWidth = this.measureText(word.substring(0, cutoffIndex)) + suffixWidth; + if (truncWordWidth > wordWrapWidth) { + cutoffIndex -= 1; + } else { + break; + } + } + } else { + while (cutoffIndex < wordLen) { + truncWordWidth = this.measureText(word.substring(0, cutoffIndex)) + suffixWidth; + if (truncWordWidth < wordWrapWidth) { + cutoffIndex += 1; + } else { + cutoffIndex -= 1; + break; + } + } + } + return word.substring(0, cutoffIndex) + (wordWrapWidth >= suffixWidth ? suffix : ""); + } + wrapText(text, wordWrapWidth, letterSpacing, indent = 0) { + return wrapText(this._context, text, wordWrapWidth, letterSpacing, indent); + } + measureText(word, space = 0) { + return measureText(this._context, word, space); + } + } + class TextTextureRendererAdvanced { + constructor(stage, canvas, settings) { + this._stage = stage; + this._canvas = canvas; + this._context = this._canvas.getContext("2d"); + this._settings = settings; + } + getPrecision() { + return this._settings.precision; + } + setFontProperties() { + const font = getFontSetting( + this._settings.fontFace, + this._settings.fontStyle, + this._settings.fontSize, + this.getPrecision(), + this._stage.getOption("defaultFontFace") + ); + this._context.font = font; + this._context.textBaseline = this._settings.textBaseline; + return font; + } + _load() { + if (Utils$1.isWeb && document.fonts) { + const fontSetting = getFontSetting( + this._settings.fontFace, + this._settings.fontStyle, + this._settings.fontSize, + this.getPrecision(), + this._stage.getOption("defaultFontFace") + ); + try { + if (!document.fonts.check(fontSetting, this._settings.text)) { + return document.fonts.load(fontSetting, this._settings.text).catch((err) => { + console.warn("Font load error", err, fontSetting); + }).then(() => { + if (!document.fonts.check(fontSetting, this._settings.text)) { + console.warn("Font not found", fontSetting); + } + }); + } + } catch (e) { + console.warn("Can't check font loading for " + fontSetting); + } + } + } + draw() { + const loadPromise = this._load(); + if (!loadPromise) { + return Utils$1.isSpark ? this._stage.platform.drawText(this) : this._draw(); + } else { + return loadPromise.then(() => { + return Utils$1.isSpark ? this._stage.platform.drawText(this) : this._draw(); + }); + } + } + _calculateRenderInfo() { + let renderInfo = {}; + const precision = this.getPrecision(); + const paddingLeft = this._settings.paddingLeft * precision; + const paddingRight = this._settings.paddingRight * precision; + const fontSize = this._settings.fontSize * precision; + const lineHeight = this._settings.lineHeight * precision || fontSize; + const w = this._settings.w != 0 ? this._settings.w * precision : this._stage.getOption("w"); + const wordWrapWidth = this._settings.wordWrapWidth * precision; + const cutSx = this._settings.cutSx * precision; + const cutEx = this._settings.cutEx * precision; + const cutSy = this._settings.cutSy * precision; + const cutEy = this._settings.cutEy * precision; + const letterSpacing = this._settings.letterSpacing || 0; + renderInfo.baseFont = this.setFontProperties(); + renderInfo.w = w; + renderInfo.width = w; + renderInfo.text = this._settings.text; + renderInfo.precision = precision; + renderInfo.fontSize = fontSize; + renderInfo.fontBaselineRatio = this._settings.fontBaselineRatio; + renderInfo.lineHeight = lineHeight; + renderInfo.letterSpacing = letterSpacing; + renderInfo.textAlign = this._settings.textAlign; + renderInfo.textColor = this._settings.textColor; + renderInfo.verticalAlign = this._settings.verticalAlign; + renderInfo.highlight = this._settings.highlight; + renderInfo.highlightColor = this._settings.highlightColor; + renderInfo.highlightHeight = this._settings.highlightHeight; + renderInfo.highlightPaddingLeft = this._settings.highlightPaddingLeft; + renderInfo.highlightPaddingRight = this._settings.highlightPaddingRight; + renderInfo.highlightOffset = this._settings.highlightOffset; + renderInfo.paddingLeft = this._settings.paddingLeft; + renderInfo.paddingRight = this._settings.paddingRight; + renderInfo.maxLines = this._settings.maxLines; + renderInfo.maxLinesSuffix = this._settings.maxLinesSuffix; + renderInfo.textOverflow = this._settings.textOverflow; + renderInfo.wordWrap = this._settings.wordWrap; + renderInfo.wordWrapWidth = wordWrapWidth; + renderInfo.shadow = this._settings.shadow; + renderInfo.shadowColor = this._settings.shadowColor; + renderInfo.shadowOffsetX = this._settings.shadowOffsetX; + renderInfo.shadowOffsetY = this._settings.shadowOffsetY; + renderInfo.shadowBlur = this._settings.shadowBlur; + renderInfo.cutSx = cutSx; + renderInfo.cutEx = cutEx; + renderInfo.cutSy = cutSy; + renderInfo.cutEy = cutEy; + renderInfo.textIndent = this._settings.textIndent * precision; + renderInfo.wordBreak = this._settings.wordBreak; + let text = renderInfo.text; + let wrapWidth = renderInfo.wordWrap ? renderInfo.wordWrapWidth || renderInfo.width : renderInfo.width; + if (renderInfo.textOverflow && !renderInfo.wordWrap) { + let suffix; + switch (this._settings.textOverflow) { + case "clip": + suffix = ""; + break; + case "ellipsis": + suffix = this._settings.maxLinesSuffix; + break; + default: + suffix = this._settings.textOverflow; + } + text = this.wrapWord(text, wordWrapWidth || renderInfo.w, suffix); + } + text = this.tokenize(text); + text = this.parse(text); + text = this.measure(text, letterSpacing, renderInfo.baseFont); + if (renderInfo.textIndent) { + text = this.indent(text, renderInfo.textIndent); + } + if (renderInfo.wordBreak) { + text = text.reduce((acc, t) => acc.concat(this.wordBreak(t, wrapWidth, renderInfo.baseFont)), []); + this.resetFontStyle(); + } + let x = paddingLeft; + let lineNo = 0; + for (const t of text) { + if (renderInfo.wordWrap && x + t.width > wrapWidth || t.text == "\n") { + x = paddingLeft; + lineNo += 1; + } + t.lineNo = lineNo; + if (t.text == "\n") { + continue; + } + t.x = x; + x += t.width; + } + renderInfo.lineNum = lineNo + 1; + if (this._settings.h) { + renderInfo.h = this._settings.h; + } else if (renderInfo.maxLines && renderInfo.maxLines < renderInfo.lineNum) { + renderInfo.h = renderInfo.maxLines * renderInfo.lineHeight + fontSize / 2; + } else { + renderInfo.h = renderInfo.lineNum * renderInfo.lineHeight + fontSize / 2; + } + const baselineOffsetInPx = renderInfo.fontBaselineRatio * renderInfo.fontSize; + let vaOffset = 0; + if (renderInfo.verticalAlign == "top" && this._context.textBaseline == "alphabetic") { + vaOffset = -baselineOffsetInPx; + } else if (renderInfo.verticalAlign == "middle") { + vaOffset = (renderInfo.lineHeight - renderInfo.fontSize - baselineOffsetInPx) / 2; + } else if (this._settings.verticalAlign == "bottom") { + vaOffset = renderInfo.lineHeight - renderInfo.fontSize; + } + renderInfo.lines = []; + for (let i = 0; i < renderInfo.lineNum; i++) { + renderInfo.lines[i] = { + width: 0, + x: 0, + y: renderInfo.lineHeight * i + vaOffset, + text: [] + }; + } + for (let t of text) { + renderInfo.lines[t.lineNo].text.push(t); + } + for (const l of renderInfo.lines) { + if (l.text.length == 0) { + continue; + } + const firstWord = l.text[0].text; + const lastWord = l.text[l.text.length - 1].text; + if (firstWord == "\n") { + l.text.shift(); + } + if (isSpace(lastWord) || lastWord == "\n") { + l.text.pop(); + } + } + for (let l of renderInfo.lines) { + l.width = l.text.reduce((acc, t) => acc + t.width, 0); + } + renderInfo.width = this._settings.w != 0 ? this._settings.w * precision : Math.max(...renderInfo.lines.map((l) => l.width)) + paddingRight; + renderInfo.w = renderInfo.width; + if (renderInfo.maxLines && renderInfo.lineNum > renderInfo.maxLines && renderInfo.maxLinesSuffix) { + const index = renderInfo.maxLines - 1; + let lastLineText = text.filter((t) => t.lineNo == index); + let suffix = renderInfo.maxLinesSuffix; + suffix = this.tokenize(suffix); + suffix = this.parse(suffix); + suffix = this.measure(suffix, renderInfo.letterSpacing, renderInfo.baseFont); + for (const s of suffix) { + s.lineNo = index; + s.x = 0; + lastLineText.push(s); + } + const spl = suffix.length + 1; + let _w = lastLineText.reduce((acc, t) => acc + t.width, 0); + while (_w > renderInfo.width || isSpace(lastLineText[lastLineText.length - spl].text)) { + lastLineText.splice(lastLineText.length - spl, 1); + _w = lastLineText.reduce((acc, t) => acc + t.width, 0); + if (lastLineText.length < spl) { + break; + } + } + this.alignLine(lastLineText, lastLineText[0].x); + renderInfo.lines[index].text = lastLineText; + renderInfo.lines[index].width = _w; + } + if (renderInfo.textAlign == "center") { + for (let l of renderInfo.lines) { + l.x = (renderInfo.width - l.width - paddingLeft) / 2; + } + } else if (renderInfo.textAlign == "right") { + for (let l of renderInfo.lines) { + l.x = renderInfo.width - l.width - paddingLeft; + } + } + return renderInfo; + } + _draw() { + const renderInfo = this._calculateRenderInfo(); + const precision = this.getPrecision(); + const paddingLeft = renderInfo.paddingLeft * precision; + let canvasWidth = renderInfo.w || renderInfo.width; + if (renderInfo.cutSx || renderInfo.cutEx) { + canvasWidth = Math.min(renderInfo.w, renderInfo.cutEx - renderInfo.cutSx); + } + let canvasHeight = renderInfo.h; + if (renderInfo.cutSy || renderInfo.cutEy) { + canvasHeight = Math.min(renderInfo.h, renderInfo.cutEy - renderInfo.cutSy); + } + this._canvas.width = Math.ceil(canvasWidth + this._stage.getOption("textRenderIssueMargin")); + this._canvas.height = Math.ceil(canvasHeight); + this.setFontProperties(); + if (renderInfo.fontSize >= 128) { + this._context.globalAlpha = 0.01; + this._context.fillRect(0, 0, 0.01, 0.01); + this._context.globalAlpha = 1; + } + if (renderInfo.cutSx || renderInfo.cutSy) { + this._context.translate(-renderInfo.cutSx, -renderInfo.cutSy); + } + if (renderInfo.highlight) { + const hlColor = renderInfo.highlightColor || 0; + const hlHeight = renderInfo.highlightHeight ? renderInfo.highlightHeight * precision : renderInfo.fontSize * 1.5; + const hlOffset = renderInfo.highlightOffset ? renderInfo.highlightOffset * precision : 0; + const hlPaddingLeft = renderInfo.highlightPaddingLeft !== null ? renderInfo.highlightPaddingLeft * precision : renderInfo.paddingLeft; + const hlPaddingRight = renderInfo.highlightPaddingRight !== null ? renderInfo.highlightPaddingRight * precision : renderInfo.paddingRight; + this._context.fillStyle = StageUtils.getRgbaString(hlColor); + const lineNum = renderInfo.maxLines ? Math.min(renderInfo.maxLines, renderInfo.lineNum) : renderInfo.lineNum; + for (let i = 0; i < lineNum; i++) { + const l = renderInfo.lines[i]; + this._context.fillRect(l.x - hlPaddingLeft + paddingLeft, l.y + hlOffset, l.width + hlPaddingLeft + hlPaddingRight, hlHeight); + } + } + let prevShadowSettings = null; + if (this._settings.shadow) { + prevShadowSettings = [this._context.shadowColor, this._context.shadowOffsetX, this._context.shadowOffsetY, this._context.shadowBlur]; + this._context.shadowColor = StageUtils.getRgbaString(this._settings.shadowColor); + this._context.shadowOffsetX = this._settings.shadowOffsetX * precision; + this._context.shadowOffsetY = this._settings.shadowOffsetY * precision; + this._context.shadowBlur = this._settings.shadowBlur * precision; + } + const defaultColor = StageUtils.getRgbaString(this._settings.textColor); + let currentColor = defaultColor; + this._context.fillStyle = defaultColor; + for (const line of renderInfo.lines) { + for (const t of line.text) { + let lx = 0; + if (t.text == "\n") { + continue; + } + if (renderInfo.maxLines && t.lineNo >= renderInfo.maxLines) { + continue; + } + if (t.color != currentColor) { + currentColor = t.color; + this._context.fillStyle = currentColor; + } + this._context.font = t.fontStyle; + if (t.letters) { + for (let l of t.letters) { + const _x = renderInfo.lines[t.lineNo].x + t.x + lx; + this._context.fillText(l.text, _x, renderInfo.lines[t.lineNo].y + renderInfo.fontSize); + lx += l.width; + } + } else { + const _x = renderInfo.lines[t.lineNo].x + t.x; + this._context.fillText(t.text, _x, renderInfo.lines[t.lineNo].y + renderInfo.fontSize); + } + } + } + if (prevShadowSettings) { + this._context.shadowColor = prevShadowSettings[0]; + this._context.shadowOffsetX = prevShadowSettings[1]; + this._context.shadowOffsetY = prevShadowSettings[2]; + this._context.shadowBlur = prevShadowSettings[3]; + } + if (renderInfo.cutSx || renderInfo.cutSy) { + this._context.translate(renderInfo.cutSx, renderInfo.cutSy); + } + renderInfo.lines = renderInfo.lines.map((l) => l.text.reduce((acc, v) => acc + v.text, "")); + if (renderInfo.maxLines) { + renderInfo.lines = renderInfo.lines.slice(0, renderInfo.maxLines); + } + this.renderInfo = renderInfo; + } + measureText(word, space = 0) { + return measureText(this._context, word, space); + } + tokenize(text) { + return tokenizeString(/ |\u200B|\n||<\/i>||<\/b>||<\/color>/g, text); + } + parse(tokens) { + let italic = 0; + let bold = 0; + let colorStack = [StageUtils.getRgbaString(this._settings.textColor)]; + let color = 0; + const colorRegexp = //; + return tokens.map((t) => { + if (t == "") { + italic += 1; + t = ""; + } else if (t == "" && italic > 0) { + italic -= 1; + t = ""; + } else if (t == "") { + bold += 1; + t = ""; + } else if (t == "" && bold > 0) { + bold -= 1; + t = ""; + } else if (t == "") { + if (colorStack.length > 1) { + color -= 1; + colorStack.pop(); + } + t = ""; + } else if (colorRegexp.test(t)) { + const matched = colorRegexp.exec(t); + colorStack.push( + StageUtils.getRgbaString(parseInt(matched[1])) + ); + color += 1; + t = ""; + } + return { + text: t, + italic, + bold, + color: colorStack[color] + }; + }).filter((o) => o.text != ""); + } + applyFontStyle(word, baseFont) { + let font = baseFont; + if (word.bold) { + font = "bold " + font; + } + if (word.italic) { + font = "italic " + font; + } + this._context.font = font; + word.fontStyle = font; + } + resetFontStyle(baseFont) { + this._context.font = baseFont; + } + measure(parsed, letterSpacing = 0, baseFont) { + for (const p of parsed) { + this.applyFontStyle(p, baseFont); + p.width = this.measureText(p.text, letterSpacing); + if (letterSpacing > 0) { + p.letters = p.text.split("").map((l) => { + return { text: l }; + }); + for (let l of p.letters) { + l.width = this.measureText(l.text, letterSpacing); + } + } + } + this.resetFontStyle(baseFont); + return parsed; + } + indent(parsed, textIndent) { + parsed.splice(0, 0, { text: "", width: textIndent }); + return parsed; + } + wrapWord(word, wordWrapWidth, suffix) { + const suffixWidth = this.measureText(suffix); + const wordLen = word.length; + const wordWidth = this.measureText(word); + if (wordWidth <= wordWrapWidth) { + return word; + } + let cutoffIndex = Math.floor(wordWrapWidth * wordLen / wordWidth); + let truncWordWidth = this.measureText(word.substring(0, cutoffIndex)) + suffixWidth; + if (truncWordWidth > wordWrapWidth) { + while (cutoffIndex > 0) { + truncWordWidth = this.measureText(word.substring(0, cutoffIndex)) + suffixWidth; + if (truncWordWidth > wordWrapWidth) { + cutoffIndex -= 1; + } else { + break; + } + } + } else { + while (cutoffIndex < wordLen) { + truncWordWidth = this.measureText(word.substring(0, cutoffIndex)) + suffixWidth; + if (truncWordWidth < wordWrapWidth) { + cutoffIndex += 1; + } else { + cutoffIndex -= 1; + break; + } + } + } + return word.substring(0, cutoffIndex) + (wordWrapWidth >= suffixWidth ? suffix : ""); + } + _getBreakIndex(word, width) { + const wordLen = word.length; + const wordWidth = this.measureText(word); + if (wordWidth <= width) { + return { breakIndex: word.length, truncWordWidth: wordWidth }; + } + let breakIndex = Math.floor(width * wordLen / wordWidth); + let truncWordWidth = this.measureText(word.substring(0, breakIndex)); + if (truncWordWidth > width) { + while (breakIndex > 0) { + truncWordWidth = this.measureText(word.substring(0, breakIndex)); + if (truncWordWidth > width) { + breakIndex -= 1; + } else { + break; + } + } + } else { + while (breakIndex < wordLen) { + truncWordWidth = this.measureText(word.substring(0, breakIndex)); + if (truncWordWidth < width) { + breakIndex += 1; + } else { + breakIndex -= 1; + truncWordWidth = this.measureText(word.substring(0, breakIndex)); + break; + } + } + } + return { breakIndex, truncWordWidth }; + } + wordBreak(word, width, baseFont) { + if (!word.text) { + return word; + } + this.applyFontStyle(word, baseFont); + const parts = []; + let text = word.text; + if (!word.letters) { + while (true) { + const { breakIndex, truncWordWidth } = this._getBreakIndex(text, width); + parts.push({ ...word }); + parts[parts.length - 1].text = text.slice(0, breakIndex); + parts[parts.length - 1].width = truncWordWidth; + if (breakIndex === text.length) { + break; + } + text = text.slice(breakIndex); + } + } else { + let totalWidth = 0; + let letters = []; + let breakIndex = 0; + for (const l of word.letters) { + if (totalWidth + l.width >= width) { + parts.push({ ...word }); + parts[parts.length - 1].text = text.slice(0, breakIndex); + parts[parts.length - 1].width = totalWidth; + parts[parts.length - 1].letters = letters; + text = text.slice(breakIndex); + totalWidth = 0; + letters = []; + breakIndex = 0; + } else { + breakIndex += 1; + letters.push(l); + totalWidth += l.width; + } + } + if (totalWidth > 0) { + parts.push({ ...word }); + parts[parts.length - 1].text = text.slice(0, breakIndex); + parts[parts.length - 1].width = totalWidth; + parts[parts.length - 1].letters = letters; + } + } + return parts; + } + alignLine(parsed, initialX = 0) { + let prevWidth = 0; + let prevX = initialX; + for (const word of parsed) { + if (word.text == "\n") { + continue; + } + word.x = prevX + prevWidth; + prevX = word.x; + prevWidth = word.width; + } + } + } + class TextTexture extends Texture { + constructor(stage) { + super(stage); + this._precision = this.stage.getOption("precision"); + } + static renderer(stage, canvas, settings) { + if (this.advancedRenderer) { + return new TextTextureRendererAdvanced(stage, canvas, settings); + } else { + return new TextTextureRenderer(stage, canvas, settings); + } + } + get text() { + return this._text; + } + set text(v) { + if (this._text !== v) { + this._text = "" + v; + this._changed(); + } + } + get w() { + return this._w; + } + set w(v) { + if (this._w !== v) { + this._w = v; + this._changed(); + } + } + get h() { + return this._h; + } + set h(v) { + if (this._h !== v) { + this._h = v; + this._changed(); + } + } + get fontStyle() { + return this._fontStyle; + } + set fontStyle(v) { + if (this._fontStyle !== v) { + this._fontStyle = v; + this._changed(); + } + } + get fontBaselineRatio() { + return this._fontBaselineRatio; + } + set fontBaselineRatio(v) { + if (this._fontBaselineRatio !== v) { + this._fontBaselineRatio = v; + this._changed(); + } + } + get fontSize() { + return this._fontSize; + } + set fontSize(v) { + if (this._fontSize !== v) { + this._fontSize = v; + this._changed(); + } + } + get fontFace() { + return this._fontFace; + } + set fontFace(v) { + if (this._fontFace !== v) { + this._fontFace = v; + this._changed(); + } + } + get wordWrap() { + return this._wordWrap; + } + set wordWrap(v) { + if (this._wordWrap !== v) { + this._wordWrap = v; + this._changed(); + } + } + get wordWrapWidth() { + return this._wordWrapWidth; + } + set wordWrapWidth(v) { + if (this._wordWrapWidth !== v) { + this._wordWrapWidth = v; + this._changed(); + } + } + get wordBreak() { + return this._wordBreak; + } + set wordBreak(v) { + if (this._wordBreak !== v) { + this._wordBreak = v; + this._changed(); + } + } + get textOverflow() { + return this._textOverflow; + } + set textOverflow(v) { + if (v != this._textOverflow) { + this._textOverflow = v; + this._changed(); + } + } + get lineHeight() { + return this._lineHeight; + } + set lineHeight(v) { + if (this._lineHeight !== v) { + this._lineHeight = v; + this._changed(); + } + } + get textBaseline() { + return this._textBaseline; + } + set textBaseline(v) { + if (this._textBaseline !== v) { + this._textBaseline = v; + this._changed(); + } + } + get textAlign() { + return this._textAlign; + } + set textAlign(v) { + if (this._textAlign !== v) { + this._textAlign = v; + this._changed(); + } + } + get verticalAlign() { + return this._verticalAlign; + } + set verticalAlign(v) { + if (this._verticalAlign !== v) { + this._verticalAlign = v; + this._changed(); + } + } + get offsetY() { + return this._offsetY; + } + set offsetY(v) { + if (this._offsetY !== v) { + this._offsetY = v; + this._changed(); + } + } + get maxLines() { + return this._maxLines; + } + set maxLines(v) { + if (this._maxLines !== v) { + this._maxLines = v; + this._changed(); + } + } + get maxLinesSuffix() { + return this._maxLinesSuffix; + } + set maxLinesSuffix(v) { + if (this._maxLinesSuffix !== v) { + this._maxLinesSuffix = v; + this._changed(); + } + } + get textColor() { + return this._textColor; + } + set textColor(v) { + if (this._textColor !== v) { + this._textColor = v; + this._changed(); + } + } + get paddingLeft() { + return this._paddingLeft; + } + set paddingLeft(v) { + if (this._paddingLeft !== v) { + this._paddingLeft = v; + this._changed(); + } + } + get paddingRight() { + return this._paddingRight; + } + set paddingRight(v) { + if (this._paddingRight !== v) { + this._paddingRight = v; + this._changed(); + } + } + get shadow() { + return this._shadow; + } + set shadow(v) { + if (this._shadow !== v) { + this._shadow = v; + this._changed(); + } + } + get shadowColor() { + return this._shadowColor; + } + set shadowColor(v) { + if (this._shadowColor !== v) { + this._shadowColor = v; + this._changed(); + } + } + get shadowOffsetX() { + return this._shadowOffsetX; + } + set shadowOffsetX(v) { + if (this._shadowOffsetX !== v) { + this._shadowOffsetX = v; + this._changed(); + } + } + get shadowOffsetY() { + return this._shadowOffsetY; + } + set shadowOffsetY(v) { + if (this._shadowOffsetY !== v) { + this._shadowOffsetY = v; + this._changed(); + } + } + get shadowBlur() { + return this._shadowBlur; + } + set shadowBlur(v) { + if (this._shadowBlur !== v) { + this._shadowBlur = v; + this._changed(); + } + } + get highlight() { + return this._highlight; + } + set highlight(v) { + if (this._highlight !== v) { + this._highlight = v; + this._changed(); + } + } + get highlightHeight() { + return this._highlightHeight; + } + set highlightHeight(v) { + if (this._highlightHeight !== v) { + this._highlightHeight = v; + this._changed(); + } + } + get highlightColor() { + return this._highlightColor; + } + set highlightColor(v) { + if (this._highlightColor !== v) { + this._highlightColor = v; + this._changed(); + } + } + get highlightOffset() { + return this._highlightOffset; + } + set highlightOffset(v) { + if (this._highlightOffset !== v) { + this._highlightOffset = v; + this._changed(); + } + } + get highlightPaddingLeft() { + return this._highlightPaddingLeft; + } + set highlightPaddingLeft(v) { + if (this._highlightPaddingLeft !== v) { + this._highlightPaddingLeft = v; + this._changed(); + } + } + get highlightPaddingRight() { + return this._highlightPaddingRight; + } + set highlightPaddingRight(v) { + if (this._highlightPaddingRight !== v) { + this._highlightPaddingRight = v; + this._changed(); + } + } + get cutSx() { + return this._cutSx; + } + set cutSx(v) { + if (this._cutSx !== v) { + this._cutSx = v; + this._changed(); + } + } + get cutEx() { + return this._cutEx; + } + set cutEx(v) { + if (this._cutEx !== v) { + this._cutEx = v; + this._changed(); + } + } + get cutSy() { + return this._cutSy; + } + set cutSy(v) { + if (this._cutSy !== v) { + this._cutSy = v; + this._changed(); + } + } + get cutEy() { + return this._cutEy; + } + set cutEy(v) { + if (this._cutEy !== v) { + this._cutEy = v; + this._changed(); + } + } + get advancedRenderer() { + return this._advancedRenderer; + } + set advancedRenderer(v) { + if (this._advancedRenderer !== v) { + this._advancedRenderer = v; + this._changed(); + } + } + set letterSpacing(v) { + if (this._letterSpacing !== v) { + this._letterSpacing = v; + this._changed(); + } + } + get letterSpacing() { + return this._letterSpacing; + } + set textIndent(v) { + if (this._textIndent !== v) { + this._textIndent = v; + this._changed(); + } + } + get textIndent() { + return this._textIndent; + } + get precision() { + return super.precision; + } + set precision(v) { + if (this.precision !== v) { + super.precision = v; + this._changed(); + } + } + _getIsValid() { + return !!this.text; + } + _getLookupId() { + let parts = []; + if (this.w !== 0) + parts.push("w " + this.w); + if (this.h !== 0) + parts.push("h " + this.h); + if (this.fontStyle !== "normal") + parts.push("fS" + this.fontStyle); + if (this.fontSize !== 40) + parts.push("fs" + this.fontSize); + if (this.fontBaselineRatio !== 0) + parts.push("fb" + this.fontBaselineRatio); + if (this.fontFace !== null) + parts.push("ff" + (Array.isArray(this.fontFace) ? this.fontFace.join(",") : this.fontFace)); + if (this.wordWrap !== true) + parts.push("wr" + (this.wordWrap ? 1 : 0)); + if (this.wordWrapWidth !== 0) + parts.push("ww" + this.wordWrapWidth); + if (this.wordBreak !== false) + parts.push( true ? 1 : undefined); + if (this.textOverflow != "") + parts.push("to" + this.textOverflow); + if (this.lineHeight !== null) + parts.push("lh" + this.lineHeight); + if (this.textBaseline !== "alphabetic") + parts.push("tb" + this.textBaseline); + if (this.textAlign !== "left") + parts.push("ta" + this.textAlign); + if (this.verticalAlign !== "top") + parts.push("va" + this.verticalAlign); + if (this.offsetY !== null) + parts.push("oy" + this.offsetY); + if (this.maxLines !== 0) + parts.push("ml" + this.maxLines); + if (this.maxLinesSuffix !== "..") + parts.push("ms" + this.maxLinesSuffix); + parts.push("pc" + this.precision); + if (this.textColor !== 4294967295) + parts.push("co" + this.textColor.toString(16)); + if (this.paddingLeft !== 0) + parts.push("pl" + this.paddingLeft); + if (this.paddingRight !== 0) + parts.push("pr" + this.paddingRight); + if (this.shadow !== false) + parts.push("sh" + (this.shadow ? 1 : 0)); + if (this.shadowColor !== 4278190080) + parts.push("sc" + this.shadowColor.toString(16)); + if (this.shadowOffsetX !== 0) + parts.push("sx" + this.shadowOffsetX); + if (this.shadowOffsetY !== 0) + parts.push("sy" + this.shadowOffsetY); + if (this.shadowBlur !== 5) + parts.push("sb" + this.shadowBlur); + if (this.highlight !== false) + parts.push("hL" + (this.highlight ? 1 : 0)); + if (this.highlightHeight !== 0) + parts.push("hh" + this.highlightHeight); + if (this.highlightColor !== 4278190080) + parts.push("hc" + this.highlightColor.toString(16)); + if (this.highlightOffset !== null) + parts.push("ho" + this.highlightOffset); + if (this.highlightPaddingLeft !== null) + parts.push("hl" + this.highlightPaddingLeft); + if (this.highlightPaddingRight !== null) + parts.push("hr" + this.highlightPaddingRight); + if (this.letterSpacing !== null) + parts.push("ls" + this.letterSpacing); + if (this.textIndent !== null) + parts.push("ti" + this.textIndent); + if (this.cutSx) + parts.push("csx" + this.cutSx); + if (this.cutEx) + parts.push("cex" + this.cutEx); + if (this.cutSy) + parts.push("csy" + this.cutSy); + if (this.cutEy) + parts.push("cey" + this.cutEy); + if (this.advancedRenderer) + parts.push( true ? 1 : undefined); + let id = "TX$" + parts.join("|") + ":" + this.text; + return id; + } + _getSourceLoader() { + const args = this.cloneArgs(); + const gl = this.stage.gl; + return function(cb) { + const canvas = this.stage.platform.getDrawingCanvas(); + const renderer = args.advancedRenderer ? new TextTextureRendererAdvanced(this.stage, canvas, args) : new TextTextureRenderer(this.stage, canvas, args); + const p = renderer.draw(); + const texParams = {}; + const sharpCfg = this.stage.getOption("fontSharp"); + let sharpen = false; + if (Utils$1.isBoolean(sharpCfg)) { + sharpen = sharpCfg; + } else if (Utils$1.isObject(sharpCfg)) { + const precision = this.stage.getRenderPrecision(); + sharpen = precision <= sharpCfg.precision && args.fontSize <= sharpCfg.fontSize; + } + if (gl && sharpen) { + texParams[gl.TEXTURE_MAG_FILTER] = gl.NEAREST; + } + if (p) { + p.then(() => { + cb(null, Object.assign({ + renderInfo: renderer.renderInfo, + throttle: false, + texParams + }, this.stage.platform.getTextureOptionsForDrawingCanvas(canvas))); + }).catch((err) => { + cb(err); + }); + } else { + cb(null, Object.assign({ + renderInfo: renderer.renderInfo, + throttle: false, + texParams + }, this.stage.platform.getTextureOptionsForDrawingCanvas(canvas))); + } + }; + } + getNonDefaults() { + const nonDefaults = super.getNonDefaults(); + if (this.text !== "") + nonDefaults["text"] = this.text; + if (this.w !== 0) + nonDefaults["w"] = this.w; + if (this.h !== 0) + nonDefaults["h"] = this.h; + if (this.fontStyle !== "normal") + nonDefaults["fontStyle"] = this.fontStyle; + if (this.fontSize !== 40) + nonDefaults["fontSize"] = this.fontSize; + if (this.fontBaselineRatio !== 0) + nonDefaults["fontBaselineRatio"] = this.fontBaselineRatio; + if (this.fontFace !== null) + nonDefaults["fontFace"] = this.fontFace; + if (this.wordWrap !== true) + nonDefaults["wordWrap"] = this.wordWrap; + if (this.wordWrapWidth !== 0) + nonDefaults["wordWrapWidth"] = this.wordWrapWidth; + if (this.wordBreak !== false) + nonDefaults["wordBreak"] = this.wordBreak; + if (this.textOverflow != "") + nonDefaults["textOverflow"] = this.textOverflow; + if (this.lineHeight !== null) + nonDefaults["lineHeight"] = this.lineHeight; + if (this.textBaseline !== "alphabetic") + nonDefaults["textBaseline"] = this.textBaseline; + if (this.textAlign !== "left") + nonDefaults["textAlign"] = this.textAlign; + if (this.verticalAlign !== "top") + nonDefaults["verticalAlign"] = this.verticalAlign; + if (this.offsetY !== null) + nonDefaults["offsetY"] = this.offsetY; + if (this.maxLines !== 0) + nonDefaults["maxLines"] = this.maxLines; + if (this.maxLinesSuffix !== "..") + nonDefaults["maxLinesSuffix"] = this.maxLinesSuffix; + if (this.precision !== this.stage.getOption("precision")) + nonDefaults["precision"] = this.precision; + if (this.textColor !== 4294967295) + nonDefaults["textColor"] = this.textColor; + if (this.paddingLeft !== 0) + nonDefaults["paddingLeft"] = this.paddingLeft; + if (this.paddingRight !== 0) + nonDefaults["paddingRight"] = this.paddingRight; + if (this.shadow !== false) + nonDefaults["shadow"] = this.shadow; + if (this.shadowColor !== 4278190080) + nonDefaults["shadowColor"] = this.shadowColor; + if (this.shadowOffsetX !== 0) + nonDefaults["shadowOffsetX"] = this.shadowOffsetX; + if (this.shadowOffsetY !== 0) + nonDefaults["shadowOffsetY"] = this.shadowOffsetY; + if (this.shadowBlur !== 5) + nonDefaults["shadowBlur"] = this.shadowBlur; + if (this.highlight !== false) + nonDefaults["highlight"] = this.highlight; + if (this.highlightHeight !== 0) + nonDefaults["highlightHeight"] = this.highlightHeight; + if (this.highlightColor !== 4278190080) + nonDefaults["highlightColor"] = this.highlightColor; + if (this.highlightOffset !== 0) + nonDefaults["highlightOffset"] = this.highlightOffset; + if (this.highlightPaddingLeft !== 0) + nonDefaults["highlightPaddingLeft"] = this.highlightPaddingLeft; + if (this.highlightPaddingRight !== 0) + nonDefaults["highlightPaddingRight"] = this.highlightPaddingRight; + if (this.letterSpacing !== 0) + nonDefaults["letterSpacing"] = this.letterSpacing; + if (this.textIndent !== 0) + nonDefaults["textIndent"] = this.textIndent; + if (this.cutSx) + nonDefaults["cutSx"] = this.cutSx; + if (this.cutEx) + nonDefaults["cutEx"] = this.cutEx; + if (this.cutSy) + nonDefaults["cutSy"] = this.cutSy; + if (this.cutEy) + nonDefaults["cutEy"] = this.cutEy; + if (this.advancedRenderer) + nonDefaults["renderer"] = this.advancedRenderer; + return nonDefaults; + } + cloneArgs() { + let obj = {}; + obj.text = this._text; + obj.w = this._w; + obj.h = this._h; + obj.fontStyle = this._fontStyle; + obj.fontSize = this._fontSize; + obj.fontBaselineRatio = this._fontBaselineRatio; + obj.fontFace = this._fontFace; + obj.wordWrap = this._wordWrap; + obj.wordWrapWidth = this._wordWrapWidth; + obj.wordBreak = this._wordBreak; + obj.textOverflow = this._textOverflow; + obj.lineHeight = this._lineHeight; + obj.textBaseline = this._textBaseline; + obj.textAlign = this._textAlign; + obj.verticalAlign = this._verticalAlign; + obj.offsetY = this._offsetY; + obj.maxLines = this._maxLines; + obj.maxLinesSuffix = this._maxLinesSuffix; + obj.precision = this._precision; + obj.textColor = this._textColor; + obj.paddingLeft = this._paddingLeft; + obj.paddingRight = this._paddingRight; + obj.shadow = this._shadow; + obj.shadowColor = this._shadowColor; + obj.shadowOffsetX = this._shadowOffsetX; + obj.shadowOffsetY = this._shadowOffsetY; + obj.shadowBlur = this._shadowBlur; + obj.highlight = this._highlight; + obj.highlightHeight = this._highlightHeight; + obj.highlightColor = this._highlightColor; + obj.highlightOffset = this._highlightOffset; + obj.highlightPaddingLeft = this._highlightPaddingLeft; + obj.highlightPaddingRight = this._highlightPaddingRight; + obj.letterSpacing = this._letterSpacing; + obj.textIndent = this._textIndent; + obj.cutSx = this._cutSx; + obj.cutEx = this._cutEx; + obj.cutSy = this._cutSy; + obj.cutEy = this._cutEy; + obj.advancedRenderer = this._advancedRenderer; + return obj; + } + } + let proto = TextTexture.prototype; + proto._text = ""; + proto._w = 0; + proto._h = 0; + proto._fontStyle = "normal"; + proto._fontSize = 40; + proto._fontFace = null; + proto._wordWrap = true; + proto._wordWrapWidth = 0; + proto._wordBreak = false; + proto._textOverflow = ""; + proto._lineHeight = null; + proto._textBaseline = "alphabetic"; + proto._textAlign = "left"; + proto._verticalAlign = "top"; + proto._offsetY = null; + proto._maxLines = 0; + proto._maxLinesSuffix = ".."; + proto._textColor = 4294967295; + proto._paddingLeft = 0; + proto._paddingRight = 0; + proto._shadow = false; + proto._shadowColor = 4278190080; + proto._shadowOffsetX = 0; + proto._shadowOffsetY = 0; + proto._shadowBlur = 5; + proto._highlight = false; + proto._highlightHeight = 0; + proto._highlightColor = 4278190080; + proto._highlightOffset = 0; + proto._highlightPaddingLeft = 0; + proto._highlightPaddingRight = 0; + proto._letterSpacing = 0; + proto._textIndent = 0; + proto._cutSx = 0; + proto._cutEx = 0; + proto._cutSy = 0; + proto._cutEy = 0; + proto._advancedRenderer = false; + proto._fontBaselineRatio = 0; + class SourceTexture extends Texture { + constructor(stage) { + super(stage); + this._textureSource = void 0; + } + get textureSource() { + return this._textureSource; + } + set textureSource(v) { + if (v !== this._textureSource) { + if (v.isResultTexture) { + this._precision = this.stage.getRenderPrecision(); + } + this._textureSource = v; + this._changed(); + } + } + _getTextureSource() { + return this._textureSource; + } + } + class Transition extends EventEmitter { + constructor(manager, settings, element, property) { + super(); + this.manager = manager; + this._settings = settings; + this._element = element; + this._getter = element.constructor.getGetter(property); + this._setter = element.constructor.getSetter(property); + this._merger = settings.merger; + if (!this._merger) { + this._merger = element.constructor.getMerger(property); + } + this._startValue = this._getter(this._element); + this._targetValue = this._startValue; + this._p = 1; + this._delayLeft = 0; + } + start(targetValue) { + this._startValue = this._getter(this._element); + if (!this.isAttached()) { + this._targetValue = targetValue; + this._p = 1; + this._updateDrawValue(); + } else { + if (targetValue === this._startValue) { + this.reset(targetValue, 1); + } else { + this._targetValue = targetValue; + this._p = 0; + this._delayLeft = this._settings.delay; + this.emit("start"); + this.add(); + } + } + } + finish() { + if (this._p < 1) { + this._p = 1; + } + } + stop() { + this.emit("stop"); + this.manager.removeActive(this); + } + pause() { + this.stop(); + } + play() { + this.manager.addActive(this); + } + reset(targetValue, p) { + if (!this.isAttached()) { + this._startValue = this._getter(this._element); + this._targetValue = targetValue; + this._p = 1; + this._updateDrawValue(); + } else { + this._startValue = this._getter(this._element); + this._targetValue = targetValue; + this._p = p; + this.add(); + } + } + _updateDrawValue() { + this._setter(this._element, this.getDrawValue()); + } + add() { + this.manager.addActive(this); + } + isAttached() { + return this._element.attached; + } + isRunning() { + return this._p < 1; + } + progress(dt) { + if (!this.isAttached()) { + this._p = 1; + } + if (this.p < 1) { + if (this.delayLeft > 0) { + this._delayLeft -= dt; + if (this.delayLeft < 0) { + dt = -this.delayLeft; + this._delayLeft = 0; + this.emit("delayEnd"); + } else { + return; + } + } + if (this._settings.duration == 0) { + this._p = 1; + } else { + this._p += dt / this._settings.duration; + } + if (this._p >= 1) { + this._p = 1; + } + } + this._updateDrawValue(); + this.invokeListeners(); + } + invokeListeners() { + this.emit("progress", this.p); + if (this.p === 1) { + this.emit("finish"); + } + } + updateTargetValue(targetValue) { + let t = this._settings.timingFunctionImpl(this.p); + if (t === 1) { + this._targetValue = targetValue; + } else if (t === 0) { + this._startValue = this._targetValue; + this._targetValue = targetValue; + } else { + this._startValue = targetValue - (targetValue - this._targetValue) / (1 - t); + this._targetValue = targetValue; + } + } + getDrawValue() { + if (this.p >= 1) { + return this.targetValue; + } else { + let v = this._settings._timingFunctionImpl(this.p); + return this._merger(this.targetValue, this.startValue, v); + } + } + skipDelay() { + this._delayLeft = 0; + } + get startValue() { + return this._startValue; + } + get targetValue() { + return this._targetValue; + } + get p() { + return this._p; + } + get delayLeft() { + return this._delayLeft; + } + get element() { + return this._element; + } + get settings() { + return this._settings; + } + set settings(v) { + this._settings = v; + } + } + Transition.prototype.isTransition = true; + class ObjectList { + constructor() { + this._items = []; + this._refs = {}; + } + get() { + return this._items; + } + get first() { + return this._items[0]; + } + get last() { + return this._items.length ? this._items[this._items.length - 1] : void 0; + } + add(item) { + this.addAt(item, this._items.length); + } + addAt(item, index) { + if (index >= 0 && index <= this._items.length) { + let currentIndex = this._items.indexOf(item); + if (currentIndex === index) { + return item; + } + if (Utils$1.isObjectLiteral(item)) { + const o = item; + item = this.createItem(o); + item.patch(o); + } + if (currentIndex != -1) { + this.setAt(item, index); + } else { + if (item.ref) { + this._refs[item.ref] = item; + } + this._items.splice(index, 0, item); + this.onAdd(item, index); + } + } else { + throw new Error("addAt: The index " + index + " is out of bounds " + this._items.length); + } + } + replaceByRef(item) { + if (item.ref) { + const existingItem = this.getByRef(item.ref); + if (!existingItem) { + throw new Error("replaceByRef: no item found with reference: " + item.ref); + } + this.replace(item, existingItem); + } else { + throw new Error("replaceByRef: no ref specified in item"); + } + this.addAt(item, this._items.length); + } + replace(item, prevItem) { + const index = this.getIndex(prevItem); + if (index === -1) { + throw new Error("replace: The previous item does not exist"); + } + this.setAt(item, index); + } + setAt(item, index) { + if (index >= 0 && index < this._items.length) { + if (Utils$1.isObjectLiteral(item)) { + const o = item; + item = this.createItem(o); + item.patch(o); + } + let currentIndex = this._items.indexOf(item); + if (currentIndex != -1) { + if (currentIndex !== index) { + const fromIndex = currentIndex; + if (fromIndex !== index) { + this._items.splice(fromIndex, 1); + this._items.splice(index, 0, item); + this.onMove(item, fromIndex, index); + } + } + } else { + if (index < this._items.length) { + if (this._items[index].ref) { + this._refs[this._items[index].ref] = void 0; + } + } + const prevItem = this._items[index]; + this._items[index] = item; + if (item.ref) { + this._refs[item.ref] = item; + } + this.onSet(item, index, prevItem); + } + } else { + throw new Error("setAt: The index " + index + " is out of bounds " + this._items.length); + } + } + getAt(index) { + return this._items[index]; + } + getIndex(item) { + return this._items.indexOf(item); + } + remove(item) { + let index = this._items.indexOf(item); + if (index !== -1) { + this.removeAt(index); + } + } + removeAt(index) { + if (index >= 0 && index < this._items.length) { + const item = this._items[index]; + if (item.ref) { + this._refs[item.ref] = void 0; + } + this._items.splice(index, 1); + this.onRemove(item, index); + return item; + } else { + throw new Error(`removeAt: The index ${index} is out of bounds ${this._items.length - 1}`); + } + } + clear() { + let n = this._items.length; + if (n) { + let prev = this._items; + this._items = []; + this._refs = {}; + this.onSync(prev, [], []); + } + } + a(o) { + if (Utils$1.isObjectLiteral(o)) { + let c = this.createItem(o); + c.patch(o); + this.add(c); + return c; + } else if (Array.isArray(o)) { + for (let i = 0, n = o.length; i < n; i++) { + this.a(o[i]); + } + return null; + } else if (this.isItem(o)) { + this.add(o); + return o; + } + } + get length() { + return this._items.length; + } + _getRefs() { + return this._refs; + } + getByRef(ref) { + return this._refs[ref]; + } + clearRef(ref) { + delete this._refs[ref]; + } + setRef(ref, child) { + this._refs[ref] = child; + } + patch(settings) { + if (Utils$1.isObjectLiteral(settings)) { + this._setByObject(settings); + } else if (Array.isArray(settings)) { + this._setByArray(settings); + } + } + _setByObject(settings) { + let refs = this._getRefs(); + let crefs = Object.keys(settings); + for (let i = 0, n = crefs.length; i < n; i++) { + let cref = crefs[i]; + let s = settings[cref]; + let c = refs[cref]; + if (!c) { + if (this.isItem(s)) { + s.ref = cref; + this.add(s); + } else { + c = this.createItem(s); + c.ref = cref; + c.patch(s); + this.add(c); + } + } else { + if (this.isItem(s)) { + if (c !== s) { + let idx = this.getIndex(c); + s.ref = cref; + this.setAt(s, idx); + } + } else { + c.patch(s); + } + } + } + } + _equalsArray(array) { + let same = true; + if (array.length === this._items.length) { + for (let i = 0, n = this._items.length; i < n && same; i++) { + same = same && this._items[i] === array[i]; + } + } else { + same = false; + } + return same; + } + _setByArray(array) { + if (this._equalsArray(array)) { + return; + } + for (let i = 0, n = this._items.length; i < n; i++) { + this._items[i].marker = true; + } + let refs; + let newItems = []; + for (let i = 0, n = array.length; i < n; i++) { + let s = array[i]; + if (this.isItem(s)) { + s.marker = false; + newItems.push(s); + } else { + let cref = s.ref; + let c; + if (cref) { + if (!refs) + refs = this._getRefs(); + c = refs[cref]; + } + if (!c) { + c = this.createItem(s); + } else { + c.marker = false; + } + if (Utils$1.isObjectLiteral(s)) { + c.patch(s); + } + newItems.push(c); + } + } + this._setItems(newItems); + } + _setItems(newItems) { + let prevItems = this._items; + this._items = newItems; + let removed = prevItems.filter((item) => { + let m = item.marker; + delete item.marker; + return m; + }); + let added = newItems.filter((item) => prevItems.indexOf(item) === -1); + if (removed.length || added.length) { + this._refs = {}; + for (let i = 0, n = this._items.length; i < n; i++) { + let ref = this._items[i].ref; + if (ref) { + this._refs[ref] = this._items[i]; + } + } + } + this.onSync(removed, added, newItems); + } + sort(f) { + const items = this._items.slice(); + items.sort(f); + this._setByArray(items); + } + onAdd(item, index) { + } + onRemove(item, index) { + } + onSync(removed, added, order) { + } + onSet(item, index, prevItem) { + } + onMove(item, fromIndex, toIndex) { + } + createItem(object) { + throw new Error("ObjectList.createItem must create and return a new object"); + } + isItem(object) { + return false; + } + forEach(f) { + this.get().forEach(f); + } + } + class ElementChildList extends ObjectList { + constructor(element) { + super(); + this._element = element; + } + _connectParent(item) { + const prevParent = item.parent; + if (prevParent && prevParent !== this._element) { + const prevChildList = item.parent.childList; + const index = prevChildList.getIndex(item); + if (item.ref) { + prevChildList._refs[item.ref] = void 0; + } + prevChildList._items.splice(index, 1); + prevParent.core.removeChildAt(index); + } + item._setParent(this._element); + } + onAdd(item, index) { + this._connectParent(item); + this._element.core.addChildAt(index, item.core); + } + onRemove(item, index) { + item._setParent(null); + this._element.core.removeChildAt(index); + } + onSync(removed, added, order) { + for (let i = 0, n = removed.length; i < n; i++) { + removed[i]._setParent(null); + } + for (let i = 0, n = added.length; i < n; i++) { + this._connectParent(added[i]); + } + let gc = (i) => i.core; + this._element.core.syncChildren(removed.map(gc), added.map(gc), order.map(gc)); + } + onSet(item, index, prevItem) { + prevItem._setParent(null); + this._connectParent(item); + this._element.core.setChildAt(index, item.core); + } + onMove(item, fromIndex, toIndex) { + this._element.core.moveChild(fromIndex, toIndex); + } + createItem(object) { + if (object.type) { + return new object.type(this._element.stage); + } else { + return this._element.stage.createElement(); + } + } + isItem(object) { + return object.isElement; + } + } + class Element { + constructor(stage) { + this.stage = stage; + this.__id = Element.id++; + this.__start(); + this._hasEventListeners = false; + this.__core = new ElementCore(this); + this.__ref = null; + this.__attached = false; + this.__enabled = false; + this.__active = false; + this.__parent = null; + this.__texture = null; + this.__displayedTexture = null; + this.__tags = null; + this.__treeTags = null; + this.__tagRoot = false; + this.__childList = null; + this._w = 0; + this._h = 0; + } + __start() { + } + get id() { + return this.__id; + } + set ref(ref) { + if (this.__ref !== ref) { + const charcode = ref.charCodeAt(0); + if (!Utils$1.isUcChar(charcode)) { + this._throwError("Ref must start with an upper case character: " + ref); + } + if (this.__ref !== null) { + this.removeTag(this.__ref); + if (this.__parent) { + this.__parent.__childList.clearRef(this.__ref); + } + } + this.__ref = ref; + if (this.__ref) { + this._addTag(this.__ref); + if (this.__parent) { + this.__parent.__childList.setRef(this.__ref, this); + } + } + } + } + get ref() { + return this.__ref; + } + get core() { + return this.__core; + } + setAsRoot() { + this.__core.setAsRoot(); + this._updateAttachedFlag(); + this._updateEnabledFlag(); + } + get isRoot() { + return this.__core.isRoot; + } + _setParent(parent) { + if (this.__parent === parent) + return; + if (this.__parent) { + this._unsetTagsParent(); + } + this.__parent = parent; + if (parent) { + this._setTagsParent(); + } + this._updateAttachedFlag(); + this._updateEnabledFlag(); + this._updateCollision(); + if (this.isRoot && parent) { + this._throwError("Root should not be added as a child! Results are unspecified!"); + } + } + getDepth() { + let depth = 0; + let p = this.__parent; + while (p) { + depth++; + p = p.__parent; + } + return depth; + } + getAncestor(l) { + let p = this; + while (l > 0 && p.__parent) { + p = p.__parent; + l--; + } + return p; + } + getAncestors() { + const a = []; + let p = this; + while (p) { + a.push(p); + p = p.__parent; + } + return a; + } + getAncestorAtDepth(depth) { + let levels = this.getDepth() - depth; + if (levels < 0) { + return null; + } + return this.getAncestor(levels); + } + isAncestorOf(c) { + let p = c; + while (p = p.parent) { + if (this === p) { + return true; + } + } + return false; + } + getSharedAncestor(c) { + let o1 = this; + let o2 = c; + let l1 = o1.getDepth(); + let l2 = o2.getDepth(); + if (l1 > l2) { + o1 = o1.getAncestor(l1 - l2); + } else if (l2 > l1) { + o2 = o2.getAncestor(l2 - l1); + } + do { + if (o1 === o2) { + return o1; + } + o1 = o1.__parent; + o2 = o2.__parent; + } while (o1 && o2); + return null; + } + get attached() { + return this.__attached; + } + get enabled() { + return this.__enabled; + } + get active() { + return this.__active; + } + _isAttached() { + return this.__parent ? this.__parent.__attached : this.stage.root === this; + } + _isEnabled() { + return this.__core.visible && this.__core.alpha > 0 && (this.__parent ? this.__parent.__enabled : this.stage.root === this); + } + _isActive() { + return this._isEnabled() && this.withinBoundsMargin; + } + _updateAttachedFlag() { + let newAttached = this._isAttached(); + if (this.__attached !== newAttached) { + this.__attached = newAttached; + if (newAttached) { + this._onSetup(); + } + let children = this._children.get(); + if (children) { + let m = children.length; + if (m > 0) { + for (let i = 0; i < m; i++) { + children[i]._updateAttachedFlag(); + } + } + } + if (newAttached) { + this._onAttach(); + } else { + this._onDetach(); + } + } + } + _updateEnabledFlag() { + let newEnabled = this._isEnabled(); + if (this.__enabled !== newEnabled) { + if (newEnabled) { + this._onEnabled(); + this._setEnabledFlag(); + } else { + this._onDisabled(); + this._unsetEnabledFlag(); + } + let children = this._children.get(); + if (children) { + let m = children.length; + if (m > 0) { + for (let i = 0; i < m; i++) { + children[i]._updateEnabledFlag(); + } + } + } + } + } + _setEnabledFlag() { + this.__enabled = true; + this._updateDimensions(); + this._updateTextureCoords(); + if (this.__texture) { + this.__texture.addElement(this); + } + if (this.withinBoundsMargin) { + this._setActiveFlag(); + } + if (this.__core.shader) { + this.__core.shader.addElement(this.__core); + } + } + _unsetEnabledFlag() { + if (this.__active) { + this._unsetActiveFlag(); + } + if (this.__texture) { + this.__texture.removeElement(this); + } + if (this.__core.shader) { + this.__core.shader.removeElement(this.__core); + } + if (this._texturizer) { + this.texturizer.filters.forEach((filter) => filter.removeElement(this.__core)); + } + this.__enabled = false; + } + _setActiveFlag() { + this.__active = true; + if (this.__texture) { + this.__texture.incActiveCount(); + } + if (this.__texture) { + this._enableTexture(); + } + this._onActive(); + } + _unsetActiveFlag() { + if (this.__texture) { + this.__texture.decActiveCount(); + } + this.__active = false; + if (this.__texture) { + this._disableTexture(); + } + if (this._hasTexturizer()) { + this.texturizer.deactivate(); + } + this._onInactive(); + } + _onSetup() { + } + _onAttach() { + } + _onDetach() { + } + _onEnabled() { + } + _onDisabled() { + } + _onActive() { + } + _onInactive() { + } + _onResize() { + } + _getRenderWidth() { + if (this._w) { + return this._w; + } else if (this.__displayedTexture) { + return this.__displayedTexture.getRenderWidth(); + } else if (this.__texture) { + return this.__texture.getRenderWidth(); + } else { + return 0; + } + } + _getRenderHeight() { + if (this._h) { + return this._h; + } else if (this.__displayedTexture) { + return this.__displayedTexture.getRenderHeight(); + } else if (this.__texture) { + return this.__texture.getRenderHeight(); + } else { + return 0; + } + } + get renderWidth() { + if (this.__enabled) { + return this.__core.getRenderWidth(); + } else { + return this._getRenderWidth(); + } + } + get renderHeight() { + if (this.__enabled) { + return this.__core.getRenderHeight(); + } else { + return this._getRenderHeight(); + } + } + get finalX() { + return this.__core.x; + } + get finalY() { + return this.__core.y; + } + get finalW() { + return this.__core.w; + } + get finalH() { + return this.__core.h; + } + textureIsLoaded() { + return this.__texture && this.__texture.isLoaded(); + } + loadTexture() { + if (this.__texture) { + this.__texture.load(); + if (!this.__texture.isUsed() || !this._isEnabled()) { + this._updateDimensions(); + } + } + } + _enableTextureError() { + const loadError = this.__texture.loadError; + if (loadError) { + this.emit("txError", loadError, this.__texture._source); + } + } + _enableTexture() { + if (this.__texture.isLoaded()) { + this._setDisplayedTexture(this.__texture); + } else { + this._setDisplayedTexture(null); + this._enableTextureError(); + } + } + _disableTexture() { + this._setDisplayedTexture(null); + } + get texture() { + return this.__texture; + } + set texture(v) { + let texture; + if (Utils$1.isObjectLiteral(v)) { + if (v.type) { + texture = new v.type(this.stage); + } else { + texture = this.texture; + } + if (texture) { + Base.patchObject(texture, v); + } + } else if (!v) { + texture = null; + } else { + if (v.isTexture) { + texture = v; + } else if (v.isTextureSource) { + texture = new SourceTexture(this.stage); + texture.textureSource = v; + } else { + console.error("[Lightning] Please specify a texture type."); + return; + } + } + const prevTexture = this.__texture; + if (texture !== prevTexture) { + this.__texture = texture; + if (this.__texture) { + if (this.__enabled) { + this.__texture.addElement(this); + if (this.withinBoundsMargin) { + if (this.__texture.isLoaded()) { + this._setDisplayedTexture(this.__texture); + } else { + this._enableTextureError(); + } + } + } + } else { + this._setDisplayedTexture(null); + } + if (prevTexture && prevTexture !== this.__displayedTexture) { + prevTexture.removeElement(this); + } + this._updateDimensions(); + } + } + get displayedTexture() { + return this.__displayedTexture; + } + _setDisplayedTexture(v) { + let prevTexture = this.__displayedTexture; + if (prevTexture && v !== prevTexture) { + if (this.__texture !== prevTexture) { + prevTexture.removeElement(this); + } + } + const prevSource = this.__core.displayedTextureSource ? this.__core.displayedTextureSource._source : null; + const sourceChanged = (v ? v._source : null) !== prevSource; + this.__displayedTexture = v; + this._updateDimensions(); + if (this.__displayedTexture) { + if (sourceChanged) { + this._updateTextureCoords(); + this.__core.setDisplayedTextureSource(this.__displayedTexture._source); + } + } else { + this.__core.setDisplayedTextureSource(null); + } + if (sourceChanged) { + if (this.__displayedTexture) { + this.emit("txLoaded", this.__displayedTexture); + } else { + this.emit("txUnloaded", this.__displayedTexture); + } + } + } + onTextureSourceLoaded() { + if (this.active) { + this._setDisplayedTexture(this.__texture); + } + } + onTextureSourceLoadError(e) { + this.emit("txError", e, this.__texture._source); + } + forceRenderUpdate() { + this.__core.setHasRenderUpdates(3); + } + onDisplayedTextureClippingChanged() { + this._updateDimensions(); + this._updateTextureCoords(); + } + onPrecisionChanged() { + this._updateDimensions(); + } + onDimensionsChanged(w, h) { + if (this.texture instanceof TextTexture) { + this.texture.w = w; + this.texture.h = h; + this.w = w; + this.h = h; + } + } + _updateDimensions() { + let w = this._getRenderWidth(); + let h = this._getRenderHeight(); + let unknownSize = false; + if (!w || !h) { + if (!this.__displayedTexture && this.__texture) { + w = w || this.__texture.mw; + h = h || this.__texture.mh; + if ((!w || !h) && this.__texture.isAutosizeTexture()) { + unknownSize = true; + } + } + } + if (this.__core.setDimensions(w, h, unknownSize)) { + this._onResize(); + } + } + _updateTextureCoords() { + if (this.displayedTexture && this.displayedTexture._source) { + let displayedTexture = this.displayedTexture; + let displayedTextureSource = this.displayedTexture._source; + let tx1 = 0, ty1 = 0, tx2 = 1, ty2 = 1; + if (displayedTexture.clipping) { + let w = displayedTextureSource.getRenderWidth(); + let h = displayedTextureSource.getRenderHeight(); + let iw, ih, rw, rh; + iw = 1 / w; + ih = 1 / h; + if (displayedTexture.pw) { + rw = displayedTexture.pw * iw; + } else { + rw = (w - displayedTexture.px) * iw; + } + if (displayedTexture.ph) { + rh = displayedTexture.ph * ih; + } else { + rh = (h - displayedTexture.py) * ih; + } + iw *= displayedTexture.px; + ih *= displayedTexture.py; + tx1 = iw; + ty1 = ih; + tx2 = tx2 * rw + iw; + ty2 = ty2 * rh + ih; + tx1 = Math.max(0, tx1); + ty1 = Math.max(0, ty1); + tx2 = Math.min(1, tx2); + ty2 = Math.min(1, ty2); + } + if (displayedTextureSource._flipTextureY) { + let tempty = ty2; + ty2 = ty1; + ty1 = tempty; + } + this.__core.setTextureCoords(tx1, ty1, tx2, ty2); + } + } + getCornerPoints() { + return this.__core.getCornerPoints(); + } + _unsetTagsParent() { + if (this.__tags) { + this.__tags.forEach((tag) => { + let p = this; + while (p = p.__parent) { + let parentTreeTags = p.__treeTags.get(tag); + parentTreeTags.delete(this); + if (p.__tagRoot) { + break; + } + } + }); + } + let tags = null; + let n = 0; + if (this.__treeTags) { + if (!this.__tagRoot) { + tags = Utils$1.iteratorToArray(this.__treeTags.keys()); + n = tags.length; + if (n > 0) { + for (let i = 0; i < n; i++) { + let tagSet = this.__treeTags.get(tags[i]); + let p = this; + while (p = p.__parent) { + let parentTreeTags = p.__treeTags.get(tags[i]); + tagSet.forEach(function(comp) { + parentTreeTags.delete(comp); + }); + if (p.__tagRoot) { + break; + } + } + } + } + } + } + } + _setTagsParent() { + if (this.__tags) { + this.__tags.forEach((tag) => { + let p = this; + while (p = p.__parent) { + if (!p.__treeTags) { + p.__treeTags = /* @__PURE__ */ new Map(); + } + let s = p.__treeTags.get(tag); + if (!s) { + s = /* @__PURE__ */ new Set(); + p.__treeTags.set(tag, s); + } + s.add(this); + if (p.__tagRoot) { + break; + } + } + }); + } + if (this.__treeTags && this.__treeTags.size) { + if (!this.__tagRoot) { + this.__treeTags.forEach((tagSet, tag) => { + let p = this; + while (!p.__tagRoot && (p = p.__parent)) { + if (p.__tagRoot) + ; + if (!p.__treeTags) { + p.__treeTags = /* @__PURE__ */ new Map(); + } + let s = p.__treeTags.get(tag); + if (!s) { + s = /* @__PURE__ */ new Set(); + p.__treeTags.set(tag, s); + } + tagSet.forEach(function(comp) { + s.add(comp); + }); + } + }); + } + } + } + _getByTag(tag) { + if (!this.__treeTags) { + return []; + } + let t = this.__treeTags.get(tag); + return t ? Utils$1.setToArray(t) : []; + } + getTags() { + return this.__tags ? this.__tags : []; + } + setTags(tags) { + tags = tags.reduce((acc, tag) => { + return acc.concat(tag.split(" ")); + }, []); + if (this.__ref) { + tags.push(this.__ref); + } + let i, n = tags.length; + let removes = []; + let adds = []; + for (i = 0; i < n; i++) { + if (!this.hasTag(tags[i])) { + adds.push(tags[i]); + } + } + let currentTags = this.tags || []; + n = currentTags.length; + for (i = 0; i < n; i++) { + if (tags.indexOf(currentTags[i]) == -1) { + removes.push(currentTags[i]); + } + } + for (i = 0; i < removes.length; i++) { + this.removeTag(removes[i]); + } + for (i = 0; i < adds.length; i++) { + this.addTag(adds[i]); + } + } + addTag(tag) { + if (tag.indexOf(" ") === -1) { + if (Utils$1.isUcChar(tag.charCodeAt(0))) { + this._throwError("Tag may not start with an upper case character."); + } + this._addTag(tag); + } else { + const tags = tag.split(" "); + for (let i = 0, m = tags.length; i < m; i++) { + const tag2 = tags[i]; + if (Utils$1.isUcChar(tag2.charCodeAt(0))) { + this._throwError("Tag may not start with an upper case character."); + } + this._addTag(tag2); + } + } + } + _addTag(tag) { + if (!this.__tags) { + this.__tags = []; + } + if (this.__tags.indexOf(tag) === -1) { + this.__tags.push(tag); + let p = this.__parent; + if (p) { + do { + if (!p.__treeTags) { + p.__treeTags = /* @__PURE__ */ new Map(); + } + let s = p.__treeTags.get(tag); + if (!s) { + s = /* @__PURE__ */ new Set(); + p.__treeTags.set(tag, s); + } + s.add(this); + } while (!p.__tagRoot && (p = p.__parent)); + } + } + } + removeTag(tag) { + let i = this.__tags.indexOf(tag); + if (i !== -1) { + this.__tags.splice(i, 1); + let p = this.__parent; + if (p) { + do { + let list = p.__treeTags.get(tag); + if (list) { + list.delete(this); + } + } while (!p.__tagRoot && (p = p.__parent)); + } + } + } + hasTag(tag) { + return this.__tags && this.__tags.indexOf(tag) !== -1; + } + _tag(tag) { + if (tag.indexOf(".") !== -1) { + return this.mtag(tag)[0]; + } else { + if (this.__treeTags) { + let t = this.__treeTags.get(tag); + if (t) { + const item = t.values().next(); + return item ? item.value : void 0; + } + } + } + } + get tag() { + return this._tag; + } + set tag(t) { + this.tags = t; + } + mtag(tag) { + let idx = tag.indexOf("."); + if (idx >= 0) { + let parts = tag.split("."); + let res = this._getByTag(parts[0]); + let level = 1; + let c = parts.length; + while (res.length && level < c) { + let resn = []; + for (let j = 0, n = res.length; j < n; j++) { + resn = resn.concat(res[j]._getByTag(parts[level])); + } + res = resn; + level++; + } + return res; + } else { + return this._getByTag(tag); + } + } + stag(tag, settings) { + let t = this.mtag(tag); + let n = t.length; + for (let i = 0; i < n; i++) { + Base.patchObject(t[i], settings); + } + } + get tagRoot() { + return this.__tagRoot; + } + set tagRoot(v) { + if (this.__tagRoot !== v) { + if (!v) { + this._setTagsParent(); + } else { + this._unsetTagsParent(); + } + this.__tagRoot = v; + } + } + sel(path) { + const results = this.select(path); + if (results.length) { + return results[0]; + } else { + return void 0; + } + } + select(path) { + if (path.indexOf(",") !== -1) { + let selectors = path.split(","); + let res = []; + for (let i = 0; i < selectors.length; i++) { + res = res.concat(this._select(selectors[i])); + } + return res; + } else { + return this._select(path); + } + } + _select(path) { + if (path === "") + return [this]; + let pointIdx = path.indexOf("."); + let arrowIdx = path.indexOf(">"); + if (pointIdx === -1 && arrowIdx === -1) { + return this.mtag(path); + } + let isRef; + if (arrowIdx === 0) { + isRef = true; + path = path.substr(1); + } else if (pointIdx === 0) { + isRef = false; + path = path.substr(1); + } else { + isRef = false; + } + return this._selectChilds(path, isRef); + } + _selectChilds(path, isRef) { + const pointIdx = path.indexOf("."); + const arrowIdx = path.indexOf(">"); + if (pointIdx === -1 && arrowIdx === -1) { + if (isRef) { + const ref = this.getByRef(path); + return ref ? [ref] : []; + } else { + return this.mtag(path); + } + } + if (arrowIdx === -1 || pointIdx !== -1 && pointIdx < arrowIdx) { + let next; + const str = path.substr(0, pointIdx); + if (isRef) { + const ref = this.getByRef(str); + next = ref ? [ref] : []; + } else { + next = this.mtag(str); + } + let total = []; + const subPath = path.substr(pointIdx + 1); + for (let i = 0, n = next.length; i < n; i++) { + total = total.concat(next[i]._selectChilds(subPath, false)); + } + return total; + } else { + let next; + const str = path.substr(0, arrowIdx); + if (isRef) { + const ref = this.getByRef(str); + next = ref ? [ref] : []; + } else { + next = this.mtag(str); + } + let total = []; + const subPath = path.substr(arrowIdx + 1); + for (let i = 0, n = next.length; i < n; i++) { + total = total.concat(next[i]._selectChilds(subPath, true)); + } + return total; + } + } + getByRef(ref) { + return this.childList.getByRef(ref); + } + getLocationString() { + let i; + i = this.__parent ? this.__parent._children.getIndex(this) : "R"; + let localTags = this.getTags(); + let str = this.__parent ? this.__parent.getLocationString() : ""; + if (this.ref) { + str += ":[" + i + "]" + this.ref; + } else if (localTags.length) { + str += ":[" + i + "]" + localTags.join(","); + } else { + str += ":[" + i + "]#" + this.id; + } + return str; + } + toString() { + let obj = this.getSettings(); + return Element.getPrettyString(obj, ""); + } + static getPrettyString(obj, indent) { + let children = obj.children; + delete obj.children; + let colorKeys = ["color", "colorUl", "colorUr", "colorBl", "colorBr"]; + let str = JSON.stringify(obj, function(k, v) { + if (colorKeys.indexOf(k) !== -1) { + return "COLOR[" + v.toString(16) + "]"; + } + return v; + }); + str = str.replace(/"COLOR\[([a-f0-9]{1,8})\]"/g, "0x$1"); + if (children) { + let childStr = ""; + if (Utils$1.isObjectLiteral(children)) { + let refs = Object.keys(children); + childStr = ""; + for (let i = 0, n = refs.length; i < n; i++) { + childStr += ` +${indent} "${refs[i]}":`; + delete children[refs[i]].ref; + childStr += Element.getPrettyString(children[refs[i]], indent + " ") + (i < n - 1 ? "," : ""); + } + let isEmpty = str === "{}"; + str = str.substr(0, str.length - 1) + (isEmpty ? "" : ",") + childStr + "\n" + indent + "}"; + } else { + let n = children.length; + childStr = "["; + for (let i = 0; i < n; i++) { + childStr += Element.getPrettyString(children[i], indent + " ") + (i < n - 1 ? "," : "") + "\n"; + } + childStr += indent + "]}"; + let isEmpty = str === "{}"; + str = str.substr(0, str.length - 1) + (isEmpty ? "" : ",") + '"children":\n' + indent + childStr + "}"; + } + } + return str; + } + getSettings() { + let settings = this.getNonDefaults(); + let children = this._children.get(); + if (children) { + let n = children.length; + if (n) { + const childArray = []; + let missing = false; + for (let i = 0; i < n; i++) { + childArray.push(children[i].getSettings()); + missing = missing || !children[i].ref; + } + if (!missing) { + settings.children = {}; + childArray.forEach((child) => { + settings.children[child.ref] = child; + }); + } else { + settings.children = childArray; + } + } + } + settings.id = this.id; + return settings; + } + getNonDefaults() { + let settings = {}; + if (this.constructor !== Element) { + settings.type = this.constructor.name; + } + if (this.__ref) { + settings.ref = this.__ref; + } + if (this.__tags && this.__tags.length) { + settings.tags = this.__tags; + } + if (this.x !== 0) + settings.x = this.x; + if (this.y !== 0) + settings.y = this.y; + if (this.w !== 0) + settings.w = this.w; + if (this.h !== 0) + settings.h = this.h; + if (this.scaleX === this.scaleY) { + if (this.scaleX !== 1) + settings.scale = this.scaleX; + } else { + if (this.scaleX !== 1) + settings.scaleX = this.scaleX; + if (this.scaleY !== 1) + settings.scaleY = this.scaleY; + } + if (this.pivotX === this.pivotY) { + if (this.pivotX !== 0.5) + settings.pivot = this.pivotX; + } else { + if (this.pivotX !== 0.5) + settings.pivotX = this.pivotX; + if (this.pivotY !== 0.5) + settings.pivotY = this.pivotY; + } + if (this.mountX === this.mountY) { + if (this.mountX !== 0) + settings.mount = this.mountX; + } else { + if (this.mountX !== 0) + settings.mountX = this.mountX; + if (this.mountY !== 0) + settings.mountY = this.mountY; + } + if (this.alpha !== 1) + settings.alpha = this.alpha; + if (!this.visible) + settings.visible = false; + if (this.rotation !== 0) + settings.rotation = this.rotation; + if (this.colorUl === this.colorUr && this.colorBl === this.colorBr && this.colorUl === this.colorBl) { + if (this.colorUl !== 4294967295) + settings.color = this.colorUl.toString(16); + } else { + if (this.colorUl !== 4294967295) + settings.colorUl = this.colorUl.toString(16); + if (this.colorUr !== 4294967295) + settings.colorUr = this.colorUr.toString(16); + if (this.colorBl !== 4294967295) + settings.colorBl = this.colorBl.toString(16); + if (this.colorBr !== 4294967295) + settings.colorBr = this.colorBr.toString(16); + } + if (this.zIndex) + settings.zIndex = this.zIndex; + if (this.forceZIndexContext) + settings.forceZIndexContext = true; + if (this.clipping) + settings.clipping = this.clipping; + if (!this.clipbox) + settings.clipbox = this.clipbox; + if (this.__texture) { + let tnd = this.__texture.getNonDefaults(); + if (Object.keys(tnd).length) { + settings.texture = tnd; + } + } + if (this.shader && Utils$1.isFunction(this.shader.getNonDefaults)) { + let tnd = this.shader.getNonDefaults(); + if (Object.keys(tnd).length) { + settings.shader = tnd; + } + } + if (this._hasTexturizer()) { + if (this.texturizer.enabled) { + settings.renderToTexture = this.texturizer.enabled; + } + if (this.texturizer.lazy) { + settings.renderToTextureLazy = this.texturizer.lazy; + } + if (this.texturizer.colorize) { + settings.colorizeResultTexture = this.texturizer.colorize; + } + if (this.texturizer.renderOffscreen) { + settings.renderOffscreen = this.texturizer.renderOffscreen; + } + } + return settings; + } + static getGetter(propertyPath) { + let getter = Element.PROP_GETTERS.get(propertyPath); + if (!getter) { + getter = new Function("obj", "return obj." + propertyPath); + Element.PROP_GETTERS.set(propertyPath, getter); + } + return getter; + } + static getSetter(propertyPath) { + let setter = Element.PROP_SETTERS.get(propertyPath); + if (!setter) { + setter = new Function("obj", "v", "obj." + propertyPath + " = v"); + Element.PROP_SETTERS.set(propertyPath, setter); + } + return setter; + } + get withinBoundsMargin() { + return this.__core._withinBoundsMargin; + } + _enableWithinBoundsMargin() { + if (this.__enabled) { + this._setActiveFlag(); + } + } + _disableWithinBoundsMargin() { + if (this.__active) { + this._unsetActiveFlag(); + } + } + set boundsMargin(v) { + if (!Array.isArray(v) && v !== null) { + throw new Error("boundsMargin should be an array of left-top-right-bottom values or null (inherit margin)"); + } + this.__core.boundsMargin = v; + } + get boundsMargin() { + return this.__core.boundsMargin; + } + get x() { + return this.__core.offsetX; + } + set x(v) { + this.__core.offsetX = v; + } + get y() { + return this.__core.offsetY; + } + set y(v) { + this.__core.offsetY = v; + } + get w() { + return this._w; + } + set w(v) { + if (Utils$1.isFunction(v)) { + this._w = 0; + this.__core.funcW = v; + } else { + v = Math.max(v, 0); + if (this._w !== v) { + this.__core.disableFuncW(); + this._w = v; + this._updateDimensions(); + } + } + } + get h() { + return this._h; + } + set h(v) { + if (Utils$1.isFunction(v)) { + this._h = 0; + this.__core.funcH = v; + } else { + v = Math.max(v, 0); + if (this._h !== v) { + this.__core.disableFuncH(); + this._h = v; + this._updateDimensions(); + } + } + } + get collision() { + return this._collision; + } + set collision(v) { + this._collision = v; + } + _updateCollision() { + if (this.collision && this.__parent && this.__parent.collision === void 0) { + this.__parent.collision = 2; + } + } + get scaleX() { + return this.__core.scaleX; + } + set scaleX(v) { + this.__core.scaleX = v; + } + get scaleY() { + return this.__core.scaleY; + } + set scaleY(v) { + this.__core.scaleY = v; + } + get scale() { + return this.__core.scale; + } + set scale(v) { + this.__core.scale = v; + } + get pivotX() { + return this.__core.pivotX; + } + set pivotX(v) { + this.__core.pivotX = v; + } + get pivotY() { + return this.__core.pivotY; + } + set pivotY(v) { + this.__core.pivotY = v; + } + get pivot() { + return this.__core.pivot; + } + set pivot(v) { + this.__core.pivot = v; + } + get mountX() { + return this.__core.mountX; + } + set mountX(v) { + this.__core.mountX = v; + } + get mountY() { + return this.__core.mountY; + } + set mountY(v) { + this.__core.mountY = v; + } + get mount() { + return this.__core.mount; + } + set mount(v) { + this.__core.mount = v; + } + get rotation() { + return this.__core.rotation; + } + set rotation(v) { + this.__core.rotation = v; + } + get alpha() { + return this.__core.alpha; + } + set alpha(v) { + this.__core.alpha = v; + } + get visible() { + return this.__core.visible; + } + set visible(v) { + this.__core.visible = v; + } + get colorUl() { + return this.__core.colorUl; + } + set colorUl(v) { + this.__core.colorUl = v; + } + get colorUr() { + return this.__core.colorUr; + } + set colorUr(v) { + this.__core.colorUr = v; + } + get colorBl() { + return this.__core.colorBl; + } + set colorBl(v) { + this.__core.colorBl = v; + } + get colorBr() { + return this.__core.colorBr; + } + set colorBr(v) { + this.__core.colorBr = v; + } + get color() { + return this.__core.colorUl; + } + set color(v) { + if (this.colorUl !== v || this.colorUr !== v || this.colorBl !== v || this.colorBr !== v) { + this.colorUl = v; + this.colorUr = v; + this.colorBl = v; + this.colorBr = v; + } + } + get colorTop() { + return this.colorUl; + } + set colorTop(v) { + if (this.colorUl !== v || this.colorUr !== v) { + this.colorUl = v; + this.colorUr = v; + } + } + get colorBottom() { + return this.colorBl; + } + set colorBottom(v) { + if (this.colorBl !== v || this.colorBr !== v) { + this.colorBl = v; + this.colorBr = v; + } + } + get colorLeft() { + return this.colorUl; + } + set colorLeft(v) { + if (this.colorUl !== v || this.colorBl !== v) { + this.colorUl = v; + this.colorBl = v; + } + } + get colorRight() { + return this.colorUr; + } + set colorRight(v) { + if (this.colorUr !== v || this.colorBr !== v) { + this.colorUr = v; + this.colorBr = v; + } + } + get zIndex() { + return this.__core.zIndex; + } + set zIndex(v) { + this.__core.zIndex = v; + } + get forceZIndexContext() { + return this.__core.forceZIndexContext; + } + set forceZIndexContext(v) { + this.__core.forceZIndexContext = v; + } + get clipping() { + return this.__core.clipping; + } + set clipping(v) { + this.__core.clipping = v; + } + get clipbox() { + return this.__core.clipbox; + } + set clipbox(v) { + this.__core.clipbox = v; + } + get tags() { + return this.getTags(); + } + set tags(v) { + if (!Array.isArray(v)) + v = [v]; + this.setTags(v); + } + set t(v) { + this.tags = v; + } + get _children() { + if (!this.__childList) { + this.__childList = new ElementChildList(this, false); + } + return this.__childList; + } + get childList() { + if (!this._allowChildrenAccess()) { + this._throwError("Direct access to children is not allowed in " + this.getLocationString()); + } + return this._children; + } + hasChildren() { + return this._allowChildrenAccess() && this.__childList && this.__childList.length > 0; + } + _allowChildrenAccess() { + return true; + } + get children() { + return this.childList.get(); + } + set children(children) { + this.childList.patch(children); + } + add(o) { + return this.childList.a(o); + } + get p() { + return this.__parent; + } + get parent() { + return this.__parent; + } + get src() { + if (this.texture && this.texture instanceof ImageTexture) { + return this.texture._src; + } else { + return void 0; + } + } + set src(v) { + const texture = new ImageTexture(this.stage); + texture.src = v; + this.texture = texture; + } + set mw(v) { + if (this.texture) { + this.texture.mw = v; + this._updateDimensions(); + } else { + this._throwError("Please set mw after setting a texture."); + } + } + set mh(v) { + if (this.texture) { + this.texture.mh = v; + this._updateDimensions(); + } else { + this._throwError("Please set mh after setting a texture."); + } + } + get rect() { + return this.texture === this.stage.rectangleTexture; + } + set rect(v) { + if (v) { + this.texture = this.stage.rectangleTexture; + } else { + this.texture = null; + } + } + enableTextTexture() { + if (!this.texture || !(this.texture instanceof TextTexture)) { + this.texture = new TextTexture(this.stage); + if (!this.texture.w && !this.texture.h) { + this.texture.w = this.w; + this.texture.h = this.h; + } + } + return this.texture; + } + get text() { + if (this.texture && this.texture instanceof TextTexture) { + return this.texture; + } else { + return null; + } + } + set text(v) { + if (!this.texture || !(this.texture instanceof TextTexture)) { + this.enableTextTexture(); + } + if (Utils$1.isString(v)) { + this.texture.text = v; + } else { + this.texture.patch(v); + } + } + set onUpdate(f) { + this.__core.onUpdate = f; + } + set onAfterCalcs(f) { + this.__core.onAfterCalcs = f; + } + set onAfterUpdate(f) { + this.__core.onAfterUpdate = f; + } + forceUpdate() { + this.__core._setHasUpdates(); + } + get shader() { + return this.__core.shader; + } + set shader(v) { + if (Utils$1.isObjectLiteral(v) && !v.type) { + if (this.shader) { + this.shader.patch(v); + } + } else { + const shader = Shader.create(this.stage, v); + if (this.__enabled && this.__core.shader) { + this.__core.shader.removeElement(this.__core); + } + this.__core.shader = shader; + if (this.__enabled && this.__core.shader) { + this.__core.shader.addElement(this.__core); + } + } + } + _hasTexturizer() { + return !!this.__core._texturizer; + } + get renderToTexture() { + return this.rtt; + } + set renderToTexture(v) { + this.rtt = v; + } + get rtt() { + return this._hasTexturizer() && this.texturizer.enabled; + } + set rtt(v) { + this.texturizer.enabled = v; + } + get rttLazy() { + return this._hasTexturizer() && this.texturizer.lazy; + } + set rttLazy(v) { + this.texturizer.lazy = v; + } + get renderOffscreen() { + return this._hasTexturizer() && this.texturizer.renderOffscreen; + } + set renderOffscreen(v) { + this.texturizer.renderOffscreen = v; + } + get colorizeResultTexture() { + return this._hasTexturizer() && this.texturizer.colorize; + } + set colorizeResultTexture(v) { + this.texturizer.colorize = v; + } + getTexture() { + return this.texturizer._getTextureSource(); + } + get texturizer() { + return this.__core.texturizer; + } + patch(settings) { + let paths = Object.keys(settings); + for (let i = 0, n = paths.length; i < n; i++) { + let path = paths[i]; + const v = settings[path]; + const firstCharCode = path.charCodeAt(0); + if (Utils$1.isUcChar(firstCharCode)) { + const child = this.getByRef(path); + if (!child) { + if (v !== void 0) { + let c; + if (Utils$1.isObjectLiteral(v)) { + c = this.childList.createItem(v); + c.patch(v); + } else if (Utils$1.isObject(v)) { + c = v; + } + if (c.isElement) { + c.ref = path; + } + this.childList.a(c); + } + } else { + if (v === void 0) { + if (child.parent) { + child.parent.childList.remove(child); + } + } else if (Utils$1.isObjectLiteral(v)) { + child.patch(v); + } else if (v.isElement) { + v.ref = path; + this.childList.replace(v, child); + } else { + this._throwError("Unexpected value for path: " + path); + } + } + } else { + Base.patchObjectProperty(this, path, v); + } + } + } + _throwError(message) { + throw new Error(this.constructor.name + " (" + this.getLocationString() + "): " + message); + } + animation(settings) { + return this.stage.animations.createAnimation(this, settings); + } + transition(property, settings = null) { + if (settings === null) { + return this._getTransition(property); + } else { + this._setTransition(property, settings); + return null; + } + } + set transitions(object) { + let keys = Object.keys(object); + keys.forEach((property) => { + this.transition(property, object[property]); + }); + } + set smooth(object) { + let keys = Object.keys(object); + keys.forEach((property) => { + let value = object[property]; + if (Array.isArray(value)) { + this.setSmooth(property, value[0], value[1]); + } else { + this.setSmooth(property, value); + } + }); + } + fastForward(property) { + if (this._transitions) { + let t = this._transitions[property]; + if (t && t.isTransition) { + t.finish(); + } + } + } + _getTransition(property) { + if (!this._transitions) { + this._transitions = {}; + } + let t = this._transitions[property]; + if (!t) { + t = new Transition(this.stage.transitions, this.stage.transitions.defaultTransitionSettings, this, property); + } else if (t.isTransitionSettings) { + t = new Transition( + this.stage.transitions, + t, + this, + property + ); + } + this._transitions[property] = t; + return t; + } + _setTransition(property, settings) { + if (!settings) { + this._removeTransition(property); + } else { + if (Utils$1.isObjectLiteral(settings)) { + settings = this.stage.transitions.createSettings(settings); + } + if (!this._transitions) { + this._transitions = {}; + } + let current = this._transitions[property]; + if (current && current.isTransition) { + current.settings = settings; + return current; + } else { + this._transitions[property] = settings; + } + } + } + _removeTransition(property) { + if (this._transitions) { + delete this._transitions[property]; + } + } + getSmooth(property, v) { + let t = this._getTransition(property); + if (t && t.isAttached()) { + return t.targetValue; + } else { + return v; + } + } + setSmooth(property, v, settings) { + if (settings) { + this._setTransition(property, settings); + } + let t = this._getTransition(property); + t.start(v); + return t; + } + get flex() { + return this.__core.flex; + } + set flex(v) { + this.__core.flex = v; + } + get flexItem() { + return this.__core.flexItem; + } + set flexItem(v) { + this.__core.flexItem = v; + } + static isColorProperty(property) { + return property.toLowerCase().indexOf("color") >= 0; + } + static getMerger(property) { + if (Element.isColorProperty(property)) { + return StageUtils.mergeColors; + } else { + return StageUtils.mergeNumbers; + } + } + toJSON() { + const ref = [`${this.constructor.name}`]; + const tree = {}; + tree[ref] = {}; + if (this.hasChildren()) { + Element.collectChildren(tree[ref], this.__childList); + } else { + tree[ref] = { ...Element.getProperties(this) }; + } + return tree; + } + static collectChildren(tree, children) { + const childList = children; + for (let i = 0, j = childList.length; i < j; i++) { + const element = childList.getAt(i); + const ref = `${element.__ref || `Element-${element.id}`}`; + const properties = this.getProperties(element); + tree[ref] = { ...properties }; + if (element.hasChildren()) { + tree[ref].children = {}; + this.collectChildren( + tree[ref].children, + element.__childList + ); + } + } + } + static getProperties(element) { + const props = {}; + const list = [ + "alpha", + "active", + "attached", + "boundsMargin", + "color", + "clipping", + "enabled", + "h", + "id", + "isComponent", + "mount", + "mountY", + "mountX", + "pivot", + "pivotX", + "pivotY", + "ref", + "renderOffscreen", + "renderToTexture", + "scale", + "scaleX", + "scaleY", + "state", + "tag", + "visible", + "w", + "x", + "y", + "zIndex", + "!!flex", + "!!flexItem", + "hasFocus()", + "hasFinalFocus()" + ]; + let n = list.length; + while (n--) { + let key = list[n]; + const getBoolean = /^!{2}/; + const isFunction = /\(\)$/; + if (getBoolean.test(key)) { + key = key.substring(2, key.length); + props[key] = !!element[key]; + } else if (isFunction.test(key)) { + key = key.substring(0, key.length - 2); + if (typeof element[key] === "function") { + props[key] = element[key](); + } + } else { + props[key] = element[key]; + } + } + return { ...props, ...element.getNonDefaults() }; + } + } + EventEmitter.addAsMixin(Element); + Element.prototype.isElement = 1; + Element.id = 1; + Element.PROP_GETTERS = /* @__PURE__ */ new Map(); + Element.PROP_SETTERS = /* @__PURE__ */ new Map(); + class StateMachine { + constructor() { + StateMachine.setupStateMachine(this); + } + static setupStateMachine(target) { + const targetConstructor = target.constructor; + const router = StateMachine.create(targetConstructor); + Object.setPrototypeOf(target, router.prototype); + target.constructor = targetConstructor; + target._initStateMachine(); + } + static create(type) { + if (!type.hasOwnProperty("_sm")) { + const stateMachineType = new StateMachineType(type); + type._sm = stateMachineType; + } + return type._sm.router; + } + fire(event, ...args) { + if (this._hasMethod(event)) { + return this[event](...args); + } + } + _getState() { + return this._state.__path; + } + _inState(statePath, currentStatePath = this._state.__path) { + const state = this._sm.getStateByPath(statePath); + const currentState = this._sm.getStateByPath(currentStatePath); + const level = state.__level; + const stateAtLevel = StateMachine._getStateAtLevel(currentState, level); + return stateAtLevel === state; + } + _hasMember(name) { + return !!this.constructor.prototype[name]; + } + _hasMethod(name) { + const member = this.constructor.prototype[name]; + return !!member && typeof member === "function"; + } + _setState(statePath, args) { + const setStateId = ++this._setStateCounter; + this._setStateId = setStateId; + if (this._state.__path !== statePath) { + let newState = this._sm._stateMap[statePath]; + if (!newState) { + newState = this._sm.getStateByPath(statePath); + } + const prevState = this._state; + const hasDifferentEnterMethod = newState.prototype.$enter !== this._state.prototype.$enter; + const hasDifferentExitMethod = newState.prototype.$exit !== this._state.prototype.$exit; + if (hasDifferentEnterMethod || hasDifferentExitMethod) { + const sharedState = StateMachine._getSharedState(this._state, newState); + const context = { + newState: newState.__path, + prevState: prevState.__path, + sharedState: sharedState.__path + }; + const sharedLevel = sharedState.__level; + if (hasDifferentExitMethod) { + const exitStates = StateMachine._getStatesUntilLevel(this._state, sharedLevel); + for (let i = 0, n = exitStates.length; i < n; i++) { + this.__setState(exitStates[i]); + this._callExit(this._state, args, context); + const stateChangeOverridden = this._setStateId !== setStateId; + if (stateChangeOverridden) { + return; + } + } + } + if (hasDifferentEnterMethod) { + const enterStates = StateMachine._getStatesUntilLevel(newState, sharedLevel).reverse(); + for (let i = 0, n = enterStates.length; i < n; i++) { + this.__setState(enterStates[i]); + this._callEnter(this._state, args, context); + const stateChangeOverridden = this._setStateId !== setStateId; + if (stateChangeOverridden) { + return; + } + } + } + } + this.__setState(newState); + if (this._changedState) { + const context = { + newState: newState.__path, + prevState: prevState.__path + }; + if (args) { + this._changedState(context, ...args); + } else { + this._changedState(context); + } + } + if (this._onStateChange) { + const context = { + newState: newState.__path, + prevState: prevState.__path + }; + this._onStateChange(context); + } + } + } + _callEnter(state, args = [], context) { + const hasParent = !!state.__parent; + if (state.prototype.$enter) { + if (!hasParent || state.__parent.prototype.$enter !== state.prototype.$enter) { + state.prototype.$enter.apply(this, [context, ...args]); + } + } + } + _callExit(state, args = [], context) { + const hasParent = !!state.__parent; + if (state.prototype.$exit) { + if (!hasParent || state.__parent.prototype.$exit !== state.prototype.$exit) { + state.prototype.$exit.apply(this, [context, ...args]); + } + } + } + __setState(state) { + this._state = state; + this._stateIndex = state.__index; + this.constructor = state; + } + _initStateMachine() { + this._state = null; + this._stateIndex = 0; + this._setStateCounter = 0; + this._sm = this._routedType._sm; + this.__setState(this._sm.getStateByPath("")); + const context = { newState: "", prevState: void 0, sharedState: void 0 }; + this._callEnter(this._state, [], context); + this._onStateChange = void 0; + } + _getMostSpecificHandledMember(memberNames) { + let cur = this._state; + do { + for (let i = 0, n = memberNames.length; i < n; i++) { + const memberName = memberNames[i]; + if (!cur.__parent) { + if (cur.prototype[memberName]) { + return memberName; + } + } else { + const alias = StateMachineType.getStateMemberAlias(cur.__path, memberName); + if (this[alias]) { + return memberName; + } + } + } + cur = cur.__parent; + } while (cur); + } + static _getStatesUntilLevel(state, level) { + const states = []; + while (state.__level > level) { + states.push(state); + state = state.__parent; + } + return states; + } + static _getSharedState(state1, state2) { + const state1Array = StateMachine._getAncestorStates(state1); + const state2Array = StateMachine._getAncestorStates(state2); + const n = Math.min(state1Array.length, state2Array.length); + for (let i = 0; i < n; i++) { + if (state1Array[i] !== state2Array[i]) { + return state1Array[i - 1]; + } + } + return state1Array[n - 1]; + } + static _getAncestorStates(state) { + const result = []; + do { + result.push(state); + } while (state = state.__parent); + return result.reverse(); + } + static _getStateAtLevel(state, level) { + if (level > state.__level) { + return void 0; + } + while (level < state.__level) { + state = state.__parent; + } + return state; + } + } + class StateMachineType { + constructor(type) { + this._type = type; + this._router = null; + this.init(); + } + get router() { + return this._router; + } + init() { + this._router = this._createRouter(); + this._stateMap = this._getStateMap(); + this._addStateMemberDelegatorsToRouter(); + } + _createRouter() { + const type = this._type; + const router = class StateMachineRouter extends type { + constructor() { + super(...arguments); + if (!this.constructor.hasOwnProperty("_isRouter")) { + throw new Error(`You need to extend ${type.name}.original instead of ${type.name}.`); + } + } + }; + router._isRouter = true; + router.prototype._routedType = type; + router.original = type; + this._mixinStateMachineMethods(router); + return router; + } + _mixinStateMachineMethods(router) { + const names = Object.getOwnPropertyNames(StateMachine.prototype); + for (let i = 0, n = names.length; i < n; i++) { + const name = names[i]; + if (name !== "constructor") { + const descriptor = Object.getOwnPropertyDescriptor(StateMachine.prototype, name); + Object.defineProperty(router.prototype, name, descriptor); + } + } + } + _addStateMemberDelegatorsToRouter() { + const members = this._getAllMemberNames(); + members.forEach((member) => { + this._addMemberRouter(member); + }); + } + _addMemberRouter(member) { + const statePaths = Object.keys(this._stateMap); + const descriptors = []; + const aliases = []; + statePaths.forEach((statePath, index) => { + const state = this._stateMap[statePath]; + const descriptor = this._getDescriptor(state, member); + if (descriptor) { + descriptors[index] = descriptor; + const alias = StateMachineType.getStateMemberAlias(descriptor._source.__path, member); + aliases[index] = alias; + if (!this._router.prototype.hasOwnProperty(alias)) { + Object.defineProperty(this._router.prototype, alias, descriptor); + } + } else { + descriptors[index] = null; + aliases[index] = null; + } + }); + let type = void 0; + descriptors.forEach((descriptor) => { + if (descriptor) { + const descType = this._getDescriptorType(descriptor); + if (type && type !== descType) { + console.warn(`[Lightning] Member ${member} in ${this._type.name} has inconsistent types.`); + return; + } + type = descType; + } + }); + switch (type) { + case "method": + this._addMethodRouter(member, descriptors, aliases); + break; + case "getter": + this._addGetterSetterRouters(member); + break; + case "property": + console.warn("[Lightning] Fixed properties are not supported; please use a getter instead!"); + break; + } + } + _getDescriptor(state, member, isValid = () => true) { + let type = state; + let curState = state; + do { + const descriptor = Object.getOwnPropertyDescriptor(type.prototype, member); + if (descriptor) { + if (isValid(descriptor)) { + descriptor._source = curState; + return descriptor; + } + } + type = Object.getPrototypeOf(type); + if (type && type.hasOwnProperty("__state")) { + curState = type; + } + } while (type && type.prototype); + return void 0; + } + _getDescriptorType(descriptor) { + if (descriptor.get || descriptor.set) { + return "getter"; + } else { + if (typeof descriptor.value === "function") { + return "method"; + } else { + return "property"; + } + } + } + static _supportsSpread() { + if (this.__supportsSpread === void 0) { + this.__supportsSpread = false; + try { + const func = new Function("return [].concat(...arguments);"); + func(); + this.__supportsSpread = true; + } catch (e) { + } + } + return this.__supportsSpread; + } + _addMethodRouter(member, descriptors, aliases) { + const code = [ + "//@ sourceURL=StateMachineRouter.js", + "var i = this._stateIndex;" + ]; + let cur = aliases[0]; + const supportsSpread = StateMachineType._supportsSpread(); + for (let i = 1, n = aliases.length; i < n; i++) { + const alias = aliases[i]; + if (alias !== cur) { + if (cur) { + if (supportsSpread) { + code.push(`if (i < ${i}) return this["${cur}"](...arguments); else`); + } else { + code.push(`if (i < ${i}) return this["${cur}"].apply(this, arguments); else`); + } + } else { + code.push(`if (i < ${i}) return ; else`); + } + } + cur = alias; + } + if (cur) { + if (supportsSpread) { + code.push(`return this["${cur}"](...arguments);`); + } else { + code.push(`return this["${cur}"].apply(this, arguments);`); + } + } else { + code.push(`;`); + } + const functionBody = code.join("\n"); + const router = new Function([], functionBody); + const descriptor = { value: router }; + Object.defineProperty(this._router.prototype, member, descriptor); + } + _addGetterSetterRouters(member) { + const getter = this._getGetterRouter(member); + const setter = this._getSetterRouter(member); + const descriptor = { + get: getter, + set: setter + }; + Object.defineProperty(this._router.prototype, member, descriptor); + } + _getGetterRouter(member) { + const statePaths = Object.keys(this._stateMap); + const aliases = []; + statePaths.forEach((statePath, index) => { + const state = this._stateMap[statePath]; + const descriptor = this._getDescriptor(state, member, (descriptor2) => descriptor2.get); + if (descriptor) { + const alias = StateMachineType.getStateMemberAlias(descriptor._source.__path, member); + aliases[index] = alias; + if (!this._router.prototype.hasOwnProperty(alias)) { + Object.defineProperty(this._router.prototype, alias, descriptor); + } + } else { + aliases[index] = null; + } + }); + const code = [ + "//@ sourceURL=StateMachineRouter.js", + "var i = this._stateIndex;" + ]; + let cur = aliases[0]; + for (let i = 1, n = aliases.length; i < n; i++) { + const alias = aliases[i]; + if (alias !== cur) { + if (cur) { + code.push(`if (i < ${i}) return this["${cur}"]; else`); + } else { + code.push(`if (i < ${i}) return ; else`); + } + } + cur = alias; + } + if (cur) { + code.push(`return this["${cur}"];`); + } else { + code.push(`;`); + } + const functionBody = code.join("\n"); + const router = new Function([], functionBody); + return router; + } + _getSetterRouter(member) { + const statePaths = Object.keys(this._stateMap); + const aliases = []; + statePaths.forEach((statePath, index) => { + const state = this._stateMap[statePath]; + const descriptor = this._getDescriptor(state, member, (descriptor2) => descriptor2.set); + if (descriptor) { + const alias = StateMachineType.getStateMemberAlias(descriptor._source.__path, member); + aliases[index] = alias; + if (!this._router.prototype.hasOwnProperty(alias)) { + Object.defineProperty(this._router.prototype, alias, descriptor); + } + } else { + aliases[index] = null; + } + }); + const code = [ + "//@ sourceURL=StateMachineRouter.js", + "var i = this._stateIndex;" + ]; + let cur = aliases[0]; + for (let i = 1, n = aliases.length; i < n; i++) { + const alias = aliases[i]; + if (alias !== cur) { + if (cur) { + code.push(`if (i < ${i}) this["${cur}"] = arg; else`); + } else { + code.push(`if (i < ${i}) ; else`); + } + } + cur = alias; + } + if (cur) { + code.push(`this["${cur}"] = arg;`); + } else { + code.push(`;`); + } + const functionBody = code.join("\n"); + const router = new Function(["arg"], functionBody); + return router; + } + static getStateMemberAlias(path, member) { + return "$" + (path ? path + "." : "") + member; + } + _getAllMemberNames() { + const stateMap = this._stateMap; + const map = Object.keys(stateMap); + let members = /* @__PURE__ */ new Set(); + map.forEach((statePath) => { + if (statePath === "") { + return; + } + const state = stateMap[statePath]; + const names = this._getStateMemberNames(state); + names.forEach((name) => { + members.add(name); + }); + }); + return [...members]; + } + _getStateMemberNames(state) { + let type = state; + let members = /* @__PURE__ */ new Set(); + const isRoot = this._type === state; + do { + const names = this._getStateMemberNamesForType(type); + names.forEach((name) => { + members.add(name); + }); + type = Object.getPrototypeOf(type); + } while (type && type.prototype && (!type.hasOwnProperty("__state") || isRoot)); + return members; + } + _getStateMemberNamesForType(type) { + const memberNames = Object.getOwnPropertyNames(type.prototype); + return memberNames.filter((memberName) => { + return memberName !== "constructor" && !StateMachineType._isStateLocalMember(memberName); + }); + } + static _isStateLocalMember(memberName) { + return memberName === "$enter" || memberName === "$exit"; + } + getStateByPath(statePath) { + if (this._stateMap[statePath]) { + return this._stateMap[statePath]; + } + const parts = statePath.split("."); + while (parts.pop()) { + const statePath2 = parts.join("."); + if (this._stateMap[statePath2]) { + return this._stateMap[statePath2]; + } + } + } + _getStateMap() { + if (!this._stateMap) { + this._stateMap = this._createStateMap(); + } + return this._stateMap; + } + _createStateMap() { + const stateMap = {}; + this._addState(this._type, null, "", stateMap); + return stateMap; + } + _addState(state, parentState, name, stateMap) { + state.__state = true; + state.__name = name; + this._addStaticStateProperty(state, parentState); + const parentPath = parentState ? parentState.__path : ""; + let path = (parentPath ? parentPath + "." : "") + name; + state.__path = path; + state.__level = parentState ? parentState.__level + 1 : 0; + state.__parent = parentState; + state.__index = Object.keys(stateMap).length; + stateMap[path] = state; + const states = state._states; + if (states) { + const isInheritedFromParent = parentState && parentState._states === states; + if (!isInheritedFromParent) { + const subStates = state._states(); + subStates.forEach((subState) => { + const stateName = StateMachineType._getStateName(subState); + this._addState(subState, state, stateName, stateMap); + }); + } + } + } + static _getStateName(state) { + const name = state.name; + const index = name.indexOf("$"); + if (index > 0) { + return name.substr(0, index); + } + return name; + } + _addStaticStateProperty(state, parentState) { + if (parentState) { + const isClassStateLevel = parentState && !parentState.__parent; + if (isClassStateLevel) { + this._router[state.__name] = state; + } else { + parentState[state.__name] = state; + } + } + } + } + class Component extends Element { + constructor(stage, properties) { + super(stage); + this.tagRoot = true; + if (Utils$1.isObjectLiteral(properties)) { + Object.assign(this, properties); + } + this.__initialized = false; + this.__firstActive = false; + this.__firstEnable = false; + this.__signals = void 0; + this.__passSignals = void 0; + this.__construct(); + const func = this.constructor.getTemplateFunc(this); + func.f(this, func.a); + this._build(); + } + __start() { + StateMachine.setupStateMachine(this); + this._onStateChange = Component.prototype.__onStateChange; + } + get state() { + return this._getState(); + } + __onStateChange() { + if (this.application) { + this.application.updateFocusPath(); + } + } + _refocus() { + if (this.application) { + this.application.updateFocusPath(); + } + } + static bindProp(name, func = null) { + return { __propertyBinding: true, __name: name, __func: func }; + } + __bindProperty(propObj, targetObj, targetProp) { + const obj = targetObj; + const prop = targetProp; + const propDependencies = Array.isArray(propObj.__name) ? propObj.__name : [propObj.__name]; + for (let i = 0; i < propDependencies.length; i++) { + const propName = propDependencies[i]; + const func = propObj.__func ? propObj.__func : (context) => context[propName]; + if (!this.hasOwnProperty(propName)) { + this[`__prop_bindings_${propName}`] = [{ __obj: obj, __prop: prop, __func: func }]; + Object.defineProperty(this, propName, { + set: (value) => { + this[`__prop_${propName}`] = value; + for (const { __obj, __prop, __func } of this[`__prop_bindings_${propName}`]) { + __obj[__prop] = __func(this); + } + }, + get: () => this[`__prop_${propName}`] + }); + } else { + this[`__prop_bindings_${propName}`].push({ __obj: obj, __prop: prop, __func: func }); + } + } + } + static getTemplateFunc(ctx) { + const name = "_templateFunc"; + const hasName = "__has" + name; + if (this[hasName] !== this) { + this[hasName] = this; + this[name] = this.parseTemplate(this._template(ctx)); + } + return this[name]; + } + static parseTemplate(obj) { + const context = { + loc: [], + store: [], + rid: 0 + }; + this.parseTemplateRec(obj, context, "element"); + const code = context.loc.join(";\n"); + const f = new Function("element", "store", code); + return { f, a: context.store }; + } + static parseTemplateRec(obj, context, cursor) { + const store = context.store; + const loc = context.loc; + const keys = Object.keys(obj); + keys.forEach((key) => { + let value = obj[key]; + if (Utils$1.isUcChar(key.charCodeAt(0))) { + if (Utils$1.isObjectLiteral(value)) { + const childCursor = `r${key.replace(/[^a-z0-9]/gi, "") + context.rid}`; + let type = value.type ? value.type : Element; + if (type === Element) { + loc.push(`var ${childCursor} = element.stage.createElement()`); + } else { + store.push(type); + loc.push(`var ${childCursor} = new store[${store.length - 1}](${cursor}.stage)`); + } + loc.push(`${childCursor}.ref = "${key}"`); + context.rid++; + this.parseTemplateRec(value, context, childCursor); + loc.push(`${cursor}.childList.add(${childCursor})`); + } else if (Utils$1.isObject(value)) { + store.push(value); + loc.push(`${cursor}.childList.add(store[${store.length - 1}])`); + } + } else { + if (key === "text") { + const propKey = cursor + "__text"; + loc.push(`var ${propKey} = ${cursor}.enableTextTexture()`); + if (value.__propertyBinding === true) { + store.push(value); + loc.push(`element.__bindProperty(store[${store.length - 1}], ${cursor}, "${key}")`); + } else { + this.parseTemplatePropRec(value, context, propKey); + } + } else if (key === "shader" && Utils$1.isObjectLiteral(value)) { + const shaderCursor = `${cursor}["shader"]`; + store.push(value); + loc.push(`${cursor}["${key}"] = store[${store.length - 1}]`); + this.parsePropertyBindings(value, context, shaderCursor); + } else if (key === "texture" && Utils$1.isObjectLiteral(value)) { + const propKey = cursor + "__texture"; + const type = value.type; + if (type) { + store.push(type); + loc.push(`var ${propKey} = new store[${store.length - 1}](${cursor}.stage)`); + this.parseTemplatePropRec(value, context, propKey); + loc.push(`${cursor}["${key}"] = ${propKey}`); + } else { + loc.push(`${propKey} = ${cursor}.texture`); + this.parseTemplatePropRec(value, context, propKey); + } + } else if (Utils$1.isObjectLiteral(value) && value.__propertyBinding === true) { + store.push(value); + loc.push(`element.__bindProperty(store[${store.length - 1}], ${cursor}, "${key}")`); + } else { + if (Utils$1.isNumber(value)) { + loc.push(`${cursor}["${key}"] = ${value}`); + } else if (Utils$1.isBoolean(value)) { + loc.push(`${cursor}["${key}"] = ${value ? "true" : "false"}`); + } else if (Utils$1.isObject(value) || Array.isArray(value)) { + store.push(value); + loc.push(`${cursor}["${key}"] = store[${store.length - 1}]`); + } else { + loc.push(`${cursor}["${key}"] = ${JSON.stringify(value)}`); + } + } + } + }); + } + static parseTemplatePropRec(obj, context, cursor) { + const store = context.store; + const loc = context.loc; + const keys = Object.keys(obj); + keys.forEach((key) => { + if (key !== "type") { + const value = obj[key]; + if (Utils$1.isNumber(value)) { + loc.push(`${cursor}["${key}"] = ${value}`); + } else if (Utils$1.isBoolean(value)) { + loc.push(`${cursor}["${key}"] = ${value ? "true" : "false"}`); + } else if (Utils$1.isObject(value) && value.__propertyBinding === true) { + store.push(value); + loc.push(`element.__bindProperty(store[${store.length - 1}], ${cursor}, "${key}")`); + } else if (Utils$1.isObject(value) || Array.isArray(value)) { + store.push(value); + loc.push(`${cursor}["${key}"] = store[${store.length - 1}]`); + } else { + loc.push(`${cursor}["${key}"] = ${JSON.stringify(value)}`); + } + } + }); + } + static parsePropertyBindings(obj, context, cursor) { + const store = context.store; + const loc = context.loc; + const keys = Object.keys(obj); + keys.forEach((key) => { + if (key !== "type") { + const value = obj[key]; + if (Utils$1.isObjectLiteral(value) && value.__propertyBinding === true) { + store.push(value); + loc.push(`element.__bindProperty(store[${store.length - 1}], ${cursor}, "${key}")`); + } + } + }); + } + _onSetup() { + if (!this.__initialized) { + this._setup(); + } + } + _setup() { + } + _onAttach() { + if (!this.__initialized) { + this.__init(); + this.__initialized = true; + } + this._attach(); + } + _attach() { + } + _onDetach() { + this._detach(); + } + _detach() { + } + _onEnabled() { + if (!this.__firstEnable) { + this._firstEnable(); + this.__firstEnable = true; + } + this._enable(); + } + _firstEnable() { + } + _enable() { + } + _onDisabled() { + this._disable(); + } + _disable() { + } + _onActive() { + if (!this.__firstActive) { + this._firstActive(); + this.__firstActive = true; + } + this._active(); + } + _firstActive() { + } + _active() { + } + _onInactive() { + this._inactive(); + } + _inactive() { + } + get application() { + return this.stage.application; + } + __construct() { + this._construct(); + } + _construct() { + } + _build() { + } + __init() { + this._init(); + } + _init() { + } + _focus(newTarget, prevTarget) { + } + _unfocus(newTarget) { + } + _focusChange(target, newTarget) { + } + _getFocused() { + return this; + } + _setFocusSettings(settings) { + } + _handleFocusSettings(settings) { + } + static _template() { + return {}; + } + hasFinalFocus() { + let path = this.application._focusPath; + return path && path.length && path[path.length - 1] === this; + } + hasFocus() { + let path = this.application._focusPath; + return path && path.indexOf(this) >= 0; + } + get cparent() { + return Component.getParent(this); + } + seekAncestorByType(type) { + let c = this.cparent; + while (c) { + if (c.constructor === type) { + return c; + } + c = c.cparent; + } + } + getSharedAncestorComponent(element) { + let ancestor = this.getSharedAncestor(element); + while (ancestor && !ancestor.isComponent) { + ancestor = ancestor.parent; + } + return ancestor; + } + get signals() { + return this.__signals; + } + set signals(v) { + if (!Utils$1.isObjectLiteral(v)) { + this._throwError("Signals: specify an object with signal-to-fire mappings"); + } + this.__signals = v; + } + set alterSignals(v) { + if (!Utils$1.isObjectLiteral(v)) { + this._throwError("Signals: specify an object with signal-to-fire mappings"); + } + if (!this.__signals) { + this.__signals = {}; + } + for (let key in v) { + const d = v[key]; + if (d === void 0) { + delete this.__signals[key]; + } else { + this.__signals[key] = v; + } + } + } + get passSignals() { + return this.__passSignals || {}; + } + set passSignals(v) { + this.__passSignals = Object.assign(this.__passSignals || {}, v); + } + set alterPassSignals(v) { + if (!Utils$1.isObjectLiteral(v)) { + this._throwError("Signals: specify an object with signal-to-fire mappings"); + } + if (!this.__passSignals) { + this.__passSignals = {}; + } + for (let key in v) { + const d = v[key]; + if (d === void 0) { + delete this.__passSignals[key]; + } else { + this.__passSignals[key] = v; + } + } + } + signal(event, ...args) { + return this._signal(event, args); + } + _signal(event, args) { + const signalParent = this._getParentSignalHandler(); + if (signalParent) { + if (this.__signals) { + let fireEvent = this.__signals[event]; + if (fireEvent === false) { + return; + } + if (fireEvent) { + if (fireEvent === true) { + fireEvent = event; + } + if (Utils$1.isFunction(fireEvent)) { + return fireEvent(...args); + } + if (signalParent._hasMethod(fireEvent)) { + return signalParent[fireEvent](...args); + } + } + } + let passSignal = this.__passSignals && this.__passSignals[event]; + if (passSignal) { + if (passSignal && passSignal !== true) { + event = passSignal; + } + return signalParent._signal(event, args); + } + } + } + _getParentSignalHandler() { + return this.cparent ? this.cparent._getSignalHandler() : null; + } + _getSignalHandler() { + if (this._signalProxy) { + return this.cparent ? this.cparent._getSignalHandler() : null; + } + return this; + } + get _signalProxy() { + return false; + } + fireAncestors(name, ...args) { + if (!name.startsWith("$")) { + throw new Error("Ancestor event name must be prefixed by dollar sign."); + } + const parent = this._getParentSignalHandler(); + if (parent) { + return parent._doFireAncestors(name, args); + } + } + _doFireAncestors(name, args) { + if (this._hasMethod(name)) { + return this.fire(name, ...args); + } else { + const signalParent = this._getParentSignalHandler(); + if (signalParent) { + return signalParent._doFireAncestors(name, args); + } + } + } + static collectSubComponents(subs, element) { + if (element.hasChildren()) { + const childList = element.__childList; + for (let i = 0, n = childList.length; i < n; i++) { + const child = childList.getAt(i); + if (child.isComponent) { + subs.push(child); + } else { + Component.collectSubComponents(subs, child); + } + } + } + } + static getComponent(element) { + let parent = element; + while (parent && !parent.isComponent) { + parent = parent.parent; + } + return parent; + } + static getParent(element) { + return Component.getComponent(element.parent); + } + } + Component.prototype.isComponent = true; + class CoreQuadList { + constructor(ctx) { + this.ctx = ctx; + this.quadTextures = []; + this.quadElements = []; + } + get length() { + return this.quadTextures.length; + } + reset() { + this.quadTextures = []; + this.quadElements = []; + this.dataLength = 0; + } + getElement(index) { + return this.quadElements[index]._element; + } + getElementCore(index) { + return this.quadElements[index]; + } + getTexture(index) { + return this.quadTextures[index]; + } + getTextureWidth(index) { + let nativeTexture = this.quadTextures[index]; + if (nativeTexture.w) { + return nativeTexture.w; + } else { + return this.quadElements[index]._displayedTextureSource.w; + } + } + getTextureHeight(index) { + let nativeTexture = this.quadTextures[index]; + if (nativeTexture.h) { + return nativeTexture.h; + } else { + return this.quadElements[index]._displayedTextureSource.h; + } + } + } + class WebGLCoreQuadList extends CoreQuadList { + constructor(ctx) { + super(ctx); + const byteSize = ctx.stage.getOption("bufferMemory"); + this.dataLength = 0; + this.data = new ArrayBuffer(byteSize); + this.floats = new Float32Array(this.data); + this.uints = new Uint32Array(this.data); + } + getAttribsDataByteOffset(index) { + return index * 80; + } + getQuadContents() { + let floats = this.floats; + let uints = this.uints; + let lines = []; + for (let i = 1; i <= this.length; i++) { + let str = "entry " + i + ": "; + for (let j = 0; j < 4; j++) { + let b = i * 20 + j * 4; + str += floats[b] + "," + floats[b + 1] + ":" + floats[b + 2] + "," + floats[b + 3] + "[" + uints[b + 4].toString(16) + "] "; + } + lines.push(str); + } + return lines; + } + } + class CoreQuadOperation { + constructor(ctx, shader, shaderOwner, renderTextureInfo, scissor, index) { + this.ctx = ctx; + this.shader = shader; + this.shaderOwner = shaderOwner; + this.renderTextureInfo = renderTextureInfo; + this.scissor = scissor; + this.index = index; + this.length = 0; + } + get quads() { + return this.ctx.renderState.quads; + } + getTexture(index) { + return this.quads.getTexture(this.index + index); + } + getElementCore(index) { + return this.quads.getElementCore(this.index + index); + } + getElement(index) { + return this.quads.getElement(this.index + index); + } + getElementWidth(index) { + return this.getElement(index).renderWidth; + } + getElementHeight(index) { + return this.getElement(index).renderHeight; + } + getTextureWidth(index) { + return this.quads.getTextureWidth(this.index + index); + } + getTextureHeight(index) { + return this.quads.getTextureHeight(this.index + index); + } + getRenderWidth() { + if (this.renderTextureInfo) { + return this.renderTextureInfo.w; + } else { + return this.ctx.stage.w; + } + } + getRenderHeight() { + if (this.renderTextureInfo) { + return this.renderTextureInfo.h; + } else { + return this.ctx.stage.h; + } + } + } + class WebGLCoreQuadOperation extends CoreQuadOperation { + constructor(ctx, shader, shaderOwner, renderTextureInfo, scissor, index) { + super(ctx, shader, shaderOwner, renderTextureInfo, scissor, index); + this.extraAttribsDataByteOffset = 0; + } + getAttribsDataByteOffset(index) { + return this.quads.getAttribsDataByteOffset(this.index + index); + } + getNormalRenderTextureCoords(x, y) { + let coords = this.shaderOwner.getRenderTextureCoords(x, y); + coords[0] /= this.getRenderWidth(); + coords[1] /= this.getRenderHeight(); + coords[0] = coords[0] * 2 - 1; + coords[1] = 1 - coords[1] * 2; + return coords; + } + getProjection() { + if (this.renderTextureInfo === null) { + return this.ctx.renderExec._projection; + } else { + return this.renderTextureInfo.nativeTexture.projection; + } + } + } + class CoreRenderExecutor { + constructor(ctx) { + this.ctx = ctx; + this.renderState = ctx.renderState; + this.gl = this.ctx.stage.gl; + } + destroy() { + this.ctx = null; + this.renderState = null; + this.gl = null; + delete this.ctx; + delete this.renderState; + delete this.gl; + } + _reset() { + this._bindRenderTexture(null); + this._setScissor(null); + this._clearRenderTexture(); + } + execute() { + this._reset(); + let qops = this.renderState.quadOperations; + let i = 0, n = qops.length; + while (i < n) { + this._processQuadOperation(qops[i]); + i++; + } + } + _processQuadOperation(quadOperation) { + if (quadOperation.renderTextureInfo && quadOperation.renderTextureInfo.ignore) { + return; + } + this._setupQuadOperation(quadOperation); + this._execQuadOperation(quadOperation); + } + _setupQuadOperation(quadOperation) { + } + _execQuadOperation(op) { + let nativeTexture = op.renderTextureInfo ? op.renderTextureInfo.nativeTexture : null; + if (this._renderTexture !== nativeTexture) { + this._bindRenderTexture(nativeTexture); + } + if (op.renderTextureInfo && !op.renderTextureInfo.cleared) { + this._setScissor(null); + this._clearRenderTexture(); + op.renderTextureInfo.cleared = true; + this._setScissor(op.scissor); + } else { + this._setScissor(op.scissor); + } + this._renderQuadOperation(op); + } + _renderQuadOperation(op) { + } + _bindRenderTexture(renderTexture) { + this._renderTexture = renderTexture; + } + _clearRenderTexture(renderTexture) { + } + _setScissor(area) { + } + } + class WebGLCoreRenderExecutor extends CoreRenderExecutor { + constructor(ctx) { + super(ctx); + this.gl = this.ctx.stage.gl; + this.init(); + } + init() { + let gl = this.gl; + this._attribsBuffer = gl.createBuffer(); + let maxQuads = Math.floor(this.renderState.quads.data.byteLength / 80); + let allIndices = new Uint16Array(maxQuads * 6); + for (let i = 0, j = 0; i < maxQuads; i += 6, j += 4) { + allIndices[i] = j; + allIndices[i + 1] = j + 1; + allIndices[i + 2] = j + 2; + allIndices[i + 3] = j; + allIndices[i + 4] = j + 2; + allIndices[i + 5] = j + 3; + } + this._quadsBuffer = gl.createBuffer(); + gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this._quadsBuffer); + gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, allIndices, gl.STATIC_DRAW); + this._projection = new Float32Array([2 / this.ctx.stage.coordsWidth, -2 / this.ctx.stage.coordsHeight]); + } + destroy() { + super.destroy(); + this.gl.deleteBuffer(this._attribsBuffer); + this.gl.deleteBuffer(this._quadsBuffer); + this.gl = null; + delete this.gl; + } + _reset() { + super._reset(); + let gl = this.gl; + gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA); + gl.enable(gl.BLEND); + gl.disable(gl.DEPTH_TEST); + this._stopShaderProgram(); + this._setupBuffers(); + } + _setupBuffers() { + let gl = this.gl; + gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this._quadsBuffer); + let element = new Float32Array(this.renderState.quads.data, 0, this.renderState.quads.dataLength); + gl.bindBuffer(gl.ARRAY_BUFFER, this._attribsBuffer); + gl.bufferData(gl.ARRAY_BUFFER, element, gl.DYNAMIC_DRAW); + } + _setupQuadOperation(quadOperation) { + super._setupQuadOperation(quadOperation); + this._useShaderProgram(quadOperation.shader, quadOperation); + } + _renderQuadOperation(op) { + let shader = op.shader; + if (op.length || op.shader.addEmpty()) { + shader.beforeDraw(op); + shader.draw(op); + shader.afterDraw(op); + } + } + _useShaderProgram(shader, operation) { + if (!shader.hasSameProgram(this._currentShaderProgram)) { + if (this._currentShaderProgram) { + this._currentShaderProgram.stopProgram(); + } + shader.useProgram(); + this._currentShaderProgram = shader; + } + shader.setupUniforms(operation); + } + _stopShaderProgram() { + if (this._currentShaderProgram) { + this._currentShaderProgram.stopProgram(); + this._currentShaderProgram = null; + } + } + _bindRenderTexture(renderTexture) { + super._bindRenderTexture(renderTexture); + let gl = this.gl; + if (!this._renderTexture) { + gl.bindFramebuffer(gl.FRAMEBUFFER, null); + gl.viewport(0, 0, this.ctx.stage.w, this.ctx.stage.h); + } else { + gl.bindFramebuffer(gl.FRAMEBUFFER, this._renderTexture.framebuffer); + gl.viewport(0, 0, this._renderTexture.w, this._renderTexture.h); + } + } + _clearRenderTexture() { + super._clearRenderTexture(); + let gl = this.gl; + if (!this._renderTexture) { + let glClearColor = this.ctx.stage.getClearColor(); + if (glClearColor) { + gl.clearColor(glClearColor[0] * glClearColor[3], glClearColor[1] * glClearColor[3], glClearColor[2] * glClearColor[3], glClearColor[3]); + gl.clear(gl.COLOR_BUFFER_BIT); + } + } else { + gl.clearColor(0, 0, 0, 0); + gl.clear(gl.COLOR_BUFFER_BIT); + } + } + _setScissor(area) { + super._setScissor(area); + if (this._scissor === area) { + return; + } + this._scissor = area; + let gl = this.gl; + if (!area) { + gl.disable(gl.SCISSOR_TEST); + } else { + gl.enable(gl.SCISSOR_TEST); + let precision = this.ctx.stage.getRenderPrecision(); + let y = area[1]; + if (this._renderTexture === null) { + y = this.ctx.stage.h / precision - (area[1] + area[3]); + } + gl.scissor(Math.round(area[0] * precision), Math.round(y * precision), Math.round(area[2] * precision), Math.round(area[3] * precision)); + } + } + } + class CoreRenderState { + constructor(ctx) { + this.ctx = ctx; + this.stage = ctx.stage; + this.defaultShader = this.stage.renderer.getDefaultShader(ctx); + this.renderer = ctx.stage.renderer; + this.quads = this.renderer.createCoreQuadList(ctx); + } + reset() { + this._renderTextureInfo = null; + this._scissor = null; + this._shader = null; + this._shaderOwner = null; + this._realShader = null; + this._check = false; + this.quadOperations = []; + this._texturizer = null; + this._texturizerTemporary = false; + this._quadOperation = null; + this.quads.reset(); + this._temporaryTexturizers = []; + this._isCachingTexturizer = false; + } + get length() { + return this.quads.quadTextures.length; + } + setShader(shader, owner) { + if (this._shaderOwner !== owner || this._realShader !== shader) { + this._realShader = shader; + if (shader.useDefault()) { + shader = this.defaultShader; + } + if (this._shader !== shader || this._shaderOwner !== owner) { + this._shader = shader; + this._shaderOwner = owner; + this._check = true; + } + } + } + get renderTextureInfo() { + return this._renderTextureInfo; + } + setScissor(area) { + if (this._scissor !== area) { + if (area) { + this._scissor = area; + } else { + this._scissor = null; + } + this._check = true; + } + } + getScissor() { + return this._scissor; + } + setRenderTextureInfo(renderTextureInfo) { + if (this._renderTextureInfo !== renderTextureInfo) { + this._renderTextureInfo = renderTextureInfo; + this._scissor = null; + this._check = true; + } + } + setTexturizer(texturizer, cache = false) { + this._texturizer = texturizer; + this._cacheTexturizer = cache; + } + set isCachingTexturizer(v) { + this._isCachingTexturizer = v; + } + get isCachingTexturizer() { + return this._isCachingTexturizer; + } + addQuad(elementCore) { + if (!this._quadOperation) { + this._createQuadOperation(); + } else if (this._check && this._hasChanges()) { + this._finishQuadOperation(); + this._check = false; + } + let nativeTexture = null; + if (this._texturizer) { + nativeTexture = this._texturizer.getResultTexture(); + if (!this._cacheTexturizer) { + this._temporaryTexturizers.push(this._texturizer); + } + } + if (!nativeTexture) { + nativeTexture = elementCore._displayedTextureSource.nativeTexture; + } + if (this._renderTextureInfo) { + if (this._shader === this.defaultShader && this._renderTextureInfo.empty) { + this._renderTextureInfo.nativeTexture = nativeTexture; + this._renderTextureInfo.offset = this.length; + } else { + this._renderTextureInfo.nativeTexture = null; + } + this._renderTextureInfo.empty = false; + } + this.quads.quadTextures.push(nativeTexture); + this.quads.quadElements.push(elementCore); + this._quadOperation.length++; + this.renderer.addQuad(this, this.quads, this.length - 1); + } + finishedRenderTexture() { + if (this._renderTextureInfo.nativeTexture) { + if (!this._isRenderTextureReusable()) { + this._renderTextureInfo.nativeTexture = null; + } + } + } + _isRenderTextureReusable() { + const offset = this._renderTextureInfo.offset; + return this.quads.quadTextures[offset].w === this._renderTextureInfo.w && this.quads.quadTextures[offset].h === this._renderTextureInfo.h && this.renderer.isRenderTextureReusable(this, this._renderTextureInfo); + } + _hasChanges() { + let q = this._quadOperation; + if (this._shader !== q.shader) + return true; + if (this._shaderOwner !== q.shaderOwner) + return true; + if (this._renderTextureInfo !== q.renderTextureInfo) + return true; + if (this._scissor !== q.scissor) { + if (this._scissor[0] !== q.scissor[0] || this._scissor[1] !== q.scissor[1] || this._scissor[2] !== q.scissor[2] || this._scissor[3] !== q.scissor[3]) { + return true; + } + } + return false; + } + _finishQuadOperation(create = true) { + if (this._quadOperation) { + if (this._quadOperation.length || this._shader.addEmpty()) { + if (!this._quadOperation.scissor || this._quadOperation.scissor[2] > 0 && this._quadOperation.scissor[3] > 0) { + this.quadOperations.push(this._quadOperation); + } + } + if (this._temporaryTexturizers.length) { + for (let i = 0, n = this._temporaryTexturizers.length; i < n; i++) { + this._temporaryTexturizers[i].releaseRenderTexture(); + } + this._temporaryTexturizers = []; + } + this._quadOperation = null; + } + if (create) { + this._createQuadOperation(); + } + } + _createQuadOperation() { + this._quadOperation = this.renderer.createCoreQuadOperation( + this.ctx, + this._shader, + this._shaderOwner, + this._renderTextureInfo, + this._scissor, + this.length + ); + this._check = false; + } + finish() { + if (this._quadOperation) { + this._finishQuadOperation(false); + } + this.renderer.finishRenderState(this); + } + } + class WebGLShaderProgram { + constructor(vertexShaderSource, fragmentShaderSource) { + this.vertexShaderSource = vertexShaderSource; + this.fragmentShaderSource = fragmentShaderSource; + this._program = null; + this.gl = null; + this._uniformLocations = /* @__PURE__ */ new Map(); + this._attributeLocations = /* @__PURE__ */ new Map(); + this._currentUniformValues = {}; + } + compile(gl) { + if (this._program) + return; + this.gl = gl; + this._program = gl.createProgram(); + let glVertShader = this._glCompile(gl.VERTEX_SHADER, this.vertexShaderSource); + let glFragShader = this._glCompile(gl.FRAGMENT_SHADER, this.fragmentShaderSource); + gl.attachShader(this._program, glVertShader); + gl.attachShader(this._program, glFragShader); + gl.linkProgram(this._program); + if (!gl.getProgramParameter(this._program, gl.LINK_STATUS)) { + console.error("[Lightning] Error: Could not initialize shader."); + console.error("[Lightning] gl.VALIDATE_STATUS", gl.getProgramParameter(this._program, gl.VALIDATE_STATUS)); + console.error("[Lightning] gl.getError()", gl.getError()); + if (gl.getProgramInfoLog(this._program) !== "") { + console.warn("[Lightning] Warning: gl.getProgramInfoLog()", gl.getProgramInfoLog(this._program)); + } + gl.deleteProgram(this._program); + this._program = null; + } + gl.deleteShader(glVertShader); + gl.deleteShader(glFragShader); + } + _glCompile(type, src) { + let shader = this.gl.createShader(type); + this.gl.shaderSource(shader, src); + this.gl.compileShader(shader); + if (!this.gl.getShaderParameter(shader, this.gl.COMPILE_STATUS)) { + console.error("[Lightning]", this.constructor.name, "Type: " + (type === this.gl.VERTEX_SHADER ? "vertex shader" : "fragment shader")); + console.error("[Lightning]", this.gl.getShaderInfoLog(shader)); + let idx = 0; + console.error("[Lightning]", "========== source ==========\n" + src.split("\n").map((line) => "" + ++idx + ": " + line).join("\n")); + return null; + } + return shader; + } + getUniformLocation(name) { + let location = this._uniformLocations.get(name); + if (location === void 0) { + location = this.gl.getUniformLocation(this._program, name); + this._uniformLocations.set(name, location); + } + return location; + } + getAttribLocation(name) { + let location = this._attributeLocations.get(name); + if (location === void 0) { + location = this.gl.getAttribLocation(this._program, name); + this._attributeLocations.set(name, location); + } + return location; + } + destroy() { + if (this._program) { + this.gl.deleteProgram(this._program); + } + this._attributeLocations = null; + this._currentUniformValues = null; + this.fragmentShaderSource = null; + this._program = null; + this.gl = null; + this._uniformLocations = null; + this.vertexShaderSource = null; + delete this.vertexShaderSource; + delete this._program; + delete this._currentUniformValues; + delete this.fragmentShaderSource; + delete this.gl; + delete this._uniformLocations; + delete this._attributeLocations; + } + get glProgram() { + return this._program; + } + get compiled() { + return !!this._program; + } + _valueEquals(v1, v2) { + if (v1.length && v2.length) { + for (let i = 0, n = v1.length; i < n; i++) { + if (v1[i] !== v2[i]) + return false; + } + return true; + } else { + return v1 === v2; + } + } + _valueClone(v) { + if (v.length) { + return v.slice(0); + } else { + return v; + } + } + setUniformValue(name, value, glFunction) { + let v = this._currentUniformValues[name]; + if (v === void 0 || !this._valueEquals(v, value)) { + let clonedValue = this._valueClone(value); + this._currentUniformValues[name] = clonedValue; + let loc = this.getUniformLocation(name); + if (loc) { + let isMatrix = glFunction === this.gl.uniformMatrix2fv || glFunction === this.gl.uniformMatrix3fv || glFunction === this.gl.uniformMatrix4fv; + if (isMatrix) { + glFunction.call(this.gl, loc, false, clonedValue); + } else { + glFunction.call(this.gl, loc, clonedValue); + } + } + } + } + } + class WebGLShader extends Shader { + constructor(ctx) { + super(ctx); + const stage = ctx.stage; + this._program = stage.renderer.shaderPrograms.get(this.constructor); + if (!this._program) { + this._program = new WebGLShaderProgram(this.constructor.vertexShaderSource, this.constructor.fragmentShaderSource); + stage.renderer.shaderPrograms.set(this.constructor, this._program); + } + this.gl = stage.gl; + } + get glProgram() { + return this._program.glProgram; + } + _init() { + if (!this._initialized) { + this.initialize(); + this._initialized = true; + } + } + initialize() { + this._program.compile(this.gl); + } + get initialized() { + return this._initialized; + } + _uniform(name) { + return this._program.getUniformLocation(name); + } + _attrib(name) { + return this._program.getAttribLocation(name); + } + _setUniform(name, value, glFunction) { + this._program.setUniformValue(name, value, glFunction); + } + useProgram() { + this._init(); + this.gl.useProgram(this.glProgram); + this.beforeUsage(); + this.enableAttribs(); + } + stopProgram() { + this.afterUsage(); + this.disableAttribs(); + } + hasSameProgram(other) { + return other && (other === this || other._program === this._program); + } + beforeUsage() { + } + afterUsage() { + } + enableAttribs() { + } + disableAttribs() { + } + getExtraAttribBytesPerVertex() { + return 0; + } + getVertexAttribPointerOffset(operation) { + return operation.extraAttribsDataByteOffset - operation.index * 4 * this.getExtraAttribBytesPerVertex(); + } + setExtraAttribsInBuffer(operation) { + } + setupUniforms(operation) { + } + _getProjection(operation) { + return operation.getProjection(); + } + getFlipY(operation) { + return this._getProjection(operation)[1] < 0; + } + beforeDraw(operation) { + } + draw(operation) { + } + afterDraw(operation) { + } + cleanup() { + this._initialized = false; + } + } + let DefaultShader$1 = class DefaultShader extends WebGLShader { + enableAttribs() { + let gl = this.gl; + gl.vertexAttribPointer(this._attrib("aVertexPosition"), 2, gl.FLOAT, false, 20, 0); + gl.enableVertexAttribArray(this._attrib("aVertexPosition")); + if (this._attrib("aTextureCoord") !== -1) { + gl.vertexAttribPointer(this._attrib("aTextureCoord"), 2, gl.FLOAT, false, 20, 2 * 4); + gl.enableVertexAttribArray(this._attrib("aTextureCoord")); + } + if (this._attrib("aColor") !== -1) { + gl.vertexAttribPointer(this._attrib("aColor"), 4, gl.UNSIGNED_BYTE, true, 20, 4 * 4); + gl.enableVertexAttribArray(this._attrib("aColor")); + } + } + disableAttribs() { + let gl = this.gl; + gl.disableVertexAttribArray(this._attrib("aVertexPosition")); + if (this._attrib("aTextureCoord") !== -1) { + gl.disableVertexAttribArray(this._attrib("aTextureCoord")); + } + if (this._attrib("aColor") !== -1) { + gl.disableVertexAttribArray(this._attrib("aColor")); + } + } + setupUniforms(operation) { + this._setUniform("projection", this._getProjection(operation), this.gl.uniform2fv, false); + } + draw(operation) { + let gl = this.gl; + let length = operation.length; + if (length) { + let glTexture = operation.getTexture(0); + let pos = 0; + for (let i = 0; i < length; i++) { + let tx = operation.getTexture(i); + if (glTexture !== tx) { + gl.bindTexture(gl.TEXTURE_2D, glTexture); + gl.drawElements(gl.TRIANGLES, 6 * (i - pos), gl.UNSIGNED_SHORT, (pos + operation.index) * 6 * 2); + glTexture = tx; + pos = i; + } + } + gl.bindTexture(gl.TEXTURE_2D, glTexture); + gl.drawElements(gl.TRIANGLES, 6 * (length - pos), gl.UNSIGNED_SHORT, (pos + operation.index) * 6 * 2); + } + } + }; + DefaultShader$1.vertexShaderSource = ` + #ifdef GL_ES + # ifdef GL_FRAGMENT_PRECISION_HIGH + precision highp float; + # else + precision lowp float; + # endif + #endif + attribute vec2 aVertexPosition; + attribute vec2 aTextureCoord; + attribute vec4 aColor; + uniform vec2 projection; + varying vec2 vTextureCoord; + varying vec4 vColor; + void main(void){ + gl_Position = vec4(aVertexPosition.x * projection.x - 1.0, aVertexPosition.y * -abs(projection.y) + 1.0, 0.0, 1.0); + vTextureCoord = aTextureCoord; + vColor = aColor; + gl_Position.y = -sign(projection.y) * gl_Position.y; + } +`; + DefaultShader$1.fragmentShaderSource = ` + #ifdef GL_ES + # ifdef GL_FRAGMENT_PRECISION_HIGH + precision highp float; + # else + precision lowp float; + # endif + #endif + varying vec2 vTextureCoord; + varying vec4 vColor; + uniform sampler2D uSampler; + void main(void){ + gl_FragColor = texture2D(uSampler, vTextureCoord) * vColor; + } +`; + class Renderer { + constructor(stage) { + this.stage = stage; + this._defaultShader = void 0; + } + gc(aggressive) { + } + destroy() { + } + getDefaultShader(ctx = this.stage.ctx) { + if (!this._defaultShader) { + this._defaultShader = this._createDefaultShader(ctx); + } + return this._defaultShader; + } + _createDefaultShader(ctx) { + } + isValidShaderType(shaderType) { + return shaderType.prototype instanceof this._getShaderBaseType(); + } + createShader(ctx, settings) { + const shaderType = settings.type; + if (!this.isValidShaderType(shaderType)) { + const convertedShaderType = this._getShaderAlternative(shaderType); + if (!convertedShaderType) { + console.warn("[Lightning] Shader has no implementation for render target: " + shaderType.name); + return this._createDefaultShader(ctx); + } + return new convertedShaderType(ctx); + } else { + const shader = new shaderType(ctx); + Base.patchObject(this, settings); + return shader; + } + } + _getShaderBaseType() { + } + _getShaderAlternative(shaderType) { + return this.getDefaultShader(); + } + copyRenderTexture(renderTexture, nativeTexture, options) { + console.warn("[Lightning] copyRenderTexture not supported by renderer"); + } + } + class WebGLRenderer extends Renderer { + constructor(stage) { + super(stage); + this.shaderPrograms = /* @__PURE__ */ new Map(); + this._compressedTextureExtensions = { + astc: stage.gl.getExtension("WEBGL_compressed_texture_astc"), + etc1: stage.gl.getExtension("WEBGL_compressed_texture_etc1"), + s3tc: stage.gl.getExtension("WEBGL_compressed_texture_s3tc"), + pvrtc: stage.gl.getExtension("WEBGL_compressed_texture_pvrtc") + }; + } + getCompressedTextureExtensions() { + return this._compressedTextureExtensions; + } + destroy() { + this.shaderPrograms.forEach((shaderProgram) => shaderProgram.destroy()); + this.shaderPrograms = null; + this._compressedTextureExtensions = null; + delete this.shaderPrograms; + delete this._compressedTextureExtensions; + } + _createDefaultShader(ctx) { + return new DefaultShader$1(ctx); + } + _getShaderBaseType() { + return WebGLShader; + } + _getShaderAlternative(shaderType) { + return shaderType.getWebGL && shaderType.getWebGL(); + } + createCoreQuadList(ctx) { + return new WebGLCoreQuadList(ctx); + } + createCoreQuadOperation(ctx, shader, shaderOwner, renderTextureInfo, scissor, index) { + return new WebGLCoreQuadOperation(ctx, shader, shaderOwner, renderTextureInfo, scissor, index); + } + createCoreRenderExecutor(ctx) { + return new WebGLCoreRenderExecutor(ctx); + } + createCoreRenderState(ctx) { + return new CoreRenderState(ctx); + } + createRenderTexture(w, h, pw, ph) { + const gl = this.stage.gl; + const glTexture = gl.createTexture(); + gl.bindTexture(gl.TEXTURE_2D, glTexture); + gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, pw, ph, 0, gl.RGBA, gl.UNSIGNED_BYTE, null); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); + glTexture.params = {}; + glTexture.params[gl.TEXTURE_MAG_FILTER] = gl.LINEAR; + glTexture.params[gl.TEXTURE_MIN_FILTER] = gl.LINEAR; + glTexture.params[gl.TEXTURE_WRAP_S] = gl.CLAMP_TO_EDGE; + glTexture.params[gl.TEXTURE_WRAP_T] = gl.CLAMP_TO_EDGE; + glTexture.options = { format: gl.RGBA, internalFormat: gl.RGBA, type: gl.UNSIGNED_BYTE }; + glTexture.framebuffer = gl.createFramebuffer(); + glTexture.projection = new Float32Array([2 / w, 2 / h]); + gl.bindFramebuffer(gl.FRAMEBUFFER, glTexture.framebuffer); + gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, glTexture, 0); + return glTexture; + } + freeRenderTexture(glTexture) { + let gl = this.stage.gl; + gl.deleteFramebuffer(glTexture.framebuffer); + gl.deleteTexture(glTexture); + } + _getBytesPerPixel(fmt, type) { + const gl = this.stage.gl; + if (fmt === gl.RGBA) { + switch (type) { + case gl.UNSIGNED_BYTE: + return 4; + case gl.UNSIGNED_SHORT_4_4_4_4: + return 2; + case gl.UNSIGNED_SHORT_5_5_5_1: + return 2; + default: + throw new Error("Invalid type specified for GL_RGBA format"); + } + } else if (fmt === gl.RGB) { + switch (type) { + case gl.UNSIGNED_BYTE: + return 3; + case gl.UNSIGNED_BYTE_5_6_5: + return 2; + default: + throw new Error("Invalid type specified for GL_RGB format"); + } + } else { + throw new Error("Invalid format specified in call to _getBytesPerPixel()"); + } + } + uploadTextureSource(textureSource, options) { + const gl = this.stage.gl; + const source = options.source; + let compressed = false; + if (options.renderInfo) { + compressed = options.renderInfo.compressed || false; + } + const format = { + premultiplyAlpha: true, + hasAlpha: true + }; + if (options && options.hasOwnProperty("premultiplyAlpha")) { + format.premultiplyAlpha = options.premultiplyAlpha; + } + if (options && options.hasOwnProperty("flipBlueRed")) { + format.flipBlueRed = options.flipBlueRed; + } + if (options && options.hasOwnProperty("hasAlpha")) { + format.hasAlpha = options.hasAlpha; + } + if (!format.hasAlpha) { + format.premultiplyAlpha = false; + } + format.texParams = options.texParams || {}; + format.texOptions = options.texOptions || {}; + let glTexture = gl.createTexture(); + gl.bindTexture(gl.TEXTURE_2D, glTexture); + gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, format.premultiplyAlpha); + if (Utils$1.isNode) { + gl.pixelStorei(gl.UNPACK_FLIP_BLUE_RED, !!format.flipBlueRed); + } + const texParams = format.texParams; + if (!texParams[gl.TEXTURE_MAG_FILTER]) + texParams[gl.TEXTURE_MAG_FILTER] = gl.LINEAR; + if (!texParams[gl.TEXTURE_MIN_FILTER]) + texParams[gl.TEXTURE_MIN_FILTER] = gl.LINEAR; + if (!texParams[gl.TEXTURE_WRAP_S]) + texParams[gl.TEXTURE_WRAP_S] = gl.CLAMP_TO_EDGE; + if (!texParams[gl.TEXTURE_WRAP_T]) + texParams[gl.TEXTURE_WRAP_T] = gl.CLAMP_TO_EDGE; + Object.keys(texParams).forEach((key) => { + const value = texParams[key]; + gl.texParameteri(gl.TEXTURE_2D, parseInt(key), value); + }); + if (compressed) { + this.stage.platform.uploadCompressedGlTexture(gl, textureSource, source); + return glTexture; + } + const texOptions = format.texOptions; + texOptions.format = texOptions.format || (format.hasAlpha ? gl.RGBA : gl.RGB); + texOptions.type = texOptions.type || gl.UNSIGNED_BYTE; + texOptions.internalFormat = texOptions.internalFormat || texOptions.format; + if (options && options.imageRef) { + texOptions.imageRef = options.imageRef; + } + this.stage.platform.uploadGlTexture(gl, textureSource, source, texOptions); + glTexture.params = Utils$1.cloneObjShallow(texParams); + glTexture.options = Utils$1.cloneObjShallow(texOptions); + glTexture.bytesPerPixel = this._getBytesPerPixel(texOptions.format, texOptions.type); + return glTexture; + } + freeTextureSource(textureSource) { + this.stage.gl.deleteTexture(textureSource.nativeTexture); + } + addQuad(renderState, quads, index) { + let offset = index * 20; + const elementCore = quads.quadElements[index]; + let r = elementCore._renderContext; + let floats = renderState.quads.floats; + let uints = renderState.quads.uints; + const mca = StageUtils.mergeColorAlpha; + if (r.tb !== 0 || r.tc !== 0) { + floats[offset++] = r.px; + floats[offset++] = r.py; + floats[offset++] = elementCore._ulx; + floats[offset++] = elementCore._uly; + uints[offset++] = mca(elementCore._colorUl, r.alpha); + floats[offset++] = r.px + elementCore._w * r.ta; + floats[offset++] = r.py + elementCore._w * r.tc; + floats[offset++] = elementCore._brx; + floats[offset++] = elementCore._uly; + uints[offset++] = mca(elementCore._colorUr, r.alpha); + floats[offset++] = r.px + elementCore._w * r.ta + elementCore._h * r.tb; + floats[offset++] = r.py + elementCore._w * r.tc + elementCore._h * r.td; + floats[offset++] = elementCore._brx; + floats[offset++] = elementCore._bry; + uints[offset++] = mca(elementCore._colorBr, r.alpha); + floats[offset++] = r.px + elementCore._h * r.tb; + floats[offset++] = r.py + elementCore._h * r.td; + floats[offset++] = elementCore._ulx; + floats[offset++] = elementCore._bry; + uints[offset] = mca(elementCore._colorBl, r.alpha); + } else { + let cx = r.px + elementCore._w * r.ta; + let cy = r.py + elementCore._h * r.td; + floats[offset++] = r.px; + floats[offset++] = r.py; + floats[offset++] = elementCore._ulx; + floats[offset++] = elementCore._uly; + uints[offset++] = mca(elementCore._colorUl, r.alpha); + floats[offset++] = cx; + floats[offset++] = r.py; + floats[offset++] = elementCore._brx; + floats[offset++] = elementCore._uly; + uints[offset++] = mca(elementCore._colorUr, r.alpha); + floats[offset++] = cx; + floats[offset++] = cy; + floats[offset++] = elementCore._brx; + floats[offset++] = elementCore._bry; + uints[offset++] = mca(elementCore._colorBr, r.alpha); + floats[offset++] = r.px; + floats[offset++] = cy; + floats[offset++] = elementCore._ulx; + floats[offset++] = elementCore._bry; + uints[offset] = mca(elementCore._colorBl, r.alpha); + } + } + isRenderTextureReusable(renderState, renderTextureInfo) { + let offset = renderState._renderTextureInfo.offset * 80 / 4; + let floats = renderState.quads.floats; + let uints = renderState.quads.uints; + return floats[offset] === 0 && floats[offset + 1] === 0 && floats[offset + 2] === 0 && floats[offset + 3] === 0 && uints[offset + 4] === 4294967295 && floats[offset + 5] === renderTextureInfo.w && floats[offset + 6] === 0 && floats[offset + 7] === 1 && floats[offset + 8] === 0 && uints[offset + 9] === 4294967295 && floats[offset + 10] === renderTextureInfo.w && floats[offset + 11] === renderTextureInfo.h && floats[offset + 12] === 1 && floats[offset + 13] === 1 && uints[offset + 14] === 4294967295 && floats[offset + 15] === 0 && floats[offset + 16] === renderTextureInfo.h && floats[offset + 17] === 0 && floats[offset + 18] === 1 && uints[offset + 19] === 4294967295; + } + finishRenderState(renderState) { + let offset = renderState.length * 80; + for (let i = 0, n = renderState.quadOperations.length; i < n; i++) { + renderState.quadOperations[i].extraAttribsDataByteOffset = offset; + let extra = renderState.quadOperations[i].shader.getExtraAttribBytesPerVertex() * 4 * renderState.quadOperations[i].length; + offset += extra; + if (extra) { + renderState.quadOperations[i].shader.setExtraAttribsInBuffer(renderState.quadOperations[i], renderState.quads); + } + } + renderState.quads.dataLength = offset; + } + copyRenderTexture(renderTexture, nativeTexture, options) { + const gl = this.stage.gl; + gl.bindTexture(gl.TEXTURE_2D, nativeTexture); + gl.bindFramebuffer(gl.FRAMEBUFFER, renderTexture.framebuffer); + const precision = renderTexture.precision; + gl.copyTexSubImage2D( + gl.TEXTURE_2D, + 0, + precision * (options.sx || 0), + precision * (options.sy || 0), + precision * (options.x || 0), + precision * (options.y || 0), + precision * (options.w || renderTexture.ow), + precision * (options.h || renderTexture.oh) + ); + } + } + class C2dCoreQuadList extends CoreQuadList { + constructor(ctx) { + super(ctx); + this.renderContexts = []; + this.modes = []; + } + setRenderContext(index, v) { + this.renderContexts[index] = v; + } + setSimpleTc(index, v) { + if (v) { + this.modes[index] |= 1; + } else { + this.modes[index] -= this.modes[index] & 1; + } + } + setWhite(index, v) { + if (v) { + this.modes[index] |= 2; + } else { + this.modes[index] -= this.modes[index] & 2; + } + } + getRenderContext(index) { + return this.renderContexts[index]; + } + getSimpleTc(index) { + return this.modes[index] & 1; + } + getWhite(index) { + return this.modes[index] & 2; + } + } + class C2dCoreQuadOperation extends CoreQuadOperation { + getRenderContext(index) { + return this.quads.getRenderContext(this.index + index); + } + getSimpleTc(index) { + return this.quads.getSimpleTc(this.index + index); + } + getWhite(index) { + return this.quads.getWhite(this.index + index); + } + } + class C2dCoreRenderExecutor extends CoreRenderExecutor { + init() { + this._mainRenderTexture = this.ctx.stage.getCanvas(); + } + _renderQuadOperation(op) { + let shader = op.shader; + if (op.length || op.shader.addEmpty()) { + const target = this._renderTexture || this._mainRenderTexture; + shader.beforeDraw(op, target); + shader.draw(op, target); + shader.afterDraw(op, target); + } + } + _clearRenderTexture() { + const ctx = this._getContext(); + let clearColor = [0, 0, 0, 0]; + if (this._mainRenderTexture.ctx === ctx) { + clearColor = this.ctx.stage.getClearColor(); + } + const renderTexture = ctx.canvas; + ctx.setTransform(1, 0, 0, 1, 0, 0); + if (!clearColor[0] && !clearColor[1] && !clearColor[2] && !clearColor[3]) { + ctx.clearRect(0, 0, renderTexture.width, renderTexture.height); + } else { + ctx.fillStyle = StageUtils.getRgbaStringFromArray(clearColor); + ctx.globalCompositeOperation = "copy"; + ctx.beginPath(); + ctx.rect(0, 0, renderTexture.width, renderTexture.height); + ctx.closePath(); + ctx.fill(); + ctx.globalCompositeOperation = "source-over"; + } + } + _getContext() { + if (this._renderTexture) { + return this._renderTexture.ctx; + } else { + return this._mainRenderTexture.ctx; + } + } + _restoreContext() { + const ctx = this._getContext(); + ctx.restore(); + ctx.save(); + ctx._scissor = null; + } + _setScissor(area) { + const ctx = this._getContext(); + if (!C2dCoreRenderExecutor._equalScissorAreas(ctx.canvas, ctx._scissor, area)) { + this._restoreContext(); + let precision = this.ctx.stage.getRenderPrecision(); + if (area) { + ctx.beginPath(); + ctx.rect(Math.round(area[0] * precision), Math.round(area[1] * precision), Math.round(area[2] * precision), Math.round(area[3] * precision)); + ctx.closePath(); + ctx.clip(); + } + ctx._scissor = area; + } + } + static _equalScissorAreas(canvas, area, current) { + if (!area) { + area = [0, 0, canvas.width, canvas.height]; + } + if (!current) { + current = [0, 0, canvas.width, canvas.height]; + } + return Utils$1.equalValues(area, current); + } + } + class C2dShader extends Shader { + beforeDraw(operation) { + } + draw(operation) { + } + afterDraw(operation) { + } + } + class DefaultShader extends C2dShader { + constructor(ctx) { + super(ctx); + this._rectangleTexture = ctx.stage.rectangleTexture.source.nativeTexture; + this._tintManager = this.ctx.stage.renderer.tintManager; + } + draw(operation, target) { + const ctx = target.ctx; + let length = operation.length; + for (let i = 0; i < length; i++) { + const tx = operation.getTexture(i); + const vc = operation.getElementCore(i); + const rc = operation.getRenderContext(i); + const white = operation.getWhite(i); + const stc = operation.getSimpleTc(i); + const precision = this.ctx.stage.getRenderPrecision(); + ctx.setTransform(rc.ta * precision, rc.tc * precision, rc.tb * precision, rc.td * precision, rc.px * precision, rc.py * precision); + const rect = tx === this._rectangleTexture; + const info = { operation, target, index: i, rect }; + if (rect) { + if (white) { + ctx.fillStyle = "white"; + } else { + this._setColorGradient(ctx, vc); + } + ctx.globalAlpha = rc.alpha; + this._beforeDrawEl(info); + ctx.fillRect(0, 0, vc.w, vc.h); + this._afterDrawEl(info); + ctx.globalAlpha = 1; + } else { + ctx.globalAlpha = rc.alpha; + this._beforeDrawEl(info); + const sourceX = stc ? 0 : vc._ulx * tx.w; + const sourceY = stc ? 0 : vc._uly * tx.h; + const sourceW = (stc ? 1 : vc._brx - vc._ulx) * tx.w; + const sourceH = (stc ? 1 : vc._bry - vc._uly) * tx.h; + let colorize = !white; + if (colorize) { + let color = vc._colorUl; + if (vc._colorUl !== vc._colorUr || vc._colorUr !== vc._colorBl || vc._colorBr !== vc._colorBl) { + color = StageUtils.mergeMultiColorsEqual([vc._colorUl, vc._colorUr, vc._colorBl, vc._colorBr]); + } + const alpha = (color / 16777216 | 0) / 255; + ctx.globalAlpha *= alpha; + const rgb = color & 16777215; + const tintTexture = this._tintManager.getTintTexture(tx, rgb); + ctx.fillStyle = "white"; + ctx.drawImage(tintTexture, sourceX, sourceY, sourceW, sourceH, 0, 0, vc.w, vc.h); + } else { + ctx.fillStyle = "white"; + ctx.drawImage(tx, sourceX, sourceY, sourceW, sourceH, 0, 0, vc.w, vc.h); + } + this._afterDrawEl(info); + ctx.globalAlpha = 1; + } + } + } + _setColorGradient(ctx, vc, w = vc.w, h = vc.h, transparency = true) { + let color = vc._colorUl; + let gradient; + if (vc._colorUl === vc._colorUr) { + if (vc._colorBl === vc._colorBr) { + if (vc._colorUl === vc.colorBl) + ; + else { + gradient = ctx.createLinearGradient(0, 0, 0, h); + if (transparency) { + gradient.addColorStop(0, StageUtils.getRgbaString(vc._colorUl)); + gradient.addColorStop(1, StageUtils.getRgbaString(vc._colorBl)); + } else { + gradient.addColorStop(0, StageUtils.getRgbString(vc._colorUl)); + gradient.addColorStop(1, StageUtils.getRgbString(vc._colorBl)); + } + } + } + } else { + if (vc._colorUl === vc._colorBl && vc._colorUr === vc._colorBr) { + gradient = ctx.createLinearGradient(0, 0, w, 0); + if (transparency) { + gradient.addColorStop(0, StageUtils.getRgbaString(vc._colorUl)); + gradient.addColorStop(1, StageUtils.getRgbaString(vc._colorBr)); + } else { + gradient.addColorStop(0, StageUtils.getRgbString(vc._colorUl)); + gradient.addColorStop(1, StageUtils.getRgbString(vc._colorBr)); + } + } + } + if (gradient) { + ctx.fillStyle = gradient; + } else { + ctx.fillStyle = transparency ? StageUtils.getRgbaString(color) : StageUtils.getRgbString(color); + } + } + _beforeDrawEl(info) { + } + _afterDrawEl(info) { + } + } + class C2dTextureTintManager { + constructor(stage) { + this.stage = stage; + this._usedMemory = 0; + this._cachedNativeTextures = /* @__PURE__ */ new Set(); + } + destroy() { + this.gc(true); + this.stage = null; + delete this.stage; + } + _addMemoryUsage(delta) { + this._usedMemory += delta; + this.stage.addMemoryUsage(delta); + } + delete(nativeTexture) { + if (this._hasCache(nativeTexture)) { + const cache = this._getCache(nativeTexture); + const prevMemUsage = cache.memoryUsage; + cache.clear(); + this._cachedNativeTextures.delete(nativeTexture); + this._addMemoryUsage(cache.memoryUsage - prevMemUsage); + } + } + getTintTexture(nativeTexture, color) { + const frame = this.stage.frameCounter; + this._cachedNativeTextures.add(nativeTexture); + const cache = this._getCache(nativeTexture); + const item = cache.get(color); + item.lf = frame; + if (item.tx) { + if (nativeTexture.update > item.u) { + this._tintTexture(item.tx, nativeTexture, color); + } + return item.tx; + } else { + const before = cache.memoryUsage; + let target = cache.reuseTexture(frame); + if (target) { + target.ctx.clearRect(0, 0, target.width, target.height); + } else { + target = document.createElement("canvas"); + target.width = nativeTexture.w; + target.height = nativeTexture.h; + target.ctx = target.getContext("2d"); + } + this._tintTexture(target, nativeTexture, color); + cache.set(color, target, frame); + const after = cache.memoryUsage; + if (after !== before) { + this._addMemoryUsage(after - before); + } + return target; + } + } + _tintTexture(target, source, color) { + let col = color.toString(16); + while (col.length < 6) { + col = "0" + col; + } + target.ctx.fillStyle = "#" + col; + target.ctx.globalCompositeOperation = "copy"; + target.ctx.fillRect(0, 0, source.w, source.h); + target.ctx.globalCompositeOperation = "multiply"; + target.ctx.drawImage(source, 0, 0, source.w, source.h, 0, 0, target.width, target.height); + target.ctx.globalCompositeOperation = "destination-in"; + target.ctx.drawImage(source, 0, 0, source.w, source.h, 0, 0, target.width, target.height); + } + _hasCache(nativeTexture) { + return !!nativeTexture._tintCache; + } + _getCache(nativeTexture) { + if (!nativeTexture._tintCache) { + nativeTexture._tintCache = new C2dTintCache(nativeTexture); + } + return nativeTexture._tintCache; + } + gc(aggressive = false) { + const frame = this.stage.frameCounter; + let delta = 0; + this._cachedNativeTextures.forEach((texture) => { + const cache = this._getCache(texture); + if (aggressive) { + delta += cache.memoryUsage; + cache.clear(); + } else { + const before = cache.memoryUsage; + cache.cleanup(frame); + cache.releaseBlancoTextures(); + delta += cache.memoryUsage - before; + } + }); + if (aggressive) { + this._cachedNativeTextures.clear(); + } + if (delta) { + this._addMemoryUsage(delta); + } + } + } + class C2dTintCache { + constructor(nativeTexture) { + this._tx = nativeTexture; + this._colors = /* @__PURE__ */ new Map(); + this._blancoTextures = null; + this._lastCleanupFrame = 0; + this._memTextures = 0; + } + get memoryUsage() { + return this._memTextures * this._tx.w * this._tx.h; + } + releaseBlancoTextures() { + this._memTextures -= this._blancoTextures.length; + this._blancoTextures = []; + } + clear() { + this._blancoTextures = null; + this._colors.clear(); + this._memTextures = 0; + } + get(color) { + let item = this._colors.get(color); + if (!item) { + item = { lf: -1, tx: void 0, u: -1 }; + this._colors.set(color, item); + } + return item; + } + set(color, texture, frame) { + const item = this.get(color); + item.lf = frame; + item.tx = texture; + item.u = frame; + this._memTextures++; + } + cleanup(frame) { + if (this._lastCleanupFrame !== frame) { + this._blancoTextures = []; + this._colors.forEach((item, color) => { + if (item.lf < frame - 1) { + if (item.tx) { + this._blancoTextures.push(item.tx); + } + this._colors.delete(color); + } + }); + this._lastCleanupFrame = frame; + } + } + reuseTexture(frame) { + this.cleanup(frame); + if (this._blancoTextures && this._blancoTextures.length) { + this._memTextures--; + return this._blancoTextures.pop(); + } + } + } + class C2dRenderer extends Renderer { + constructor(stage) { + super(stage); + this.tintManager = new C2dTextureTintManager(stage); + this.setupC2d(this.stage.c2d.canvas); + } + destroy() { + this.tintManager.destroy(); + this.tintManager = null; + delete this.tintManager; + } + _createDefaultShader(ctx) { + return new DefaultShader(ctx); + } + _getShaderBaseType() { + return C2dShader; + } + _getShaderAlternative(shaderType) { + return shaderType.getC2d && shaderType.getC2d(); + } + createCoreQuadList(ctx) { + return new C2dCoreQuadList(ctx); + } + createCoreQuadOperation(ctx, shader, shaderOwner, renderTextureInfo, scissor, index) { + return new C2dCoreQuadOperation(ctx, shader, shaderOwner, renderTextureInfo, scissor, index); + } + createCoreRenderExecutor(ctx) { + return new C2dCoreRenderExecutor(ctx); + } + createCoreRenderState(ctx) { + return new CoreRenderState(ctx); + } + createRenderTexture(w, h, pw, ph) { + const canvas = document.createElement("canvas"); + canvas.width = pw; + canvas.height = ph; + this.setupC2d(canvas); + return canvas; + } + freeRenderTexture(nativeTexture) { + this.tintManager.delete(nativeTexture); + } + gc(aggressive) { + this.tintManager.gc(aggressive); + } + uploadTextureSource(textureSource, options) { + if (options.source.buffer) { + const canvas = document.createElement("canvas"); + canvas.width = options.w; + canvas.height = options.h; + const imageData = new ImageData(new Uint8ClampedArray(options.source.buffer), options.w, options.h); + canvas.getContext("2d").putImageData(imageData, 0, 0); + return canvas; + } + return options.source; + } + freeTextureSource(textureSource) { + this.tintManager.delete(textureSource.nativeTexture); + } + addQuad(renderState, quads, index) { + const elementCore = quads.quadElements[index]; + quads.setRenderContext(index, elementCore._renderContext); + quads.setWhite(index, elementCore.isWhite()); + quads.setSimpleTc(index, elementCore.hasSimpleTexCoords()); + } + isRenderTextureReusable(renderState, renderTextureInfo) { + return false; + } + finishRenderState(renderState) { + } + setupC2d(canvas) { + const ctx = canvas.getContext("2d"); + canvas.ctx = ctx; + ctx._scissor = null; + canvas.ctx.save(); + } + } + class SparkShader extends WebGLShader { + enableAttribs() { + let gl = this.gl; + gl.vertexAttribPointer(this._attrib("aVertexPosition"), 2, gl.FLOAT, false, 20, 0); + gl.enableVertexAttribArray(this._attrib("aVertexPosition")); + if (this._attrib("aTextureCoord") !== -1) { + gl.vertexAttribPointer(this._attrib("aTextureCoord"), 2, gl.FLOAT, false, 20, 2 * 4); + gl.enableVertexAttribArray(this._attrib("aTextureCoord")); + } + if (this._attrib("aColor") !== -1) { + gl.vertexAttribPointer(this._attrib("aColor"), 4, gl.UNSIGNED_BYTE, true, 20, 4 * 4); + gl.enableVertexAttribArray(this._attrib("aColor")); + } + } + disableAttribs() { + let gl = this.gl; + gl.disableVertexAttribArray(this._attrib("aVertexPosition")); + if (this._attrib("aTextureCoord") !== -1) { + gl.disableVertexAttribArray(this._attrib("aTextureCoord")); + } + if (this._attrib("aColor") !== -1) { + gl.disableVertexAttribArray(this._attrib("aColor")); + } + } + setupUniforms(operation) { + this._setUniform("projection", this._getProjection(operation), this.gl.uniform2fv, false); + } + draw(operation) { + let gl = this.gl; + let length = operation.length; + if (length) { + let glTexture = operation.getTexture(0); + let pos = 0; + for (let i = 0; i < length; i++) { + let tx = operation.getTexture(i); + if (glTexture !== tx) { + if (glTexture.options && glTexture.options.imageRef) { + let elementPostion = i > 0 ? i - 1 : i; + const precision = this.ctx.stage.getOption("precision"); + let vc = operation.getElementCore(elementPostion); + this.ctx.stage.platform.paint(gl, glTexture.options.imageRef, vc._worldContext.px * precision, vc._worldContext.py * precision, vc._colorUl, vc); + } else { + gl.bindTexture(gl.TEXTURE_2D, glTexture); + gl.drawElements(gl.TRIANGLES, 6 * (i - pos), gl.UNSIGNED_SHORT, (pos + operation.index) * 6 * 2); + } + glTexture = tx; + pos = i; + } + } + if (pos < length) { + if (glTexture.options && glTexture.options.imageRef) { + const precision = this.ctx.stage.getOption("precision"); + let vc = operation.getElementCore(pos); + this.ctx.stage.platform.paint(gl, glTexture.options.imageRef, vc._worldContext.px * precision, vc._worldContext.py * precision, vc._colorUl, vc); + } else { + gl.bindTexture(gl.TEXTURE_2D, glTexture); + gl.drawElements(gl.TRIANGLES, 6 * (length - pos), gl.UNSIGNED_SHORT, (pos + operation.index) * 6 * 2); + } + } + } + } + } + SparkShader.vertexShaderSource = ` + #ifdef GL_ES + # ifdef GL_FRAGMENT_PRECISION_HIGH + precision highp float; + # else + precision lowp float; + # endif + #endif + attribute vec2 aVertexPosition; + attribute vec2 aTextureCoord; + attribute vec4 aColor; + uniform vec2 projection; + varying vec2 vTextureCoord; + varying vec4 vColor; + void main(void){ + gl_Position = vec4(aVertexPosition.x * projection.x - 1.0, aVertexPosition.y * -abs(projection.y) + 1.0, 0.0, 1.0); + vTextureCoord = aTextureCoord; + vColor = aColor; + gl_Position.y = -sign(projection.y) * gl_Position.y; + } +`; + SparkShader.fragmentShaderSource = ` + #ifdef GL_ES + # ifdef GL_FRAGMENT_PRECISION_HIGH + precision highp float; + # else + precision lowp float; + # endif + #endif + varying vec2 vTextureCoord; + varying vec4 vColor; + uniform sampler2D uSampler; + void main(void){ + gl_FragColor = texture2D(uSampler, vTextureCoord) * vColor; + } +`; + class SparkRenderer extends WebGLRenderer { + constructor(stage) { + super(stage); + } + _createDefaultShader(ctx) { + return new SparkShader(ctx); + } + createCoreRenderExecutor(ctx) { + global.beginDrawing(); + let ret = super.createCoreRenderExecutor(ctx); + global.endDrawing(); + return ret; + } + } + class ImageWorker { + constructor(options = {}) { + this._items = /* @__PURE__ */ new Map(); + this._id = 0; + this._initWorker(); + } + destroy() { + if (this._worker) { + this._worker.terminate(); + } + this._items = null; + this._worker = null; + delete this._items; + delete this._worker; + } + _initWorker() { + const code = `(${createWorker.toString()})()`; + const blob = new Blob([code.replace('"use strict";', "")]); + const blobURL = (window.URL ? URL : webkitURL).createObjectURL(blob, { + type: "application/javascript; charset=utf-8" + }); + this._worker = new Worker(blobURL); + this._worker.postMessage({ type: "config", config: { path: window.location.href, protocol: window.location.protocol } }); + this._worker.onmessage = (e) => { + if (e.data && e.data.id) { + const id = e.data.id; + const item = this._items.get(id); + if (item) { + if (e.data.type == "data") { + this.finish(item, e.data.info); + } else { + this.error(item, e.data.info); + } + } + } + }; + } + create(src) { + const id = ++this._id; + const item = new ImageWorkerImage(this, id, src); + this._items.set(id, item); + this._worker.postMessage({ type: "add", id, src }); + return item; + } + cancel(image) { + this._worker.postMessage({ type: "cancel", id: image.id }); + this._items.delete(image.id); + } + error(image, info) { + image.error(info); + this._items.delete(image.id); + } + finish(image, info) { + image.load(info); + this._items.delete(image.id); + } + } + class ImageWorkerImage { + constructor(manager, id, src) { + this._manager = manager; + this._id = id; + this._src = src; + this._onError = null; + this._onLoad = null; + } + get id() { + return this._id; + } + get src() { + return this._src; + } + set onError(f) { + this._onError = f; + } + set onLoad(f) { + this._onLoad = f; + } + cancel() { + this._manager.cancel(this); + } + load(info) { + if (this._onLoad) { + this._onLoad(info); + } + } + error(info) { + if (this._onError) { + this._onError(info); + } + } + } + const createWorker = function() { + function ImageWorkerServer() { + this.items = /* @__PURE__ */ new Map(); + var t = this; + onmessage = function(e) { + t._receiveMessage(e); + }; + } + ImageWorkerServer.isPathAbsolute = function(path) { + return /^(?:\/|[a-z]+:\/\/)/.test(path) || path.substr(0, 5) == "data:"; + }; + ImageWorkerServer.prototype._receiveMessage = function(e) { + if (e.data.type === "config") { + this.config = e.data.config; + var base = this.config.path; + var hasHashPath = /#.*?\//; + if (hasHashPath.test(base)) { + base = base.replace(/#.*$/, ""); + } + var parts = base.split("/"); + parts.pop(); + this._relativeBase = parts.join("/") + "/"; + } else if (e.data.type === "add") { + this.add(e.data.id, e.data.src); + } else if (e.data.type === "cancel") { + this.cancel(e.data.id); + } + }; + ImageWorkerServer.prototype.add = function(id, src) { + if (!ImageWorkerServer.isPathAbsolute(src)) { + src = this._relativeBase + src; + } + if (src.substr(0, 2) === "//") { + src = this.config.protocol + src; + } + var item = new ImageWorkerServerItem(id, src); + var t = this; + item.onFinish = function(result) { + t.finish(item, result); + }; + item.onError = function(info) { + t.error(item, info); + }; + this.items.set(id, item); + item.start(); + }; + ImageWorkerServer.prototype.cancel = function(id) { + var item = this.items.get(id); + if (item) { + item.cancel(); + this.items.delete(id); + } + }; + ImageWorkerServer.prototype.finish = function(item, { imageBitmap, hasAlphaChannel }) { + postMessage({ + type: "data", + id: item.id, + info: { + imageBitmap, + hasAlphaChannel + } + }, [imageBitmap]); + this.items.delete(item.id); + }; + ImageWorkerServer.prototype.error = function(item, { type, message }) { + postMessage({ + type: "error", + id: item.id, + info: { + type, + message + } + }); + this.items.delete(item.id); + }; + ImageWorkerServer.isWPEBrowser = function() { + return navigator.userAgent.indexOf("WPE") !== -1; + }; + function ImageWorkerServerItem(id, src) { + this._onError = void 0; + this._onFinish = void 0; + this._id = id; + this._src = src; + this._xhr = void 0; + this._mimeType = void 0; + this._canceled = false; + } + Object.defineProperty(ImageWorkerServerItem.prototype, "id", { + get: function() { + return this._id; + } + }); + Object.defineProperty(ImageWorkerServerItem.prototype, "onFinish", { + get: function() { + return this._onFinish; + }, + set: function(f) { + this._onFinish = f; + } + }); + Object.defineProperty(ImageWorkerServerItem.prototype, "onError", { + get: function() { + return this._onError; + }, + set: function(f) { + this._onError = f; + } + }); + ImageWorkerServerItem.prototype.start = function() { + this._xhr = new XMLHttpRequest(); + this._xhr.open("GET", this._src, true); + this._xhr.responseType = "blob"; + var t = this; + this._xhr.onerror = function(oEvent) { + t.error({ type: "connection", message: "Connection error" }); + }; + this._xhr.onload = function(oEvent) { + var blob = t._xhr.response; + t._mimeType = blob.type; + t._createImageBitmap(blob); + }; + this._xhr.send(); + }; + ImageWorkerServerItem.prototype._createImageBitmap = function(blob) { + var t = this; + createImageBitmap(blob, { premultiplyAlpha: "premultiply", colorSpaceConversion: "none", imageOrientation: "none" }).then(function(imageBitmap) { + t.finish({ + imageBitmap, + hasAlphaChannel: t._hasAlphaChannel() + }); + }).catch(function(e) { + t.error({ type: "parse", message: "Error parsing image data" }); + }); + }; + ImageWorkerServerItem.prototype._hasAlphaChannel = function() { + if (ImageWorkerServer.isWPEBrowser()) { + return true; + } else { + return this._mimeType.indexOf("image/png") !== -1; + } + }; + ImageWorkerServerItem.prototype.cancel = function() { + if (this._canceled) + return; + if (this._xhr) { + this._xhr.abort(); + } + this._canceled = true; + }; + ImageWorkerServerItem.prototype.error = function(type, message) { + if (!this._canceled && this._onError) { + this._onError({ type, message }); + } + }; + ImageWorkerServerItem.prototype.finish = function(info) { + if (!this._canceled && this._onFinish) { + this._onFinish(info); + } + }; + new ImageWorkerServer(); + }; + class WebPlatform { + init(stage) { + this.stage = stage; + this._looping = false; + this._awaitingLoop = false; + this._loopHandler = null; + this._idleLoopCounter = 0; + this._idleLoopDelay = 60; + if (this.stage.getOption("useImageWorker")) { + if (!window.createImageBitmap || !window.Worker) { + console.warn("[Lightning] Can't use image worker because browser does not have createImageBitmap and Web Worker support"); + } else { + this._imageWorker = new ImageWorker(); + } + } + this._registerVisibilityChangeHandler(); + } + destroy() { + if (this._imageWorker) { + this._imageWorker.destroy(); + } + clearInterval(this._loopHandler); + this._removeKeyHandler(); + this._removeClickHandler(); + this._removeHoverHandler(); + this._removeScrollWheelHandler(); + this._removeVisibilityChangeHandler(); + this.stage = null; + delete this.stage; + } + startLoop() { + this._looping = true; + if (!this._awaitingLoop) { + this.loop(); + } + } + stopLoop() { + this._looping = false; + } + switchLoop() { + if (this._idleLoopCounter < this._idleLoopDelay) { + this._idleLoopCounter++; + return; + } + if (!this.stage.ctx.hasRenderUpdates()) { + this.stopLoop(); + this._loopHandler = setInterval(() => { + this.stage.updateFrame(); + this.stage.idleFrame(); + if (this.stage.ctx.hasRenderUpdates()) { + clearInterval(this._loopHandler); + this.startLoop(); + } + }, 1e3 / 60); + } else { + this._idleLoopCounter = 0; + } + } + loop() { + let self2 = this; + let lp = function() { + self2._awaitingLoop = false; + if (self2._looping) { + self2.stage.updateFrame(); + if (self2.stage.getOption("pauseRafLoopOnIdle")) { + self2.switchLoop(); + } + self2.stage.renderFrame(); + requestAnimationFrame(lp); + self2._awaitingLoop = true; + } + }; + requestAnimationFrame(lp); + } + uploadCompressedGlTexture(gl, textureSource, source, options) { + const view = !source.pvr ? new DataView(source.mipmaps[0]) : source.mipmaps[0]; + gl.compressedTexImage2D( + gl.TEXTURE_2D, + 0, + source.glInternalFormat, + source.pixelWidth, + source.pixelHeight, + 0, + view + ); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR); + } + uploadGlTexture(gl, textureSource, source, options) { + if (source instanceof ImageData || source instanceof HTMLImageElement || source instanceof HTMLVideoElement || window.ImageBitmap && source instanceof ImageBitmap) { + gl.texImage2D(gl.TEXTURE_2D, 0, options.internalFormat, options.format, options.type, source); + } else if (source instanceof HTMLCanvasElement) { + if (Utils$1.isZiggo || this.stage.getOption("forceTxCanvasSource")) { + gl.texImage2D(gl.TEXTURE_2D, 0, options.internalFormat, options.format, options.type, source); + } else if (source.width > 0 && source.height > 0) { + const ctx = source.getContext("2d"); + gl.texImage2D(gl.TEXTURE_2D, 0, options.internalFormat, options.format, options.type, ctx.getImageData(0, 0, source.width, source.height)); + } + } else { + gl.texImage2D(gl.TEXTURE_2D, 0, options.internalFormat, textureSource.w, textureSource.h, 0, options.format, options.type, source); + } + } + handleKtxLoad(cb, src) { + var self2 = this; + return function() { + var arraybuffer = this.response; + var view = new DataView(arraybuffer); + var targetIdentifier = 3632701469; + if (targetIdentifier !== view.getUint32(0) + view.getUint32(4) + view.getUint32(8)) { + cb("Parsing failed: identifier ktx mismatch:", src); + } + var littleEndian = view.getUint32(12) === 16909060 ? true : false; + var data = { + glType: view.getUint32(16, littleEndian), + glTypeSize: view.getUint32(20, littleEndian), + glFormat: view.getUint32(24, littleEndian), + glInternalFormat: view.getUint32(28, littleEndian), + glBaseInternalFormat: view.getUint32(32, littleEndian), + pixelWidth: view.getUint32(36, littleEndian), + pixelHeight: view.getUint32(40, littleEndian), + pixelDepth: view.getUint32(44, littleEndian), + numberOfArrayElements: view.getUint32(48, littleEndian), + numberOfFaces: view.getUint32(52, littleEndian), + numberOfMipmapLevels: view.getUint32(56, littleEndian), + bytesOfKeyValueData: view.getUint32(60, littleEndian), + kvps: [], + mipmaps: [], + get width() { + return this.pixelWidth; + }, + get height() { + return this.pixelHeight; + } + }; + const props = (obj) => { + const p = []; + for (let v in obj) { + p.push(obj[v]); + } + return p; + }; + const formats = Object.values(self2.stage.renderer.getCompressedTextureExtensions()).filter((obj) => obj != null).map((obj) => props(obj)).reduce((prev, current) => prev.concat(current)); + if (!formats.includes(data.glInternalFormat)) { + console.warn("[Lightning] Unrecognized texture extension format:", src, data.glInternalFormat, self2.stage.renderer.getCompressedTextureExtensions()); + } + var offset = 64; + offset += data.bytesOfKeyValueData; + for (var i = 0; i < data.numberOfMipmapLevels; i++) { + var imageSize = view.getUint32(offset); + offset += 4; + data.mipmaps.push(view.buffer.slice(offset, imageSize)); + offset += imageSize; + } + cb(null, { + source: data, + renderInfo: { src, compressed: true } + }); + }; + } + handlePvrLoad(cb, src) { + return function() { + const pvrHeaderLength = 13; + const pvrFormatEtc1 = 36196; + const pvrWidth = 7; + const pvrHeight = 6; + const pvrMipmapCount = 11; + const pvrMetadata = 12; + const arrayBuffer = this.response; + const header = new Int32Array(arrayBuffer, 0, pvrHeaderLength); + const dataOffset = header[pvrMetadata] + 52; + const pvrtcData = new Uint8Array(arrayBuffer, dataOffset); + var data = { + glInternalFormat: pvrFormatEtc1, + pixelWidth: header[pvrWidth], + pixelHeight: header[pvrHeight], + numberOfMipmapLevels: header[pvrMipmapCount], + mipmaps: [], + pvr: true, + get width() { + return this.pixelWidth; + }, + get height() { + return this.pixelHeight; + } + }; + let offset = 0; + let width = data.pixelWidth; + let height = data.pixelHeight; + for (var i = 0; i < data.numberOfMipmapLevels; i++) { + const level = (width + 3 >> 2) * (height + 3 >> 2) * 8; + const view = new Uint8Array(arrayBuffer, pvrtcData.byteOffset + offset, level); + data.mipmaps.push(view); + offset += level; + width = width >> 1; + height = height >> 1; + } + cb(null, { + source: data, + renderInfo: { src, compressed: true } + }); + }; + } + loadSrcTexture({ src, hasAlpha }, cb) { + let cancelCb = void 0; + let isPng = src.toLowerCase().indexOf(".png") >= 0 || src.substr(0, 21) == "data:image/png;base64"; + let isKtx = src.indexOf(".ktx") >= 0; + let isPvr = src.indexOf(".pvr") >= 0; + if (isKtx || isPvr) { + let request = new XMLHttpRequest(); + request.addEventListener( + "load", + isKtx ? this.handleKtxLoad(cb, src) : this.handlePvrLoad(cb, src) + ); + request.open("GET", src); + request.responseType = "arraybuffer"; + request.send(); + cancelCb = function() { + request.abort(); + }; + } else if (this._imageWorker) { + const image = this._imageWorker.create(src); + image.onError = function(err) { + return cb("Image load error"); + }; + image.onLoad = function({ imageBitmap, hasAlphaChannel }) { + cb(null, { + source: imageBitmap, + renderInfo: { src, compressed: false }, + hasAlpha: hasAlphaChannel, + premultiplyAlpha: true + }); + }; + cancelCb = function() { + image.cancel(); + }; + } else { + let image = new Image(); + if (!(src.substr(0, 5) == "data:") && !Utils$1.isPS4) { + image.crossOrigin = "Anonymous"; + } + image.onerror = function(err) { + if (image.src) { + return cb("Image load error"); + } + }; + image.onload = function() { + cb(null, { + source: image, + renderInfo: { src, compressed: false }, + hasAlpha: isPng || hasAlpha + }); + }; + image.src = src; + cancelCb = function() { + image.onerror = null; + image.onload = null; + image.removeAttribute("src"); + }; + } + return cancelCb; + } + createWebGLContext(w, h) { + let canvas = this.stage.getOption("canvas") || document.createElement("canvas"); + if (w && h) { + canvas.width = w; + canvas.height = h; + } + let opts = { + alpha: true, + antialias: false, + premultipliedAlpha: true, + stencil: true, + preserveDrawingBuffer: false + }; + let gl = canvas.getContext("webgl", opts) || canvas.getContext("experimental-webgl", opts) || canvas.getContext("webgl2", opts); + if (!gl) { + throw new Error("This browser does not support webGL."); + } + return gl; + } + createCanvasContext(w, h) { + let canvas = this.stage.getOption("canvas") || document.createElement("canvas"); + if (w && h) { + canvas.width = w; + canvas.height = h; + } + let c2d = canvas.getContext("2d"); + if (!c2d) { + throw new Error("This browser does not support 2d canvas."); + } + return c2d; + } + getHrTime() { + return window.performance ? window.performance.now() : new Date().getTime(); + } + getDrawingCanvas() { + return document.createElement("canvas"); + } + getTextureOptionsForDrawingCanvas(canvas) { + let options = {}; + options.source = canvas; + return options; + } + nextFrame(changes) { + } + registerKeydownHandler(keyhandler) { + this._keydownListener = (e) => { + keyhandler(e); + }; + window.addEventListener("keydown", this._keydownListener); + } + registerKeyupHandler(keyhandler) { + this._keyupListener = (e) => { + keyhandler(e); + }; + window.addEventListener("keyup", this._keyupListener); + } + _removeKeyHandler() { + if (this._keydownListener) { + window.removeEventListener("keydown", this._keydownListener); + } + if (this._keyupListener) { + window.removeEventListener("keyup", this._keyupListener); + } + } + registerClickHandler(clickHandler) { + this._clickListener = (e) => { + clickHandler(e); + }; + window.addEventListener("mousedown", this._clickListener); + } + _removeClickHandler() { + if (this._clickListener) { + window.removeEventListener("mousedown", this._clickListener); + } + } + registerHoverHandler(hoverHandler) { + this._hoverListener = (e) => { + hoverHandler(e); + }; + window.addEventListener("mousemove", this._hoverListener); + } + _removeHoverHandler() { + if (this._hoverListener) { + window.removeEventListener("mousemove", this._hoverListener); + } + } + registerScrollWheelHandler(registerScrollWheelHandler) { + this._scrollWheelListener = (e) => { + registerScrollWheelHandler(e); + }; + window.addEventListener("wheel", this._scrollWheelListener); + } + _removeScrollWheelHandler() { + if (this._scrollWheelListener) { + window.removeEventListener("wheel", this._scrollWheelListener); + } + } + _registerVisibilityChangeHandler() { + this._visibilityChangeHandler = () => { + if (document.visibilityState === "visible") { + this.stage.root.core.setHasRenderUpdates(2); + this.stage.renderFrame(); + } + }; + document.addEventListener("visibilitychange", this._visibilityChangeHandler); + } + _removeVisibilityChangeHandler() { + if (this._visibilityChangeHandler) { + document.removeEventListener("visibilitychange", this._visibilityChangeHandler); + } + } + } + class PlatformLoader { + static load(options) { + if (options.platform) { + return options.platform; + } else { + return WebPlatform; + } + } + } + class Utils { + static isFunction(value) { + return typeof value === "function"; + } + static isNumber(value) { + return typeof value === "number"; + } + static isInteger(value) { + return typeof value === "number" && value % 1 === 0; + } + static isBoolean(value) { + return value === true || value === false; + } + static isString(value) { + return typeof value == "string"; + } + static isObject(value) { + let type = typeof value; + return !!value && (type == "object" || type == "function"); + } + static isPlainObject(value) { + let type = typeof value; + return !!value && type == "object"; + } + static isObjectLiteral(value) { + return typeof value === "object" && value && value.constructor === Object; + } + static getArrayIndex(index, arr) { + return Utils.getModuloIndex(index, arr.length); + } + static equalValues(v1, v2) { + if (typeof v1 !== typeof v2) + return false; + if (Utils.isObjectLiteral(v1)) { + return Utils.isObjectLiteral(v2) && Utils.equalObjectLiterals(v1, v2); + } else if (Array.isArray(v1)) { + return Array.isArray(v2) && Utils.equalArrays(v1, v2); + } else { + return v1 === v2; + } + } + static equalObjectLiterals(obj1, obj2) { + let keys1 = Object.keys(obj1); + let keys2 = Object.keys(obj2); + if (keys1.length !== keys2.length) { + return false; + } + for (let i = 0, n = keys1.length; i < n; i++) { + const k1 = keys1[i]; + const k2 = keys2[i]; + if (k1 !== k2) { + return false; + } + const v1 = obj1[k1]; + const v2 = obj2[k2]; + if (!Utils.equalValues(v1, v2)) { + return false; + } + } + return true; + } + static equalArrays(v1, v2) { + if (v1.length !== v2.length) { + return false; + } + for (let i = 0, n = v1.length; i < n; i++) { + if (!this.equalValues(v1[i], v2[i])) { + return false; + } + } + return true; + } + } + class WebGLState { + constructor(id, gl) { + this._id = id; + this._gl = gl; + this._program = void 0; + this._buffers = /* @__PURE__ */ new Map(); + this._framebuffers = /* @__PURE__ */ new Map(); + this._renderbuffers = /* @__PURE__ */ new Map(); + this._vertexAttribs = new Array(16); + this._nonDefaultFlags = /* @__PURE__ */ new Set(); + this._settings = /* @__PURE__ */ new Map(); + this._textures = new Array(8); + this._maxTexture = 0; + this._activeTexture = gl.TEXTURE0; + this._pixelStorei = new Array(5); + } + _getDefaultFlag(cap) { + return cap === this._gl.DITHER; + } + setFlag(cap, v) { + const def = this._getDefaultFlag(cap); + if (v === def) { + return this._nonDefaultFlags.delete(cap); + } else { + if (!this._nonDefaultFlags.has(cap)) { + this._nonDefaultFlags.add(cap); + return true; + } else { + return false; + } + } + } + setBuffer(target, buffer) { + const change = this._buffers.get(target) !== buffer; + this._buffers.set(target, buffer); + if (change && target === this._gl.ARRAY_BUFFER) { + this._vertexAttribs = []; + } + return change; + } + setFramebuffer(target, buffer) { + const change = this._framebuffers.get(target) !== buffer; + this._framebuffers.set(target, buffer); + return change; + } + setRenderbuffer(target, buffer) { + const change = this._renderbuffers.get(target) !== buffer; + this._renderbuffers.set(target, buffer); + return change; + } + setProgram(program) { + const change = this._program !== program; + this._program = program; + return change; + } + setSetting(func, v) { + const s = this._settings.get(func); + const change = !s || !Utils.equalValues(s, v); + this._settings.set(func, v); + return change; + } + disableVertexAttribArray(index) { + const va = this._vertexAttribs[index]; + if (va && va[5]) { + va[5] = false; + return true; + } + return false; + } + enableVertexAttribArray(index) { + const va = this._vertexAttribs[index]; + if (va) { + if (!va[0]) { + va[0] = true; + return true; + } + } else { + this._vertexAttribs[index] = [0, 0, 0, 0, 0, true]; + return true; + } + return false; + } + vertexAttribPointer(index, props) { + let va = this._vertexAttribs[index]; + let equal = false; + if (va) { + equal = va[0] === props[0] && va[1] === props[1] && va[2] === props[2] && va[3] === props[3] && va[4] === props[4]; + } + if (equal) { + return false; + } else { + props[5] = va ? va[5] : false; + return true; + } + } + setActiveTexture(texture) { + const changed = this._activeTexture !== texture; + this._activeTexture = texture; + return changed; + } + bindTexture(target, texture) { + const activeIndex = WebGLState._getTextureIndex(this._activeTexture); + this._maxTexture = Math.max(this._maxTexture, activeIndex + 1); + const current = this._textures[activeIndex]; + const targetIndex = WebGLState._getTextureTargetIndex(target); + if (current) { + if (current[targetIndex] === texture) { + return false; + } + current[targetIndex] = texture; + return true; + } else { + if (texture) { + this._textures[activeIndex] = []; + this._textures[activeIndex][targetIndex] = texture; + return true; + } else { + return false; + } + } + } + setPixelStorei(pname, param) { + const i = WebGLState._getPixelStoreiIndex(pname); + const change = !Utils.equalValues(this._pixelStorei[i], param); + this._pixelStorei[i] = param; + return change; + } + migrate(s) { + const t = this; + this._migrateFlags(t, s); + if (s._program !== t._program) { + this._gl._useProgram(s._program); + } + this._migrateFramebuffers(t, s); + this._migrateRenderbuffers(t, s); + const buffersChanged = this._migrateBuffers(t, s); + this._migrateAttributes(t, s, buffersChanged); + this._migrateFlags(t, s); + this._migrateSettings(t, s); + this._migratePixelStorei(t, s); + this._migrateTextures(t, s); + } + _migratePixelStorei(t, s) { + for (let i = 0, n = t._pixelStorei.length; i < n; i++) { + if (t._pixelStorei[i] !== s._pixelStorei[i]) { + const value = s._pixelStorei[i] !== void 0 ? s._pixelStorei[i] : WebGLState._getDefaultPixelStoreiByIndex(i); + this._gl._pixelStorei(WebGLState._getPixelStoreiByIndex(i), value); + } + } + } + _migrateTextures(t, s) { + const max = Math.max(t._maxTexture, s._maxTexture); + let activeTexture = t._activeTexture; + for (let i = 0; i < max; i++) { + const sTargets = s._textures[i]; + const tTargets = t._textures[i]; + const textureNumb = WebGLState._getTextureByIndex(i); + const targetMax = Math.max(tTargets ? tTargets.length : 0, sTargets ? sTargets.length : 0); + for (let j = 0, n = targetMax; j < n; j++) { + const target = WebGLState._getTextureTargetByIndex(j); + if (activeTexture !== textureNumb) { + this._gl._activeTexture(textureNumb); + activeTexture = textureNumb; + } + const texture = sTargets && sTargets[j] || null; + this._gl._bindTexture(target, texture); + } + } + if (s._activeTexture !== activeTexture) { + this._gl._activeTexture(s._activeTexture); + } + } + _migrateBuffers(t, s) { + s._buffers.forEach((framebuffer, target) => { + if (t._buffers.get(target) !== framebuffer) { + this._gl._bindBuffer(target, framebuffer); + } + }); + t._buffers.forEach((buffer, target) => { + const b = s._buffers.get(target); + if (b === void 0) { + this._gl._bindBuffer(target, null); + } + }); + return s._buffers.get(this._gl.ARRAY_BUFFER) !== t._buffers.get(this._gl.ARRAY_BUFFER); + } + _migrateFramebuffers(t, s) { + s._framebuffers.forEach((framebuffer, target) => { + if (t._framebuffers.get(target) !== framebuffer) { + this._gl._bindFramebuffer(target, framebuffer); + } + }); + t._framebuffers.forEach((framebuffer, target) => { + const fb = s._framebuffers.get(target); + if (fb === void 0) { + this._gl._bindFramebuffer(target, null); + } + }); + } + _migrateRenderbuffers(t, s) { + s._renderbuffers.forEach((renderbuffer, target) => { + if (t._renderbuffers.get(target) !== renderbuffer) { + this._gl._bindRenderbuffer(target, renderbuffer); + } + }); + t._renderbuffers.forEach((renderbuffer, target) => { + const fb = s._renderbuffers.get(target); + if (fb === void 0) { + this._gl._bindRenderbuffer(target, null); + } + }); + } + _migrateAttributes(t, s, buffersChanged) { + if (!buffersChanged) { + t._vertexAttribs.forEach((attrib, index) => { + if (!s._vertexAttribs[index]) { + this._gl._disableVertexAttribArray(index); + } + }); + s._vertexAttribs.forEach((attrib, index) => { + this._gl._vertexAttribPointer(index, attrib[0], attrib[1], attrib[2], attrib[4]); + if (attrib[5]) { + this._gl._enableVertexAttribArray(index); + } else { + this._gl._disableVertexAttribArray(index); + } + }); + } else { + s._vertexAttribs.forEach((attrib, index) => { + if (attrib[0]) { + this._gl._vertexAttribPointer(index, attrib[0], attrib[1], attrib[2], attrib[3], attrib[4]); + } + if (attrib[5]) { + this._gl._enableVertexAttribArray(index); + } + }); + } + } + _migrateSettings(t, s) { + const defaults = this.constructor.getDefaultSettings(); + t._settings.forEach((value, func) => { + const name = func.name || func.xname; + if (!s._settings.has(func)) { + let args = defaults.get(name); + if (Utils.isFunction(args)) { + args = args(this._gl); + } + s._settings.set(func, args); + func.apply(this._gl, args); + } + }); + s._settings.forEach((value, func) => { + const tValue = t._settings.get(func); + if (!tValue || !Utils.equalValues(tValue, value)) { + func.apply(this._gl, value); + } + }); + } + _migrateFlags(t, s) { + t._nonDefaultFlags.forEach((setting) => { + if (!s._nonDefaultFlags.has(setting)) { + if (this._getDefaultFlag(setting)) { + this._gl._enable(setting); + } else { + this._gl._disable(setting); + } + } + }); + s._nonDefaultFlags.forEach((setting) => { + if (!t._nonDefaultFlags.has(setting)) { + if (this._getDefaultFlag(setting)) { + this._gl._disable(setting); + } else { + this._gl._enable(setting); + } + } + }); + } + static getDefaultSettings() { + if (!this._defaultSettings) { + this._defaultSettings = /* @__PURE__ */ new Map(); + const d = this._defaultSettings; + const g = WebGLRenderingContext.prototype; + d.set("viewport", function(gl) { + return [0, 0, gl.canvas.width, gl.canvas.height]; + }); + d.set("scissor", function(gl) { + return [0, 0, gl.canvas.width, gl.canvas.height]; + }); + d.set("blendColor", [0, 0, 0, 0]); + d.set("blendEquation", [g.FUNC_ADD]); + d.set("blendEquationSeparate", [g.FUNC_ADD, g.FUNC_ADD]); + d.set("blendFunc", [g.ONE, g.ZERO]); + d.set("blendFuncSeparate", [g.ONE, g.ZERO, g.ONE, g.ZERO]); + d.set("clearColor", [0, 0, 0, 0]); + d.set("clearDepth", [1]); + d.set("clearStencil", [0]); + d.set("colorMask", [true, true, true, true]); + d.set("cullFace", [g.BACK]); + d.set("depthFunc", [g.LESS]); + d.set("depthMask", [true]); + d.set("depthRange", [0, 1]); + d.set("frontFace", [g.CCW]); + d.set("lineWidth", [1]); + d.set("polygonOffset", [0, 0]); + d.set("sampleCoverage", [1, false]); + d.set("stencilFunc", [g.ALWAYS, 0, 1]); + d.set("_stencilFuncSeparateFront", [g.ALWAYS, 0, 1]); + d.set("_stencilFuncSeparateBack", [g.ALWAYS, 0, 1]); + d.set("_stencilFuncSeparateFrontAndBack", [g.ALWAYS, 0, 1]); + d.set("stencilMask", [1]); + d.set("_stencilMaskSeparateFront", [1]); + d.set("_stencilMaskSeparateBack", [1]); + d.set("_stencilMaskSeparateFrontAndBack", [1]); + d.set("stencilOp", [g.KEEP, g.KEEP, g.KEEP]); + d.set("_stencilOpSeparateFront", [g.KEEP, g.KEEP, g.KEEP]); + d.set("_stencilOpSeparateBack", [g.KEEP, g.KEEP, g.KEEP]); + d.set("_stencilOpSeparateFrontAndBack", [g.KEEP, g.KEEP, g.KEEP]); + d.set("vertexAttrib1f", []); + d.set("vertexAttrib1fv", []); + d.set("vertexAttrib2f", []); + d.set("vertexAttrib2fv", []); + d.set("vertexAttrib3f", []); + d.set("vertexAttrib3fv", []); + d.set("vertexAttrib4f", []); + d.set("vertexAttrib4fv", []); + } + return this._defaultSettings; + } + static _getTextureTargetIndex(target) { + switch (target) { + case 3553: + return 0; + case 34067: + return 1; + default: + throw new Error("Unknown texture target: " + target); + } + } + static _getTextureTargetByIndex(index) { + if (!this._textureTargetIndices) { + this._textureTargetIndices = [3553, 34067]; + } + return this._textureTargetIndices[index]; + } + static _getTextureIndex(index) { + return index - 33984; + } + static _getTextureByIndex(index) { + return index + 33984; + } + static _getPixelStoreiIndex(pname) { + switch (pname) { + case 3333: + return 0; + case 3317: + return 1; + case 37440: + return 2; + case 37441: + return 3; + case 37443: + return 4; + case 37445: + return 5; + default: + throw new Error("Unknown pixelstorei: " + pname); + } + } + static _getPixelStoreiByIndex(index) { + if (!this._pixelStoreiIndices) { + this._pixelStoreiIndices = [3333, 3317, 37440, 37441, 37443]; + } + return this._pixelStoreiIndices[index]; + } + static _getDefaultPixelStoreiByIndex(index) { + if (!this._pixelStoreiDefaults) { + this._pixelStoreiDefaults = [4, 4, false, false, WebGLRenderingContext.prototype.BROWSER_DEFAULT_WEBGL]; + } + return this._pixelStoreiDefaults[index]; + } + } + class WebGLStateManager { + _initStateManager(id = "default") { + this._states = {}; + this._state = this._getState(id); + } + _getState(id) { + if (!this._states[id]) { + this._states[id] = new WebGLState(id, this); + } + return this._states[id]; + } + switchState(id = "default") { + if (this._state._id !== id) { + const newState = this._getState(id); + this._state.migrate(newState); + this._state = newState; + } + } + $useProgram(program) { + if (this._state.setProgram(program)) + this._useProgram(program); + } + $bindBuffer(target, fb) { + if (this._state.setBuffer(target, fb)) + this._bindBuffer(target, fb); + } + $bindFramebuffer(target, fb) { + if (this._state.setFramebuffer(target, fb)) + this._bindFramebuffer(target, fb); + } + $bindRenderbuffer(target, fb) { + if (this._state.setRenderbuffer(target, fb)) + this._bindRenderbuffer(target, fb); + } + $enable(cap) { + if (this._state.setFlag(cap, true)) + this._enable(cap); + } + $disable(cap) { + if (this._state.setFlag(cap, false)) + this._disable(cap); + } + $viewport(x, y, w, h) { + if (this._state.setSetting(this._viewport, [x, y, w, h])) + this._viewport(x, y, w, h); + } + $scissor(x, y, w, h) { + if (this._state.setSetting(this._scissor, [x, y, w, h])) + this._scissor(x, y, w, h); + } + $disableVertexAttribArray(index) { + if (this._state.disableVertexAttribArray(index)) + this._disableVertexAttribArray(index); + } + $enableVertexAttribArray(index) { + if (this._state.enableVertexAttribArray(index)) + this._enableVertexAttribArray(index); + } + $vertexAttribPointer(index, size, type, normalized, stride, offset) { + if (this._state.vertexAttribPointer(index, [size, type, normalized, stride, offset])) + this._vertexAttribPointer(index, size, type, normalized, stride, offset); + } + $activeTexture(texture) { + if (this._state.setActiveTexture(texture)) + this._activeTexture(texture); + } + $bindTexture(target, texture) { + if (this._state.bindTexture(target, texture)) + this._bindTexture(target, texture); + } + $pixelStorei(pname, param) { + if (this._state.setPixelStorei(pname, param)) { + this._pixelStorei(pname, param); + } + } + $stencilFuncSeparate(face, func, ref, mask) { + let f; + switch (face) { + case this.FRONT: + f = this._stencilFuncSeparateFront; + break; + case this.BACK: + f = this._stencilFuncSeparateBack; + break; + case this.FRONT_AND_BACK: + f = this._stencilFuncSeparateFrontAndBack; + break; + } + if (this._state.setSetting(f, [func, ref, mask])) + f.apply(this, [func, ref, mask]); + } + _stencilFuncSeparateFront(func, ref, mask) { + this._stencilFuncSeparate(this.FRONT, func, ref, mask); + } + _stencilFuncSeparateBack(func, ref, mask) { + this._stencilFuncSeparate(this.BACK, func, ref, mask); + } + _stencilFuncSeparateFrontAndBack(func, ref, mask) { + this._stencilFuncSeparate(this.FRONT_AND_BACK, func, ref, mask); + } + $stencilMaskSeparate(face, mask) { + let f; + switch (face) { + case this.FRONT: + f = this._stencilMaskSeparateFront; + break; + case this.BACK: + f = this._stencilMaskSeparateBack; + break; + case this.FRONT_AND_BACK: + f = this._stencilMaskSeparateFrontAndBack; + break; + } + if (this._state.setSetting(f, [mask])) + f.apply(this, [mask]); + } + _stencilMaskSeparateFront(mask) { + this._stencilMaskSeparate(this.FRONT, mask); + } + _stencilMaskSeparateBack(mask) { + this._stencilMaskSeparate(this.BACK, mask); + } + _stencilMaskSeparateFrontAndBack(mask) { + this._stencilMaskSeparate(this.FRONT_AND_BACK, mask); + } + $stencilOpSeparate(face, fail, zfail, zpass) { + let f; + switch (face) { + case this.FRONT: + f = this._stencilOpSeparateFront; + break; + case this.BACK: + f = this._stencilOpSeparateBack; + break; + case this.FRONT_AND_BACK: + f = this._stencilOpSeparateFrontAndBack; + break; + } + if (this._state.setSetting(f, [fail, zfail, zpass])) + f.apply(this, [fail, zfail, zpass]); + } + _stencilOpSeparateFront(fail, zfail, zpass) { + this._stencilOpSeparate(this.FRONT, fail, zfail, zpass); + } + _stencilOpSeparateBack(fail, zfail, zpass) { + this._stencilOpSeparate(this.BACK, fail, zfail, zpass); + } + _stencilOpSeparateFrontAndBack(fail, zfail, zpass) { + this._stencilOpSeparate(this.FRONT_AND_BACK, fail, zfail, zpass); + } + $blendColor(red, green, blue, alpha) { + if (this._state.setSetting(this._blendColor, [red, green, blue, alpha])) + this._blendColor(red, green, blue, alpha); + } + $blendEquation(mode) { + if (this._state.setSetting(this._blendEquation, [mode])) + this._blendEquation(mode); + } + $blendEquationSeparate(modeRGB, modeAlpha) { + if (this._state.setSetting(this._blendEquationSeparate, [modeRGB, modeAlpha])) + this._blendEquationSeparate(modeRGB, modeAlpha); + } + $blendFunc(sfactor, dfactor) { + if (this._state.setSetting(this._blendFunc, [sfactor, dfactor])) + this._blendFunc(sfactor, dfactor); + } + $blendFuncSeparate(srcRGB, dstRGB, srcAlpha, dstAlpha) { + if (this._state.setSetting(this._blendFuncSeparate, [srcRGB, dstRGB, srcAlpha, dstAlpha])) + this._blendFuncSeparate(srcRGB, dstRGB, srcAlpha, dstAlpha); + } + $clearColor(red, green, blue, alpha) { + if (this._state.setSetting(this._clearColor, [red, green, blue, alpha])) + this._clearColor(red, green, blue, alpha); + } + $clearDepth(depth) { + if (this._state.setSetting(this._clearDepth, [depth])) + this._clearDepth(depth); + } + $clearStencil(s) { + if (this._state.setSetting(this._clearStencil, [s])) + this._clearStencil(s); + } + $colorMask(red, green, blue, alpha) { + if (this._state.setSetting(this._colorMask, [red, green, blue, alpha])) + this._colorMask(red, green, blue, alpha); + } + $cullFace(mode) { + if (this._state.setSetting(this._cullFace, [mode])) + this._cullFace(mode); + } + $depthFunc(func) { + if (this._state.setSetting(this._depthFunc, [func])) + this._depthFunc(func); + } + $depthMask(flag) { + if (this._state.setSetting(this._depthMask, [flag])) + this._depthMask(flag); + } + $depthRange(zNear, zFar) { + if (this._state.setSetting(this._depthRange, [zNear, zFar])) + this._depthRange(zNear, zFar); + } + $frontFace(mode) { + if (this._state.setSetting(this._frontFace, [mode])) + this._frontFace(mode); + } + $lineWidth(width) { + if (this._state.setSetting(this._lineWidth, [width])) + this._lineWidth(width); + } + $polygonOffset(factor, units) { + if (this._state.setSetting(this._polygonOffset, [factor, units])) + this._polygonOffset(factor, units); + } + $sampleCoverage(value, invert) { + if (this._state.setSetting(this._sampleCoverage, [value, invert])) + this._sampleCoverage(value, invert); + } + $stencilFunc(func, ref, mask) { + if (this._state.setSetting(this._stencilFunc, [func, ref, mask])) + this._stencilFunc(func, ref, mask); + } + $stencilMask(mask) { + if (this._state.setSetting(this._stencilMask, [mask])) + this._stencilMask(mask); + } + $stencilOp(fail, zfail, zpass) { + if (this._state.setSetting(this._stencilOp, [fail, zfail, zpass])) + this._stencilOp(fail, zfail, zpass); + } + $vertexAttrib1f(indx, x) { + if (this._state.setSetting(this._vertexAttrib1f, [indx, x])) + this._vertexAttrib1f(indx, x); + } + $vertexAttrib1fv(indx, values) { + if (this._state.setSetting(this._vertexAttrib1fv, [indx, values])) + this._vertexAttrib1fv(indx, values); + } + $vertexAttrib2f(indx, x, y) { + if (this._state.setSetting(this._vertexAttrib2f, [indx, x, y])) + this._vertexAttrib2f(indx, x, y); + } + $vertexAttrib2fv(indx, values) { + if (this._state.setSetting(this._vertexAttrib2fv, [indx, values])) + this._vertexAttrib2fv(indx, values); + } + $vertexAttrib3f(indx, x, y, z) { + if (this._state.setSetting(this._vertexAttrib3f, [indx, x, y, z])) + this._vertexAttrib3f(indx, x, y, z); + } + $vertexAttrib3fv(indx, values) { + if (this._state.setSetting(this._vertexAttrib3fv, [indx, values])) + this._vertexAttrib3fv(indx, values); + } + $vertexAttrib4f(indx, x, y, z, w) { + if (this._state.setSetting(this._vertexAttrib4f, [indx, x, y, z, w])) + this._vertexAttrib4f(indx, x, y, z, w); + } + $vertexAttrib4fv(indx, values) { + if (this._state.setSetting(this._vertexAttrib4fv, [indx, values])) + this._vertexAttrib4fv(indx, values); + } + static enable(gl, id = "default") { + const names = Object.getOwnPropertyNames(WebGLStateManager.prototype); + gl.__proto__; + names.forEach((name) => { + if (name !== "constructor") { + const method = WebGLStateManager.prototype[name]; + if (name.charAt(0) === "$") { + name = name.substr(1); + } + if (gl[name] !== method) { + if (gl[name]) { + if (!gl[name].name) { + gl[name].xname = name; + } + gl["_" + name] = gl[name]; + } + gl[name] = method; + } + } + }); + WebGLStateManager.prototype._initStateManager.call(gl, id); + return gl; + } + } + class TextureManager { + constructor(stage) { + this.stage = stage; + this._usedMemory = 0; + this._uploadedTextureSources = []; + this.textureSourceHashmap = /* @__PURE__ */ new Map(); + } + get usedMemory() { + return this._usedMemory; + } + destroy() { + for (let i = 0, n = this._uploadedTextureSources.length; i < n; i++) { + this._nativeFreeTextureSource(this._uploadedTextureSources[i]); + } + this.textureSourceHashmap.clear(); + this._usedMemory = 0; + } + getReusableTextureSource(id) { + return this.textureSourceHashmap.get(id); + } + getTextureSource(func, id) { + let textureSource = id ? this.textureSourceHashmap.get(id) : null; + if (!textureSource) { + textureSource = new TextureSource(this, func); + if (id) { + textureSource.lookupId = id; + this.textureSourceHashmap.set(id, textureSource); + } + } + return textureSource; + } + uploadTextureSource(textureSource, options) { + if (textureSource.isLoaded()) + return; + this._addMemoryUsage(textureSource.w * textureSource.h); + const nativeTexture = this._nativeUploadTextureSource(textureSource, options); + textureSource._nativeTexture = nativeTexture; + nativeTexture.w = textureSource.w; + nativeTexture.h = textureSource.h; + nativeTexture.update = this.stage.frameCounter; + this._uploadedTextureSources.push(textureSource); + this.addToLookupMap(textureSource); + this._updateVramUsage(textureSource, 1); + } + _addMemoryUsage(delta) { + this._usedMemory += delta; + this.stage.addMemoryUsage(delta); + } + _updateVramUsage(textureSource, sign) { + const nativeTexture = textureSource.nativeTexture; + var usage; + if (!Stage.isWebglSupported()) + return; + if (!textureSource.isLoaded()) + return; + if (!nativeTexture.hasOwnProperty("bytesPerPixel") || isNaN(nativeTexture.bytesPerPixel)) + return; + usage = sign * (textureSource.w * textureSource.h * nativeTexture.bytesPerPixel); + this.stage.addVramUsage(usage, textureSource.hasAlpha); + } + addToLookupMap(textureSource) { + const lookupId = textureSource.lookupId; + if (lookupId) { + if (!this.textureSourceHashmap.has(lookupId)) { + this.textureSourceHashmap.set(lookupId, textureSource); + } + } + } + gc() { + this.freeUnusedTextureSources(); + this._cleanupLookupMap(); + } + freeUnusedTextureSources() { + let remainingTextureSources = []; + for (let i = 0, n = this._uploadedTextureSources.length; i < n; i++) { + let ts = this._uploadedTextureSources[i]; + if (ts.allowCleanup()) { + this._freeManagedTextureSource(ts); + } else { + remainingTextureSources.push(ts); + } + } + this._uploadedTextureSources = remainingTextureSources; + this._cleanupLookupMap(); + } + _freeManagedTextureSource(textureSource) { + if (textureSource.isLoaded()) { + this._nativeFreeTextureSource(textureSource); + this._addMemoryUsage(-textureSource.w * textureSource.h); + this._updateVramUsage(textureSource, -1); + } + textureSource.loadingSince = null; + } + _cleanupLookupMap() { + this.textureSourceHashmap.forEach((textureSource, lookupId) => { + if (!(textureSource.isLoaded() || textureSource.isLoading()) && !textureSource.isUsed()) { + this.textureSourceHashmap.delete(lookupId); + } + }); + } + freeTextureSource(textureSource) { + const index = this._uploadedTextureSources.indexOf(textureSource); + const managed = index !== -1; + if (textureSource.isLoaded()) { + if (managed) { + this._addMemoryUsage(-textureSource.w * textureSource.h); + this._uploadedTextureSources.splice(index, 1); + } + this._nativeFreeTextureSource(textureSource); + } + textureSource.loadingSince = null; + } + _nativeUploadTextureSource(textureSource, options) { + return this.stage.renderer.uploadTextureSource(textureSource, options); + } + _nativeFreeTextureSource(textureSource) { + this.stage.renderer.freeTextureSource(textureSource); + textureSource.clearNativeTexture(); + } + } + class TextureThrottler { + constructor(stage) { + this.stage = stage; + this.genericCancelCb = (textureSource) => { + this._remove(textureSource); + }; + this._sources = []; + this._data = []; + } + destroy() { + this._sources = []; + this._data = []; + this.stage = null; + delete this._sources; + delete this._data; + delete this.stage; + } + processSome() { + if (this._sources.length) { + const start = Date.now(); + do { + this._processItem(); + } while (this._sources.length && Date.now() - start < TextureThrottler.MAX_UPLOAD_TIME_PER_FRAME); + } + } + _processItem() { + const source = this._sources.pop(); + const data = this._data.pop(); + if (source.isLoading()) { + source.processLoadedSource(data); + } + } + add(textureSource, data) { + this._sources.push(textureSource); + this._data.push(data); + } + _remove(textureSource) { + const index = this._sources.indexOf(textureSource); + if (index >= 0) { + this._sources.splice(index, 1); + this._data.splice(index, 1); + } + } + } + TextureThrottler.MAX_UPLOAD_TIME_PER_FRAME = 10; + class CoreContext { + constructor(stage) { + this.stage = stage; + this.root = null; + this.updateTreeOrder = 0; + this.renderState = this.stage.renderer.createCoreRenderState(this); + this.renderExec = this.stage.renderer.createCoreRenderExecutor(this); + this.renderExec.init(); + this._usedMemory = 0; + this._renderTexturePool = []; + this._renderTextureId = 1; + this._zSorts = []; + this.renderToTextureCount = 0; + } + get usedMemory() { + return this._usedMemory; + } + destroy() { + this._renderTexturePool.forEach((texture) => this._freeRenderTexture(texture)); + this._usedMemory = 0; + this.stage = null; + this.root = null; + this.renderState = null; + this.renderExec = null; + this._renderTexturePool = null; + this._zSorts = null; + delete this.stage; + delete this.root; + delete this.renderState; + delete this.renderExec; + delete this._renderTexturePool; + delete this._zSorts; + } + hasRenderUpdates() { + return !!this.root._parent._hasRenderUpdates; + } + render() { + this.root._parent._hasRenderUpdates = 0; + this._render(); + } + update() { + this._update(); + if (this.root._hasUpdates) { + this._update(); + } + this._performForcedZSorts(); + } + _performForcedZSorts() { + const n = this._zSorts.length; + if (n) { + for (let i = 0, n2 = this._zSorts.length; i < n2; i++) { + if (this._zSorts[i].zSort) { + this._zSorts[i].sortZIndexedChildren(); + } + } + this._zSorts = []; + } + } + _update() { + this.updateTreeOrder = 0; + this.root.update(); + } + _render() { + const debugFrame = this.stage.getOption("debugFrame"); + this._fillRenderState(); + if (this.stage.getOption("readPixelsBeforeDraw")) { + this._readPixels(); + } + this._performRender(); + if (debugFrame) { + console.log(`[Lightning] RTT Renders in frame: ${this.renderToTextureCount}`); + } + if (this.stage.getOption("readPixelsAfterDraw") && this.renderToTextureCount >= this.stage.getOption("readPixelsAfterDrawThreshold")) { + if (debugFrame) { + console.log(`[Lightning] readPixelsAfterDraw behavior triggered`); + } + this._readPixels(); + } + this.renderToTextureCount = 0; + } + _readPixels() { + const pixels = new Uint8Array(4); + const gl = this.stage.gl; + gl.readPixels(0, 0, 1, 1, gl.RGBA, gl.UNSIGNED_BYTE, pixels); + } + _fillRenderState() { + this.renderState.reset(); + this.root.render(); + this.renderState.finish(); + } + _performRender() { + this.renderExec.execute(); + } + _addMemoryUsage(delta) { + this._usedMemory += delta; + this.stage.addMemoryUsage(delta); + } + allocateRenderTexture(w, h) { + let prec = this.stage.getRenderPrecision(); + let pw = Math.max(1, Math.round(w * prec)); + let ph = Math.max(1, Math.round(h * prec)); + const n = this._renderTexturePool.length; + for (let i = n - 1; i >= 0; i--) { + const texture2 = this._renderTexturePool[i]; + if (texture2.w === pw && texture2.h === ph && texture2.update !== this.stage.frameCounter) { + texture2.f = this.stage.frameCounter; + this._renderTexturePool.splice(i, 1); + return texture2; + } + } + const texture = this._createRenderTexture(w, h, pw, ph); + texture.precision = prec; + return texture; + } + releaseRenderTexture(texture) { + this._renderTexturePool.push(texture); + } + freeUnusedRenderTextures(maxAge = 60) { + let limit = this.stage.frameCounter - maxAge; + this._renderTexturePool = this._renderTexturePool.filter((texture) => { + if (texture.f <= limit) { + this._freeRenderTexture(texture); + return false; + } + return true; + }); + } + _createRenderTexture(w, h, pw, ph) { + this._addMemoryUsage(pw * ph); + const texture = this.stage.renderer.createRenderTexture(w, h, pw, ph); + texture.id = this._renderTextureId++; + texture.f = this.stage.frameCounter; + texture.ow = w; + texture.oh = h; + texture.w = pw; + texture.h = ph; + return texture; + } + _freeRenderTexture(nativeTexture) { + this.stage.renderer.freeRenderTexture(nativeTexture); + this._addMemoryUsage(-nativeTexture.w * nativeTexture.h); + } + copyRenderTexture(renderTexture, nativeTexture, options) { + this.stage.renderer.copyRenderTexture(renderTexture, nativeTexture, options); + } + forceZSort(elementCore) { + this._zSorts.push(elementCore); + } + } + class TransitionSettings { + constructor(stage) { + this.stage = stage; + this._timingFunction = "ease"; + this._timingFunctionImpl = StageUtils.getTimingFunction(this._timingFunction); + this.delay = 0; + this.duration = 0.2; + this.merger = null; + } + get timingFunction() { + return this._timingFunction; + } + set timingFunction(v) { + this._timingFunction = v; + this._timingFunctionImpl = StageUtils.getTimingFunction(v); + } + get timingFunctionImpl() { + return this._timingFunctionImpl; + } + patch(settings) { + Base.patchObject(this, settings); + } + } + TransitionSettings.prototype.isTransitionSettings = true; + class TransitionManager { + constructor(stage) { + this.stage = stage; + this.stage.on("frameStart", () => this.progress()); + this.active = /* @__PURE__ */ new Set(); + this.defaultTransitionSettings = new TransitionSettings(this.stage); + } + progress() { + if (this.active.size) { + let dt = this.stage.dt; + let filter = false; + this.active.forEach(function(a) { + a.progress(dt); + if (!a.isRunning()) { + filter = true; + } + }); + if (filter) { + this.active = new Set([...this.active].filter((t) => t.isRunning())); + } + } + } + createSettings(settings) { + const transitionSettings = new TransitionSettings(); + Base.patchObject(transitionSettings, settings); + return transitionSettings; + } + addActive(transition) { + this.active.add(transition); + } + removeActive(transition) { + this.active.delete(transition); + } + } + class MultiSpline { + constructor() { + this._clear(); + } + _clear() { + this._p = []; + this._pe = []; + this._idp = []; + this._f = []; + this._v = []; + this._lv = []; + this._sm = []; + this._s = []; + this._ve = []; + this._sme = []; + this._se = []; + this._length = 0; + } + parse(rgba, def) { + let i, n; + if (!Utils$1.isObjectLiteral(def)) { + def = { 0: def }; + } + let defaultSmoothness = 0.5; + let items = []; + for (let key in def) { + if (def.hasOwnProperty(key)) { + let obj = def[key]; + if (!Utils$1.isObjectLiteral(obj)) { + obj = { v: obj }; + } + let p = parseFloat(key); + if (key === "sm") { + defaultSmoothness = obj.v; + } else if (!isNaN(p) && p >= 0 && p <= 2) { + obj.p = p; + obj.f = Utils$1.isFunction(obj.v); + obj.lv = obj.f ? obj.v(0, 0) : obj.v; + items.push(obj); + } + } + } + items = items.sort(function(a, b) { + return a.p - b.p; + }); + n = items.length; + for (i = 0; i < n; i++) { + let last = i === n - 1; + if (!items[i].hasOwnProperty("pe")) { + items[i].pe = last ? items[i].p <= 1 ? 1 : 2 : items[i + 1].p; + } else { + const max = i < n - 1 ? items[i + 1].p : 1; + if (items[i].pe > max) { + items[i].pe = max; + } + } + if (items[i].pe === items[i].p) { + items[i].idp = 0; + } else { + items[i].idp = 1 / (items[i].pe - items[i].p); + } + } + for (i = 0; i < n; i++) { + if (!items[i].hasOwnProperty("sm")) { + items[i].sm = defaultSmoothness; + } + if (!items[i].hasOwnProperty("s")) { + if (i === 0 || i === n - 1 || items[i].p === 1) { + items[i].s = rgba ? [0, 0, 0, 0] : 0; + } else { + const pi = items[i - 1]; + const ni = items[i + 1]; + if (pi.p === ni.p) { + items[i].s = rgba ? [0, 0, 0, 0] : 0; + } else { + if (rgba) { + const nc = MultiSpline.getRgbaComponents(ni.lv); + const pc = MultiSpline.getRgbaComponents(pi.lv); + const d = 1 / (ni.p - pi.p); + items[i].s = [ + d * (nc[0] - pc[0]), + d * (nc[1] - pc[1]), + d * (nc[2] - pc[2]), + d * (nc[3] - pc[3]) + ]; + } else { + items[i].s = (ni.lv - pi.lv) / (ni.p - pi.p); + } + } + } + } + } + for (i = 0; i < n - 1; i++) { + if (!items[i].f) { + let last = i === n - 1; + if (!items[i].hasOwnProperty("ve")) { + items[i].ve = last ? items[i].lv : items[i + 1].lv; + } + if (Utils$1.isNumber(items[i].v) && Utils$1.isNumber(items[i].lv)) { + if (!items[i].hasOwnProperty("sme")) { + items[i].sme = last ? defaultSmoothness : items[i + 1].sm; + } + if (!items[i].hasOwnProperty("se")) { + items[i].se = last ? rgba ? [0, 0, 0, 0] : 0 : items[i + 1].s; + } + if (rgba) { + items[i].v = MultiSpline.getSplineRgbaValueFunction(items[i].v, items[i].ve, items[i].p, items[i].pe, items[i].sm, items[i].sme, items[i].s, items[i].se); + } else { + items[i].v = MultiSpline.getSplineValueFunction(items[i].v, items[i].ve, items[i].p, items[i].pe, items[i].sm, items[i].sme, items[i].s, items[i].se); + } + items[i].f = true; + } + } + } + if (this.length) { + this._clear(); + } + for (i = 0, n = items.length; i < n; i++) { + this._add(items[i]); + } + } + _add(item) { + this._p.push(item.p || 0); + this._pe.push(item.pe || 0); + this._idp.push(item.idp || 0); + this._f.push(item.f || false); + this._v.push(item.hasOwnProperty("v") ? item.v : 0); + this._lv.push(item.lv || 0); + this._sm.push(item.sm || 0); + this._s.push(item.s || 0); + this._ve.push(item.ve || 0); + this._sme.push(item.sme || 0); + this._se.push(item.se || 0); + this._length++; + } + _getItem(p) { + const n = this._length; + if (!n) { + return -1; + } + if (p < this._p[0]) { + return 0; + } + for (let i = 0; i < n; i++) { + if (this._p[i] <= p && p < this._pe[i]) { + return i; + } + } + return n - 1; + } + getValue(p) { + const i = this._getItem(p); + if (i === -1) { + return void 0; + } else { + if (this._f[i]) { + const o = Math.min(1, Math.max(0, (p - this._p[i]) * this._idp[i])); + return this._v[i](o); + } else { + return this._v[i]; + } + } + } + get length() { + return this._length; + } + static getRgbaComponents(argb) { + let r = (argb / 65536 | 0) % 256; + let g = (argb / 256 | 0) % 256; + let b = argb % 256; + let a = argb / 16777216 | 0; + return [r, g, b, a]; + } + static getSplineValueFunction(v1, v2, p1, p2, o1, i2, s1, s2) { + let dp = p2 - p1; + s1 *= dp; + s2 *= dp; + let helpers = MultiSpline.getSplineHelpers(v1, v2, o1, i2, s1, s2); + if (!helpers) { + return function(p) { + if (p === 0) + return v1; + if (p === 1) + return v2; + return v2 * p + v1 * (1 - p); + }; + } else { + return function(p) { + if (p === 0) + return v1; + if (p === 1) + return v2; + return MultiSpline.calculateSpline(helpers, p); + }; + } + } + static getSplineRgbaValueFunction(v1, v2, p1, p2, o1, i2, s1, s2) { + let dp = p2 - p1; + s1[0] *= dp; + s1[1] *= dp; + s1[2] *= dp; + s1[3] *= dp; + s2[0] *= dp; + s2[1] *= dp; + s2[2] *= dp; + s2[3] *= dp; + let cv1 = MultiSpline.getRgbaComponents(v1); + let cv2 = MultiSpline.getRgbaComponents(v2); + let helpers = [ + MultiSpline.getSplineHelpers(cv1[0], cv2[0], o1, i2, s1[0], s2[0]), + MultiSpline.getSplineHelpers(cv1[1], cv2[1], o1, i2, s1[1], s2[1]), + MultiSpline.getSplineHelpers(cv1[2], cv2[2], o1, i2, s1[2], s2[2]), + MultiSpline.getSplineHelpers(cv1[3], cv2[3], o1, i2, s1[3], s2[3]) + ]; + if (!helpers[0]) { + return function(p) { + if (p === 0) + return v1; + if (p === 1) + return v2; + return MultiSpline.mergeColors(v2, v1, p); + }; + } else { + return function(p) { + if (p === 0) + return v1; + if (p === 1) + return v2; + return MultiSpline.getArgbNumber([ + Math.min(255, MultiSpline.calculateSpline(helpers[0], p)), + Math.min(255, MultiSpline.calculateSpline(helpers[1], p)), + Math.min(255, MultiSpline.calculateSpline(helpers[2], p)), + Math.min(255, MultiSpline.calculateSpline(helpers[3], p)) + ]); + }; + } + } + static getSplineHelpers(v1, v2, o1, i2, s1, s2) { + if (!o1 && !i2) { + return null; + } + let csx = o1; + let csy = v1 + s1 * o1; + let cex = 1 - i2; + let cey = v2 - s2 * i2; + let xa = 3 * csx - 3 * cex + 1; + let xb = -6 * csx + 3 * cex; + let xc = 3 * csx; + let ya = 3 * csy - 3 * cey + v2 - v1; + let yb = 3 * (cey + v1) - 6 * csy; + let yc = 3 * (csy - v1); + let yd = v1; + return [xa, xb, xc, ya, yb, yc, yd]; + } + static calculateSpline(helpers, p) { + let xa = helpers[0]; + let xb = helpers[1]; + let xc = helpers[2]; + let ya = helpers[3]; + let yb = helpers[4]; + let yc = helpers[5]; + let yd = helpers[6]; + if (xa === -2 && ya === -2 && xc === 0 && yc === 0) { + return p; + } + let t = 0.5, cbx, dx; + for (let it = 0; it < 20; it++) { + cbx = t * (t * (t * xa + xb) + xc); + dx = p - cbx; + if (dx > -1e-8 && dx < 1e-8) { + return t * (t * (t * ya + yb) + yc) + yd; + } + let cbxd = t * (t * (3 * xa) + 2 * xb) + xc; + if (cbxd > 1e-10 && cbxd < 1e-10) { + break; + } + t += dx / cbxd; + } + let minT = 0; + let maxT = 1; + for (let it = 0; it < 20; it++) { + t = 0.5 * (minT + maxT); + cbx = t * (t * (t * xa + xb) + xc); + dx = p - cbx; + if (dx > -1e-8 && dx < 1e-8) { + return t * (t * (t * ya + yb) + yc) + yd; + } + if (dx < 0) { + maxT = t; + } else { + minT = t; + } + } + return t; + } + static mergeColors(c1, c2, p) { + let r1 = (c1 / 65536 | 0) % 256; + let g1 = (c1 / 256 | 0) % 256; + let b1 = c1 % 256; + let a1 = c1 / 16777216 | 0; + let r2 = (c2 / 65536 | 0) % 256; + let g2 = (c2 / 256 | 0) % 256; + let b2 = c2 % 256; + let a2 = c2 / 16777216 | 0; + let r = r1 * p + r2 * (1 - p); + let g = g1 * p + g2 * (1 - p); + let b = b1 * p + b2 * (1 - p); + let a = a1 * p + a2 * (1 - p); + return Math.round(a) * 16777216 + Math.round(r) * 65536 + Math.round(g) * 256 + Math.round(b); + } + static getArgbNumber(rgba) { + rgba[0] = Math.max(0, Math.min(255, rgba[0])); + rgba[1] = Math.max(0, Math.min(255, rgba[1])); + rgba[2] = Math.max(0, Math.min(255, rgba[2])); + rgba[3] = Math.max(0, Math.min(255, rgba[3])); + let v = ((rgba[3] | 0) << 24) + ((rgba[0] | 0) << 16) + ((rgba[1] | 0) << 8) + (rgba[2] | 0); + if (v < 0) { + v = 4294967295 + v + 1; + } + return v; + } + } + class AnimationActionSettings { + constructor(animationSettings) { + this.animationSettings = animationSettings; + this._selector = ""; + this._items = new MultiSpline(); + this._props = []; + this._propSetters = []; + this._resetValue = void 0; + this._hasResetValue = false; + this._hasColorProperty = void 0; + } + getResetValue() { + if (this._hasResetValue) { + return this._resetValue; + } else { + return this._items.getValue(0); + } + } + apply(element, p, factor) { + const elements = this.getAnimatedElements(element); + let v = this._items.getValue(p); + if (v === void 0 || !elements.length) { + return; + } + if (factor !== 1) { + let sv = this.getResetValue(); + if (Utils$1.isNumber(v) && Utils$1.isNumber(sv)) { + if (this.hasColorProperty()) { + v = StageUtils.mergeColors(v, sv, factor); + } else { + v = StageUtils.mergeNumbers(v, sv, factor); + } + } + } + const n = this._propSetters.length; + const m = elements.length; + for (let j = 0; j < m; j++) { + for (let i = 0; i < n; i++) { + this._propSetters[i](elements[j], v); + } + } + } + getAnimatedElements(element) { + return element.select(this._selector); + } + reset(element) { + const elements = this.getAnimatedElements(element); + let v = this.getResetValue(); + if (v === void 0 || !elements.length) { + return; + } + const n = this._propSetters.length; + const m = elements.length; + for (let j = 0; j < m; j++) { + for (let i = 0; i < n; i++) { + this._propSetters[i](elements[j], v); + } + } + } + set selector(v) { + this._selector = v; + } + set t(v) { + this.selector = v; + } + get resetValue() { + return this._resetValue; + } + set resetValue(v) { + this._resetValue = v; + this._hasResetValue = v !== void 0; + } + set rv(v) { + this.resetValue = v; + } + set value(v) { + this._items.parse(this.hasColorProperty(), v); + } + set v(v) { + this.value = v; + } + set properties(v) { + if (!Array.isArray(v)) { + v = [v]; + } + this._props = []; + v.forEach((prop) => { + this._props.push(prop); + this._propSetters.push(Element.getSetter(prop)); + }); + } + set property(v) { + this._hasColorProperty = void 0; + this.properties = v; + } + set p(v) { + this.properties = v; + } + patch(settings) { + Base.patchObject(this, settings); + } + hasColorProperty() { + if (this._hasColorProperty === void 0) { + this._hasColorProperty = this._props.length ? Element.isColorProperty(this._props[0]) : false; + } + return this._hasColorProperty; + } + } + AnimationActionSettings.prototype.isAnimationActionSettings = true; + class AnimationSettings { + constructor() { + this._actions = []; + this.delay = 0; + this.duration = 1; + this.repeat = 0; + this.repeatOffset = 0; + this.repeatDelay = 0; + this.autostop = false; + this.stopMethod = AnimationSettings.STOP_METHODS.FADE; + this._stopTimingFunction = "ease"; + this._stopTimingFunctionImpl = StageUtils.getTimingFunction(this._stopTimingFunction); + this.stopDuration = 0; + this.stopDelay = 0; + } + get actions() { + return this._actions; + } + set actions(v) { + this._actions = []; + for (let i = 0, n = v.length; i < n; i++) { + const e = v[i]; + if (!e.isAnimationActionSettings) { + const aas = new AnimationActionSettings(this); + aas.patch(e); + this._actions.push(aas); + } else { + this._actions.push(e); + } + } + } + apply(element, p, factor = 1) { + this._actions.forEach(function(action) { + action.apply(element, p, factor); + }); + } + reset(element) { + this._actions.forEach(function(action) { + action.reset(element); + }); + } + get stopTimingFunction() { + return this._stopTimingFunction; + } + set stopTimingFunction(v) { + this._stopTimingFunction = v; + this._stopTimingFunctionImpl = StageUtils.getTimingFunction(v); + } + get stopTimingFunctionImpl() { + return this._stopTimingFunctionImpl; + } + patch(settings) { + Base.patchObject(this, settings); + } + } + AnimationSettings.STOP_METHODS = { + FADE: "fade", + REVERSE: "reverse", + FORWARD: "forward", + IMMEDIATE: "immediate", + ONETOTWO: "onetotwo" + }; + class Animation extends EventEmitter { + constructor(manager, settings, element) { + super(); + this.manager = manager; + this._settings = settings; + this._element = element; + this._state = Animation.STATES.IDLE; + this._p = 0; + this._delayLeft = 0; + this._repeatsLeft = 0; + this._stopDelayLeft = 0; + this._stopP = 0; + } + start() { + if (this._element && this._element.attached) { + this._p = 0; + this._delayLeft = this.settings.delay; + this._repeatsLeft = this.settings.repeat; + this._state = Animation.STATES.PLAYING; + this.emit("start"); + this.checkActive(); + } else { + console.warn("[Lightning] Element must be attached before starting animation"); + } + } + play() { + if (this._state === Animation.STATES.PAUSED) { + this._state = Animation.STATES.PLAYING; + this.checkActive(); + this.emit("resume"); + } else if (this._state == Animation.STATES.STOPPING && this.settings.stopMethod == AnimationSettings.STOP_METHODS.REVERSE) { + this._state = Animation.STATES.PLAYING; + this.emit("stopContinue"); + } else if (this._state != Animation.STATES.PLAYING && this._state != Animation.STATES.FINISHED) { + this.start(); + } + } + pause() { + if (this._state === Animation.STATES.PLAYING) { + this._state = Animation.STATES.PAUSED; + this.emit("pause"); + } + } + replay() { + if (this._state == Animation.STATES.FINISHED) { + this.start(); + } else { + this.play(); + } + } + skipDelay() { + this._delayLeft = 0; + this._stopDelayLeft = 0; + } + finish() { + if (this._state === Animation.STATES.PLAYING) { + this._delayLeft = 0; + this._p = 1; + } else if (this._state === Animation.STATES.STOPPING) { + this._stopDelayLeft = 0; + this._p = 0; + } + } + stop() { + if (this._state === Animation.STATES.STOPPED || this._state === Animation.STATES.IDLE) + return; + this._stopDelayLeft = this.settings.stopDelay || 0; + if (this.settings.stopMethod === AnimationSettings.STOP_METHODS.IMMEDIATE && !this._stopDelayLeft || this._delayLeft > 0) { + this._state = Animation.STATES.STOPPING; + this.emit("stop"); + } else { + if (this.settings.stopMethod === AnimationSettings.STOP_METHODS.FADE) { + this._stopP = 0; + } + this._state = Animation.STATES.STOPPING; + this.emit("stop"); + } + this.checkActive(); + } + stopNow() { + if (this._state !== Animation.STATES.STOPPED || this._state !== Animation.STATES.IDLE) { + this._state = Animation.STATES.STOPPING; + this._p = 0; + this.emit("stop"); + this.reset(); + this._state = Animation.STATES.STOPPED; + this.emit("stopFinish"); + } + } + isPaused() { + return this._state === Animation.STATES.PAUSED; + } + isPlaying() { + return this._state === Animation.STATES.PLAYING; + } + isStopping() { + return this._state === Animation.STATES.STOPPING; + } + isFinished() { + return this._state === Animation.STATES.FINISHED; + } + checkActive() { + if (this.isActive()) { + this.manager.addActive(this); + } + } + isActive() { + return (this._state == Animation.STATES.PLAYING || this._state == Animation.STATES.STOPPING) && this._element && this._element.attached; + } + progress(dt) { + if (!this._element) + return; + this._progress(dt); + this.apply(); + } + _progress(dt) { + if (this._state == Animation.STATES.STOPPING) { + this._stopProgress(dt); + return; + } + if (this._state != Animation.STATES.PLAYING) { + return; + } + if (this._delayLeft > 0) { + this._delayLeft -= dt; + if (this._delayLeft < 0) { + dt = -this._delayLeft; + this._delayLeft = 0; + this.emit("delayEnd"); + } else { + return; + } + } + if (this.settings.duration === 0) { + this._p = 1; + } else if (this.settings.duration > 0) { + this._p += dt / this.settings.duration; + } + if (this._p >= 1) { + if (this.settings.repeat == -1 || this._repeatsLeft > 0) { + if (this._repeatsLeft > 0) { + this._repeatsLeft--; + } + this._p = this.settings.repeatOffset; + this.emit("progress", this._p); + if (this.settings.repeatDelay) { + this._delayLeft = this.settings.repeatDelay; + } + this.emit("repeat", this._repeatsLeft); + } else { + this._p = 1; + this.emit("progress", this._p); + this._state = Animation.STATES.FINISHED; + this.emit("finish"); + if (this.settings.autostop) { + this.stop(); + } + } + } else { + this.emit("progress", this._p); + } + } + _stopProgress(dt) { + let duration = this._getStopDuration(); + if (this._stopDelayLeft > 0) { + this._stopDelayLeft -= dt; + if (this._stopDelayLeft < 0) { + dt = -this._stopDelayLeft; + this._stopDelayLeft = 0; + this.emit("stopDelayEnd"); + } else { + return; + } + } + if (this.settings.stopMethod == AnimationSettings.STOP_METHODS.IMMEDIATE) { + this._state = Animation.STATES.STOPPED; + this.emit("stopFinish"); + } else if (this.settings.stopMethod == AnimationSettings.STOP_METHODS.REVERSE) { + if (duration === 0) { + this._p = 0; + } else if (duration > 0) { + this._p -= dt / duration; + } + if (this._p <= 0) { + this._p = 0; + this._state = Animation.STATES.STOPPED; + this.emit("stopFinish"); + } + } else if (this.settings.stopMethod == AnimationSettings.STOP_METHODS.FADE) { + this._progressStopTransition(dt); + if (this._stopP >= 1) { + this._p = 0; + this._state = Animation.STATES.STOPPED; + this.emit("stopFinish"); + } + } else if (this.settings.stopMethod == AnimationSettings.STOP_METHODS.ONETOTWO) { + if (this._p < 2) { + if (duration === 0) { + this._p = 2; + } else if (duration > 0) { + if (this._p < 1) { + this._p += dt / this.settings.duration; + } else { + this._p += dt / duration; + } + } + if (this._p >= 2) { + this._p = 2; + this._state = Animation.STATES.STOPPED; + this.emit("stopFinish"); + } else { + this.emit("progress", this._p); + } + } + } else if (this.settings.stopMethod == AnimationSettings.STOP_METHODS.FORWARD) { + if (this._p < 1) { + if (this.settings.duration == 0) { + this._p = 1; + } else { + this._p += dt / this.settings.duration; + } + if (this._p >= 1) { + if (this.settings.stopMethod == AnimationSettings.STOP_METHODS.FORWARD) { + this._p = 1; + this._state = Animation.STATES.STOPPED; + this.emit("stopFinish"); + } else { + if (this._repeatsLeft > 0) { + this._repeatsLeft--; + this._p = 0; + this.emit("repeat", this._repeatsLeft); + } else { + this._p = 1; + this._state = Animation.STATES.STOPPED; + this.emit("stopFinish"); + } + } + } else { + this.emit("progress", this._p); + } + } + } + } + _progressStopTransition(dt) { + if (this._stopP < 1) { + if (this._stopDelayLeft > 0) { + this._stopDelayLeft -= dt; + if (this._stopDelayLeft < 0) { + dt = -this._stopDelayLeft; + this._stopDelayLeft = 0; + this.emit("delayEnd"); + } else { + return; + } + } + const duration = this._getStopDuration(); + if (duration == 0) { + this._stopP = 1; + } else { + this._stopP += dt / duration; + } + if (this._stopP >= 1) { + this._stopP = 1; + } + } + } + _getStopDuration() { + return this.settings.stopDuration || this.settings.duration; + } + apply() { + if (this._state === Animation.STATES.STOPPED) { + this.reset(); + } else { + let factor = 1; + if (this._state === Animation.STATES.STOPPING && this.settings.stopMethod === AnimationSettings.STOP_METHODS.FADE) { + factor = 1 - this.settings.stopTimingFunctionImpl(this._stopP); + } + this._settings.apply(this._element, this._p, factor); + } + } + reset() { + this._settings.reset(this._element); + } + get state() { + return this._state; + } + get p() { + return this._p; + } + get delayLeft() { + return this._delayLeft; + } + get element() { + return this._element; + } + get frame() { + return Math.round(this._p * this._settings.duration * 60); + } + get settings() { + return this._settings; + } + } + Animation.STATES = { + IDLE: 0, + PLAYING: 1, + STOPPING: 2, + STOPPED: 3, + FINISHED: 4, + PAUSED: 5 + }; + class AnimationManager { + constructor(stage) { + this.stage = stage; + this.stage.on("frameStart", () => this.progress()); + this.active = /* @__PURE__ */ new Set(); + } + progress() { + if (this.active.size) { + let dt = this.stage.dt; + let filter = false; + this.active.forEach(function(a) { + if (a.isActive()) { + a.progress(dt); + } else { + filter = true; + } + }); + if (filter) { + this.active = new Set([...this.active].filter((t) => t.isActive())); + } + } + } + createAnimation(element, settings) { + if (Utils$1.isObjectLiteral(settings)) { + settings = this.createSettings(settings); + } + return new Animation( + this, + settings, + element + ); + } + createSettings(settings) { + const animationSettings = new AnimationSettings(); + Base.patchObject(animationSettings, settings); + return animationSettings; + } + addActive(transition) { + this.active.add(transition); + } + } + class RectangleTexture extends Texture { + _getLookupId() { + return "__whitepix"; + } + _getSourceLoader() { + return function(cb) { + var whitePixel = new Uint8Array([255, 255, 255, 255]); + cb(null, { source: whitePixel, w: 1, h: 1, permanent: true }); + }; + } + isAutosizeTexture() { + return false; + } + } + class Stage extends EventEmitter { + constructor(options = {}) { + super(); + this._setOptions(options); + this._usedMemory = 0; + this._lastGcFrame = 0; + this._usedVramAlpha = 0; + this._usedVramNonAlpha = 0; + const platformType = Stage.platform ? Stage.platform : PlatformLoader.load(options); + this.platform = new platformType(); + if (this.platform.init) { + this.platform.init(this); + } + this.gl = null; + this.c2d = null; + const context = this.getOption("context"); + if (context) { + if (context.useProgram) { + this.gl = context; + } else { + this.c2d = context; + } + } else { + if (Utils$1.isWeb && (!Stage.isWebglSupported() || this.getOption("canvas2d"))) { + this.c2d = this.platform.createCanvasContext(this.getOption("w"), this.getOption("h")); + } else { + this.gl = this.platform.createWebGLContext(this.getOption("w"), this.getOption("h")); + } + } + if (this.gl) { + WebGLStateManager.enable(this.gl, "lightning"); + } + this._mode = this.gl ? 0 : 1; + if (this.getCanvas()) { + if (this.getOption("devicePixelRatio") !== 1) { + const ratio = this.getOption("devicePixelRatio"); + this.getCanvas().style.width = this._options["w"] / ratio + "px"; + this.getCanvas().style.height = this._options["h"] / ratio + "px"; + } + this._options.w = this.getCanvas().width; + this._options.h = this.getCanvas().height; + } + if (this._mode === 0) { + if (Utils$1.isSpark) { + this._renderer = new SparkRenderer(this); + } else { + this._renderer = new WebGLRenderer(this); + } + } else { + this._renderer = new C2dRenderer(this); + } + this.setClearColor(this.getOption("clearColor")); + this.frameCounter = 0; + this.transitions = new TransitionManager(this); + this.animations = new AnimationManager(this); + this.textureManager = new TextureManager(this); + this.textureThrottler = new TextureThrottler(this); + this.startTime = 0; + this.currentTime = 0; + this.dt = 0; + this.rectangleTexture = new RectangleTexture(this); + this.rectangleTexture.load(); + this.rectangleTexture.source.permanent = true; + this.ctx = new CoreContext(this); + this._updateSourceTextures = /* @__PURE__ */ new Set(); + } + get renderer() { + return this._renderer; + } + static isWebglSupported() { + if (Utils$1.isNode) { + return true; + } + try { + return !!window.WebGLRenderingContext; + } catch (e) { + return false; + } + } + get mode() { + return this._mode; + } + isWebgl() { + return this.mode === 0; + } + isC2d() { + return this.mode === 1; + } + getOption(name) { + return this._options[name]; + } + _setOptions(o) { + this._options = {}; + let opt = (name, def) => { + let value = o[name]; + if (value === void 0) { + this._options[name] = def; + } else { + this._options[name] = value; + } + }; + opt("canvas", null); + opt("context", null); + opt("w", 1920); + opt("h", 1080); + opt("srcBasePath", null); + opt("memoryPressure", 24e6); + opt("bufferMemory", 2e6); + opt("textRenderIssueMargin", 0); + opt("fontSharp", { precision: 0.6666666667, fontSize: 24 }); + opt("clearColor", [0, 0, 0, 0]); + opt("defaultFontFace", "sans-serif"); + opt("fixedDt", 0); + opt("useImageWorker", true); + opt("autostart", true); + opt("precision", 1); + opt("canvas2d", false); + opt("platform", null); + opt("readPixelsBeforeDraw", false); + opt("devicePixelRatio", 1); + opt("readPixelsAfterDraw", false); + opt("readPixelsAfterDrawThreshold", 0); + opt("debugFrame", false); + opt("forceTxCanvasSource", false); + opt("pauseRafLoopOnIdle", false); + if (o["devicePixelRatio"] != null && o["devicePixelRatio"] !== 1) { + this._options["precision"] *= o["devicePixelRatio"]; + this._options["w"] *= o["devicePixelRatio"]; + this._options["h"] *= o["devicePixelRatio"]; + } + } + setApplication(app) { + this.application = app; + } + init() { + if (this.application.getOption("debug") && this.platform._imageWorker) { + console.log("[Lightning] Using image worker!"); + } + if (this.application.getOption("debug") && this.c2d) { + console.log("[Lightning] Using canvas2d renderer"); + } + this.application.setAsRoot(); + if (this.getOption("autostart")) { + this.platform.startLoop(); + } + } + destroy() { + this.platform.stopLoop(); + this.platform.destroy(); + this.ctx.destroy(); + this.textureManager.destroy(); + this._renderer.destroy(); + if (this.gl) { + this.gl.clearColor(0, 0, 0, 0); + this.gl.clear(this.gl.COLOR_BUFFER_BIT); + } else if (this.c2d) { + this.c2d.clearRect( + 0, + 0, + this.c2d.canvas.width, + this.c2d.canvas.height + ); + } + this.gl = null; + this.c2d = null; + this.ctx = null; + this._options = null; + this.platform = null; + this.textureManager = null; + this._renderer = null; + delete this.gl; + delete this.c2d; + delete this.ctx; + delete this._options; + delete this.platform; + delete this.textureManager; + delete this._renderer; + } + stop() { + this.platform.stopLoop(); + } + resume() { + this.platform.startLoop(); + } + get root() { + return this.application; + } + getCanvas() { + return this._mode ? this.c2d.canvas : this.gl.canvas; + } + getRenderPrecision() { + return this._options.precision; + } + addUpdateSourceTexture(texture) { + if (this._updatingFrame) { + texture._performUpdateSource(); + } else { + this._updateSourceTextures.add(texture); + } + } + removeUpdateSourceTexture(texture) { + if (this._updateSourceTextures) { + this._updateSourceTextures.delete(texture); + } + } + hasUpdateSourceTexture(texture) { + return this._updateSourceTextures && this._updateSourceTextures.has(texture); + } + _performUpdateSource() { + if (this._updateSourceTextures.size) { + this._updateSourceTextures.forEach((texture) => { + texture._performUpdateSource(); + }); + this._updateSourceTextures = /* @__PURE__ */ new Set(); + } + } + _calculateDt() { + this.startTime = this.currentTime; + this.currentTime = this.platform.getHrTime(); + if (this._options.fixedDt) { + this.dt = this._options.fixedDt; + } else { + this.dt = !this.startTime ? 0.02 : 1e-3 * (this.currentTime - this.startTime); + } + } + updateFrame() { + this._calculateDt(); + this.emit("frameStart"); + this._performUpdateSource(); + this.emit("update"); + } + idleFrame() { + this.textureThrottler.processSome(); + this.emit("frameEnd"); + this.frameCounter++; + } + renderFrame() { + const changes = this.ctx.hasRenderUpdates(); + this.textureThrottler.processSome(); + if (changes) { + this._updatingFrame = true; + this.ctx.update(); + this.ctx.render(); + this._updatingFrame = false; + } + this.platform.nextFrame(changes); + this.emit("frameEnd"); + this.frameCounter++; + } + isUpdatingFrame() { + return this._updatingFrame; + } + drawFrame() { + this.updateFrame(); + this.renderFrame(); + } + forceRenderUpdate() { + if (this.root) { + this.root.core._parent.setHasRenderUpdates(1); + } + } + setClearColor(clearColor) { + this.forceRenderUpdate(); + if (clearColor === null) { + this._clearColor = null; + } else if (Array.isArray(clearColor)) { + this._clearColor = clearColor; + } else { + this._clearColor = StageUtils.getRgbaComponentsNormalized(clearColor); + } + } + getClearColor() { + return this._clearColor; + } + createElement(settings) { + if (settings) { + return this.element(settings); + } else { + return new Element(this); + } + } + createShader(settings) { + return Shader.create(this, settings); + } + element(settings) { + if (settings.isElement) + return settings; + let element; + if (settings.type) { + element = new settings.type(this); + } else { + element = new Element(this); + } + element.patch(settings); + return element; + } + c(settings) { + return this.element(settings); + } + get w() { + return this._options.w; + } + get h() { + return this._options.h; + } + get coordsWidth() { + return this.w / this._options.precision; + } + get coordsHeight() { + return this.h / this._options.precision; + } + addMemoryUsage(delta) { + this._usedMemory += delta; + if (this._lastGcFrame !== this.frameCounter) { + if (this._usedMemory > this.getOption("memoryPressure")) { + this.gc(false); + if (this._usedMemory > this.getOption("memoryPressure") - 2e6) { + this.gc(true); + } + } + } + } + get usedMemory() { + return this._usedMemory; + } + addVramUsage(delta, alpha) { + if (alpha) { + this._usedVramAlpha += delta; + } else { + this._usedVramNonAlpha += delta; + } + } + get usedVramAlpha() { + return this._usedVramAlpha; + } + get usedVramNonAlpha() { + return this._usedVramNonAlpha; + } + get usedVram() { + return this._usedVramAlpha + this._usedVramNonAlpha; + } + gc(aggressive) { + if (this._lastGcFrame !== this.frameCounter) { + this._lastGcFrame = this.frameCounter; + const memoryUsageBefore = this._usedMemory; + this.gcTextureMemory(aggressive); + this.gcRenderTextureMemory(aggressive); + this.renderer.gc(aggressive); + if (this.application.getOption("debug")) { + console.log(`[Lightning] GC${aggressive ? "[aggressive]" : ""}! Frame ${this._lastGcFrame} Freed ${((memoryUsageBefore - this._usedMemory) / 1e6).toFixed(2)}MP from GPU memory. Remaining: ${(this._usedMemory / 1e6).toFixed(2)}MP`); + const other = this._usedMemory - this.textureManager.usedMemory - this.ctx.usedMemory; + console.log(`[Lightning] Textures: ${(this.textureManager.usedMemory / 1e6).toFixed(2)}MP, Render Textures: ${(this.ctx.usedMemory / 1e6).toFixed(2)}MP, Renderer caches: ${(other / 1e6).toFixed(2)}MP`); + } + } + } + gcTextureMemory(aggressive = false) { + if (aggressive && this.ctx.root.visible) { + this.ctx.root.visible = false; + this.textureManager.gc(); + this.ctx.root.visible = true; + } else { + this.textureManager.gc(); + } + } + gcRenderTextureMemory(aggressive = false) { + if (aggressive && this.root.visible) { + this.root.visible = false; + this.ctx.freeUnusedRenderTextures(0); + this.root.visible = true; + } else { + this.ctx.freeUnusedRenderTextures(0); + } + } + getDrawingCanvas() { + return this.platform.getDrawingCanvas(); + } + update() { + this.ctx.update(); + } + addServiceProvider(serviceprovider) { + if (Utils$1.isSpark) { + this.platform.addServiceProvider(serviceprovider); + } + } + getChildrenByPosition(x, y) { + const children = []; + this.root.core.update(); + this.root.core.collectAtCoord(x, y, children); + return children; + } + } + class Application extends Component { + constructor(options = {}, properties) { + Application._temp_options = options; + Application.booting = true; + const stage = new Stage(options.stage); + super(stage, properties); + Application.booting = false; + this.__updateFocusCounter = 0; + this.__keypressTimers = /* @__PURE__ */ new Map(); + this.__hoveredChild = null; + this.stage.init(); + this.updateFocusSettings(); + this.__keymap = this.getOption("keys"); + if (this.__keymap) { + this.stage.platform.registerKeydownHandler((e) => { + this._receiveKeydown(e); + }); + this.stage.platform.registerKeyupHandler((e) => { + this._receiveKeyup(e); + }); + } + if (this.getOption("enablePointer")) { + this.stage.platform.registerClickHandler((e) => { + this._receiveClick(e); + }); + this.stage.platform.registerHoverHandler((e) => { + this._receiveHover(e); + }); + this.stage.platform.registerScrollWheelHandler((e) => { + this._recieveScrollWheel(e); + }); + this.cursor = "default"; + } + } + getOption(name) { + return this.__options[name]; + } + _setOptions(o) { + this.__options = {}; + let opt = (name, def) => { + let value = o[name]; + if (value === void 0) { + this.__options[name] = def; + } else { + this.__options[name] = value; + } + }; + opt("debug", false); + opt("keys", { + 38: "Up", + 40: "Down", + 37: "Left", + 39: "Right", + 13: "Enter", + 8: "Back", + 27: "Exit" + }); + opt("enablePointer", false); + } + __construct() { + this.stage.setApplication(this); + this._setOptions(Application._temp_options); + delete Application._temp_options; + super.__construct(); + } + __init() { + super.__init(); + this.__updateFocus(); + } + updateFocusPath() { + this.__updateFocus(); + } + __updateFocus() { + const notOverridden = this.__updateFocusRec(); + if (!Application.booting && notOverridden) { + this.updateFocusSettings(); + } + } + __updateFocusRec() { + const updateFocusId = ++this.__updateFocusCounter; + this.__updateFocusId = updateFocusId; + const newFocusPath = this.__getFocusPath(); + const newFocusedComponent = newFocusPath[newFocusPath.length - 1]; + const prevFocusedComponent = this._focusPath ? this._focusPath[this._focusPath.length - 1] : void 0; + if (!prevFocusedComponent) { + this._focusPath = []; + for (let i = 0, n = newFocusPath.length; i < n; i++) { + this._focusPath.push(newFocusPath[i]); + this._focusPath[i]._focus(newFocusedComponent, void 0); + const focusOverridden = this.__updateFocusId !== updateFocusId; + if (focusOverridden) { + return false; + } + } + return true; + } else { + let m = Math.min(this._focusPath.length, newFocusPath.length); + let index; + for (index = 0; index < m; index++) { + if (this._focusPath[index] !== newFocusPath[index]) { + break; + } + } + if (this._focusPath.length !== newFocusPath.length || index !== newFocusPath.length) { + if (this.getOption("debug")) { + console.log("[Lightning] Focus changed: " + newFocusedComponent.getLocationString()); + } + for (let i = this._focusPath.length - 1; i >= index; i--) { + const unfocusedElement = this._focusPath.pop(); + unfocusedElement._unfocus(newFocusedComponent, prevFocusedComponent); + const focusOverridden = this.__updateFocusId !== updateFocusId; + if (focusOverridden) { + return false; + } + } + for (let i = index, n = newFocusPath.length; i < n; i++) { + this._focusPath.push(newFocusPath[i]); + this._focusPath[i]._focus(newFocusedComponent, prevFocusedComponent); + const focusOverridden = this.__updateFocusId !== updateFocusId; + if (focusOverridden) { + return false; + } + } + for (let i = 0; i < index; i++) { + this._focusPath[i]._focusChange(newFocusedComponent, prevFocusedComponent); + } + } + } + return true; + } + updateFocusSettings() { + const focusedComponent = this._focusPath[this._focusPath.length - 1]; + const focusSettings = {}; + const defaultSetFocusSettings = Component.prototype._setFocusSettings; + for (let i = 0, n = this._focusPath.length; i < n; i++) { + if (this._focusPath[i]._setFocusSettings !== defaultSetFocusSettings) { + this._focusPath[i]._setFocusSettings(focusSettings); + } + } + const defaultHandleFocusSettings = Component.prototype._handleFocusSettings; + for (let i = 0, n = this._focusPath.length; i < n; i++) { + if (this._focusPath[i]._handleFocusSettings !== defaultHandleFocusSettings) { + this._focusPath[i]._handleFocusSettings(focusSettings, this.__prevFocusSettings, focusedComponent); + } + } + this.__prevFocusSettings = focusSettings; + } + _handleFocusSettings(settings, prevSettings, focused, prevFocused) { + } + __getFocusPath() { + const path = [this]; + let current = this; + do { + const nextFocus = current._getFocused(); + if (!nextFocus || nextFocus === current) { + break; + } + let ptr = nextFocus.cparent; + if (ptr === current) { + path.push(nextFocus); + } else { + const newParts = [nextFocus]; + do { + if (!ptr) { + current._throwError("Return value for _getFocused must be an attached descendant component but its '" + nextFocus.getLocationString() + "'"); + } + newParts.push(ptr); + ptr = ptr.cparent; + } while (ptr !== current); + for (let i = 0, n = newParts.length; i < n; i++) { + path.push(newParts[n - i - 1]); + } + } + current = nextFocus; + } while (true); + return path; + } + get focusPath() { + return this._focusPath; + } + focusTopDownEvent(events, ...args) { + const path = this.focusPath; + const n = path.length; + for (let i = 0; i < n; i++) { + const event = path[i]._getMostSpecificHandledMember(events); + if (event !== void 0) { + const returnValue = path[i][event](...args); + if (returnValue !== false) { + return true; + } + } + } + return false; + } + focusBottomUpEvent(events, ...args) { + const path = this.focusPath; + const n = path.length; + for (let i = n - 1; i >= 0; i--) { + const event = path[i]._getMostSpecificHandledMember(events); + if (event !== void 0) { + const returnValue = path[i][event](...args); + if (returnValue !== false) { + return true; + } + } + } + return false; + } + _receiveKeydown(e) { + const obj = e; + const key = this.__keymap[e.keyCode]; + const path = this.focusPath; + let keys; + if (key) { + keys = Array.isArray(key) ? key : [key]; + } + if (keys) { + for (let i = 0, n = keys.length; i < n; i++) { + const hasTimer = this.__keypressTimers.has(keys[i]); + if (path[path.length - 1].longpress && hasTimer) { + return; + } + if (!this.stage.application.focusTopDownEvent([`_capture${keys[i]}`, "_captureKey"], obj)) { + this.stage.application.focusBottomUpEvent([`_handle${keys[i]}`, "_handleKey"], obj); + } + } + } else { + if (!this.stage.application.focusTopDownEvent(["_captureKey"], obj)) { + this.stage.application.focusBottomUpEvent(["_handleKey"], obj); + } + } + this.updateFocusPath(); + const consumer = path[path.length - 1]; + if (keys && consumer.longpress) { + for (let i = 0, n = keys.length; i < n; i++) { + this._startLongpressTimer(keys[i], consumer); + } + } + } + _receiveKeyup(e) { + const obj = e; + const key = this.__keymap[e.keyCode]; + let keys; + if (key) { + keys = Array.isArray(key) ? key : [key]; + } + if (keys) { + for (let i = 0, n = keys.length; i < n; i++) { + if (!this.stage.application.focusTopDownEvent([`_capture${keys[i]}Release`, "_captureKeyRelease"], obj)) { + this.stage.application.focusBottomUpEvent([`_handle${keys[i]}Release`, "_handleKeyRelease"], obj); + } + } + } else { + if (!this.stage.application.focusTopDownEvent(["_captureKeyRelease"], obj)) { + this.stage.application.focusBottomUpEvent(["_handleKeyRelease"], obj); + } + } + this.updateFocusPath(); + if (keys) { + for (let i = 0, n = keys.length; i < n; i++) { + if (this.__keypressTimers.has(keys[i])) { + clearTimeout(this.__keypressTimers.get(keys[i])); + this.__keypressTimers.delete(keys[i]); + } + } + } + } + _startLongpressTimer(key, element) { + const config = element.longpress; + const lookup = key.toLowerCase(); + if (config[lookup]) { + const timeout = config[lookup]; + if (!Utils$1.isNumber(timeout)) { + element._throwError("config value for longpress must be a number"); + } else { + this.__keypressTimers.set(key, setTimeout(() => { + if (!this.stage.application.focusTopDownEvent([`_capture${key}Long`, "_captureKey"], {})) { + this.stage.application.focusBottomUpEvent([`_handle${key}Long`, "_handleKey"], {}); + } + this.__keypressTimers.delete(key); + }, timeout || 500)); + } + } + return; + } + _recieveScrollWheel(e) { + const obj = e; + const { clientX, clientY } = obj; + if (clientX <= this.stage.w && clientY <= this.stage.h) { + if (!this.fireTopDownScrollWheelHandler("_captureScroll", obj)) { + this.fireBottomUpScrollWheelHandler("_handleScroll", obj); + } + } + } + fireTopDownScrollWheelHandler(event, obj) { + let children = this.stage.application.children; + let affected = this._findChildren([], children).reverse(); + let n = affected.length; + while (n--) { + const child = affected[n]; + if (child && child[event]) { + child._captureScroll(obj); + return true; + } + } + return false; + } + fireBottomUpScrollWheelHandler(event, obj) { + const { clientX, clientY } = obj; + const target = this._getTargetChild(clientX, clientY); + let child = target; + while (child !== null) { + if (child && child[event]) { + child._handleScroll(obj); + return true; + } + child = child.parent; + } + return false; + } + _receiveClick(e) { + const obj = e; + const { clientX, clientY } = obj; + if (clientX <= this.stage.w && clientY <= this.stage.h) { + this.stage.application.fireBottomUpClickHandler(obj); + } + } + fireBottomUpClickHandler(obj) { + const { clientX, clientY } = obj; + const target = this._getTargetChild(clientX, clientY); + const precision = this.stage.getRenderPrecision() / this.stage.getOption("devicePixelRatio"); + let child = target; + while (child !== null) { + if (child && child["_handleClick"]) { + const { px, py } = child.core._worldContext; + const cx = px * precision; + const cy = py * precision; + const localCoords = { + x: clientX - cx, + y: clientY - cy + }; + const returnValue = child._handleClick(target, localCoords); + if (returnValue !== false) { + break; + } + } + child = child.parent; + } + } + _receiveHover(e) { + const obj = e; + const { clientX, clientY } = obj; + if (clientX <= this.stage.w && clientY <= this.stage.h) { + this.stage.application.fireBottomUpHoverHandler(obj); + } + } + fireBottomUpHoverHandler(obj) { + const { clientX, clientY } = obj; + const target = this._getTargetChild(clientX, clientY); + if (target !== this.__hoveredChild) { + let hoveredBranch = /* @__PURE__ */ new Set(); + let newHoveredBranch = /* @__PURE__ */ new Set(); + if (target) { + newHoveredBranch = new Set(target.getAncestors()); + } + if (this.__hoveredChild) { + hoveredBranch = new Set(this.__hoveredChild.getAncestors()); + for (const elem of [...hoveredBranch].filter((e) => !newHoveredBranch.has(e))) { + const c = Component.getComponent(elem); + if (c["_handleUnhover"]) { + c._handleUnhover(elem); + } + if (elem.parent && elem.parent.cursor) { + this.stage.getCanvas().style.cursor = elem.parent.cursor; + } + } + } + this.__hoveredChild = target; + const diffBranch = [...newHoveredBranch].filter((e) => !hoveredBranch.has(e)); + for (const elem of diffBranch) { + const c = Component.getComponent(elem); + if (c["_handleHover"]) { + c._handleHover(elem); + } + } + const lastElement = diffBranch[0]; + if (lastElement && lastElement.cursor) { + this.stage.getCanvas().style.cursor = lastElement.cursor; + } + if (diffBranch.length === 0 && target) { + const c = Component.getComponent(target); + if (c["_handleHover"]) { + c._handleHover(target); + } + } + } + } + _getTargetChild(clientX, clientY) { + let children = this.stage.application.children; + let affected = this._findChildren([], children); + let hoverableChildren = this._withinClickableRange(affected, clientX, clientY); + hoverableChildren.sort((a, b) => { + if (a.zIndex > b.zIndex) { + return 1; + } else if (a.zIndex < b.zIndex) { + return -1; + } else { + return a.id > b.id ? 1 : -1; + } + }); + if (hoverableChildren.length) { + return hoverableChildren.slice(-1)[0]; + } else { + return null; + } + } + _findChildren(bucket, children) { + let n = children.length; + while (n--) { + const child = children[n]; + if (child.__active && child.collision) { + if (child.collision === true) { + bucket.push(child); + } + if (child.hasChildren()) { + this._findChildren(bucket, child.children); + } + } + } + return bucket; + } + _withinClickableRange(affectedChildren, cursorX, cursorY) { + let n = affectedChildren.length; + const candidates = []; + while (n--) { + const child = affectedChildren[n]; + const precision = this.stage.getRenderPrecision() / this.stage.getOption("devicePixelRatio"); + const ctx = child.core._worldContext; + const cx = ctx.px * precision; + const cy = ctx.py * precision; + const cw = child.finalW * ctx.ta * precision; + const ch = child.finalH * ctx.td * precision; + if (cx > this.stage.w || cy > this.stage.h) { + continue; + } + if (child.parent.core._scissor) { + const scissor = child.parent.core._scissor.map((v) => v * precision); + if (!this._testCollision(cursorX, cursorY, ...scissor)) + continue; + } + if (this._testCollision(cursorX, cursorY, cx, cy, cw, ch)) { + candidates.push(child); + } + } + return candidates; + } + _testCollision(px, py, cx, cy, cw, ch) { + if (px >= cx && px <= cx + cw && py >= cy && py <= cy + ch) { + return true; + } + return false; + } + destroy() { + if (!this._destroyed) { + this._destroy(); + this.stage.destroy(); + this._destroyed = true; + } + } + _destroy() { + this.stage.setApplication(void 0); + this._updateAttachedFlag(); + this._updateEnabledFlag(); + if (this.__keypressTimers.size) { + for (const timer of this.__keypressTimers.values()) { + clearTimeout(timer); + } + this.__keypressTimers.clear(); + } + } + getCanvas() { + return this.stage.getCanvas(); + } + } + class StaticCanvasTexture extends Texture { + constructor(stage) { + super(stage); + this._factory = void 0; + this._lookupId = void 0; + } + set content({ factory, lookupId = void 0 }) { + this._factory = factory; + this._lookupId = lookupId; + this._changed(); + } + _getIsValid() { + return !!this._factory; + } + _getLookupId() { + return this._lookupId; + } + _getSourceLoader() { + const f = this._factory; + return (cb) => { + return f((err, canvas) => { + if (err) { + return cb(err); + } + cb(null, this.stage.platform.getTextureOptionsForDrawingCanvas(canvas)); + }, this.stage); + }; + } + } + class Tools { + static getCanvasTexture(canvasFactory, lookupId) { + return { type: StaticCanvasTexture, content: { factory: canvasFactory, lookupId } }; + } + static getRoundRect(w, h, radius, strokeWidth, strokeColor, fill, fillColor) { + if (!Array.isArray(radius)) { + radius = [radius, radius, radius, radius]; + } + let factory = (cb, stage) => { + if (Utils$1.isSpark) { + stage.platform.createRoundRect(cb, stage, w, h, radius, strokeWidth, strokeColor, fill, fillColor); + } else { + cb(null, this.createRoundRect(stage, w, h, radius, strokeWidth, strokeColor, fill, fillColor)); + } + }; + let id = "rect" + [w, h, strokeWidth, strokeColor, fill ? 1 : 0, fillColor].concat(radius).join(","); + return Tools.getCanvasTexture(factory, id); + } + static createRoundRect(stage, w, h, radius, strokeWidth, strokeColor, fill, fillColor) { + if (fill === void 0) + fill = true; + if (strokeWidth === void 0) + strokeWidth = 0; + let canvas = stage.platform.getDrawingCanvas(); + let ctx = canvas.getContext("2d"); + ctx.imageSmoothingEnabled = true; + canvas.width = w + strokeWidth + 2; + canvas.height = h + strokeWidth + 2; + ctx.beginPath(); + let x = 0.5 * strokeWidth + 1, y = 0.5 * strokeWidth + 1; + ctx.moveTo(x + radius[0], y); + ctx.lineTo(x + w - radius[1], y); + ctx.arcTo(x + w, y, x + w, y + radius[1], radius[1]); + ctx.lineTo(x + w, y + h - radius[2]); + ctx.arcTo(x + w, y + h, x + w - radius[2], y + h, radius[2]); + ctx.lineTo(x + radius[3], y + h); + ctx.arcTo(x, y + h, x, y + h - radius[3], radius[3]); + ctx.lineTo(x, y + radius[0]); + ctx.arcTo(x, y, x + radius[0], y, radius[0]); + ctx.closePath(); + if (fill) { + if (Utils$1.isNumber(fillColor)) { + ctx.fillStyle = StageUtils.getRgbaString(fillColor); + } else { + ctx.fillStyle = "white"; + } + ctx.fill(); + } + if (strokeWidth) { + if (Utils$1.isNumber(strokeColor)) { + ctx.strokeStyle = StageUtils.getRgbaString(strokeColor); + } else { + ctx.strokeStyle = "white"; + } + ctx.lineWidth = strokeWidth; + ctx.stroke(); + } + return canvas; + } + static getShadowRect(w, h, radius = 0, blur = 5, margin = blur * 2) { + if (!Array.isArray(radius)) { + radius = [radius, radius, radius, radius]; + } + let factory = (cb, stage) => { + if (Utils$1.isSpark) { + stage.platform.createShadowRect(cb, stage, w, h, radius, blur, margin); + } else { + cb(null, this.createShadowRect(stage, w, h, radius, blur, margin)); + } + }; + let id = "shadow" + [w, h, blur, margin].concat(radius).join(","); + return Tools.getCanvasTexture(factory, id); + } + static createShadowRect(stage, w, h, radius, blur, margin) { + let canvas = stage.platform.getDrawingCanvas(); + let ctx = canvas.getContext("2d"); + ctx.imageSmoothingEnabled = true; + canvas.width = w + margin * 2; + canvas.height = h + margin * 2; + ctx.globalAlpha = 0.01; + ctx.fillRect(0, 0, 0.01, 0.01); + ctx.globalAlpha = 1; + ctx.shadowColor = StageUtils.getRgbaString(4294967295); + ctx.fillStyle = StageUtils.getRgbaString(4294967295); + ctx.shadowBlur = blur; + ctx.shadowOffsetX = w + 10 + margin; + ctx.shadowOffsetY = margin; + ctx.beginPath(); + const x = -(w + 10); + const y = 0; + ctx.moveTo(x + radius[0], y); + ctx.lineTo(x + w - radius[1], y); + ctx.arcTo(x + w, y, x + w, y + radius[1], radius[1]); + ctx.lineTo(x + w, y + h - radius[2]); + ctx.arcTo(x + w, y + h, x + w - radius[2], y + h, radius[2]); + ctx.lineTo(x + radius[3], y + h); + ctx.arcTo(x, y + h, x, y + h - radius[3], radius[3]); + ctx.lineTo(x, y + radius[0]); + ctx.arcTo(x, y, x + radius[0], y, radius[0]); + ctx.closePath(); + ctx.fill(); + return canvas; + } + static getSvgTexture(url, w, h) { + let factory = (cb, stage) => { + if (Utils$1.isSpark) { + stage.platform.createSvg(cb, stage, url, w, h); + } else { + this.createSvg(cb, stage, url, w, h); + } + }; + let id = "svg" + [w, h, url].join(","); + return Tools.getCanvasTexture(factory, id); + } + static createSvg(cb, stage, url, w, h) { + let canvas = stage.platform.getDrawingCanvas(); + let ctx = canvas.getContext("2d"); + ctx.imageSmoothingEnabled = true; + let img = new Image(); + img.onload = () => { + canvas.width = w; + canvas.height = h; + ctx.drawImage(img, 0, 0, canvas.width, canvas.height); + cb(null, canvas); + }; + img.onError = (err) => { + cb(err); + }; + if (!Utils$1.isPS4) { + img.crossOrigin = "Anonymous"; + } + img.src = url; + } + } + class ObjMerger { + static isMf(f) { + return Utils$1.isFunction(f) && f.__mf; + } + static mf(f) { + f.__mf = true; + return f; + } + static merge(a, b) { + const aks = Object.keys(a); + const bks = Object.keys(b); + if (!bks.length) { + return a; + } + const ai = {}; + const bi = {}; + for (let i = 0, n = bks.length; i < n; i++) { + const key = bks[i]; + ai[key] = -1; + bi[key] = i; + } + for (let i = 0, n = aks.length; i < n; i++) { + const key = aks[i]; + ai[key] = i; + if (bi[key] === void 0) { + bi[key] = -1; + } + } + const aksl = aks.length; + const result = {}; + for (let i = 0, n = bks.length; i < n; i++) { + const key = bks[i]; + const aIndex = ai[key]; + let curIndex2 = aIndex; + while (--curIndex2 >= 0) { + const akey = aks[curIndex2]; + if (bi[akey] !== -1) { + break; + } + } + while (++curIndex2 < aIndex) { + const akey = aks[curIndex2]; + result[akey] = a[akey]; + } + const bv = b[key]; + const av = a[key]; + let r; + if (this.isMf(bv)) { + r = bv(av); + } else { + if (!Utils$1.isObjectLiteral(av) || !Utils$1.isObjectLiteral(bv)) { + r = bv; + } else { + r = ObjMerger.merge(av, bv); + } + } + if (r !== void 0) { + result[key] = r; + } + } + let curIndex = aksl; + while (--curIndex >= 0) { + const akey = aks[curIndex]; + if (bi[akey] !== -1) { + break; + } + } + while (++curIndex < aksl) { + const akey = aks[curIndex]; + result[akey] = a[akey]; + } + return result; + } + } + class ObjectListProxy extends ObjectList { + constructor(target) { + super(); + this._target = target; + } + onAdd(item, index) { + this._target.addAt(item, index); + } + onRemove(item, index) { + this._target.removeAt(index); + } + onSync(removed, added, order) { + this._target._setByArray(order); + } + onSet(item, index) { + this._target.setAt(item, index); + } + onMove(item, fromIndex, toIndex) { + this._target.setAt(item, toIndex); + } + createItem(object) { + return this._target.createItem(object); + } + isItem(object) { + return this._target.isItem(object); + } + } + class ObjectListWrapper extends ObjectListProxy { + constructor(target, wrap) { + super(target); + this._wrap = wrap; + } + wrap(item) { + let wrapper = this._wrap(item); + item._wrapper = wrapper; + return wrapper; + } + onAdd(item, index) { + item = this.wrap(item); + super.onAdd(item, index); + } + onRemove(item, index) { + super.onRemove(item, index); + } + onSync(removed, added, order) { + added.forEach((a) => this.wrap(a)); + order = order.map((a) => a._wrapper); + super.onSync(removed, added, order); + } + onSet(item, index) { + item = this.wrap(item); + super.onSet(item, index); + } + onMove(item, fromIndex, toIndex) { + super.onMove(item, fromIndex, toIndex); + } + } + class NoiseTexture extends Texture { + _getLookupId() { + return "__noise"; + } + _getSourceLoader() { + const gl = this.stage.gl; + return function(cb) { + const noise = new Uint8Array(128 * 128 * 4); + for (let i = 0; i < 128 * 128 * 4; i += 4) { + const v = Math.floor(Math.random() * 256); + noise[i] = v; + noise[i + 1] = v; + noise[i + 2] = v; + noise[i + 3] = 255; + } + const texParams = {}; + if (gl) { + texParams[gl.TEXTURE_WRAP_S] = gl.REPEAT; + texParams[gl.TEXTURE_WRAP_T] = gl.REPEAT; + texParams[gl.TEXTURE_MIN_FILTER] = gl.NEAREST; + texParams[gl.TEXTURE_MAG_FILTER] = gl.NEAREST; + } + cb(null, { source: noise, w: 128, h: 128, texParams }); + }; + } + } + class HtmlTexture extends Texture { + constructor(stage) { + super(stage); + this._htmlElement = void 0; + this._scale = 1; + } + set htmlElement(v) { + this._htmlElement = v; + this._changed(); + } + get htmlElement() { + return this._htmlElement; + } + set scale(v) { + this._scale = v; + this._changed(); + } + get scale() { + return this._scale; + } + set html(v) { + if (!v) { + this.htmlElement = void 0; + } else { + const d = document.createElement("div"); + d.innerHTML = "
" + v + "
"; + this.htmlElement = d.firstElementChild; + } + } + get html() { + return this._htmlElement.innerHTML; + } + _getIsValid() { + return this.htmlElement; + } + _getLookupId() { + return this._scale + ":" + this._htmlElement.innerHTML; + } + _getSourceLoader() { + const htmlElement = this._htmlElement; + const scale = this._scale; + return function(cb) { + if (!window.html2canvas) { + return cb(new Error("Please include html2canvas (https://html2canvas.hertzen.com/)")); + } + const area = HtmlTexture.getPreloadArea(); + area.appendChild(htmlElement); + html2canvas(htmlElement, { backgroundColor: null, scale }).then(function(canvas) { + area.removeChild(htmlElement); + if (canvas.height === 0) { + return cb(new Error("Canvas height is 0")); + } + cb(null, { source: canvas, width: canvas.width, height: canvas.height }); + }).catch((e) => { + console.error("[Lightning]", e); + }); + }; + } + static getPreloadArea() { + if (!this._preloadArea) { + this._preloadArea = document.createElement("div"); + if (this._preloadArea.attachShadow) { + this._preloadArea.attachShadow({ mode: "closed" }); + } + this._preloadArea.style.opacity = 0; + this._preloadArea.style.pointerEvents = "none"; + this._preloadArea.style.position = "fixed"; + this._preloadArea.style.display = "block"; + this._preloadArea.style.top = "100vh"; + this._preloadArea.style.overflow = "hidden"; + document.body.appendChild(this._preloadArea); + } + return this._preloadArea; + } + } + class StaticTexture extends Texture { + constructor(stage, options) { + super(stage); + this._options = options; + } + set options(v) { + if (this._options !== v) { + this._options = v; + this._changed(); + } + } + get options() { + return this._options; + } + _getIsValid() { + return !!this._options; + } + _getSourceLoader() { + return (cb) => { + cb(null, this._options); + }; + } + } + class ListComponent extends Component { + constructor(stage) { + super(stage); + this._wrapper = super._children.a({}); + this._reloadVisibleElements = false; + this._visibleItems = /* @__PURE__ */ new Set(); + this._index = 0; + this._started = false; + this._scrollTransitionSettings = this.stage.transitions.createSettings({}); + this._itemSize = 100; + this._viewportScrollOffset = 0; + this._itemScrollOffset = 0; + this._roll = false; + this._rollMin = 0; + this._rollMax = 0; + this._progressAnimation = null; + this._invertDirection = false; + this._horizontal = true; + this.itemList = new ListItems(this); + } + _allowChildrenAccess() { + return false; + } + get items() { + return this.itemList.get(); + } + set items(children) { + this.itemList.patch(children); + } + start() { + this._wrapper.transition(this.property, this._scrollTransitionSettings); + this._scrollTransition = this._wrapper.transition(this.property); + this._scrollTransition.on("progress", (p) => this.update()); + this.setIndex(0, true, true); + this._started = true; + this.update(); + } + setIndex(index, immediate = false, closest = false) { + let nElements = this.length; + if (!nElements) + return; + this.emit("unfocus", this.getElement(this.realIndex), this._index, this.realIndex); + if (closest) { + let offset = Utils$1.getModuloIndex(index, nElements); + let o = Utils$1.getModuloIndex(this.index, nElements); + let diff = offset - o; + if (diff > 0.5 * nElements) { + diff -= nElements; + } else if (diff < -0.5 * nElements) { + diff += nElements; + } + this._index += diff; + } else { + this._index = index; + } + if (this._roll || this.viewportSize > this._itemSize * nElements) { + this._index = Utils$1.getModuloIndex(this._index, nElements); + } + let direction = this._horizontal ^ this._invertDirection ? -1 : 1; + let value = direction * this._index * this._itemSize; + if (this._roll) { + let min, max, scrollDelta; + if (direction == 1) { + max = (nElements - 1) * this._itemSize; + scrollDelta = this._viewportScrollOffset * this.viewportSize - this._itemScrollOffset * this._itemSize; + max -= scrollDelta; + min = this.viewportSize - (this._itemSize + scrollDelta); + if (this._rollMin) + min -= this._rollMin; + if (this._rollMax) + max += this._rollMax; + value = Math.max(Math.min(value, max), min); + } else { + max = nElements * this._itemSize - this.viewportSize; + scrollDelta = this._viewportScrollOffset * this.viewportSize - this._itemScrollOffset * this._itemSize; + max += scrollDelta; + let min2 = scrollDelta; + if (this._rollMin) + min2 -= this._rollMin; + if (this._rollMax) + max += this._rollMax; + value = Math.min(Math.max(-max, value), -min2); + } + } + this._scrollTransition.start(value); + if (immediate) { + this._scrollTransition.finish(); + } + this.emit("focus", this.getElement(this.realIndex), this._index, this.realIndex); + } + getAxisPosition() { + let target = -this._scrollTransition._targetValue; + let direction = this._horizontal ^ this._invertDirection ? -1 : 1; + let value = -direction * this._index * this._itemSize; + return this._viewportScrollOffset * this.viewportSize + (value - target); + } + update() { + if (!this._started) + return; + let nElements = this.length; + if (!nElements) + return; + let direction = this._horizontal ^ this._invertDirection ? -1 : 1; + let v = this._horizontal ? this._wrapper.x : this._wrapper.y; + let viewportSize = this.viewportSize; + let scrollDelta = this._viewportScrollOffset * viewportSize - this._itemScrollOffset * this._itemSize; + v += scrollDelta; + let s, e, ps, pe; + if (direction == -1) { + s = Math.floor(-v / this._itemSize); + ps = 1 - (-v / this._itemSize - s); + e = Math.floor((viewportSize - v) / this._itemSize); + pe = (viewportSize - v) / this._itemSize - e; + } else { + s = Math.ceil(v / this._itemSize); + ps = 1 + v / this._itemSize - s; + e = Math.ceil((v - viewportSize) / this._itemSize); + pe = e - (v - viewportSize) / this._itemSize; + } + if (this._roll || viewportSize > this._itemSize * nElements) { + if (e >= nElements) { + e = nElements - 1; + pe = 1; + } + if (s >= nElements) { + s = nElements - 1; + ps = 1; + } + if (e <= -1) { + e = 0; + pe = 1; + } + if (s <= -1) { + s = 0; + ps = 1; + } + } + let offset = -direction * s * this._itemSize; + let item; + for (let index = s; direction == -1 ? index <= e : index >= e; direction == -1 ? index++ : index--) { + let realIndex = Utils$1.getModuloIndex(index, nElements); + let element = this.getElement(realIndex); + item = element.parent; + this._visibleItems.delete(item); + if (this._horizontal) { + item.x = offset + scrollDelta; + } else { + item.y = offset + scrollDelta; + } + let wasVisible = item.visible; + item.visible = true; + if (!wasVisible || this._reloadVisibleElements) { + this.emit("visible", index, realIndex); + } + if (this._progressAnimation) { + let p = 1; + if (index == s) { + p = ps; + } else if (index == e) { + p = pe; + } + this._progressAnimation.apply(element, p); + } + offset += this._itemSize; + } + let self2 = this; + this._visibleItems.forEach(function(invisibleItem) { + invisibleItem.visible = false; + self2._visibleItems.delete(invisibleItem); + }); + for (let index = s; direction == -1 ? index <= e : index >= e; direction == -1 ? index++ : index--) { + let realIndex = Utils$1.getModuloIndex(index, nElements); + this._visibleItems.add(this.getWrapper(realIndex)); + } + this._reloadVisibleElements = false; + } + setPrevious() { + this.setIndex(this._index - 1); + } + setNext() { + this.setIndex(this._index + 1); + } + getWrapper(index) { + return this._wrapper.children[index]; + } + getElement(index) { + let e = this._wrapper.children[index]; + return e ? e.children[0] : null; + } + reload() { + this._reloadVisibleElements = true; + this.update(); + } + get element() { + let e = this._wrapper.children[this.realIndex]; + return e ? e.children[0] : null; + } + get length() { + return this._wrapper.children.length; + } + get property() { + return this._horizontal ? "x" : "y"; + } + get viewportSize() { + return this._horizontal ? this.w : this.h; + } + get index() { + return this._index; + } + get realIndex() { + return Utils$1.getModuloIndex(this._index, this.length); + } + get itemSize() { + return this._itemSize; + } + set itemSize(v) { + this._itemSize = v; + this.update(); + } + get viewportScrollOffset() { + return this._viewportScrollOffset; + } + set viewportScrollOffset(v) { + this._viewportScrollOffset = v; + this.update(); + } + get itemScrollOffset() { + return this._itemScrollOffset; + } + set itemScrollOffset(v) { + this._itemScrollOffset = v; + this.update(); + } + get scrollTransitionSettings() { + return this._scrollTransitionSettings; + } + set scrollTransitionSettings(v) { + this._scrollTransitionSettings.patch(v); + } + set scrollTransition(v) { + this._scrollTransitionSettings.patch(v); + } + get scrollTransition() { + return this._scrollTransition; + } + get progressAnimation() { + return this._progressAnimation; + } + set progressAnimation(v) { + if (Utils$1.isObjectLiteral(v)) { + this._progressAnimation = this.stage.animations.createSettings(v); + } else { + this._progressAnimation = v; + } + this.update(); + } + get roll() { + return this._roll; + } + set roll(v) { + this._roll = v; + this.update(); + } + get rollMin() { + return this._rollMin; + } + set rollMin(v) { + this._rollMin = v; + this.update(); + } + get rollMax() { + return this._rollMax; + } + set rollMax(v) { + this._rollMax = v; + this.update(); + } + get invertDirection() { + return this._invertDirection; + } + set invertDirection(v) { + if (!this._started) { + this._invertDirection = v; + } + } + get horizontal() { + return this._horizontal; + } + set horizontal(v) { + if (v !== this._horizontal) { + if (!this._started) { + this._horizontal = v; + } + } + } + } + class ListItems extends ObjectListWrapper { + constructor(list) { + let wrap = (item) => { + let parent = item.stage.createElement(); + parent.add(item); + parent.visible = false; + return parent; + }; + super(list._wrapper._children, wrap); + this.list = list; + } + onAdd(item, index) { + super.onAdd(item, index); + this.checkStarted(index); + } + checkStarted(index) { + this.list._reloadVisibleElements = true; + if (!this.list._started) { + this.list.start(); + } else { + if (this.list.length === 1) { + this.list.setIndex(0, true, true); + } else { + if (this.list._index >= this.list.length) { + this.list.setIndex(0); + } + } + this.list.update(); + } + } + onRemove(item, index) { + super.onRemove(item, index); + let ri = this.list.realIndex; + if (ri === index) { + if (ri === this.list.length) { + ri--; + } + if (ri >= 0) { + this.list.setIndex(ri); + } + } else if (ri > index) { + this.list.setIndex(ri - 1); + } + this.list._reloadVisibleElements = true; + } + onSet(item, index) { + super.onSet(item, index); + this.checkStarted(index); + } + onSync(removed, added, order) { + super.onSync(removed, added, order); + this.checkStarted(0); + } + get _signalProxy() { + return true; + } + } + class LinearBlurShader extends DefaultShader$1 { + constructor(context) { + super(context); + this._direction = new Float32Array([1, 0]); + this._kernelRadius = 1; + } + get x() { + return this._direction[0]; + } + set x(v) { + this._direction[0] = v; + this.redraw(); + } + get y() { + return this._direction[1]; + } + set y(v) { + this._direction[1] = v; + this.redraw(); + } + get kernelRadius() { + return this._kernelRadius; + } + set kernelRadius(v) { + this._kernelRadius = v; + this.redraw(); + } + useDefault() { + return this._kernelRadius === 0; + } + setupUniforms(operation) { + super.setupUniforms(operation); + this._setUniform("direction", this._direction, this.gl.uniform2fv); + this._setUniform("kernelRadius", this._kernelRadius, this.gl.uniform1i); + const w = operation.getRenderWidth(); + const h = operation.getRenderHeight(); + this._setUniform("resolution", new Float32Array([w, h]), this.gl.uniform2fv); + } + } + LinearBlurShader.fragmentShaderSource = ` + #ifdef GL_ES + # ifdef GL_FRAGMENT_PRECISION_HIGH + precision highp float; + # else + precision lowp float; + # endif + #endif + uniform vec2 resolution; + varying vec2 vTextureCoord; + varying vec4 vColor; + uniform sampler2D uSampler; + uniform vec2 direction; + uniform int kernelRadius; + + vec4 blur1(sampler2D image, vec2 uv, vec2 resolution, vec2 direction) { + vec4 color = vec4(0.0); + vec2 off1 = vec2(1.3333333333333333) * direction; + color += texture2D(image, uv) * 0.29411764705882354; + color += texture2D(image, uv + (off1 / resolution)) * 0.35294117647058826; + color += texture2D(image, uv - (off1 / resolution)) * 0.35294117647058826; + return color; + } + + vec4 blur2(sampler2D image, vec2 uv, vec2 resolution, vec2 direction) { + vec4 color = vec4(0.0); + vec2 off1 = vec2(1.3846153846) * direction; + vec2 off2 = vec2(3.2307692308) * direction; + color += texture2D(image, uv) * 0.2270270270; + color += texture2D(image, uv + (off1 / resolution)) * 0.3162162162; + color += texture2D(image, uv - (off1 / resolution)) * 0.3162162162; + color += texture2D(image, uv + (off2 / resolution)) * 0.0702702703; + color += texture2D(image, uv - (off2 / resolution)) * 0.0702702703; + return color; + } + + vec4 blur3(sampler2D image, vec2 uv, vec2 resolution, vec2 direction) { + vec4 color = vec4(0.0); + vec2 off1 = vec2(1.411764705882353) * direction; + vec2 off2 = vec2(3.2941176470588234) * direction; + vec2 off3 = vec2(5.176470588235294) * direction; + color += texture2D(image, uv) * 0.1964825501511404; + color += texture2D(image, uv + (off1 / resolution)) * 0.2969069646728344; + color += texture2D(image, uv - (off1 / resolution)) * 0.2969069646728344; + color += texture2D(image, uv + (off2 / resolution)) * 0.09447039785044732; + color += texture2D(image, uv - (off2 / resolution)) * 0.09447039785044732; + color += texture2D(image, uv + (off3 / resolution)) * 0.010381362401148057; + color += texture2D(image, uv - (off3 / resolution)) * 0.010381362401148057; + return color; + } + + void main(void){ + if (kernelRadius == 1) { + gl_FragColor = blur1(uSampler, vTextureCoord, resolution, direction) * vColor; + } else if (kernelRadius == 2) { + gl_FragColor = blur2(uSampler, vTextureCoord, resolution, direction) * vColor; + } else { + gl_FragColor = blur3(uSampler, vTextureCoord, resolution, direction) * vColor; + } + } +`; + class BoxBlurShader extends DefaultShader$1 { + setupUniforms(operation) { + super.setupUniforms(operation); + const dx = 1 / operation.getTextureWidth(0); + const dy = 1 / operation.getTextureHeight(0); + this._setUniform("stepTextureCoord", new Float32Array([dx, dy]), this.gl.uniform2fv); + } + } + BoxBlurShader.vertexShaderSource = ` + #ifdef GL_ES + # ifdef GL_FRAGMENT_PRECISION_HIGH + precision highp float; + # else + precision lowp float; + # endif + #endif + uniform vec2 stepTextureCoord; + attribute vec2 aVertexPosition; + attribute vec2 aTextureCoord; + attribute vec4 aColor; + uniform vec2 projection; + varying vec4 vColor; + varying vec2 vTextureCoordUl; + varying vec2 vTextureCoordUr; + varying vec2 vTextureCoordBl; + varying vec2 vTextureCoordBr; + void main(void){ + gl_Position = vec4(aVertexPosition.x * projection.x - 1.0, aVertexPosition.y * -abs(projection.y) + 1.0, 0.0, 1.0); + vTextureCoordUl = aTextureCoord - stepTextureCoord; + vTextureCoordBr = aTextureCoord + stepTextureCoord; + vTextureCoordUr = vec2(vTextureCoordBr.x, vTextureCoordUl.y); + vTextureCoordBl = vec2(vTextureCoordUl.x, vTextureCoordBr.y); + vColor = aColor; + gl_Position.y = -sign(projection.y) * gl_Position.y; + } +`; + BoxBlurShader.fragmentShaderSource = ` + #ifdef GL_ES + # ifdef GL_FRAGMENT_PRECISION_HIGH + precision highp float; + # else + precision lowp float; + # endif + #endif + varying vec2 vTextureCoordUl; + varying vec2 vTextureCoordUr; + varying vec2 vTextureCoordBl; + varying vec2 vTextureCoordBr; + varying vec4 vColor; + uniform sampler2D uSampler; + void main(void){ + vec4 color = 0.25 * (texture2D(uSampler, vTextureCoordUl) + texture2D(uSampler, vTextureCoordUr) + texture2D(uSampler, vTextureCoordBl) + texture2D(uSampler, vTextureCoordBr)); + gl_FragColor = color * vColor; + } +`; + class BlurShader extends DefaultShader { + constructor(context) { + super(context); + this._kernelRadius = 1; + } + get kernelRadius() { + return this._kernelRadius; + } + set kernelRadius(v) { + this._kernelRadius = v; + this.redraw(); + } + useDefault() { + return this._amount === 0; + } + _beforeDrawEl({ target }) { + target.ctx.filter = "blur(" + this._kernelRadius + "px)"; + } + _afterDrawEl({ target }) { + target.ctx.filter = "none"; + } + } + class FastBlurComponent extends Component { + static _template() { + return {}; + } + get wrap() { + return this.tag("Wrap"); + } + set content(v) { + return this.wrap.content = v; + } + get content() { + return this.wrap.content; + } + set padding(v) { + this.wrap._paddingX = v; + this.wrap._paddingY = v; + this.wrap._updateBlurSize(); + } + set paddingX(v) { + this.wrap._paddingX = v; + this.wrap._updateBlurSize(); + } + set paddingY(v) { + this.wrap._paddingY = v; + this.wrap._updateBlurSize(); + } + set amount(v) { + return this.wrap.amount = v; + } + get amount() { + return this.wrap.amount; + } + _onResize() { + this.wrap.w = this.renderWidth; + this.wrap.h = this.renderHeight; + } + get _signalProxy() { + return true; + } + _build() { + this.patch({ + Wrap: { type: this.stage.gl ? WebGLFastBlurComponent : C2dFastBlurComponent } + }); + } + } + class C2dFastBlurComponent extends Component { + static _template() { + return { + forceZIndexContext: true, + rtt: true, + Textwrap: { shader: { type: BlurShader }, Content: {} } + }; + } + constructor(stage) { + super(stage); + this._textwrap = this.sel("Textwrap"); + this._wrapper = this.sel("Textwrap>Content"); + this._amount = 0; + this._paddingX = 0; + this._paddingY = 0; + } + static getSpline() { + if (!this._multiSpline) { + this._multiSpline = new MultiSpline(); + this._multiSpline.parse(false, { 0: 0, 0.25: 1.5, 0.5: 5.5, 0.75: 18, 1: 39 }); + } + return this._multiSpline; + } + get content() { + return this.sel("Textwrap>Content"); + } + set content(v) { + this.sel("Textwrap>Content").patch(v, true); + } + set padding(v) { + this._paddingX = v; + this._paddingY = v; + this._updateBlurSize(); + } + set paddingX(v) { + this._paddingX = v; + this._updateBlurSize(); + } + set paddingY(v) { + this._paddingY = v; + this._updateBlurSize(); + } + _updateBlurSize() { + let w = this.renderWidth; + let h = this.renderHeight; + let paddingX = this._paddingX; + let paddingY = this._paddingY; + this._wrapper.x = paddingX; + this._textwrap.x = -paddingX; + this._wrapper.y = paddingY; + this._textwrap.y = -paddingY; + this._textwrap.w = w + paddingX * 2; + this._textwrap.h = h + paddingY * 2; + } + get amount() { + return this._amount; + } + set amount(v) { + this._amount = v; + this._textwrap.shader.kernelRadius = C2dFastBlurComponent._amountToKernelRadius(v); + } + static _amountToKernelRadius(v) { + return C2dFastBlurComponent.getSpline().getValue(Math.min(1, v * 0.25)); + } + get _signalProxy() { + return true; + } + } + class WebGLFastBlurComponent extends Component { + static _template() { + const onUpdate = function(element, elementCore) { + if (elementCore._recalc & 2 + 128) { + const w = elementCore.w; + const h = elementCore.h; + let cur = elementCore; + do { + cur = cur._children[0]; + cur._element.w = w; + cur._element.h = h; + } while (cur._children); + } + }; + return { + Textwrap: { rtt: true, forceZIndexContext: true, renderOffscreen: true, Content: {} }, + Layers: { + L0: { rtt: true, onUpdate, renderOffscreen: true, visible: false, Content: { shader: { type: BoxBlurShader } } }, + L1: { rtt: true, onUpdate, renderOffscreen: true, visible: false, Content: { shader: { type: BoxBlurShader } } }, + L2: { rtt: true, onUpdate, renderOffscreen: true, visible: false, Content: { shader: { type: BoxBlurShader } } }, + L3: { rtt: true, onUpdate, renderOffscreen: true, visible: false, Content: { shader: { type: BoxBlurShader } } } + }, + Result: { shader: { type: FastBlurOutputShader }, visible: false } + }; + } + get _signalProxy() { + return true; + } + constructor(stage) { + super(stage); + this._textwrap = this.sel("Textwrap"); + this._wrapper = this.sel("Textwrap>Content"); + this._layers = this.sel("Layers"); + this._output = this.sel("Result"); + this._amount = 0; + this._paddingX = 0; + this._paddingY = 0; + } + _buildLayers() { + const filterShaderSettings = [{ x: 1, y: 0, kernelRadius: 1 }, { x: 0, y: 1, kernelRadius: 1 }, { x: 1.5, y: 0, kernelRadius: 1 }, { x: 0, y: 1.5, kernelRadius: 1 }]; + const filterShaders = filterShaderSettings.map((s) => { + const shader = Shader.create(this.stage, Object.assign({ type: LinearBlurShader }, s)); + return shader; + }); + this._setLayerTexture(this.getLayerContents(0), this._textwrap.getTexture(), []); + this._setLayerTexture(this.getLayerContents(1), this.getLayer(0).getTexture(), [filterShaders[0], filterShaders[1]]); + this._setLayerTexture(this.getLayerContents(2), this.getLayer(1).getTexture(), [filterShaders[0], filterShaders[1], filterShaders[2], filterShaders[3]]); + this._setLayerTexture(this.getLayerContents(3), this.getLayer(2).getTexture(), [filterShaders[0], filterShaders[1], filterShaders[2], filterShaders[3]]); + } + _setLayerTexture(element, texture, steps) { + if (!steps.length) { + element.texture = texture; + } else { + const step = steps.pop(); + const child = element.stage.c({ rtt: true, shader: step }); + this._setLayerTexture(child, texture, steps); + element.childList.add(child); + } + return element; + } + get content() { + return this.sel("Textwrap>Content"); + } + set content(v) { + this.sel("Textwrap>Content").patch(v, true); + } + set padding(v) { + this._paddingX = v; + this._paddingY = v; + this._updateBlurSize(); + } + set paddingX(v) { + this._paddingX = v; + this._updateBlurSize(); + } + set paddingY(v) { + this._paddingY = v; + this._updateBlurSize(); + } + getLayer(i) { + return this._layers.sel("L" + i); + } + getLayerContents(i) { + return this.getLayer(i).sel("Content"); + } + _onResize() { + this._updateBlurSize(); + } + _updateBlurSize() { + let w = this.renderWidth; + let h = this.renderHeight; + let paddingX = this._paddingX; + let paddingY = this._paddingY; + let fw = w + paddingX * 2; + let fh = h + paddingY * 2; + this._textwrap.w = fw; + this._wrapper.x = paddingX; + this.getLayer(0).w = this.getLayerContents(0).w = fw / 2; + this.getLayer(1).w = this.getLayerContents(1).w = fw / 4; + this.getLayer(2).w = this.getLayerContents(2).w = fw / 8; + this.getLayer(3).w = this.getLayerContents(3).w = fw / 16; + this._output.x = -paddingX; + this._textwrap.x = -paddingX; + this._output.w = fw; + this._textwrap.h = fh; + this._wrapper.y = paddingY; + this.getLayer(0).h = this.getLayerContents(0).h = fh / 2; + this.getLayer(1).h = this.getLayerContents(1).h = fh / 4; + this.getLayer(2).h = this.getLayerContents(2).h = fh / 8; + this.getLayer(3).h = this.getLayerContents(3).h = fh / 16; + this._output.y = -paddingY; + this._textwrap.y = -paddingY; + this._output.h = fh; + this.w = w; + this.h = h; + } + set amount(v) { + this._amount = v; + this._update(); + } + get amount() { + return this._amount; + } + _update() { + let v = Math.min(4, Math.max(0, this._amount)); + if (v === 0) { + this._textwrap.renderToTexture = false; + this._output.shader.otherTextureSource = null; + this._output.visible = false; + } else { + this._textwrap.renderToTexture = true; + this._output.visible = true; + this.getLayer(0).visible = v > 0; + this.getLayer(1).visible = v > 1; + this.getLayer(2).visible = v > 2; + this.getLayer(3).visible = v > 3; + if (v <= 1) { + this._output.texture = this._textwrap.getTexture(); + this._output.shader.otherTextureSource = this.getLayer(0).getTexture(); + this._output.shader.a = v; + } else if (v <= 2) { + this._output.texture = this.getLayer(0).getTexture(); + this._output.shader.otherTextureSource = this.getLayer(1).getTexture(); + this._output.shader.a = v - 1; + } else if (v <= 3) { + this._output.texture = this.getLayer(1).getTexture(); + this._output.shader.otherTextureSource = this.getLayer(2).getTexture(); + this._output.shader.a = v - 2; + } else if (v <= 4) { + this._output.texture = this.getLayer(2).getTexture(); + this._output.shader.otherTextureSource = this.getLayer(3).getTexture(); + this._output.shader.a = v - 3; + } + } + } + set shader(s) { + super.shader = s; + if (!this.renderToTexture) { + console.warn("[Lightning] Please enable renderToTexture to use with a shader."); + } + } + _firstActive() { + this._buildLayers(); + } + } + class FastBlurOutputShader extends DefaultShader$1 { + constructor(ctx) { + super(ctx); + this._a = 0; + this._otherTextureSource = null; + } + get a() { + return this._a; + } + set a(v) { + this._a = v; + this.redraw(); + } + set otherTextureSource(v) { + this._otherTextureSource = v; + this.redraw(); + } + setupUniforms(operation) { + super.setupUniforms(operation); + this._setUniform("a", this._a, this.gl.uniform1f); + this._setUniform("uSampler2", 1, this.gl.uniform1i); + } + beforeDraw(operation) { + let glTexture = this._otherTextureSource ? this._otherTextureSource.nativeTexture : null; + let gl = this.gl; + gl.activeTexture(gl.TEXTURE1); + gl.bindTexture(gl.TEXTURE_2D, glTexture); + gl.activeTexture(gl.TEXTURE0); + } + } + FastBlurOutputShader.fragmentShaderSource = ` + #ifdef GL_ES + # ifdef GL_FRAGMENT_PRECISION_HIGH + precision highp float; + # else + precision lowp float; + # endif + #endif + varying vec2 vTextureCoord; + varying vec4 vColor; + uniform sampler2D uSampler; + uniform sampler2D uSampler2; + uniform float a; + void main(void){ + if (a == 1.0) { + gl_FragColor = texture2D(uSampler2, vTextureCoord) * vColor; + } else { + gl_FragColor = ((1.0 - a) * texture2D(uSampler, vTextureCoord) + (a * texture2D(uSampler2, vTextureCoord))) * vColor; + } + } +`; + class BloomComponent extends Component { + static _template() { + const onUpdate = function(element, elementCore) { + if (elementCore._recalc & 2 + 128) { + const w = elementCore.w; + const h = elementCore.h; + let cur = elementCore; + do { + cur = cur._children[0]; + cur._element.w = w; + cur._element.h = h; + } while (cur._children); + } + }; + return { + Textwrap: { + rtt: true, + forceZIndexContext: true, + renderOffscreen: true, + BloomBase: { + shader: { type: BloomBaseShader }, + Content: {} + } + }, + Layers: { + L0: { rtt: true, onUpdate, scale: 2, pivot: 0, visible: false, Content: { shader: { type: BoxBlurShader } } }, + L1: { rtt: true, onUpdate, scale: 4, pivot: 0, visible: false, Content: { shader: { type: BoxBlurShader } } }, + L2: { rtt: true, onUpdate, scale: 8, pivot: 0, visible: false, Content: { shader: { type: BoxBlurShader } } }, + L3: { rtt: true, onUpdate, scale: 16, pivot: 0, visible: false, Content: { shader: { type: BoxBlurShader } } } + } + }; + } + get _signalProxy() { + return true; + } + constructor(stage) { + super(stage); + this._textwrap = this.sel("Textwrap"); + this._wrapper = this.sel("Textwrap.Content"); + this._layers = this.sel("Layers"); + this._amount = 0; + this._paddingX = 0; + this._paddingY = 0; + } + _build() { + const filterShaderSettings = [{ x: 1, y: 0, kernelRadius: 3 }, { x: 0, y: 1, kernelRadius: 3 }, { x: 1.5, y: 0, kernelRadius: 3 }, { x: 0, y: 1.5, kernelRadius: 3 }]; + const filterShaders = filterShaderSettings.map((s) => { + const shader = this.stage.createShader(Object.assign({ type: LinearBlurShader }, s)); + return shader; + }); + this._setLayerTexture(this.getLayerContents(0), this._textwrap.getTexture(), []); + this._setLayerTexture(this.getLayerContents(1), this.getLayer(0).getTexture(), [filterShaders[0], filterShaders[1]]); + this._setLayerTexture(this.getLayerContents(2), this.getLayer(1).getTexture(), [filterShaders[0], filterShaders[1], filterShaders[2], filterShaders[3]]); + this._setLayerTexture(this.getLayerContents(3), this.getLayer(2).getTexture(), [filterShaders[0], filterShaders[1], filterShaders[2], filterShaders[3]]); + } + _setLayerTexture(element, texture, steps) { + if (!steps.length) { + element.texture = texture; + } else { + const step = steps.pop(); + const child = element.stage.c({ rtt: true, shader: step }); + this._setLayerTexture(child, texture, steps); + element.childList.add(child); + } + return element; + } + get content() { + return this.sel("Textwrap.Content"); + } + set content(v) { + this.sel("Textwrap.Content").patch(v); + } + set padding(v) { + this._paddingX = v; + this._paddingY = v; + this._updateBlurSize(); + } + set paddingX(v) { + this._paddingX = v; + this._updateBlurSize(); + } + set paddingY(v) { + this._paddingY = v; + this._updateBlurSize(); + } + getLayer(i) { + return this._layers.sel("L" + i); + } + getLayerContents(i) { + return this.getLayer(i).sel("Content"); + } + _onResize() { + this._updateBlurSize(); + } + _updateBlurSize() { + let w = this.renderWidth; + let h = this.renderHeight; + let paddingX = this._paddingX; + let paddingY = this._paddingY; + let fw = w + paddingX * 2; + let fh = h + paddingY * 2; + this._textwrap.w = fw; + this._wrapper.x = paddingX; + this.getLayer(0).w = this.getLayerContents(0).w = fw / 2; + this.getLayer(1).w = this.getLayerContents(1).w = fw / 4; + this.getLayer(2).w = this.getLayerContents(2).w = fw / 8; + this.getLayer(3).w = this.getLayerContents(3).w = fw / 16; + this._textwrap.x = -paddingX; + this._textwrap.h = fh; + this._wrapper.y = paddingY; + this.getLayer(0).h = this.getLayerContents(0).h = fh / 2; + this.getLayer(1).h = this.getLayerContents(1).h = fh / 4; + this.getLayer(2).h = this.getLayerContents(2).h = fh / 8; + this.getLayer(3).h = this.getLayerContents(3).h = fh / 16; + this._textwrap.y = -paddingY; + this.w = w; + this.h = h; + } + set amount(v) { + this._amount = v; + this._update(); + } + get amount() { + return this._amount; + } + _update() { + let v = Math.min(4, Math.max(0, this._amount)); + if (v > 0) { + this.getLayer(0).visible = v > 0; + this.getLayer(1).visible = v > 1; + this.getLayer(2).visible = v > 2; + this.getLayer(3).visible = v > 3; + } + } + set shader(s) { + super.shader = s; + if (!this.renderToTexture) { + console.warn("[Lightning] Please enable renderToTexture to use with a shader."); + } + } + _firstActive() { + this._build(); + } + } + class BloomBaseShader extends DefaultShader$1 { + } + BloomBaseShader.fragmentShaderSource = ` + #ifdef GL_ES + # ifdef GL_FRAGMENT_PRECISION_HIGH + precision highp float; + # else + precision lowp float; + # endif + #endif + varying vec2 vTextureCoord; + varying vec4 vColor; + uniform sampler2D uSampler; + void main(void){ + vec4 color = texture2D(uSampler, vTextureCoord) * vColor; + float m = max(max(color.r, color.g), color.b); + float c = max(0.0, (m - 0.80)) * 5.0; + color = color * c; + gl_FragColor = color; + } +`; + class SmoothScaleComponent extends Component { + static _template() { + return { + ContentWrap: { + renderOffscreen: true, + forceZIndexContext: true, + onAfterUpdate: SmoothScaleComponent._updateDimensions, + Content: {} + }, + Scale: { visible: false } + }; + } + constructor(stage) { + super(stage); + this._smoothScale = 1; + this._iterations = 0; + } + get content() { + return this.tag("Content"); + } + set content(v) { + this.tag("Content").patch(v, true); + } + get smoothScale() { + return this._smoothScale; + } + set smoothScale(v) { + if (this._smoothScale !== v) { + let its = 0; + while (v < 0.5 && its < 12) { + its++; + v = v * 2; + } + this.scale = v; + this._setIterations(its); + this._smoothScale = v; + } + } + _setIterations(its) { + if (this._iterations !== its) { + const scalers = this.sel("Scale").childList; + const content = this.sel("ContentWrap"); + while (scalers.length < its) { + const first = scalers.length === 0; + const texture = first ? content.getTexture() : scalers.last.getTexture(); + scalers.a({ rtt: true, renderOffscreen: true, texture }); + } + SmoothScaleComponent._updateDimensions(this.tag("ContentWrap"), true); + const useScalers = its > 0; + this.patch({ + ContentWrap: { renderToTexture: useScalers }, + Scale: { visible: useScalers } + }); + for (let i = 0, n = scalers.length; i < n; i++) { + scalers.getAt(i).patch({ + visible: i < its, + renderOffscreen: i !== its - 1 + }); + } + this._iterations = its; + } + } + static _updateDimensions(contentWrap, force) { + const content = contentWrap.children[0]; + let w = content.renderWidth; + let h = content.renderHeight; + if (w !== contentWrap.w || h !== contentWrap.h || force) { + contentWrap.w = w; + contentWrap.h = h; + const scalers = contentWrap.parent.tag("Scale").children; + for (let i = 0, n = scalers.length; i < n; i++) { + w = w * 0.5; + h = h * 0.5; + scalers[i].w = w; + scalers[i].h = h; + } + } + } + get _signalProxy() { + return true; + } + } + class BorderComponent extends Component { + static _template() { + return { + Content: {}, + Borders: { + Top: { rect: true, visible: false, mountY: 1 }, + Right: { rect: true, visible: false }, + Bottom: { rect: true, visible: false }, + Left: { rect: true, visible: false, mountX: 1 } + } + }; + } + get _signalProxy() { + return true; + } + constructor(stage) { + super(stage); + this._borderTop = this.tag("Top"); + this._borderRight = this.tag("Right"); + this._borderBottom = this.tag("Bottom"); + this._borderLeft = this.tag("Left"); + this.onAfterUpdate = function(element) { + const content = element.childList.first; + let w = element.core.w || content.renderWidth; + let h = element.core.h || content.renderHeight; + element._borderTop.w = w; + element._borderBottom.y = h; + element._borderBottom.w = w; + element._borderLeft.h = h + element._borderTop.h + element._borderBottom.h; + element._borderLeft.y = -element._borderTop.h; + element._borderRight.x = w; + element._borderRight.h = h + element._borderTop.h + element._borderBottom.h; + element._borderRight.y = -element._borderTop.h; + }; + this.borderWidth = 1; + } + get content() { + return this.sel("Content"); + } + set content(v) { + this.sel("Content").patch(v, true); + } + get borderWidth() { + return this.borderWidthTop; + } + get borderWidthTop() { + return this._borderTop.h; + } + get borderWidthRight() { + return this._borderRight.w; + } + get borderWidthBottom() { + return this._borderBottom.h; + } + get borderWidthLeft() { + return this._borderLeft.w; + } + set borderWidth(v) { + this.borderWidthTop = v; + this.borderWidthRight = v; + this.borderWidthBottom = v; + this.borderWidthLeft = v; + } + set borderWidthTop(v) { + this._borderTop.h = v; + this._borderTop.visible = v > 0; + } + set borderWidthRight(v) { + this._borderRight.w = v; + this._borderRight.visible = v > 0; + } + set borderWidthBottom(v) { + this._borderBottom.h = v; + this._borderBottom.visible = v > 0; + } + set borderWidthLeft(v) { + this._borderLeft.w = v; + this._borderLeft.visible = v > 0; + } + get colorBorder() { + return this.colorBorderTop; + } + get colorBorderTop() { + return this._borderTop.color; + } + get colorBorderRight() { + return this._borderRight.color; + } + get colorBorderBottom() { + return this._borderBottom.color; + } + get colorBorderLeft() { + return this._borderLeft.color; + } + set colorBorder(v) { + this.colorBorderTop = v; + this.colorBorderRight = v; + this.colorBorderBottom = v; + this.colorBorderLeft = v; + } + set colorBorderTop(v) { + this._borderTop.color = v; + } + set colorBorderRight(v) { + this._borderRight.color = v; + } + set colorBorderBottom(v) { + this._borderBottom.color = v; + } + set colorBorderLeft(v) { + this._borderLeft.color = v; + } + get borderTop() { + return this._borderTop; + } + set borderTop(settings) { + this.borderTop.patch(settings); + } + get borderRight() { + return this._borderRight; + } + set borderRight(settings) { + this.borderRight.patch(settings); + } + get borderBottom() { + return this._borderBottom; + } + set borderBottom(settings) { + this.borderBottom.patch(settings); + } + get borderLeft() { + return this._borderLeft; + } + set borderLeft(settings) { + this.borderLeft.patch(settings); + } + set borders(settings) { + this.borderTop = settings; + this.borderLeft = settings; + this.borderBottom = settings; + this.borderRight = settings; + } + } + class WebGLGrayscaleShader extends DefaultShader$1 { + constructor(context) { + super(context); + this._amount = 1; + } + static getC2d() { + return C2dGrayscaleShader; + } + set amount(v) { + this._amount = v; + this.redraw(); + } + get amount() { + return this._amount; + } + useDefault() { + return this._amount === 0; + } + setupUniforms(operation) { + super.setupUniforms(operation); + this._setUniform("amount", this._amount, this.gl.uniform1f); + } + } + WebGLGrayscaleShader.fragmentShaderSource = ` + #ifdef GL_ES + # ifdef GL_FRAGMENT_PRECISION_HIGH + precision highp float; + # else + precision lowp float; + # endif + #endif + varying vec2 vTextureCoord; + varying vec4 vColor; + uniform sampler2D uSampler; + uniform float amount; + void main(void){ + vec4 color = texture2D(uSampler, vTextureCoord) * vColor; + float grayness = 0.2 * color.r + 0.6 * color.g + 0.2 * color.b; + gl_FragColor = vec4(amount * vec3(grayness, grayness, grayness) + (1.0 - amount) * color.rgb, color.a); + } +`; + class C2dGrayscaleShader extends DefaultShader { + constructor(context) { + super(context); + this._amount = 1; + } + static getWebGL() { + return WebGLGrayscaleShader; + } + set amount(v) { + this._amount = v; + this.redraw(); + } + get amount() { + return this._amount; + } + useDefault() { + return this._amount === 0; + } + _beforeDrawEl({ target }) { + target.ctx.filter = "grayscale(" + this._amount + ")"; + } + _afterDrawEl({ target }) { + target.ctx.filter = "none"; + } + } + class DitheringShader extends DefaultShader$1 { + constructor(ctx) { + super(ctx); + this._noiseTexture = new NoiseTexture(ctx.stage); + this._graining = 1 / 256; + this._random = false; + } + set graining(v) { + this._graining = v; + this.redraw(); + } + set random(v) { + this._random = v; + this.redraw(); + } + setExtraAttribsInBuffer(operation) { + this._noiseTexture.load(); + let offset = operation.extraAttribsDataByteOffset / 4; + let floats = operation.quads.floats; + let length = operation.length; + for (let i = 0; i < length; i++) { + let brx = operation.getElementWidth(i) / this._noiseTexture.getRenderWidth(); + let bry = operation.getElementHeight(i) / this._noiseTexture.getRenderHeight(); + let ulx = 0; + let uly = 0; + if (this._random) { + ulx = Math.random(); + uly = Math.random(); + brx += ulx; + bry += uly; + if (Math.random() < 0.5) { + const t = ulx; + ulx = brx; + brx = t; + } + if (Math.random() < 0.5) { + const t = uly; + uly = bry; + bry = t; + } + } + floats[offset] = ulx; + floats[offset + 1] = uly; + floats[offset + 2] = brx; + floats[offset + 3] = uly; + floats[offset + 4] = brx; + floats[offset + 5] = bry; + floats[offset + 6] = ulx; + floats[offset + 7] = bry; + offset += 8; + } + } + beforeDraw(operation) { + let gl = this.gl; + gl.vertexAttribPointer(this._attrib("aNoiseTextureCoord"), 2, gl.FLOAT, false, 8, this.getVertexAttribPointerOffset(operation)); + let glTexture = this._noiseTexture.source.nativeTexture; + gl.activeTexture(gl.TEXTURE1); + gl.bindTexture(gl.TEXTURE_2D, glTexture); + gl.activeTexture(gl.TEXTURE0); + } + getExtraAttribBytesPerVertex() { + return 8; + } + setupUniforms(operation) { + super.setupUniforms(operation); + this._setUniform("uNoiseSampler", 1, this.gl.uniform1i); + this._setUniform("graining", 2 * this._graining, this.gl.uniform1f); + } + enableAttribs() { + super.enableAttribs(); + let gl = this.gl; + gl.enableVertexAttribArray(this._attrib("aNoiseTextureCoord")); + } + disableAttribs() { + super.disableAttribs(); + let gl = this.gl; + gl.disableVertexAttribArray(this._attrib("aNoiseTextureCoord")); + } + useDefault() { + return this._graining === 0; + } + afterDraw(operation) { + if (this._random) { + this.redraw(); + } + } + } + DitheringShader.vertexShaderSource = ` + #ifdef GL_ES + # ifdef GL_FRAGMENT_PRECISION_HIGH + precision highp float; + # else + precision lowp float; + # endif + #endif + attribute vec2 aVertexPosition; + attribute vec2 aTextureCoord; + attribute vec2 aNoiseTextureCoord; + attribute vec4 aColor; + uniform vec2 projection; + varying vec2 vTextureCoord; + varying vec2 vNoiseTextureCoord; + varying vec4 vColor; + void main(void){ + gl_Position = vec4(aVertexPosition.x * projection.x - 1.0, aVertexPosition.y * -abs(projection.y) + 1.0, 0.0, 1.0); + vTextureCoord = aTextureCoord; + vNoiseTextureCoord = aNoiseTextureCoord; + vColor = aColor; + gl_Position.y = -sign(projection.y) * gl_Position.y; + } +`; + DitheringShader.fragmentShaderSource = ` + #ifdef GL_ES + # ifdef GL_FRAGMENT_PRECISION_HIGH + precision highp float; + # else + precision lowp float; + # endif + #endif + varying vec2 vTextureCoord; + varying vec2 vNoiseTextureCoord; + varying vec4 vColor; + uniform sampler2D uSampler; + uniform sampler2D uNoiseSampler; + uniform float graining; + void main(void){ + vec4 noise = texture2D(uNoiseSampler, vNoiseTextureCoord); + vec4 color = texture2D(uSampler, vTextureCoord); + gl_FragColor = (color * vColor) + graining * (noise.r - 0.5); + } +`; + class CircularPushShader extends DefaultShader$1 { + constructor(ctx) { + super(ctx); + this._inputValue = 0; + this._maxDerivative = 0.01; + this._normalizedValue = 0; + this._offset = 0; + this._amount = 0.1; + this._aspectRatio = 1; + this._offsetX = 0; + this._offsetY = 0; + this.buckets = 100; + } + get aspectRatio() { + return this._aspectRatio; + } + set aspectRatio(v) { + this._aspectRatio = v; + this.redraw(); + } + get offsetX() { + return this._offsetX; + } + set offsetX(v) { + this._offsetX = v; + this.redraw(); + } + get offsetY() { + return this._offsetY; + } + set offsetY(v) { + this._offsetY = v; + this.redraw(); + } + set amount(v) { + this._amount = v; + this.redraw(); + } + get amount() { + return this._amount; + } + set inputValue(v) { + this._inputValue = v; + } + get inputValue() { + return this._inputValue; + } + set maxDerivative(v) { + this._maxDerivative = v; + } + get maxDerivative() { + return this._maxDerivative; + } + set buckets(v) { + if (v > 100) { + console.warn("[Lightning] CircularPushShader: supports max 100 buckets"); + v = 100; + } + this._buckets = v; + this._values = new Uint8Array(this._getValues(v)); + this.redraw(); + } + get buckets() { + return this._buckets; + } + _getValues(n) { + const v = []; + for (let i = 0; i < n; i++) { + v.push(this._inputValue); + } + return v; + } + progress(o) { + this._offset += o * this._buckets; + const full = Math.floor(this._offset); + this._offset -= full; + this._shiftBuckets(full); + this.redraw(); + } + _shiftBuckets(n) { + for (let i = this._buckets - 1; i >= 0; i--) { + const targetIndex = i - n; + if (targetIndex < 0) { + this._normalizedValue = Math.min(this._normalizedValue + this._maxDerivative, Math.max(this._normalizedValue - this._maxDerivative, this._inputValue)); + this._values[i] = 255 * this._normalizedValue; + } else { + this._values[i] = this._values[targetIndex]; + } + } + } + set offset(v) { + this._offset = v; + this.redraw(); + } + setupUniforms(operation) { + super.setupUniforms(operation); + this._setUniform("aspectRatio", this._aspectRatio, this.gl.uniform1f); + this._setUniform("offsetX", this._offsetX, this.gl.uniform1f); + this._setUniform("offsetY", this._offsetY, this.gl.uniform1f); + this._setUniform("amount", this._amount, this.gl.uniform1f); + this._setUniform("offset", this._offset, this.gl.uniform1f); + this._setUniform("buckets", this._buckets, this.gl.uniform1f); + this._setUniform("uValueSampler", 1, this.gl.uniform1i); + } + useDefault() { + return this._amount === 0; + } + beforeDraw(operation) { + const gl = this.gl; + gl.activeTexture(gl.TEXTURE1); + if (!this._valuesTexture) { + this._valuesTexture = gl.createTexture(); + gl.bindTexture(gl.TEXTURE_2D, this._valuesTexture); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); + if (Utils$1.isNode) { + gl.pixelStorei(gl.UNPACK_FLIP_BLUE_RED, false); + } + gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false); + } else { + gl.bindTexture(gl.TEXTURE_2D, this._valuesTexture); + } + gl.texImage2D(gl.TEXTURE_2D, 0, gl.ALPHA, this._buckets, 1, 0, gl.ALPHA, gl.UNSIGNED_BYTE, this._values); + gl.activeTexture(gl.TEXTURE0); + } + cleanup() { + if (this._valuesTexture) { + this.gl.deleteTexture(this._valuesTexture); + } + } + } + CircularPushShader.vertexShaderSource = ` + #ifdef GL_ES + # ifdef GL_FRAGMENT_PRECISION_HIGH + precision highp float; + # else + precision lowp float; + # endif + #endif + attribute vec2 aVertexPosition; + attribute vec2 aTextureCoord; + attribute vec4 aColor; + uniform vec2 projection; + uniform float offsetX; + uniform float offsetY; + uniform float aspectRatio; + varying vec2 vTextureCoord; + varying vec2 vPos; + varying vec4 vColor; + void main(void){ + gl_Position = vec4(aVertexPosition.x * projection.x - 1.0, aVertexPosition.y * -abs(projection.y) + 1.0, 0.0, 1.0); + vTextureCoord = aTextureCoord; + vPos = vTextureCoord * 2.0 - 1.0; + vPos.y = vPos.y * aspectRatio; + vPos.y = vPos.y + offsetY; + vPos.x = vPos.x + offsetX; + vColor = aColor; + gl_Position.y = -sign(projection.y) * gl_Position.y; + } +`; + CircularPushShader.fragmentShaderSource = ` + #ifdef GL_ES + # ifdef GL_FRAGMENT_PRECISION_HIGH + precision highp float; + # else + precision lowp float; + # endif + #endif + varying vec2 vTextureCoord; + varying vec4 vColor; + varying vec2 vPos; + uniform float amount; + uniform float offset; + uniform float values[100]; + uniform float buckets; + uniform sampler2D uSampler; + uniform sampler2D uValueSampler; + void main(void){ + float l = length(vPos); + float m = (l * buckets * 0.678 - offset) / buckets; + float f = texture2D(uValueSampler, vec2(m, 0.0)).a * amount; + vec2 unit = vPos / l; + gl_FragColor = texture2D(uSampler, vTextureCoord - f * unit) * vColor; + } +`; + class InversionShader extends DefaultShader$1 { + constructor(context) { + super(context); + this._amount = 1; + } + set amount(v) { + this._amount = v; + this.redraw(); + } + get amount() { + return this._amount; + } + useDefault() { + return this._amount === 0; + } + setupUniforms(operation) { + super.setupUniforms(operation); + this._setUniform("amount", this._amount, this.gl.uniform1f); + } + } + InversionShader.fragmentShaderSource = ` + #ifdef GL_ES + # ifdef GL_FRAGMENT_PRECISION_HIGH + precision highp float; + # else + precision lowp float; + # endif + #endif + varying vec2 vTextureCoord; + varying vec4 vColor; + uniform sampler2D uSampler; + uniform float amount; + void main(void){ + vec4 color = texture2D(uSampler, vTextureCoord); + color.rgb = color.rgb * (1.0 - amount) + amount * (1.0 * color.a - color.rgb); + gl_FragColor = color * vColor; + } +`; + class OutlineShader extends DefaultShader$1 { + constructor(ctx) { + super(ctx); + this._width = 5; + this._col = 4294967295; + this._color = [1, 1, 1, 1]; + } + set width(v) { + this._width = v; + this.redraw(); + } + get color() { + return this._col; + } + set color(v) { + if (this._col !== v) { + const col = StageUtils.getRgbaComponentsNormalized(v); + col[0] = col[0] * col[3]; + col[1] = col[1] * col[3]; + col[2] = col[2] * col[3]; + this._color = col; + this.redraw(); + this._col = v; + } + } + useDefault() { + return this._width === 0 || this._col[3] === 0; + } + setupUniforms(operation) { + super.setupUniforms(operation); + let gl = this.gl; + this._setUniform("color", new Float32Array(this._color), gl.uniform4fv); + } + enableAttribs() { + super.enableAttribs(); + this.gl.enableVertexAttribArray(this._attrib("aCorner")); + } + disableAttribs() { + super.disableAttribs(); + this.gl.disableVertexAttribArray(this._attrib("aCorner")); + } + setExtraAttribsInBuffer(operation) { + let offset = operation.extraAttribsDataByteOffset / 4; + let floats = operation.quads.floats; + let length = operation.length; + for (let i = 0; i < length; i++) { + const elementCore = operation.getElementCore(i); + const ddw = this._width / elementCore.w; + const dw = ddw / (1 - 2 * ddw); + const ddh = this._width / elementCore.h; + const dh = ddh / (1 - 2 * ddh); + floats[offset] = -dw; + floats[offset + 1] = -dh; + floats[offset + 2] = 1 + dw; + floats[offset + 3] = -dh; + floats[offset + 4] = 1 + dw; + floats[offset + 5] = 1 + dh; + floats[offset + 6] = -dw; + floats[offset + 7] = 1 + dh; + offset += 8; + } + } + beforeDraw(operation) { + let gl = this.gl; + gl.vertexAttribPointer(this._attrib("aCorner"), 2, gl.FLOAT, false, 8, this.getVertexAttribPointerOffset(operation)); + } + getExtraAttribBytesPerVertex() { + return 8; + } + } + OutlineShader.vertexShaderSource = ` + #ifdef GL_ES + # ifdef GL_FRAGMENT_PRECISION_HIGH + precision highp float; + # else + precision lowp float; + # endif + #endif + attribute vec2 aVertexPosition; + attribute vec2 aTextureCoord; + attribute vec4 aColor; + attribute vec2 aCorner; + uniform vec2 projection; + varying vec2 vTextureCoord; + varying vec2 vCorner; + varying vec4 vColor; + void main(void){ + gl_Position = vec4(aVertexPosition.x * projection.x - 1.0, aVertexPosition.y * -abs(projection.y) + 1.0, 0.0, 1.0); + vTextureCoord = aTextureCoord; + vCorner = aCorner; + vColor = aColor; + gl_Position.y = -sign(projection.y) * gl_Position.y; + } +`; + OutlineShader.fragmentShaderSource = ` + #ifdef GL_ES + # ifdef GL_FRAGMENT_PRECISION_HIGH + precision highp float; + # else + precision lowp float; + # endif + #endif + varying vec2 vTextureCoord; + varying vec4 vColor; + varying vec2 vCorner; + uniform vec4 color; + uniform sampler2D uSampler; + void main(void){ + vec2 m = min(vCorner, 1.0 - vCorner); + float value = step(0.0, min(m.x, m.y)); + gl_FragColor = mix(color, texture2D(uSampler, vTextureCoord) * vColor, value); + } +`; + class PixelateShader extends DefaultShader$1 { + constructor(ctx) { + super(ctx); + this._size = new Float32Array([4, 4]); + } + get x() { + return this._size[0]; + } + set x(v) { + this._size[0] = v; + this.redraw(); + } + get y() { + return this._size[1]; + } + set y(v) { + this._size[1] = v; + this.redraw(); + } + get size() { + return this._size[0]; + } + set size(v) { + this._size[0] = v; + this._size[1] = v; + this.redraw(); + } + useDefault() { + return this._size[0] === 0 && this._size[1] === 0; + } + static getWebGLImpl() { + return WebGLPixelateShaderImpl; + } + setupUniforms(operation) { + super.setupUniforms(operation); + let gl = this.gl; + this._setUniform("size", new Float32Array(this._size), gl.uniform2fv); + } + getExtraAttribBytesPerVertex() { + return 8; + } + enableAttribs() { + super.enableAttribs(); + this.gl.enableVertexAttribArray(this._attrib("aTextureRes")); + } + disableAttribs() { + super.disableAttribs(); + this.gl.disableVertexAttribArray(this._attrib("aTextureRes")); + } + setExtraAttribsInBuffer(operation) { + let offset = operation.extraAttribsDataByteOffset / 4; + let floats = operation.quads.floats; + let length = operation.length; + for (let i = 0; i < length; i++) { + let w = operation.quads.getTextureWidth(operation.index + i); + let h = operation.quads.getTextureHeight(operation.index + i); + floats[offset] = w; + floats[offset + 1] = h; + floats[offset + 2] = w; + floats[offset + 3] = h; + floats[offset + 4] = w; + floats[offset + 5] = h; + floats[offset + 6] = w; + floats[offset + 7] = h; + offset += 8; + } + } + beforeDraw(operation) { + let gl = this.gl; + gl.vertexAttribPointer(this._attrib("aTextureRes"), 2, gl.FLOAT, false, this.getExtraAttribBytesPerVertex(), this.getVertexAttribPointerOffset(operation)); + } + } + PixelateShader.vertexShaderSource = ` + #ifdef GL_ES + # ifdef GL_FRAGMENT_PRECISION_HIGH + precision highp float; + # else + precision lowp float; + # endif + #endif + attribute vec2 aVertexPosition; + attribute vec2 aTextureCoord; + attribute vec4 aColor; + attribute vec2 aTextureRes; + uniform vec2 projection; + varying vec2 vTextureCoord; + varying vec4 vColor; + varying vec2 vTextureRes; + void main(void){ + gl_Position = vec4(aVertexPosition.x * projection.x - 1.0, aVertexPosition.y * -abs(projection.y) + 1.0, 0.0, 1.0); + vTextureCoord = aTextureCoord; + vColor = aColor; + vTextureRes = aTextureRes; + gl_Position.y = -sign(projection.y) * gl_Position.y; + } +`; + PixelateShader.fragmentShaderSource = ` + #ifdef GL_ES + # ifdef GL_FRAGMENT_PRECISION_HIGH + precision highp float; + # else + precision lowp float; + # endif + #endif + varying vec2 vTextureCoord; + varying vec4 vColor; + varying vec2 vTextureRes; + + uniform vec2 size; + uniform sampler2D uSampler; + + vec2 mapCoord( vec2 coord ) + { + coord *= vTextureRes.xy; + return coord; + } + + vec2 unmapCoord( vec2 coord ) + { + coord /= vTextureRes.xy; + return coord; + } + + vec2 pixelate(vec2 coord, vec2 size) + { + return floor( coord / size ) * size; + } + + void main(void) + { + vec2 coord = mapCoord(vTextureCoord); + coord = pixelate(coord, size); + coord = unmapCoord(coord); + gl_FragColor = texture2D(uSampler, coord) * vColor; + } +`; + class RadialFilterShader extends DefaultShader$1 { + constructor(context) { + super(context); + this._radius = 0; + this._cutoff = 1; + } + set radius(v) { + this._radius = v; + this.redraw(); + } + get radius() { + return this._radius; + } + set cutoff(v) { + this._cutoff = v; + this.redraw(); + } + get cutoff() { + return this._cutoff; + } + useDefault() { + return this._radius === 0; + } + setupUniforms(operation) { + super.setupUniforms(operation); + this._setUniform("radius", 2 * (this._radius - 0.5) / operation.getRenderWidth(), this.gl.uniform1f); + this._setUniform("cutoff", 0.5 * operation.getRenderWidth() / this._cutoff, this.gl.uniform1f); + } + } + RadialFilterShader.vertexShaderSource = ` + #ifdef GL_ES + # ifdef GL_FRAGMENT_PRECISION_HIGH + precision highp float; + # else + precision lowp float; + # endif + #endif + attribute vec2 aVertexPosition; + attribute vec2 aTextureCoord; + attribute vec4 aColor; + uniform vec2 projection; + varying vec2 pos; + varying vec2 vTextureCoord; + varying vec4 vColor; + void main(void){ + gl_Position = vec4(aVertexPosition.x * projection.x - 1.0, aVertexPosition.y * -abs(projection.y) + 1.0, 0.0, 1.0); + vTextureCoord = aTextureCoord; + vColor = aColor; + gl_Position.y = -sign(projection.y) * gl_Position.y; + pos = gl_Position.xy; + } +`; + RadialFilterShader.fragmentShaderSource = ` + #ifdef GL_ES + # ifdef GL_FRAGMENT_PRECISION_HIGH + precision highp float; + # else + precision lowp float; + # endif + #endif + varying vec2 vTextureCoord; + varying vec2 pos; + varying vec4 vColor; + uniform sampler2D uSampler; + uniform float radius; + uniform float cutoff; + void main(void){ + vec4 color = texture2D(uSampler, vTextureCoord); + float f = max(0.0, min(1.0, 1.0 - (length(pos) - radius) * cutoff)); + gl_FragColor = texture2D(uSampler, vTextureCoord) * vColor * f; + } +`; + class RoundedRectangleShader extends DefaultShader$1 { + constructor(context) { + super(context); + this._blend = 0; + this._radius = [1, 1, 1, 1]; + this._stroke = 0; + this._fc = 16777215; + this._fillColor = this._getNormalizedColor(4294967295); + this._strokeColor = this._getNormalizedColor(16777215); + } + set blend(p) { + this._blend = Math.min(Math.max(p, 0), 1); + } + set radius(v) { + if (Array.isArray(v)) { + if (v.length === 2) { + this._radius = [v[0], v[1], v[0], v[1]]; + } else if (v.length === 3) { + this._radius = [v[0], v[1], v[2], this._radius[3]]; + } else if (v.length === 4) { + this._radius = v; + } else { + this._radius = [v[0], v[0], v[0], v[0]]; + } + } else { + this._radius = [v, v, v, v]; + } + this.redraw(); + } + get radius() { + return this._radius; + } + set topLeft(num) { + this._radius[0] = num; + this.redraw(); + } + get topLeft() { + return this._radius[0]; + } + set topRight(num) { + this._radius[1] = num; + this.redraw(); + } + get topRight() { + return this._radius[1]; + } + set bottomRight(num) { + this._radius[2] = num; + this.redraw(); + } + get bottomRight() { + return this._radius[2]; + } + set bottomLeft(num) { + this._radius[3] = num; + this.redraw(); + } + get bottomLeft() { + return this._radius[4]; + } + set strokeColor(argb) { + this._sc = argb; + this._strokeColor = this._getNormalizedColor(argb); + this.redraw(); + } + get strokeColor() { + return this._sc; + } + set fillColor(argb) { + this._fc = argb; + this._fillColor = this._getNormalizedColor(argb); + this.redraw(); + } + get fillColor() { + return this._fc; + } + set stroke(num) { + this._stroke = num; + this.redraw(); + } + get stroke() { + return this._stroke; + } + _getNormalizedColor(color) { + const col = StageUtils.getRgbaComponentsNormalized(color); + col[0] *= col[3]; + col[1] *= col[3]; + col[2] *= col[3]; + return new Float32Array(col); + } + setupUniforms(operation) { + super.setupUniforms(operation); + const owner = operation.shaderOwner; + const renderPrecision = this.ctx.stage.getRenderPrecision(); + const _radius = this._radius.map((r) => (r + 0.5) * renderPrecision); + this._setUniform("radius", new Float32Array(_radius), this.gl.uniform4fv); + this._setUniform("alpha", operation.getElementCore(0).renderContext.alpha, this.gl.uniform1f); + this._setUniform("blend", this._blend, this.gl.uniform1f); + this._setUniform("strokeColor", this._strokeColor, this.gl.uniform4fv); + this._setUniform("fillColor", this._fillColor, this.gl.uniform4fv); + this._setUniform("stroke", this._stroke * renderPrecision, this.gl.uniform1f); + this._setUniform("resolution", new Float32Array([owner._w * renderPrecision, owner._h * renderPrecision]), this.gl.uniform2fv); + } + } + RoundedRectangleShader.vertexShaderSource = ` + #ifdef GL_ES + # ifdef GL_FRAGMENT_PRECISION_HIGH + precision highp float; + # else + precision lowp float; + # endif + #endif + attribute vec2 aVertexPosition; + attribute vec2 aTextureCoord; + + attribute vec4 aColor; + uniform vec2 projection; + varying vec2 vTextureCoord; + varying vec4 vColor; + + void main(void){ + gl_Position = vec4(aVertexPosition.x * projection.x - 1.0, aVertexPosition.y * -abs(projection.y) + 1.0, 0.0, 1.0); + vTextureCoord = aTextureCoord; + vColor = aColor; + gl_Position.y = -sign(projection.y) * gl_Position.y; + } +`; + RoundedRectangleShader.fragmentShaderSource = ` + #ifdef GL_ES + # ifdef GL_FRAGMENT_PRECISION_HIGH + precision highp float; + # else + precision lowp float; + # endif + #endif + + #define PI 3.14159265359 + + varying vec2 vTextureCoord; + varying vec4 vColor; + + uniform sampler2D uSampler; + uniform vec2 resolution; + uniform vec4 radius; + uniform float stroke; + uniform vec4 strokeColor; + uniform vec4 fillColor; + uniform float alpha; + uniform float fill; + uniform float blend; + + float boxDist(vec2 p, vec2 size, float radius){ + size -= vec2(radius); + vec2 d = abs(p) - size; + return min(max(d.x, d.y), 0.0) + length(max(d, 0.0)) - radius; + } + + float fillMask(float dist){ + return clamp(-dist, 0.0, 1.0); + } + + float innerBorderMask(float dist, float width){ + float alpha1 = clamp(dist + width, 0.0, 1.0); + float alpha2 = clamp(dist, 0.0, 1.0); + return alpha1 - alpha2; + } + + void main() { + vec2 halfRes = 0.5 * resolution.xy; + float r = 0.0; + if (vTextureCoord.x < 0.5 && vTextureCoord.y < 0.5) { + r = radius[0]; + } else if (vTextureCoord.x >= 0.5 && vTextureCoord.y < 0.5) { + r = radius[1]; + } else if (vTextureCoord.x >= 0.5 && vTextureCoord.y >= 0.5) { + r = radius[2]; + } else { + r = radius[3]; + } + + float b = boxDist(vTextureCoord.xy * resolution - halfRes, halfRes - 0.005, r); + vec4 tex = texture2D(uSampler, vTextureCoord) * vColor; + vec4 blend = mix(vec4(1.0) * alpha, tex, blend); + vec4 layer1 = mix(vec4(0.0), tex * fillColor, fillMask(b)); + gl_FragColor = mix(layer1, blend * strokeColor, innerBorderMask(b, stroke)); + } +`; + class FadeOutShader extends DefaultShader$1 { + constructor(context) { + super(context); + this._fade = [0, 0, 0, 0]; + } + set top(num) { + this._fade[0] = num; + this.redraw(); + } + get top() { + return this._fade[0]; + } + set right(num) { + this._fade[1] = num; + this.redraw(); + } + get right() { + return this._fade[1]; + } + set bottom(num) { + this._fade[2] = num; + this.redraw(); + } + get bottom() { + return this._fade[2]; + } + set left(num) { + this._fade[3] = num; + this.redraw(); + } + get left() { + return this._fade[3]; + } + set fade(v) { + if (Array.isArray(v)) { + if (v.length === 2) { + this._fade = [v[0], v[1], v[0], v[1]]; + } else if (v.length === 3) { + this._fade = [v[0], v[1], v[2], this._fade[3]]; + } else if (v.length === 4) { + this._fade = v; + } else { + this._fade = [v[0], v[0], v[0], v[0]]; + } + } else { + this._fade = [v, v, v, v]; + } + this.redraw(); + } + get fade() { + return this._fade; + } + setupUniforms(operation) { + super.setupUniforms(operation); + const owner = operation.shaderOwner; + const renderPrecision = this.ctx.stage.getRenderPrecision(); + const fade = this._fade.map((f) => f * renderPrecision); + this._setUniform("fade", new Float32Array(fade), this.gl.uniform4fv); + this._setUniform("resolution", new Float32Array([owner._w * renderPrecision, owner._h * renderPrecision]), this.gl.uniform2fv); + } + } + FadeOutShader.fragmentShaderSource = ` + #ifdef GL_ES + # ifdef GL_FRAGMENT_PRECISION_HIGH + precision highp float; + # else + precision lowp float; + # endif + #endif + varying vec2 vTextureCoord; + varying vec4 vColor; + uniform sampler2D uSampler; + uniform vec2 resolution; + uniform vec4 fade; + + void main() { + vec4 color = texture2D(uSampler, vTextureCoord) * vColor; + vec2 halfRes = 0.5 * resolution.xy; + vec2 point = vTextureCoord.xy * resolution.xy; + + vec2 pos1; + vec2 pos2; + vec2 d; + float c; + float t = 0.0; + + if(fade[0] > 0.0) { + pos1 = vec2(point.x, point.y); + pos2 = vec2(point.x, point.y + fade[0]); + d = pos2 - pos1; + c = dot(pos1, d) / dot(d, d); + t = smoothstep(0.0, 1.0, clamp(c, 0.0, 1.0)); + color = mix(vec4(0.0), color, t); + } + + if(fade[1] > 0.0) { + vec2 pos1 = vec2(point.x - resolution.x - fade[1], vTextureCoord.y); + vec2 pos2 = vec2(point.x - resolution.x, vTextureCoord.y); + d = pos1 - pos2; + c = dot(pos2, d) / dot(d, d); + t = smoothstep(0.0, 1.0, clamp(c, 0.0, 1.0)); + color = mix(vec4(0.0), color, t); + } + + if(fade[2] > 0.0) { + vec2 pos1 = vec2(vTextureCoord.x, point.y - resolution.y - fade[2]); + vec2 pos2 = vec2(vTextureCoord.x, point.y - resolution.y); + d = pos1 - pos2; + c = dot(pos2, d) / dot(d, d); + t = smoothstep(0.0, 1.0, clamp(c, 0.0, 1.0)); + color = mix(vec4(0.0), color, t); + } + + if(fade[3] > 0.0) { + pos1 = vec2(point.x, point.y); + pos2 = vec2(point.x + fade[3], point.y); + d = pos2 - pos1; + c = dot(pos1, d) / dot(d, d); + t = smoothstep(0.0, 1.0, clamp(c, 0.0, 1.0)); + color = mix(vec4(0.0), color, t); + } + + gl_FragColor = color; + } +`; + class VignetteShader extends DefaultShader$1 { + constructor(context) { + super(context); + this._magnitude = 1.3; + this._intensity = 0.7; + this._pivot = [0.5, 0.5]; + } + setupUniforms(operation) { + super.setupUniforms(operation); + this._setUniform("magnitude", this._magnitude, this.gl.uniform1f); + this._setUniform("intensity", this._intensity, this.gl.uniform1f); + this._setUniform("pivot", new Float32Array(this._pivot), this.gl.uniform2fv); + this.redraw(); + } + set pivot(v) { + if (Array.isArray(v)) { + this._pivot = v; + } else { + this._pivot = [v, v]; + } + this.redraw(); + } + get pivotX() { + return this._pivot[0]; + } + set pivotX(v) { + this._pivot[0] = v; + this.redraw(); + } + get pivotY() { + return this._pivot[1]; + } + set pivotY(v) { + this._pivot[1] = v; + this.redraw(); + } + get intensity() { + return this._intensity; + } + set intensity(v) { + this._intensity = v; + this.redraw(); + } + get magnitude() { + return this._magnitude; + } + set magnitude(v) { + this._magnitude = v; + this.redraw(); + } + } + VignetteShader.vertexShaderSource = DefaultShader$1.vertexShaderSource; + VignetteShader.fragmentShaderSource = ` + #ifdef GL_ES + # ifdef GL_FRAGMENT_PRECISION_HIGH + precision highp float; + # else + precision lowp float; + # endif + #endif + varying vec2 vTextureCoord; + varying vec4 vColor; + uniform sampler2D uSampler; + + uniform float magnitude; + uniform float intensity; + uniform vec2 pivot; + + void main() { + vec2 uv = vTextureCoord.xy - pivot + vec2(0.5); + uv.x = clamp(uv.x, 0.0, 1.0); + uv.y = clamp(uv.y, 0.0, 1.0); + + uv *= 1.00 - uv.yx; + float vig = uv.x * uv.y * 25.0 * intensity; + vig = pow(vig, 0.45 * magnitude); + vec4 fragColor = vec4(vig) * vColor; + gl_FragColor = texture2D(uSampler, vTextureCoord) * fragColor; + + } +`; + class SpinnerShader extends DefaultShader$1 { + constructor(ctx) { + super(ctx); + this._radius = 100; + this._width = 50; + this._period = 1; + this._angle = 0.5; + this._smooth = 5e-3; + this._color = 4294967295; + this._backgroundColor = 4278190080; + this._time = Date.now(); + } + set radius(v) { + this._radius = v; + this.redraw(); + } + set width(v) { + this._width = v; + this.redraw(); + } + set period(v) { + this._period = v; + this.redraw(); + } + set angle(v) { + this._angle = v; + this.redraw(); + } + set smooth(v) { + this._smooth = v; + this.redraw(); + } + set color(v) { + this._color = v; + this.redraw(); + } + set backgroundColor(v) { + this._backgroundColor = v; + this.redraw(); + } + setupUniforms(operation) { + super.setupUniforms(operation); + const owner = operation.shaderOwner; + this._setUniform("iTime", Date.now() - this._time, this.gl.uniform1f); + const renderPrecision = this.ctx.stage.getRenderPrecision(); + this._setUniform("radius", this._radius * renderPrecision, this.gl.uniform1f); + this._setUniform("width", this._width * renderPrecision, this.gl.uniform1f); + this._setUniform("period", this._period, this.gl.uniform1f); + this._setUniform("angle", this._angle, this.gl.uniform1f); + this._setUniform("smooth", this._smooth, this.gl.uniform1f); + this._setUniform("color", new Float32Array(StageUtils.getRgbaComponentsNormalized(this._color)), this.gl.uniform4fv); + this._setUniform("backgroundColor", new Float32Array(StageUtils.getRgbaComponentsNormalized(this._backgroundColor)), this.gl.uniform4fv); + this._setUniform("resolution", new Float32Array([owner._w * renderPrecision, owner._h * renderPrecision]), this.gl.uniform2fv); + this.redraw(); + } + } + SpinnerShader.vertexShaderSource = DefaultShader$1.vertexShaderSource; + SpinnerShader.fragmentShaderSource = ` + #ifdef GL_ES + # ifdef GL_FRAGMENT_PRECISION_HIGH + precision highp float; + # else + precision lowp float; + # endif + #endif + varying vec2 vTextureCoord; + varying vec4 vColor; + uniform sampler2D uSampler; + + uniform float iTime; + uniform float radius; + uniform float width; + uniform float period; + uniform float angle; + uniform float smooth; + uniform vec2 resolution; + + uniform vec4 color; + uniform vec4 backgroundColor; + + float ratio = resolution.y / resolution.x; + + vec2 transpose_pos(vec2 pos) { + if (ratio < 1.) { + float diff = 0.5 - pos.x; + pos.x = 0.5 - diff / ratio; + } else { + float diff = 0.5 - pos.y; + pos.y = 0.5 - diff * ratio; + } + return pos; + } + + float get_angle(vec2 pos) { + pos = transpose_pos(pos); + float a = atan(pos.y - 0.5, pos.x - 0.5); + a = (1.0+a/3.14159)/2.0; + + return a; + } + + float dist(vec2 pos1, vec2 pos2) { + pos1 = transpose_pos(pos1); + return distance(pos1, pos2); + } + + void main() + { + vec2 fragCoord = vTextureCoord; + vec4 fragColor = vColor; + + vec2 st = vTextureCoord; + float pct = dist(st, vec2(0.5)); + + float a = get_angle(st); + float t = iTime / 1000.0 / period; + + float inner = max((radius - width) / resolution.x, (radius - width) / resolution.y); + float outer = max(radius / resolution.x, radius / resolution.y); + + float x1 = mod(t, 1.0); + float x2 = mod(t + angle, 1.0); + + if (x1 < x2) { + if (a > x1 && a < x2) { + float val = (1.0 - (x2 - a) / angle) * smoothstep(0.0, 3. * smooth, (x2 - a)); + fragColor = mix(backgroundColor, color, val); + } else { + fragColor = backgroundColor; + } + } else { + if (a < x2) { + float val = (1.0 - (x2 - a) / angle) * smoothstep(0.0, 3. * smooth, (x2 - a)); + fragColor = mix(backgroundColor, color, val); + } else if (a > x1) { + float val = (1.0 - (1.0 + x2 - a) / angle) * smoothstep(0.0, 3. * smooth, (1.0 + x2 - a)); + fragColor = mix(backgroundColor, color, val); + } else { + fragColor = backgroundColor; + } + } + + float s = smoothstep(inner, inner + smooth + 0.00001, pct) * (1.0 - smoothstep(outer, outer + smooth + 0.00001, pct)); + gl_FragColor = texture2D(uSampler, fragCoord) * vColor * (1. - s * fragColor.a) + fragColor * s; + } +`; + class HoleShader extends DefaultShader$1 { + constructor(context) { + super(context); + this._x = 0; + this._y = 0; + this._w = 0; + this._h = 0; + this._radius = 0; + } + get x() { + return this._x; + } + set x(v) { + this._x = v; + this.redraw(); + } + get y() { + return this._y; + } + set y(v) { + this._y = v; + this.redraw(); + } + get w() { + return this._w; + } + set w(v) { + this._w = v; + this.redraw(); + } + get h() { + return this._h; + } + set h(v) { + this._h = v; + this.redraw(); + } + get radius() { + return this._radius; + } + set radius(v) { + this._radius = v; + this.redraw(); + } + setupUniforms(operation) { + super.setupUniforms(operation); + const owner = operation.shaderOwner; + const renderPrecision = this.ctx.stage.getRenderPrecision(); + this._setUniform("x", this._x * renderPrecision, this.gl.uniform1f); + this._setUniform("y", this._y * renderPrecision, this.gl.uniform1f); + this._setUniform("w", this._w * renderPrecision, this.gl.uniform1f); + this._setUniform("h", this._h * renderPrecision, this.gl.uniform1f); + this._setUniform("radius", (this._radius + 0.5) * renderPrecision, this.gl.uniform1f); + this._setUniform("resolution", new Float32Array([owner._w * renderPrecision, owner._h * renderPrecision]), this.gl.uniform2fv); + } + useDefault() { + return this._x === 0 && this._y === 0 && this._w === 0 && this._h === 0; + } + } + HoleShader.vertexShaderSource = DefaultShader$1.vertexShaderSource; + HoleShader.fragmentShaderSource = ` + #ifdef GL_ES + # ifdef GL_FRAGMENT_PRECISION_HIGH + precision highp float; + # else + precision lowp float; + # endif + #endif + varying vec2 vTextureCoord; + varying vec4 vColor; + uniform sampler2D uSampler; + uniform float x; + uniform float y; + uniform float w; + uniform float h; + uniform vec2 resolution; + uniform float radius; + + float roundBox(vec2 p, vec2 b, float r) { + float d = length(max(abs(p)-b+r, 0.1))-r; + return smoothstep(1.0, 0.0, d); + } + + void main(void){ + vec4 color = texture2D(uSampler, vTextureCoord); + vec2 pos = vTextureCoord.xy * resolution - vec2(x, y) - vec2(w, h) / 2.0; + vec2 size = vec2(w, h) / 2.0; + float b = roundBox(pos, size, radius); + gl_FragColor = mix(color, vec4(0.0), b) * vColor; + } +`; + class RadialGradientShader extends DefaultShader$1 { + constructor(context) { + super(context); + this._pivot = [0, 0]; + this._ic = 4294967295; + this._normalizedIC = this._getNormalizedColor(this._ic); + this._oc = 16777215; + this._normalizedOC = this._getNormalizedColor(this._oc); + this._radius = 0; + } + set radiusX(v) { + this.radius = v; + } + get radiusX() { + return this._radius; + } + set radiusY(v) { + this._radiusY = v; + this.redraw(); + } + get radiusY() { + return this._radiusY; + } + set radius(v) { + this._radius = v; + this.redraw(); + } + set innerColor(argb) { + this._ic = argb; + this._normalizedIC = this._getNormalizedColor(argb); + this.redraw(); + } + get innerColor() { + return this._ic; + } + set outerColor(argb) { + this._oc = argb; + this._normalizedOC = this._getNormalizedColor(argb); + this.redraw(); + } + set color(argb) { + this.innerColor = argb; + } + get color() { + return this.innerColor; + } + get outerColor() { + return this._ic; + } + set x(f) { + this._x = f; + this.redraw(); + } + set y(f) { + this._y = f; + this.redraw(); + } + set pivot(v) { + if (Array.isArray(v) && v.length === 2) { + this._pivot = v; + } else if (Array.isArray(v)) { + this._pivot = [v[0], v[1] || v[0]]; + } else { + this._pivot = [v, v]; + } + this.redraw(); + } + get pivot() { + return this._pivot[0]; + } + set pivotY(f) { + this._pivot[1] = f; + this.redraw(); + } + get pivotY() { + return this._pivot[1]; + } + set pivotX(f) { + this._pivot[0] = f; + this.redraw(); + } + get pivotX() { + return this._pivot[0]; + } + _getNormalizedColor(color) { + const col = StageUtils.getRgbaComponentsNormalized(color); + col[0] *= col[3]; + col[1] *= col[3]; + col[2] *= col[3]; + return new Float32Array(col); + } + setupUniforms(operation) { + super.setupUniforms(operation); + const owner = operation.shaderOwner; + if (this._x) { + this._pivot[0] = this._x / owner.w; + } + if (this._y) { + this._pivot[1] = this._y / owner.h; + } + if (this._radius === 0) { + this._radius = owner.w * 0.5; + } + this._setUniform("innerColor", this._normalizedIC, this.gl.uniform4fv); + this._setUniform("fill", StageUtils.getRgbaComponentsNormalized(this._oc)[3], this.gl.uniform1f); + this._setUniform("outerColor", this._normalizedOC, this.gl.uniform4fv); + this._setUniform("pivot", new Float32Array(this._pivot), this.gl.uniform2fv); + this._setUniform("resolution", new Float32Array([owner._w, owner._h]), this.gl.uniform2fv); + this._setUniform("alpha", operation.getElementCore(0).renderContext.alpha, this.gl.uniform1f); + this._setUniform("radius", this._radius, this.gl.uniform1f); + this._setUniform("radiusY", this._radiusY || this._radius, this.gl.uniform1f); + } + } + RadialGradientShader.fragmentShaderSource = ` + #ifdef GL_ES + # ifdef GL_FRAGMENT_PRECISION_HIGH + precision highp float; + # else + precision lowp float; + # endif + #endif + + #define PI 3.14159265359 + + varying vec2 vTextureCoord; + varying vec4 vColor; + uniform sampler2D uSampler; + uniform vec2 resolution; + uniform vec2 pivot; + uniform vec4 innerColor; + uniform vec4 outerColor; + uniform float radius; + uniform float radiusY; + uniform float alpha; + uniform float fill; + uniform float aspectRatio; + + void main() { + vec2 point = vTextureCoord.xy * resolution; + vec2 projection = vec2(pivot.x * resolution.x, pivot.y * resolution.y); + float d = length((point - projection) / vec2(radius * 2.0, radiusY * 2.0)); + vec4 color = mix(texture2D(uSampler, vTextureCoord) * vColor, outerColor * alpha, fill); + gl_FragColor = mix(innerColor * alpha, color, smoothstep(0.0, 1.0, d)); + } +`; + class Light3dShader extends DefaultShader$1 { + constructor(ctx) { + super(ctx); + this._strength = 0.5; + this._ambient = 0.5; + this._fudge = 0.4; + this._rx = 0; + this._ry = 0; + this._z = 0; + this._pivotX = NaN; + this._pivotY = NaN; + this._pivotZ = 0; + this._lightY = 0; + this._lightZ = 0; + } + setupUniforms(operation) { + super.setupUniforms(operation); + let vr = operation.shaderOwner; + let element = vr.element; + let pivotX = isNaN(this._pivotX) ? element.pivotX * vr.w : this._pivotX; + let pivotY = isNaN(this._pivotY) ? element.pivotY * vr.h : this._pivotY; + let coords = vr.getRenderTextureCoords(pivotX, pivotY); + let rz = -Math.atan2(vr._renderContext.tc, vr._renderContext.ta); + let gl = this.gl; + this._setUniform("pivot", new Float32Array([coords[0], coords[1], this._pivotZ]), gl.uniform3fv); + this._setUniform("rot", new Float32Array([this._rx, this._ry, rz]), gl.uniform3fv); + this._setUniform("z", this._z, gl.uniform1f); + this._setUniform("lightY", this.lightY, gl.uniform1f); + this._setUniform("lightZ", this.lightZ, gl.uniform1f); + this._setUniform("strength", this._strength, gl.uniform1f); + this._setUniform("ambient", this._ambient, gl.uniform1f); + this._setUniform("fudge", this._fudge, gl.uniform1f); + } + set strength(v) { + this._strength = v; + this.redraw(); + } + get strength() { + return this._strength; + } + set ambient(v) { + this._ambient = v; + this.redraw(); + } + get ambient() { + return this._ambient; + } + set fudge(v) { + this._fudge = v; + this.redraw(); + } + get fudge() { + return this._fudge; + } + get rx() { + return this._rx; + } + set rx(v) { + this._rx = v; + this.redraw(); + } + get ry() { + return this._ry; + } + set ry(v) { + this._ry = v; + this.redraw(); + } + get z() { + return this._z; + } + set z(v) { + this._z = v; + this.redraw(); + } + get pivotX() { + return this._pivotX; + } + set pivotX(v) { + this._pivotX = v + 1; + this.redraw(); + } + get pivotY() { + return this._pivotY; + } + set pivotY(v) { + this._pivotY = v + 1; + this.redraw(); + } + get lightY() { + return this._lightY; + } + set lightY(v) { + this._lightY = v; + this.redraw(); + } + get pivotZ() { + return this._pivotZ; + } + set pivotZ(v) { + this._pivotZ = v; + this.redraw(); + } + get lightZ() { + return this._lightZ; + } + set lightZ(v) { + this._lightZ = v; + this.redraw(); + } + useDefault() { + return this._rx === 0 && this._ry === 0 && this._z === 0 && this._strength === 0 && this._ambient === 1; + } + } + Light3dShader.vertexShaderSource = ` + #ifdef GL_ES + # ifdef GL_FRAGMENT_PRECISION_HIGH + precision highp float; + # else + precision lowp float; + # endif + #endif + attribute vec2 aVertexPosition; + attribute vec2 aTextureCoord; + attribute vec4 aColor; + uniform vec2 projection; + varying vec2 vTextureCoord; + varying vec4 vColor; + + uniform float fudge; + uniform float strength; + uniform float ambient; + uniform float z; + uniform float lightY; + uniform float lightZ; + uniform vec3 pivot; + uniform vec3 rot; + varying vec3 pos; + + void main(void) { + pos = vec3(aVertexPosition.xy, z); + + pos -= pivot; + + // Undo XY rotation + mat2 iRotXy = mat2( cos(rot.z), sin(rot.z), + -sin(rot.z), cos(rot.z)); + pos.xy = iRotXy * pos.xy; + + // Perform 3d rotations + gl_Position.x = cos(rot.x) * pos.x - sin(rot.x) * pos.z; + gl_Position.y = pos.y; + gl_Position.z = sin(rot.x) * pos.x + cos(rot.x) * pos.z; + + pos.x = gl_Position.x; + pos.y = cos(rot.y) * gl_Position.y - sin(rot.y) * gl_Position.z; + pos.z = sin(rot.y) * gl_Position.y + cos(rot.y) * gl_Position.z; + + // Redo XY rotation + iRotXy[0][1] = -iRotXy[0][1]; + iRotXy[1][0] = -iRotXy[1][0]; + pos.xy = iRotXy * pos.xy; + + // Undo translate to pivot position + pos.xyz += pivot; + + pos = vec3(pos.x * projection.x - 1.0, pos.y * -abs(projection.y) + 1.0, pos.z * projection.x); + + // Set depth perspective + float perspective = 1.0 + fudge * pos.z; + + pos.z += lightZ * projection.x; + + // Map coords to gl coordinate space. + // Set z to 0 because we don't want to perform z-clipping + gl_Position = vec4(pos.xy, 0.0, perspective); + + // Correct light source position. + pos.y += lightY * abs(projection.y); + + vTextureCoord = aTextureCoord; + vColor = aColor; + + gl_Position.y = -sign(projection.y) * gl_Position.y; + } +`; + Light3dShader.fragmentShaderSource = ` + #ifdef GL_ES + # ifdef GL_FRAGMENT_PRECISION_HIGH + precision highp float; + # else + precision lowp float; + # endif + #endif + varying vec2 vTextureCoord; + varying vec4 vColor; + varying vec3 pos; + uniform sampler2D uSampler; + uniform float ambient; + uniform float strength; + void main(void){ + vec4 rgba = texture2D(uSampler, vTextureCoord); + float d = length(pos); + float n = 1.0 / max(0.1, d); + rgba.rgb = rgba.rgb * (strength * n + ambient); + gl_FragColor = rgba * vColor; + } +`; + class PerspectiveShader extends DefaultShader$1 { + constructor(ctx) { + super(ctx); + this._fudge = 0.2; + this._rx = 0; + this._ry = 0; + this._z = 1; + } + setupUniforms(operation) { + super.setupUniforms(operation); + const vr = operation.shaderOwner; + const element = vr.element; + const pivotX = element.pivotX * vr.w; + const pivotY = element.pivotY * vr.h; + const coords = vr.getRenderTextureCoords(pivotX, pivotY); + const rz = -Math.atan2(vr._renderContext.tc, vr._renderContext.ta); + const gl = this.gl; + this._setUniform("pivot", new Float32Array([coords[0], coords[1], 0]), gl.uniform3fv); + this._setUniform("rot", new Float32Array([this._rx, this._ry, rz]), gl.uniform3fv); + this._setUniform("z", this._z, gl.uniform1f); + this._setUniform("fudge", this._fudge, gl.uniform1f); + } + set fudge(v) { + this._fudge = v; + this.redraw(); + } + get fudge() { + return this._fudge; + } + get rx() { + return this._rx; + } + set rx(v) { + this._rx = v; + this.redraw(); + } + get ry() { + return this._ry; + } + set ry(v) { + this._ry = v; + this.redraw(); + } + get z() { + return this._z; + } + set z(v) { + this._z = v; + this.redraw(); + } + useDefault() { + return this._rx === 0 && this._ry === 0 && this._z === 0; + } + } + PerspectiveShader.vertexShaderSource = ` + #ifdef GL_ES + # ifdef GL_FRAGMENT_PRECISION_HIGH + precision highp float; + # else + precision lowp float; + # endif + #endif + attribute vec2 aVertexPosition; + attribute vec2 aTextureCoord; + attribute vec4 aColor; + uniform vec2 projection; + varying vec2 vTextureCoord; + varying vec4 vColor; + + uniform float z; + uniform vec3 pivot; + uniform vec3 rot; + varying vec3 pos; + + void main(void) { + pos = vec3(aVertexPosition.xy, z); + + pos -= pivot; + + // Undo XY rotation + mat2 iRotXy = mat2( cos(rot.z), sin(rot.z), + -sin(rot.z), cos(rot.z)); + pos.xy = iRotXy * pos.xy; + + // Perform 3d rotations + gl_Position.x = cos(rot.x) * pos.x - sin(rot.x) * pos.z; + gl_Position.y = pos.y; + gl_Position.z = sin(rot.x) * pos.x + cos(rot.x) * pos.z; + + pos.x = gl_Position.x; + pos.y = cos(rot.y) * gl_Position.y - sin(rot.y) * gl_Position.z; + pos.z = sin(rot.y) * gl_Position.y + cos(rot.y) * gl_Position.z; + + // Redo XY rotation + iRotXy[0][1] = -iRotXy[0][1]; + iRotXy[1][0] = -iRotXy[1][0]; + pos.xy = iRotXy * pos.xy; + + // Undo translate to pivot position + pos.xyz += pivot; + + pos = vec3(pos.x * projection.x - 1.0, pos.y * -abs(projection.y) + 1.0, pos.z * projection.x); + + // Map coords to gl coordinate space. + // Set z to 0 because we don't want to perform z-clipping + gl_Position = vec4(pos.xy, 0.0, z); + + vTextureCoord = aTextureCoord; + vColor = aColor; + + gl_Position.y = -sign(projection.y) * gl_Position.y; + } +`; + PerspectiveShader.fragmentShaderSource = ` + #ifdef GL_ES + # ifdef GL_FRAGMENT_PRECISION_HIGH + precision highp float; + # else + precision lowp float; + # endif + #endif + varying vec2 vTextureCoord; + varying vec4 vColor; + uniform sampler2D uSampler; + + uniform vec3 rot; + uniform float fudge; + + void main(void) { + vec2 coords = vTextureCoord; + + coords.xy -= vec2(0.5); + coords.y = coords.y + (sign(rot[0]) * 0.5 - coords.x) * sin(rot[0]) * fudge * coords.y; + coords.x = coords.x + (sign(rot[1]) * 0.5 - coords.y) * sin(rot[1]) * fudge * coords.x; + coords.xy += vec2(0.5); + + if (coords.x < 0.0 || coords.x > 1.0 || coords.y < 0.0 || coords.y > 1.0) { + gl_FragColor = vec4(0.0); + } else { + gl_FragColor = texture2D(uSampler, coords) * vColor; + } + } +`; + class MagnifierShader extends DefaultShader$1 { + constructor(context) { + super(context); + this._x = 0; + this._y = 0; + this._w = 0; + this._h = 0; + this._radius = 0; + this._magnification = 0.6; + } + get x() { + return this._x; + } + set x(v) { + this._x = v; + this.redraw(); + } + get y() { + return this._y; + } + set y(v) { + this._y = v; + this.redraw(); + } + get w() { + return this._w; + } + set w(v) { + this._w = v; + this.redraw(); + } + get h() { + return this._h; + } + set h(v) { + this._h = v; + this.redraw(); + } + get magnification() { + return this._magnification; + } + set magnification(v) { + this._magnification = v; + this.redraw(); + } + get radius() { + return this._radius; + } + set radius(v) { + this._radius = v; + this.redraw(); + } + setupUniforms(operation) { + super.setupUniforms(operation); + const owner = operation.shaderOwner; + const renderPrecision = this.ctx.stage.getRenderPrecision(); + this._setUniform("x", this._x * renderPrecision, this.gl.uniform1f); + this._setUniform("y", this._y * renderPrecision, this.gl.uniform1f); + this._setUniform("w", this._w * renderPrecision, this.gl.uniform1f); + this._setUniform("h", this._h * renderPrecision, this.gl.uniform1f); + this._setUniform("magnification", this._magnification, this.gl.uniform1f); + this._setUniform( + "radius", + (this._radius + 0.5) * renderPrecision, + this.gl.uniform1f + ); + this._setUniform( + "resolution", + new Float32Array([ + owner._w * renderPrecision, + owner._h * renderPrecision + ]), + this.gl.uniform2fv + ); + } + useDefault() { + return this._w === 0 && this._h === 0; + } + } + MagnifierShader.vertexShaderSource = DefaultShader$1.vertexShaderSource; + MagnifierShader.fragmentShaderSource = ` + #ifdef GL_ES + # ifdef GL_FRAGMENT_PRECISION_HIGH + precision highp float; + # else + precision lowp float; + # endif + #endif + + varying vec2 vTextureCoord; + varying vec4 vColor; + uniform sampler2D uSampler; + uniform float x; + uniform float y; + uniform float w; + uniform float h; + uniform vec2 resolution; + uniform float radius; + uniform float magnification; + + float roundBox(vec2 p, vec2 b, float r) { + float d = length(max(abs(p)-b+r, 0.1))-r; + return smoothstep(1.0, 0.0, d); + } + + float inside(vec2 v) { + vec2 s = step(vec2(0.0, 0.0), v) - step(vec2(1.0, 1.0), v); + return s.x * s.y; + } + + void main(void) { + vec4 color = texture2D(uSampler, vTextureCoord); + vec2 pos = vTextureCoord.xy * resolution - vec2(x, y) - vec2(w, h) / 2.0; + vec2 size = vec2(w, h) / 2.0; + float b = roundBox(pos, size, radius); + vec2 pos2 = (vTextureCoord.xy * magnification * resolution + vec2(x, y) * magnification) / resolution; + gl_FragColor = mix(color, texture2D(uSampler, pos2) * inside(pos2), b) * vColor; + } + `; + class SpinnerShader2 extends DefaultShader$1 { + constructor(context) { + super(context); + this._period = 1; + this._stroke = 0; + this._showDot = true; + this._clockwise = true; + this._bc = 4278190080; + this._normalizedBC = this._getNormalizedColor(this._bc); + this._c = 4294967295; + this._normalizedC = this._getNormalizedColor(this._c); + } + set radius(v) { + if (v === 0) { + v = 1; + } + this._radius = v; + } + set stroke(value) { + this._stroke = Math.abs(value); + } + get stroke() { + return this._stroke; + } + set color(argb) { + this._c = argb; + this._normalizedC = this._getNormalizedColor(argb); + } + get color() { + return this._c; + } + set backgroundColor(argb) { + this._bc = argb; + this._normalizedBC = this._getNormalizedColor(argb); + } + get backgroundColor() { + return this._sc; + } + set showDot(bool) { + this._showDot = bool; + } + get showDot() { + return this._showDot; + } + set clockwise(bool) { + this._clockwise = bool; + } + get clockwise() { + return this._clockwise; + } + set period(v) { + this._period = v; + } + get period() { + return this._period; + } + _getNormalizedColor(color) { + const col = StageUtils.getRgbaComponentsNormalized(color); + col[0] *= col[3]; + col[1] *= col[3]; + col[2] *= col[3]; + return new Float32Array(col); + } + setupUniforms(operation) { + super.setupUniforms(operation); + const owner = operation.shaderOwner; + const radius = this._radius || owner._w / 2; + if (this._stroke === 0) { + this._stroke = radius * 0.33; + } + this._setUniform("resolution", new Float32Array([owner._w, owner._h]), this.gl.uniform2fv); + this._setUniform("color", this._normalizedC, this.gl.uniform4fv); + this._setUniform("backgroundColor", this._normalizedBC, this.gl.uniform4fv); + this._setUniform("stroke", this._stroke, this.gl.uniform1f); + this._setUniform("radius", radius, this.gl.uniform1f); + this._setUniform("direction", this._clockwise ? -1 : 1, this.gl.uniform1f); + this._setUniform("showDot", !!this._showDot, this.gl.uniform1f); + this._setUniform("time", Date.now() - SpinnerShader2.spinSync, this.gl.uniform1f); + this._setUniform("period", this._period, this.gl.uniform1f); + this._setUniform("alpha", operation.getElementCore(0).renderContext.alpha, this.gl.uniform1f); + if (this._sc !== this._bc || this._stroke !== radius * 0.5) { + this.redraw(); + } + } + } + SpinnerShader2.spinSync = Date.now(); + SpinnerShader2.fragmentShaderSource = ` + #ifdef GL_ES + # ifdef GL_FRAGMENT_PRECISION_HIGH + precision highp float; + # else + precision lowp float; + # endif + #endif + + #define PI 3.14159265359 + + varying vec2 vTextureCoord; + varying vec4 vColor; + + uniform sampler2D uSampler; + uniform vec2 resolution; + uniform vec4 color; + uniform vec4 backgroundColor; + uniform float direction; + uniform float radius; + uniform float time; + uniform float stroke; + uniform float showDot; + uniform float period; + uniform float alpha; + + float circleDist(vec2 p, float radius){ + return length(p) - radius; + } + + float fillMask(float dist){ + return clamp(-dist, 0.0, 1.0); + } + + void main() { + vec2 halfRes = 0.5 * resolution.xy; + vec2 center = vTextureCoord.xy * resolution - halfRes; + + float c = max(-circleDist(center, radius - stroke), circleDist(center, radius)); + float rot = -(time / 1000.0 / period) * 6.0 * direction; + center *= mat2(cos(rot), sin(rot), -sin(rot), cos(rot)); + + float a = direction * atan(center.x, center.y) * PI * 0.05 + 0.45; + + float strokeRad = stroke * 0.5; + a = mix(a, max(a, fillMask(circleDist(vec2(center.x, center.y + (radius - strokeRad)), strokeRad))), showDot); + vec4 base = mix(vec4(0.0), backgroundColor * alpha, fillMask(c)); + gl_FragColor = mix(base, color * alpha, fillMask(c) * a); + } +`; + const lightning = { + Application, + Component, + Base, + Utils: Utils$1, + StageUtils, + Element, + Tools, + Stage, + ElementCore, + ElementTexturizer, + Texture, + EventEmitter, + shaders: { + Grayscale: WebGLGrayscaleShader, + BoxBlur: BoxBlurShader, + Dithering: DitheringShader, + CircularPush: CircularPushShader, + Inversion: InversionShader, + LinearBlur: LinearBlurShader, + Outline: OutlineShader, + Pixelate: PixelateShader, + RadialFilter: RadialFilterShader, + RoundedRectangle: RoundedRectangleShader, + Spinner2: SpinnerShader2, + FadeOut: FadeOutShader, + Hole: HoleShader, + Vignette: VignetteShader, + Spinner: SpinnerShader, + RadialGradient: RadialGradientShader, + Light3d: Light3dShader, + Perspective: PerspectiveShader, + Magnifier: MagnifierShader, + WebGLShader, + WebGLDefaultShader: DefaultShader$1, + C2dShader, + C2dDefaultShader: DefaultShader, + c2d: { + Grayscale: C2dGrayscaleShader, + Blur: BlurShader + } + }, + textures: { + RectangleTexture, + NoiseTexture, + TextTexture, + ImageTexture, + HtmlTexture, + StaticTexture, + StaticCanvasTexture, + SourceTexture + }, + components: { + FastBlurComponent, + BloomComponent, + SmoothScaleComponent, + BorderComponent, + ListComponent + }, + tools: { + ObjMerger, + ObjectListProxy, + ObjectListWrapper + } + }; + if (Utils$1.isWeb) { + window.lng = lightning; + } + return lightning; +}); +//# sourceMappingURL=lightning.js.map + +/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../../../webpack/buildin/global.js */ "./node_modules/webpack/buildin/global.js"))) + +/***/ }), + +/***/ "./node_modules/@lightningjs/sdk/index.js": +/*!************************************************!*\ + !*** ./node_modules/@lightningjs/sdk/index.js ***! + \************************************************/ +/*! exports provided: Accessibility, Ads, AppData, Application, AudioPlayer, Colors, Img, Keyboard, Launch, Lightning, Locale, Language, Log, MediaPlayer, Metrics, Pin, Profile, Purchase, Registry, Router, Settings, Storage, TV, Utils, VideoPlayer, Metadata, Subtitles */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var _src_Accessibility__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./src/Accessibility */ "./node_modules/@lightningjs/sdk/src/Accessibility/index.js"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Accessibility", function() { return _src_Accessibility__WEBPACK_IMPORTED_MODULE_0__["default"]; }); + +/* harmony import */ var _src_Ads__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./src/Ads */ "./node_modules/@lightningjs/sdk/src/Ads/index.js"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Ads", function() { return _src_Ads__WEBPACK_IMPORTED_MODULE_1__["default"]; }); + +/* harmony import */ var _src_Application__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./src/Application */ "./node_modules/@lightningjs/sdk/src/Application/index.js"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AppData", function() { return _src_Application__WEBPACK_IMPORTED_MODULE_2__["AppData"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Application", function() { return _src_Application__WEBPACK_IMPORTED_MODULE_2__["default"]; }); + +/* harmony import */ var _src_AudioPlayer__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./src/AudioPlayer */ "./node_modules/@lightningjs/sdk/src/AudioPlayer/index.js"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AudioPlayer", function() { return _src_AudioPlayer__WEBPACK_IMPORTED_MODULE_3__["default"]; }); + +/* harmony import */ var _src_Colors__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./src/Colors */ "./node_modules/@lightningjs/sdk/src/Colors/index.js"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Colors", function() { return _src_Colors__WEBPACK_IMPORTED_MODULE_4__["default"]; }); + +/* harmony import */ var _src_Img__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./src/Img */ "./node_modules/@lightningjs/sdk/src/Img/index.js"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Img", function() { return _src_Img__WEBPACK_IMPORTED_MODULE_5__["default"]; }); + +/* harmony import */ var _src_Keyboard__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./src/Keyboard */ "./node_modules/@lightningjs/sdk/src/Keyboard/index.js"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Keyboard", function() { return _src_Keyboard__WEBPACK_IMPORTED_MODULE_6__["default"]; }); + +/* harmony import */ var _src_Launch__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./src/Launch */ "./node_modules/@lightningjs/sdk/src/Launch/index.js"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Launch", function() { return _src_Launch__WEBPACK_IMPORTED_MODULE_7__["default"]; }); + +/* harmony import */ var _src_Lightning__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./src/Lightning */ "./node_modules/@lightningjs/sdk/src/Lightning/index.js"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Lightning", function() { return _src_Lightning__WEBPACK_IMPORTED_MODULE_8__["default"]; }); + +/* harmony import */ var _src_Locale__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./src/Locale */ "./node_modules/@lightningjs/sdk/src/Locale/index.js"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Locale", function() { return _src_Locale__WEBPACK_IMPORTED_MODULE_9__["default"]; }); + +/* harmony import */ var _src_Language__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./src/Language */ "./node_modules/@lightningjs/sdk/src/Language/index.js"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Language", function() { return _src_Language__WEBPACK_IMPORTED_MODULE_10__["default"]; }); + +/* harmony import */ var _src_Log__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ./src/Log */ "./node_modules/@lightningjs/sdk/src/Log/index.js"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Log", function() { return _src_Log__WEBPACK_IMPORTED_MODULE_11__["default"]; }); + +/* harmony import */ var _src_MediaPlayer__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ./src/MediaPlayer */ "./node_modules/@lightningjs/sdk/src/MediaPlayer/index.js"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "MediaPlayer", function() { return _src_MediaPlayer__WEBPACK_IMPORTED_MODULE_12__["default"]; }); + +/* harmony import */ var _src_Metrics__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ./src/Metrics */ "./node_modules/@lightningjs/sdk/src/Metrics/index.js"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Metrics", function() { return _src_Metrics__WEBPACK_IMPORTED_MODULE_13__["default"]; }); + +/* harmony import */ var _src_Pin__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ./src/Pin */ "./node_modules/@lightningjs/sdk/src/Pin/index.js"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Pin", function() { return _src_Pin__WEBPACK_IMPORTED_MODULE_14__["default"]; }); + +/* harmony import */ var _src_Profile__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ./src/Profile */ "./node_modules/@lightningjs/sdk/src/Profile/index.js"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Profile", function() { return _src_Profile__WEBPACK_IMPORTED_MODULE_15__["default"]; }); + +/* harmony import */ var _src_Purchase__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(/*! ./src/Purchase */ "./node_modules/@lightningjs/sdk/src/Purchase/index.js"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Purchase", function() { return _src_Purchase__WEBPACK_IMPORTED_MODULE_16__["default"]; }); + +/* harmony import */ var _src_Registry__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(/*! ./src/Registry */ "./node_modules/@lightningjs/sdk/src/Registry/index.js"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Registry", function() { return _src_Registry__WEBPACK_IMPORTED_MODULE_17__["default"]; }); + +/* harmony import */ var _src_Router__WEBPACK_IMPORTED_MODULE_18__ = __webpack_require__(/*! ./src/Router */ "./node_modules/@lightningjs/sdk/src/Router/index.js"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Router", function() { return _src_Router__WEBPACK_IMPORTED_MODULE_18__["default"]; }); + +/* harmony import */ var _src_Settings__WEBPACK_IMPORTED_MODULE_19__ = __webpack_require__(/*! ./src/Settings */ "./node_modules/@lightningjs/sdk/src/Settings/index.js"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Settings", function() { return _src_Settings__WEBPACK_IMPORTED_MODULE_19__["default"]; }); + +/* harmony import */ var _src_Storage__WEBPACK_IMPORTED_MODULE_20__ = __webpack_require__(/*! ./src/Storage */ "./node_modules/@lightningjs/sdk/src/Storage/index.js"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Storage", function() { return _src_Storage__WEBPACK_IMPORTED_MODULE_20__["default"]; }); + +/* harmony import */ var _src_TV__WEBPACK_IMPORTED_MODULE_21__ = __webpack_require__(/*! ./src/TV */ "./node_modules/@lightningjs/sdk/src/TV/index.js"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "TV", function() { return _src_TV__WEBPACK_IMPORTED_MODULE_21__["default"]; }); + +/* harmony import */ var _src_Utils__WEBPACK_IMPORTED_MODULE_22__ = __webpack_require__(/*! ./src/Utils */ "./node_modules/@lightningjs/sdk/src/Utils/index.js"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Utils", function() { return _src_Utils__WEBPACK_IMPORTED_MODULE_22__["default"]; }); + +/* harmony import */ var _src_VideoPlayer__WEBPACK_IMPORTED_MODULE_23__ = __webpack_require__(/*! ./src/VideoPlayer */ "./node_modules/@lightningjs/sdk/src/VideoPlayer/index.js"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "VideoPlayer", function() { return _src_VideoPlayer__WEBPACK_IMPORTED_MODULE_23__["default"]; }); + +/* harmony import */ var _src_Metadata__WEBPACK_IMPORTED_MODULE_24__ = __webpack_require__(/*! ./src/Metadata */ "./node_modules/@lightningjs/sdk/src/Metadata/index.js"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Metadata", function() { return _src_Metadata__WEBPACK_IMPORTED_MODULE_24__["default"]; }); + +/* harmony import */ var _src_Subtitles__WEBPACK_IMPORTED_MODULE_25__ = __webpack_require__(/*! ./src/Subtitles */ "./node_modules/@lightningjs/sdk/src/Subtitles/index.js"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Subtitles", function() { return _src_Subtitles__WEBPACK_IMPORTED_MODULE_25__["default"]; }); + +/* + * If not stated otherwise in this file or this component's LICENSE file the + * following copyright and licenses apply: + * + * Copyright 2020 Metrological + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +/***/ }), + +/***/ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/EventEmitter.mjs": +/*!************************************************************************************************!*\ + !*** ./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/EventEmitter.mjs ***! + \************************************************************************************************/ +/*! exports provided: default */ +/***/ (function(__webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return EventEmitter; }); +/* + * If not stated otherwise in this file or this component's LICENSE file the + * following copyright and licenses apply: + * + * Copyright 2020 Metrological + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * This is a partial (and more efficient) implementation of the event emitter. + * It attempts to maintain a one-to-one mapping between events and listeners, skipping an array lookup. + * Only if there are multiple listeners, they are combined in an array. + */ +class EventEmitter { + + constructor() { + // This is set (and kept) to true when events are used at all. + this._hasEventListeners = false; + } + + on(name, listener) { + if (!this._hasEventListeners) { + this._eventFunction = {} + this._eventListeners = {} + this._hasEventListeners = true; + } + + const current = this._eventFunction[name]; + if (!current) { + this._eventFunction[name] = listener; + } else { + if (this._eventFunction[name] !== EventEmitter.combiner) { + this._eventListeners[name] = [this._eventFunction[name], listener]; + this._eventFunction[name] = EventEmitter.combiner; + } else { + this._eventListeners[name].push(listener); + } + } + } + + once(name, listener) { + const wrapper = (arg1, arg2, arg3) => { + listener(arg1, arg2, arg3); + this.off(name, wrapper); + } + wrapper.__originalFunc = listener; + this.on(name, wrapper); + } + + has(name, listener) { + if (this._hasEventListeners) { + const current = this._eventFunction[name]; + if (current) { + if (current === EventEmitter.combiner) { + const listeners = this._eventListeners[name]; + for (const l of listeners) { + if (l === listener || l.__originalFunc == listener) { + return true; + } + } + } else if (this._eventFunction[name] === listener || this._eventFunction[name].__originalFunc === listener) { + return true; + } + } + } + return false; + } + + off(name, listener) { + if (this._hasEventListeners) { + const current = this._eventFunction[name]; + if (current) { + if (current === EventEmitter.combiner) { + const listeners = this._eventListeners[name]; + let index = listeners.indexOf(listener); + if (index >= 0) { + listeners.splice(index, 1); + } + index = listeners.map((l) => l.__originalFunc).indexOf(listener); + if (index >= 0) { + listeners.splice(index, 1); + } + if (listeners.length === 1) { + this._eventFunction[name] = listeners[0]; + this._eventListeners[name] = undefined; + } + } else if (this._eventFunction[name] === listener || this._eventFunction[name].__originalFunc === listener) { + this._eventFunction[name] = undefined; + } + } + } + } + + removeListener(name, listener) { + this.off(name, listener); + } + + emit(name, arg1, arg2, arg3) { + if (this._hasEventListeners) { + const func = this._eventFunction[name]; + if (func) { + if (func === EventEmitter.combiner) { + func(this, name, arg1, arg2, arg3); + } else { + func(arg1, arg2, arg3); + } + } + } + } + + listenerCount(name) { + if (this._hasEventListeners) { + const func = this._eventFunction[name]; + if (func) { + if (func === EventEmitter.combiner) { + return this._eventListeners[name].length; + } else { + return 1; + } + } + } + return 0; + } + + removeAllListeners(name) { + if (this._hasEventListeners) { + delete this._eventFunction[name]; + delete this._eventListeners[name]; + } + } + +} + +EventEmitter.combiner = function(object, name, arg1, arg2, arg3) { + const listeners = object._eventListeners[name]; + if (listeners) { + /* Because listener may detach itself while being invoked and therefore invalidate the iterator, + we need to create a copy to loop over it */ + for (const listener of [...listeners]) { + listener(arg1, arg2, arg3); + } + } +} + +EventEmitter.addAsMixin = function(cls) { + cls.prototype.on = EventEmitter.prototype.on; + cls.prototype.once = EventEmitter.prototype.once; + cls.prototype.has = EventEmitter.prototype.has; + cls.prototype.off = EventEmitter.prototype.off; + cls.prototype.removeListener = EventEmitter.prototype.removeListener; + cls.prototype.emit = EventEmitter.prototype.emit; + cls.prototype.listenerCount = EventEmitter.prototype.listenerCount; + cls.prototype.removeAllListeners = EventEmitter.prototype.removeAllListeners; +} + + + +/***/ }), + +/***/ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/animation/Animation.mjs": +/*!*******************************************************************************************************!*\ + !*** ./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/animation/Animation.mjs ***! + \*******************************************************************************************************/ +/*! exports provided: default */ +/***/ (function(__webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return Animation; }); +/* harmony import */ var _EventEmitter_mjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../EventEmitter.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/EventEmitter.mjs"); +/* harmony import */ var _AnimationSettings_mjs__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./AnimationSettings.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/animation/AnimationSettings.mjs"); +/* + * If not stated otherwise in this file or this component's LICENSE file the + * following copyright and licenses apply: + * + * Copyright 2020 Metrological + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + + +class Animation extends _EventEmitter_mjs__WEBPACK_IMPORTED_MODULE_0__["default"] { + + constructor(manager, settings, element) { + super(); + + this.manager = manager; + + this._settings = settings; + + this._element = element; + + this._state = Animation.STATES.IDLE; + + this._p = 0; + this._delayLeft = 0; + this._repeatsLeft = 0; + + this._stopDelayLeft = 0; + this._stopP = 0; + } + + start() { + if (this._element && this._element.attached) { + this._p = 0; + this._delayLeft = this.settings.delay; + this._repeatsLeft = this.settings.repeat; + this._state = Animation.STATES.PLAYING; + this.emit('start'); + this.checkActive(); + } else { + console.warn("[Lightning] Element must be attached before starting animation"); + } + } + + play() { + if (this._state === Animation.STATES.PAUSED) { + // Continue.; + this._state = Animation.STATES.PLAYING; + this.checkActive(); + this.emit('resume'); + } else if (this._state == Animation.STATES.STOPPING && this.settings.stopMethod == _AnimationSettings_mjs__WEBPACK_IMPORTED_MODULE_1__["default"].STOP_METHODS.REVERSE) { + // Continue.; + this._state = Animation.STATES.PLAYING; + this.emit('stopContinue'); + } else if (this._state != Animation.STATES.PLAYING && this._state != Animation.STATES.FINISHED) { + // Restart.; + this.start(); + } + } + + pause() { + if (this._state === Animation.STATES.PLAYING) { + this._state = Animation.STATES.PAUSED; + this.emit('pause'); + } + } + + replay() { + if (this._state == Animation.STATES.FINISHED) { + this.start(); + } else { + this.play(); + } + } + + skipDelay() { + this._delayLeft = 0; + this._stopDelayLeft = 0; + } + + finish() { + if (this._state === Animation.STATES.PLAYING) { + this._delayLeft = 0; + this._p = 1; + } else if (this._state === Animation.STATES.STOPPING) { + this._stopDelayLeft = 0; + this._p = 0; + } + } + + stop() { + if (this._state === Animation.STATES.STOPPED || this._state === Animation.STATES.IDLE) return; + + this._stopDelayLeft = this.settings.stopDelay || 0; + + if (((this.settings.stopMethod === _AnimationSettings_mjs__WEBPACK_IMPORTED_MODULE_1__["default"].STOP_METHODS.IMMEDIATE) && !this._stopDelayLeft) || this._delayLeft > 0) { + // Stop upon next progress.; + this._state = Animation.STATES.STOPPING; + this.emit('stop'); + } else { + if (this.settings.stopMethod === _AnimationSettings_mjs__WEBPACK_IMPORTED_MODULE_1__["default"].STOP_METHODS.FADE) { + this._stopP = 0; + } + + this._state = Animation.STATES.STOPPING; + this.emit('stop'); + } + + this.checkActive(); + } + + stopNow() { + if (this._state !== Animation.STATES.STOPPED || this._state !== Animation.STATES.IDLE) { + this._state = Animation.STATES.STOPPING; + this._p = 0; + this.emit('stop'); + this.reset(); + this._state = Animation.STATES.STOPPED; + this.emit('stopFinish'); + } + } + + isPaused() { + return this._state === Animation.STATES.PAUSED; + } + + isPlaying() { + return this._state === Animation.STATES.PLAYING; + } + + isStopping() { + return this._state === Animation.STATES.STOPPING; + } + + isFinished() { + return this._state === Animation.STATES.FINISHED; + } + + checkActive() { + if (this.isActive()) { + this.manager.addActive(this); + } + } + + isActive() { + return (this._state == Animation.STATES.PLAYING || this._state == Animation.STATES.STOPPING) && this._element && this._element.attached; + } + + progress(dt) { + if (!this._element) return; + this._progress(dt); + this.apply(); + } + + _progress(dt) { + if (this._state == Animation.STATES.STOPPING) { + this._stopProgress(dt); + return; + } + + if (this._state != Animation.STATES.PLAYING) { + return; + } + + if (this._delayLeft > 0) { + this._delayLeft -= dt; + + if (this._delayLeft < 0) { + dt = -this._delayLeft; + this._delayLeft = 0; + + this.emit('delayEnd'); + } else { + return; + } + } + + if (this.settings.duration === 0) { + this._p = 1; + } else if (this.settings.duration > 0) { + this._p += dt / this.settings.duration; + } + if (this._p >= 1) { + // Finished!; + if (this.settings.repeat == -1 || this._repeatsLeft > 0) { + if (this._repeatsLeft > 0) { + this._repeatsLeft--; + } + this._p = this.settings.repeatOffset; + this.emit('progress', this._p); + + if (this.settings.repeatDelay) { + this._delayLeft = this.settings.repeatDelay; + } + + this.emit('repeat', this._repeatsLeft); + } else { + this._p = 1; + this.emit('progress', this._p); + + this._state = Animation.STATES.FINISHED; + this.emit('finish'); + if (this.settings.autostop) { + this.stop(); + } + } + } else { + this.emit('progress', this._p); + } + } + + _stopProgress(dt) { + let duration = this._getStopDuration(); + + if (this._stopDelayLeft > 0) { + this._stopDelayLeft -= dt; + + if (this._stopDelayLeft < 0) { + dt = -this._stopDelayLeft; + this._stopDelayLeft = 0; + + this.emit('stopDelayEnd'); + } else { + return; + } + } + if (this.settings.stopMethod == _AnimationSettings_mjs__WEBPACK_IMPORTED_MODULE_1__["default"].STOP_METHODS.IMMEDIATE) { + this._state = Animation.STATES.STOPPED; + this.emit('stopFinish'); + } else if (this.settings.stopMethod == _AnimationSettings_mjs__WEBPACK_IMPORTED_MODULE_1__["default"].STOP_METHODS.REVERSE) { + if (duration === 0) { + this._p = 0; + } else if (duration > 0) { + this._p -= dt / duration; + } + + if (this._p <= 0) { + this._p = 0; + this._state = Animation.STATES.STOPPED; + this.emit('stopFinish'); + } + } else if (this.settings.stopMethod == _AnimationSettings_mjs__WEBPACK_IMPORTED_MODULE_1__["default"].STOP_METHODS.FADE) { + this._progressStopTransition(dt); + if (this._stopP >= 1) { + this._p = 0; + this._state = Animation.STATES.STOPPED; + this.emit('stopFinish'); + } + } else if (this.settings.stopMethod == _AnimationSettings_mjs__WEBPACK_IMPORTED_MODULE_1__["default"].STOP_METHODS.ONETOTWO) { + if (this._p < 2) { + if (duration === 0) { + this._p = 2; + } else if (duration > 0) { + if (this._p < 1) { + this._p += dt / this.settings.duration; + } else { + this._p += dt / duration; + } + } + if (this._p >= 2) { + this._p = 2; + this._state = Animation.STATES.STOPPED; + this.emit('stopFinish'); + } else { + this.emit('progress', this._p); + } + } + } else if (this.settings.stopMethod == _AnimationSettings_mjs__WEBPACK_IMPORTED_MODULE_1__["default"].STOP_METHODS.FORWARD) { + if (this._p < 1) { + if (this.settings.duration == 0) { + this._p = 1; + } else { + this._p += dt / this.settings.duration; + } + if (this._p >= 1) { + if (this.settings.stopMethod == _AnimationSettings_mjs__WEBPACK_IMPORTED_MODULE_1__["default"].STOP_METHODS.FORWARD) { + this._p = 1; + this._state = Animation.STATES.STOPPED; + this.emit('stopFinish'); + } else { + if (this._repeatsLeft > 0) { + this._repeatsLeft--; + this._p = 0; + this.emit('repeat', this._repeatsLeft); + } else { + this._p = 1; + this._state = Animation.STATES.STOPPED; + this.emit('stopFinish'); + } + } + } else { + this.emit('progress', this._p); + } + } + } + + } + + _progressStopTransition(dt) { + if (this._stopP < 1) { + if (this._stopDelayLeft > 0) { + this._stopDelayLeft -= dt; + + if (this._stopDelayLeft < 0) { + dt = -this._stopDelayLeft; + this._stopDelayLeft = 0; + + this.emit('delayEnd'); + } else { + return; + } + } + + const duration = this._getStopDuration(); + + if (duration == 0) { + this._stopP = 1; + } else { + this._stopP += dt / duration; + } + if (this._stopP >= 1) { + // Finished!; + this._stopP = 1; + } + } + } + + _getStopDuration() { + return this.settings.stopDuration || this.settings.duration; + } + + apply() { + if (this._state === Animation.STATES.STOPPED) { + this.reset(); + } else { + let factor = 1; + if (this._state === Animation.STATES.STOPPING && this.settings.stopMethod === _AnimationSettings_mjs__WEBPACK_IMPORTED_MODULE_1__["default"].STOP_METHODS.FADE) { + factor = (1 - this.settings.stopTimingFunctionImpl(this._stopP)); + } + this._settings.apply(this._element, this._p, factor); + } + } + + reset() { + this._settings.reset(this._element); + } + + get state() { + return this._state; + } + + get p() { + return this._p; + } + + get delayLeft() { + return this._delayLeft; + } + + get element() { + return this._element; + } + + get frame() { + return Math.round(this._p * this._settings.duration * 60); + } + + get settings() { + return this._settings; + } + +} + +Animation.STATES = { + IDLE: 0, + PLAYING: 1, + STOPPING: 2, + STOPPED: 3, + FINISHED: 4, + PAUSED: 5 +} + + +/***/ }), + +/***/ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/animation/AnimationActionSettings.mjs": +/*!*********************************************************************************************************************!*\ + !*** ./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/animation/AnimationActionSettings.mjs ***! + \*********************************************************************************************************************/ +/*! exports provided: default */ +/***/ (function(__webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return AnimationActionSettings; }); +/* harmony import */ var _tools_MultiSpline_mjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../tools/MultiSpline.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/tools/MultiSpline.mjs"); +/* harmony import */ var _tree_Element_mjs__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../tree/Element.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/tree/Element.mjs"); +/* harmony import */ var _tree_StageUtils_mjs__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../tree/StageUtils.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/tree/StageUtils.mjs"); +/* harmony import */ var _tree_Utils_mjs__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../tree/Utils.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/tree/Utils.mjs"); +/* harmony import */ var _tree_Base_mjs__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../tree/Base.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/tree/Base.mjs"); +/* + * If not stated otherwise in this file or this component's LICENSE file the + * following copyright and licenses apply: + * + * Copyright 2020 Metrological + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +class AnimationActionSettings { + + constructor(animationSettings) { + + this.animationSettings = animationSettings; + + /** + * The selector that selects the elements. + * @type {string} + */ + this._selector = ""; + + /** + * The value items, ordered by progress offset. + * @type {MultiSpline} + * @private; + */ + this._items = new _tools_MultiSpline_mjs__WEBPACK_IMPORTED_MODULE_0__["default"](); + + /** + * The affected properties (paths). + * @private; + */ + this._props = []; + + /** + * Property setters, indexed according to props. + * @private; + */ + this._propSetters = []; + + this._resetValue = undefined; + this._hasResetValue = false; + + this._hasColorProperty = undefined; + } + + getResetValue() { + if (this._hasResetValue) { + return this._resetValue; + } else { + return this._items.getValue(0); + } + } + + apply(element, p, factor) { + const elements = this.getAnimatedElements(element); + + let v = this._items.getValue(p); + + if (v === undefined || !elements.length) { + return; + } + + if (factor !== 1) { + // Stop factor.; + let sv = this.getResetValue(); + + if (_tree_Utils_mjs__WEBPACK_IMPORTED_MODULE_3__["default"].isNumber(v) && _tree_Utils_mjs__WEBPACK_IMPORTED_MODULE_3__["default"].isNumber(sv)) { + if (this.hasColorProperty()) { + v = _tree_StageUtils_mjs__WEBPACK_IMPORTED_MODULE_2__["default"].mergeColors(v, sv, factor); + } else { + v = _tree_StageUtils_mjs__WEBPACK_IMPORTED_MODULE_2__["default"].mergeNumbers(v, sv, factor); + } + } + } + + // Apply transformation to all components.; + const n = this._propSetters.length; + + const m = elements.length; + for (let j = 0; j < m; j++) { + for (let i = 0; i < n; i++) { + this._propSetters[i](elements[j], v); + } + } + } + + getAnimatedElements(element) { + return element.select(this._selector); + } + + reset(element) { + const elements = this.getAnimatedElements(element); + + let v = this.getResetValue(); + + if (v === undefined || !elements.length) { + return; + } + + // Apply transformation to all components. + const n = this._propSetters.length; + + const m = elements.length; + for (let j = 0; j < m; j++) { + for (let i = 0; i < n; i++) { + this._propSetters[i](elements[j], v); + } + } + } + + set selector(v) { + this._selector = v; + } + + set t(v) { + this.selector = v; + } + + get resetValue() { + return this._resetValue; + } + + set resetValue(v) { + this._resetValue = v; + this._hasResetValue = (v !== undefined); + } + + set rv(v) { + this.resetValue = v; + } + + set value(v) { + this._items.parse(this.hasColorProperty(), v); + } + + set v(v) { + this.value = v; + } + + set properties(v) { + if (!Array.isArray(v)) { + v = [v]; + } + + this._props = []; + + v.forEach((prop) => { + this._props.push(prop); + this._propSetters.push(_tree_Element_mjs__WEBPACK_IMPORTED_MODULE_1__["default"].getSetter(prop)); + }); + } + + set property(v) { + this._hasColorProperty = undefined; + this.properties = v; + } + + set p(v) { + this.properties = v; + } + + patch(settings) { + _tree_Base_mjs__WEBPACK_IMPORTED_MODULE_4__["default"].patchObject(this, settings); + } + + hasColorProperty() { + if (this._hasColorProperty === undefined) { + this._hasColorProperty = this._props.length ? _tree_Element_mjs__WEBPACK_IMPORTED_MODULE_1__["default"].isColorProperty(this._props[0]) : false; + } + return this._hasColorProperty; + } +} + +AnimationActionSettings.prototype.isAnimationActionSettings = true; + + + + + + + + +/***/ }), + +/***/ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/animation/AnimationManager.mjs": +/*!**************************************************************************************************************!*\ + !*** ./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/animation/AnimationManager.mjs ***! + \**************************************************************************************************************/ +/*! exports provided: default */ +/***/ (function(__webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return AnimationManager; }); +/* harmony import */ var _tree_Base_mjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../tree/Base.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/tree/Base.mjs"); +/* harmony import */ var _tree_Utils_mjs__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../tree/Utils.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/tree/Utils.mjs"); +/* harmony import */ var _AnimationSettings_mjs__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./AnimationSettings.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/animation/AnimationSettings.mjs"); +/* harmony import */ var _Animation_mjs__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./Animation.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/animation/Animation.mjs"); +/* + * If not stated otherwise in this file or this component's LICENSE file the + * following copyright and licenses apply: + * + * Copyright 2020 Metrological + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +class AnimationManager { + + constructor(stage) { + this.stage = stage; + + this.stage.on('frameStart', () => this.progress()); + + /** + * All running animations on attached subjects. + * @type {Set} + */ + this.active = new Set(); + } + + progress() { + if (this.active.size) { + let dt = this.stage.dt; + + let filter = false; + this.active.forEach(function(a) { + if (a.isActive()) { + a.progress(dt); + } else { + filter = true; + } + }); + + if (filter) { + this.active = new Set([...this.active].filter(t => t.isActive())); + } + } + } + + createAnimation(element, settings) { + if (_tree_Utils_mjs__WEBPACK_IMPORTED_MODULE_1__["default"].isObjectLiteral(settings)) { + // Convert plain object to proper settings object. + settings = this.createSettings(settings); + } + + return new _Animation_mjs__WEBPACK_IMPORTED_MODULE_3__["default"]( + this, + settings, + element + ); + } + + createSettings(settings) { + const animationSettings = new _AnimationSettings_mjs__WEBPACK_IMPORTED_MODULE_2__["default"](); + _tree_Base_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].patchObject(animationSettings, settings); + return animationSettings; + } + + addActive(transition) { + this.active.add(transition); + } +} + + + + + + + +/***/ }), + +/***/ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/animation/AnimationSettings.mjs": +/*!***************************************************************************************************************!*\ + !*** ./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/animation/AnimationSettings.mjs ***! + \***************************************************************************************************************/ +/*! exports provided: default */ +/***/ (function(__webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return AnimationSettings; }); +/* harmony import */ var _tree_StageUtils_mjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../tree/StageUtils.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/tree/StageUtils.mjs"); +/* harmony import */ var _AnimationActionSettings_mjs__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./AnimationActionSettings.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/animation/AnimationActionSettings.mjs"); +/* harmony import */ var _tree_Base_mjs__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../tree/Base.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/tree/Base.mjs"); +/* + * If not stated otherwise in this file or this component's LICENSE file the + * following copyright and licenses apply: + * + * Copyright 2020 Metrological + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + + + +class AnimationSettings { + constructor() { + /** + * @type {AnimationActionSettings[]} + */ + this._actions = []; + + this.delay = 0; + this.duration = 1; + + this.repeat = 0; + this.repeatOffset = 0; + this.repeatDelay = 0; + + this.autostop = false; + + this.stopMethod = AnimationSettings.STOP_METHODS.FADE; + this._stopTimingFunction = 'ease'; + this._stopTimingFunctionImpl = _tree_StageUtils_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].getTimingFunction(this._stopTimingFunction); + this.stopDuration = 0; + this.stopDelay = 0; + } + + get actions() { + return this._actions; + } + + set actions(v) { + this._actions = []; + for (let i = 0, n = v.length; i < n; i++) { + const e = v[i]; + if (!e.isAnimationActionSettings) { + const aas = new _AnimationActionSettings_mjs__WEBPACK_IMPORTED_MODULE_1__["default"](this); + aas.patch(e); + this._actions.push(aas); + } else { + this._actions.push(e); + } + } + } + + /** + * Applies the animation to the specified element, for the specified progress between 0 and 1. + * @param {Element} element; + * @param {number} p; + * @param {number} factor; + */ + apply(element, p, factor = 1) { + this._actions.forEach(function(action) { + action.apply(element, p, factor); + }); + } + + /** + * Resets the animation to the reset values. + * @param {Element} element; + */ + reset(element) { + this._actions.forEach(function(action) { + action.reset(element); + }); + } + + get stopTimingFunction() { + return this._stopTimingFunction; + } + + set stopTimingFunction(v) { + this._stopTimingFunction = v; + this._stopTimingFunctionImpl = _tree_StageUtils_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].getTimingFunction(v); + } + + get stopTimingFunctionImpl() { + return this._stopTimingFunctionImpl; + } + + patch(settings) { + _tree_Base_mjs__WEBPACK_IMPORTED_MODULE_2__["default"].patchObject(this, settings); + } + +} + +AnimationSettings.STOP_METHODS = { + FADE: 'fade', + REVERSE: 'reverse', + FORWARD: 'forward', + IMMEDIATE: 'immediate', + ONETOTWO: 'onetotwo' +}; + + + +/***/ }), + +/***/ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/animation/Transition.mjs": +/*!********************************************************************************************************!*\ + !*** ./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/animation/Transition.mjs ***! + \********************************************************************************************************/ +/*! exports provided: default */ +/***/ (function(__webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return Transition; }); +/* harmony import */ var _EventEmitter_mjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../EventEmitter.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/EventEmitter.mjs"); +/* + * If not stated otherwise in this file or this component's LICENSE file the + * following copyright and licenses apply: + * + * Copyright 2020 Metrological + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + +class Transition extends _EventEmitter_mjs__WEBPACK_IMPORTED_MODULE_0__["default"] { + + constructor(manager, settings, element, property) { + super(); + + this.manager = manager; + + this._settings = settings; + + this._element = element; + + this._getter = element.constructor.getGetter(property); + this._setter = element.constructor.getSetter(property); + + this._merger = settings.merger; + + if (!this._merger) { + this._merger = element.constructor.getMerger(property); + } + + this._startValue = this._getter(this._element); + this._targetValue = this._startValue; + + this._p = 1; + this._delayLeft = 0; + } + + start(targetValue) { + this._startValue = this._getter(this._element); + + if (!this.isAttached()) { + // We don't support transitions on non-attached elements. Just set value without invoking listeners. + this._targetValue = targetValue; + this._p = 1; + this._updateDrawValue(); + } else { + if (targetValue === this._startValue) { + this.reset(targetValue, 1); + } else { + this._targetValue = targetValue; + this._p = 0; + this._delayLeft = this._settings.delay; + this.emit('start'); + this.add(); + } + } + } + + finish() { + if (this._p < 1) { + // Value setting and will must be invoked (async) upon next transition cycle. + this._p = 1; + } + } + + stop() { + // Just stop where the transition is at. + this.emit('stop'); + this.manager.removeActive(this); + } + + pause() { + this.stop(); + } + + play() { + this.manager.addActive(this); + } + + reset(targetValue, p) { + if (!this.isAttached()) { + // We don't support transitions on non-attached elements. Just set value without invoking listeners. + this._startValue = this._getter(this._element); + this._targetValue = targetValue; + this._p = 1; + this._updateDrawValue(); + } else { + this._startValue = this._getter(this._element); + this._targetValue = targetValue; + this._p = p; + this.add(); + } + } + + _updateDrawValue() { + this._setter(this._element, this.getDrawValue()); + } + + add() { + this.manager.addActive(this); + } + + isAttached() { + return this._element.attached; + } + + isRunning() { + return (this._p < 1.0); + } + + progress(dt) { + if (!this.isAttached()) { + // Skip to end of transition so that it is removed. + this._p = 1; + } + + if (this.p < 1) { + if (this.delayLeft > 0) { + this._delayLeft -= dt; + + if (this.delayLeft < 0) { + dt = -this.delayLeft; + this._delayLeft = 0; + + this.emit('delayEnd'); + } else { + return; + } + } + + if (this._settings.duration == 0) { + this._p = 1; + } else { + this._p += dt / this._settings.duration; + } + if (this._p >= 1) { + // Finished!; + this._p = 1; + } + } + + this._updateDrawValue(); + + this.invokeListeners(); + } + + invokeListeners() { + this.emit('progress', this.p); + if (this.p === 1) { + this.emit('finish'); + } + } + + updateTargetValue(targetValue) { + let t = this._settings.timingFunctionImpl(this.p); + if (t === 1) { + this._targetValue = targetValue; + } else if (t === 0) { + this._startValue = this._targetValue; + this._targetValue = targetValue; + } else { + this._startValue = targetValue - ((targetValue - this._targetValue) / (1 - t)); + this._targetValue = targetValue; + } + } + + getDrawValue() { + if (this.p >= 1) { + return this.targetValue; + } else { + let v = this._settings._timingFunctionImpl(this.p); + return this._merger(this.targetValue, this.startValue, v); + } + } + + skipDelay() { + this._delayLeft = 0; + } + + get startValue() { + return this._startValue; + } + + get targetValue() { + return this._targetValue; + } + + get p() { + return this._p; + } + + get delayLeft() { + return this._delayLeft; + } + + get element() { + return this._element; + } + + get settings() { + return this._settings; + } + + set settings(v) { + this._settings = v; + } + +} + +Transition.prototype.isTransition = true; + + +/***/ }), + +/***/ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/animation/TransitionManager.mjs": +/*!***************************************************************************************************************!*\ + !*** ./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/animation/TransitionManager.mjs ***! + \***************************************************************************************************************/ +/*! exports provided: default */ +/***/ (function(__webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return TransitionManager; }); +/* harmony import */ var _tree_Base_mjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../tree/Base.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/tree/Base.mjs"); +/* harmony import */ var _TransitionSettings_mjs__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./TransitionSettings.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/animation/TransitionSettings.mjs"); +/* harmony import */ var _Transition_mjs__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./Transition.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/animation/Transition.mjs"); +/* + * If not stated otherwise in this file or this component's LICENSE file the + * following copyright and licenses apply: + * + * Copyright 2020 Metrological + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +class TransitionManager { + + constructor(stage) { + this.stage = stage; + + this.stage.on('frameStart', () => this.progress()); + + /** + * All transitions that are running and attached. + * (we don't support transitions on un-attached elements to prevent memory leaks) + * @type {Set} + */ + this.active = new Set(); + + this.defaultTransitionSettings = new _TransitionSettings_mjs__WEBPACK_IMPORTED_MODULE_1__["default"](this.stage); + } + + progress() { + if (this.active.size) { + let dt = this.stage.dt; + + let filter = false; + this.active.forEach(function(a) { + a.progress(dt); + if (!a.isRunning()) { + filter = true; + } + }); + + if (filter) { + this.active = new Set([...this.active].filter(t => (t.isRunning()))); + } + } + } + + createSettings(settings) { + const transitionSettings = new _TransitionSettings_mjs__WEBPACK_IMPORTED_MODULE_1__["default"](); + _tree_Base_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].patchObject(transitionSettings, settings); + return transitionSettings; + } + + addActive(transition) { + this.active.add(transition); + } + + removeActive(transition) { + this.active.delete(transition); + } +} + + + + + + +/***/ }), + +/***/ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/animation/TransitionSettings.mjs": +/*!****************************************************************************************************************!*\ + !*** ./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/animation/TransitionSettings.mjs ***! + \****************************************************************************************************************/ +/*! exports provided: default */ +/***/ (function(__webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return TransitionSettings; }); +/* harmony import */ var _tree_StageUtils_mjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../tree/StageUtils.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/tree/StageUtils.mjs"); +/* harmony import */ var _tree_Base_mjs__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../tree/Base.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/tree/Base.mjs"); +/* + * If not stated otherwise in this file or this component's LICENSE file the + * following copyright and licenses apply: + * + * Copyright 2020 Metrological + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + + +class TransitionSettings { + constructor(stage) { + this.stage = stage; + this._timingFunction = 'ease'; + this._timingFunctionImpl = _tree_StageUtils_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].getTimingFunction(this._timingFunction); + this.delay = 0; + this.duration = 0.2; + this.merger = null; + } + + get timingFunction() { + return this._timingFunction; + } + + set timingFunction(v) { + this._timingFunction = v; + this._timingFunctionImpl = _tree_StageUtils_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].getTimingFunction(v); + } + + get timingFunctionImpl() { + return this._timingFunctionImpl; + } + + patch(settings) { + _tree_Base_mjs__WEBPACK_IMPORTED_MODULE_1__["default"].patchObject(this, settings); + } +} + +TransitionSettings.prototype.isTransitionSettings = true; + + + +/***/ }), + +/***/ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/application/Application.mjs": +/*!***********************************************************************************************************!*\ + !*** ./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/application/Application.mjs ***! + \***********************************************************************************************************/ +/*! exports provided: default */ +/***/ (function(__webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return Application; }); +/* harmony import */ var _Component_mjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./Component.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/application/Component.mjs"); +/* harmony import */ var _tree_Utils_mjs__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../tree/Utils.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/tree/Utils.mjs"); +/* harmony import */ var _tree_Stage_mjs__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../tree/Stage.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/tree/Stage.mjs"); +/* + * If not stated otherwise in this file or this component's LICENSE file the + * following copyright and licenses apply: + * + * Copyright 2020 Metrological + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + + +class Application extends _Component_mjs__WEBPACK_IMPORTED_MODULE_0__["default"] { + + constructor(options = {}, properties) { + // Save options temporarily to avoid having to pass it through the constructor. + Application._temp_options = options; + + // Booting flag is used to postpone updateFocusSettings; + Application.booting = true; + const stage = new _tree_Stage_mjs__WEBPACK_IMPORTED_MODULE_2__["default"](options.stage); + super(stage, properties); + Application.booting = false; + + this.__updateFocusCounter = 0; + this.__keypressTimers = new Map(); + this.__hoveredChild = null; + + // We must construct while the application is not yet attached. + // That's why we 'init' the stage later (which actually emits the attach event). + this.stage.init(); + + // Initially, the focus settings are updated after both the stage and application are constructed. + this.updateFocusSettings(); + + this.__keymap = this.getOption('keys'); + + if (this.__keymap) { + this.stage.platform.registerKeydownHandler((e) => { + this._receiveKeydown(e); + }); + + this.stage.platform.registerKeyupHandler((e) => { + this._receiveKeyup(e); + }); + } + + if (this.getOption("enablePointer")) { + this.stage.platform.registerClickHandler((e) => { + this._receiveClick(e); + }); + + this.stage.platform.registerHoverHandler((e) => { + this._receiveHover(e); + }); + + this.stage.platform.registerScrollWheelHandler((e) => { + this._recieveScrollWheel(e); + }); + + this.cursor = 'default'; + } + } + + getOption(name) { + return this.__options[name]; + } + + _setOptions(o) { + this.__options = {}; + + let opt = (name, def) => { + let value = o[name]; + + if (value === undefined) { + this.__options[name] = def; + } else { + this.__options[name] = value; + } + } + + opt('debug', false); + opt('keys', { + 38: "Up", + 40: "Down", + 37: "Left", + 39: "Right", + 13: "Enter", + 8: "Back", + 27: "Exit" + }); + opt('enablePointer', false); + } + + __construct() { + this.stage.setApplication(this); + + this._setOptions(Application._temp_options); + delete Application._temp_options; + + super.__construct(); + } + + __init() { + super.__init(); + this.__updateFocus(); + } + + updateFocusPath() { + this.__updateFocus(); + } + + __updateFocus() { + const notOverridden = this.__updateFocusRec(); + + if (!Application.booting && notOverridden) { + this.updateFocusSettings(); + } + } + + __updateFocusRec() { + const updateFocusId = ++this.__updateFocusCounter; + this.__updateFocusId = updateFocusId; + + const newFocusPath = this.__getFocusPath(); + const newFocusedComponent = newFocusPath[newFocusPath.length - 1]; + const prevFocusedComponent = this._focusPath ? this._focusPath[this._focusPath.length - 1] : undefined; + + if (!prevFocusedComponent) { + // Focus events. + this._focusPath = []; + for (let i = 0, n = newFocusPath.length; i < n; i++) { + this._focusPath.push(newFocusPath[i]); + this._focusPath[i]._focus(newFocusedComponent, undefined); + const focusOverridden = (this.__updateFocusId !== updateFocusId); + if (focusOverridden) { + return false; + } + } + return true; + } else { + let m = Math.min(this._focusPath.length, newFocusPath.length); + let index; + for (index = 0; index < m; index++) { + if (this._focusPath[index] !== newFocusPath[index]) { + break; + } + } + + if (this._focusPath.length !== newFocusPath.length || index !== newFocusPath.length) { + + if (this.getOption('debug')) { + console.log('[Lightning] Focus changed: ' + newFocusedComponent.getLocationString()); + } + + // Unfocus events. + for (let i = this._focusPath.length - 1; i >= index; i--) { + const unfocusedElement = this._focusPath.pop(); + unfocusedElement._unfocus(newFocusedComponent, prevFocusedComponent); + const focusOverridden = (this.__updateFocusId !== updateFocusId); + if (focusOverridden) { + return false; + } + } + + // Focus events. + for (let i = index, n = newFocusPath.length; i < n; i++) { + this._focusPath.push(newFocusPath[i]); + this._focusPath[i]._focus(newFocusedComponent, prevFocusedComponent); + const focusOverridden = (this.__updateFocusId !== updateFocusId); + if (focusOverridden) { + return false; + } + } + + // Focus changed events. + for (let i = 0; i < index; i++) { + this._focusPath[i]._focusChange(newFocusedComponent, prevFocusedComponent); + } + } + } + + return true; + } + + updateFocusSettings() { + const focusedComponent = this._focusPath[this._focusPath.length - 1]; + + // Get focus settings. These can be used for dynamic application-wide settings that depend on the + // focus directly (such as the application background). + const focusSettings = {}; + const defaultSetFocusSettings = _Component_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].prototype._setFocusSettings; + for (let i = 0, n = this._focusPath.length; i < n; i++) { + if (this._focusPath[i]._setFocusSettings !== defaultSetFocusSettings) { + this._focusPath[i]._setFocusSettings(focusSettings); + } + } + + const defaultHandleFocusSettings = _Component_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].prototype._handleFocusSettings; + for (let i = 0, n = this._focusPath.length; i < n; i++) { + if (this._focusPath[i]._handleFocusSettings !== defaultHandleFocusSettings) { + this._focusPath[i]._handleFocusSettings(focusSettings, this.__prevFocusSettings, focusedComponent); + } + } + + this.__prevFocusSettings = focusSettings; + } + + _handleFocusSettings(settings, prevSettings, focused, prevFocused) { + // Override to handle focus-based settings. + } + + __getFocusPath() { + const path = [this]; + let current = this; + do { + const nextFocus = current._getFocused(); + if (!nextFocus || (nextFocus === current)) { + // Found!; + break; + } + + + let ptr = nextFocus.cparent; + if (ptr === current) { + path.push(nextFocus); + } else { + // Not an immediate child: include full path to descendant. + const newParts = [nextFocus]; + do { + if (!ptr) { + current._throwError("Return value for _getFocused must be an attached descendant component but its '" + nextFocus.getLocationString() + "'"); + } + newParts.push(ptr); + ptr = ptr.cparent; + } while (ptr !== current); + + // Add them reversed. + for (let i = 0, n = newParts.length; i < n; i++) { + path.push(newParts[n - i - 1]); + } + } + + current = nextFocus; + } while (true); + + return path; + } + + get focusPath() { + return this._focusPath; + } + + /** + * Injects an event in the state machines, top-down from application to focused component. + */ + focusTopDownEvent(events, ...args) { + const path = this.focusPath; + const n = path.length; + + // Multiple events. + for (let i = 0; i < n; i++) { + const event = path[i]._getMostSpecificHandledMember(events); + if (event !== undefined) { + const returnValue = path[i][event](...args); + if (returnValue !== false) { + return true; + } + } + } + + return false; + } + + /** + * Injects an event in the state machines, bottom-up from focused component to application. + */ + focusBottomUpEvent(events, ...args) { + const path = this.focusPath; + const n = path.length; + + // Multiple events. + for (let i = n - 1; i >= 0; i--) { + const event = path[i]._getMostSpecificHandledMember(events); + if (event !== undefined) { + const returnValue = path[i][event](...args); + if (returnValue !== false) { + return true; + } + } + } + + return false; + } + + _receiveKeydown(e) { + const obj = e; + const key = this.__keymap[e.keyCode]; + const path = this.focusPath; + + let keys; + if (key) { + keys = Array.isArray(key) ? key : [key]; + } + + if (keys) { + for (let i = 0, n = keys.length; i < n; i++) { + const hasTimer = this.__keypressTimers.has(keys[i]); + // prevent event from getting fired when the timeout is still active + if (path[path.length - 1].longpress && hasTimer) { + return; + } + + if (!this.stage.application.focusTopDownEvent([`_capture${keys[i]}`, "_captureKey"], obj)) { + this.stage.application.focusBottomUpEvent([`_handle${keys[i]}`, "_handleKey"], obj); + } + } + } else { + if (!this.stage.application.focusTopDownEvent(["_captureKey"], obj)) { + this.stage.application.focusBottomUpEvent(["_handleKey"], obj); + } + } + + this.updateFocusPath(); + + const consumer = path[path.length - 1]; + + if (keys && consumer.longpress) { + for (let i = 0, n = keys.length; i < n; i++) { + this._startLongpressTimer(keys[i], consumer); + } + } + } + + /** + * Keyup listener + * To take away some confusion we add `Release` to the event to prevent ending up with method names like: + * _handleLeftUp / _handleUpUp / _handleEnterUp etc + * + * @param e + * @private + */ + _receiveKeyup(e) { + const obj = e; + const key = this.__keymap[e.keyCode]; + + let keys; + if (key) { + keys = Array.isArray(key) ? key : [key]; + } + + if (keys) { + for (let i = 0, n = keys.length; i < n; i++) { + if (!this.stage.application.focusTopDownEvent([`_capture${keys[i]}Release`, "_captureKeyRelease"], obj)) { + this.stage.application.focusBottomUpEvent([`_handle${keys[i]}Release`, "_handleKeyRelease"], obj); + } + } + } else { + if (!this.stage.application.focusTopDownEvent(["_captureKeyRelease"], obj)) { + this.stage.application.focusBottomUpEvent(["_handleKeyRelease"], obj); + } + } + + this.updateFocusPath(); + + if (keys) { + for (let i = 0, n = keys.length; i < n; i++) { + if (this.__keypressTimers.has(keys[i])) { + // keyup has fired before end of timeout so we clear it + clearTimeout(this.__keypressTimers.get(keys[i])); + // delete so we can register it again + this.__keypressTimers.delete(keys[i]); + } + } + } + } + + /** + * Registers and starts a timer for the pressed key. Timer will be cleared when the key is released + * before the timer goes off. + * + * If key is not release (keyup) the longpress handler will be fired. + * Configuration can be via the Components template: + * + * static _template() { + * return { + * w:100, h:100, + * longpress:{up:700, down:500} + * } + * } * + * // this will get called when up has been pressed for 700ms + * _handleUpLong() { + * + * } + * + * @param key + * @param element + * @private + */ + _startLongpressTimer(key, element) { + const config = element.longpress; + const lookup = key.toLowerCase(); + + if (config[lookup]) { + const timeout = config[lookup]; + if (!_tree_Utils_mjs__WEBPACK_IMPORTED_MODULE_1__["default"].isNumber(timeout)) { + element._throwError("config value for longpress must be a number"); + } else { + this.__keypressTimers.set(key, setTimeout(() => { + if (!this.stage.application.focusTopDownEvent([`_capture${key}Long`, "_captureKey"], {})) { + this.stage.application.focusBottomUpEvent([`_handle${key}Long`, "_handleKey"], {}); + } + + this.__keypressTimers.delete(key); + }, timeout || 500 /* prevent 0ms */)); + } + } + return; + } + + _recieveScrollWheel(e) { + const obj = e; + const { clientX, clientY } = obj; + + if (clientX <= this.stage.w && clientY <= this.stage.h) { + if (!this.fireTopDownScrollWheelHandler("_captureScroll", obj)) { + this.fireBottomUpScrollWheelHandler("_handleScroll", obj); + } + } + } + + fireTopDownScrollWheelHandler(event, obj) { + let children = this.stage.application.children; + let affected = this._findChildren([], children).reverse(); + let n = affected.length; + + while (n--) { + const child = affected[n]; + if (child && child[event]) { + child._captureScroll(obj); + return true; + } + } + return false; + } + + fireBottomUpScrollWheelHandler(event, obj) { + const { clientX, clientY } = obj; + const target = this._getTargetChild(clientX, clientY); + let child = target; + + // Search tree bottom up for a handler + while (child !== null) { + if (child && child[event]) { + child._handleScroll(obj); + return true; + } + child = child.parent; + } + return false; + } + + _receiveClick(e) { + const obj = e; + const { clientX, clientY } = obj; + + if (clientX <= this.stage.w && clientY <= this.stage.h) { + this.stage.application.fireBottomUpClickHandler(obj); + } + } + + fireBottomUpClickHandler(obj) { + const { clientX, clientY } = obj; + const target = this._getTargetChild(clientX, clientY); + const precision = this.stage.getRenderPrecision() / this.stage.getOption('devicePixelRatio'); + let child = target; + + // Search tree bottom up for a handler + while (child !== null) { + if (child && child["_handleClick"]) { + const { px, py } = child.core._worldContext; + const cx = px * precision; + const cy = py * precision; + + const localCoords = { + x: clientX - cx, + y: clientY - cy + } + + const returnValue = child._handleClick(target, localCoords); + if (returnValue !== false) { + break; + } + } + child = child.parent; + } + } + + _receiveHover(e) { + const obj = e; + const { clientX, clientY } = obj; + + if (clientX <= this.stage.w && clientY <= this.stage.h) { + this.stage.application.fireBottomUpHoverHandler(obj); + } + } + + fireBottomUpHoverHandler(obj) { + const { clientX, clientY } = obj; + const target = this._getTargetChild(clientX, clientY); + + // Only fire handlers when pointer target changes + if (target !== this.__hoveredChild) { + + let hoveredBranch = new Set(); + let newHoveredBranch = new Set(); + + if (target) { + newHoveredBranch = new Set(target.getAncestors()); + } + + if (this.__hoveredChild) { + hoveredBranch = new Set(this.__hoveredChild.getAncestors()); + for (const elem of [...hoveredBranch].filter((e) => !newHoveredBranch.has(e))) { + const c = _Component_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].getComponent(elem); + if (c["_handleUnhover"]) { + c._handleUnhover(elem); + } + if (elem.parent && elem.parent.cursor) { + this.stage.getCanvas().style.cursor = elem.parent.cursor; + } + } + } + + this.__hoveredChild = target; + + const diffBranch = [...newHoveredBranch].filter((e) => !hoveredBranch.has(e)) + for (const elem of diffBranch) { + const c = _Component_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].getComponent(elem); + if (c["_handleHover"]) { + c._handleHover(elem); + } + } + + // New element hover cursor + const lastElement = diffBranch[0]; + if (lastElement && lastElement.cursor) { + this.stage.getCanvas().style.cursor = lastElement.cursor; + } + + // Rerun _handleHover for target element in case it's been hovered + // back from its child + if (diffBranch.length === 0 && target) { + const c = _Component_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].getComponent(target); + if (c["_handleHover"]) { + c._handleHover(target); + } + } + } + } + + _getTargetChild(clientX, clientY) { + let children = this.stage.application.children; + let affected = this._findChildren([], children); + let hoverableChildren = this._withinClickableRange(affected, clientX, clientY); + + hoverableChildren.sort((a, b) => { + // Sort by zIndex and then id + if (a.zIndex > b.zIndex) { + return 1; + } else if (a.zIndex < b.zIndex) { + return -1; + } else { + return a.id > b.id ? 1 : -1; + } + }); + + if (hoverableChildren.length) { + // Assume target has highest zIndex (id when zIndex equal) + return hoverableChildren.slice(-1)[0]; + } else { + return null; + } + } + + _findChildren(bucket, children) { + let n = children.length; + while (n--) { + const child = children[n]; + // only add active children + if (child.__active && child.collision) { + if (child.collision === true) { + bucket.push(child); + } + if (child.hasChildren()) { + this._findChildren(bucket, child.children); + } + } + } + return bucket; + } + + _withinClickableRange(affectedChildren, cursorX, cursorY) { + let n = affectedChildren.length; + const candidates = []; + + // loop through affected children + // and perform collision detection + while (n--) { + const child = affectedChildren[n]; + const precision = this.stage.getRenderPrecision() / this.stage.getOption('devicePixelRatio'); + const ctx = child.core._worldContext; + + const cx = ctx.px * precision; + const cy = ctx.py * precision; + const cw = child.finalW * ctx.ta * precision; + const ch = child.finalH * ctx.td * precision; + + if (cx > this.stage.w || cy > this.stage.h) { + continue; + } + + if (child.parent.core._scissor) { + const scissor = child.parent.core._scissor.map((v) => v * precision); + if (!this._testCollision(cursorX, cursorY, ...scissor)) + continue + } + + if (this._testCollision(cursorX, cursorY, cx, cy, cw, ch)) { + candidates.push(child); + } + } + return candidates; + } + + _testCollision(px, py, cx, cy, cw, ch) { + if (px >= cx && + px <= cx + cw && + py >= cy && + py <= cy + ch) { + return true; + } + return false; + } + + destroy() { + if (!this._destroyed) { + this._destroy(); + this.stage.destroy(); + this._destroyed = true; + } + } + + _destroy() { + // This forces the _detach, _disabled and _active events to be called. + this.stage.setApplication(undefined); + this._updateAttachedFlag(); + this._updateEnabledFlag(); + + if (this.__keypressTimers.size) { + for (const timer of this.__keypressTimers.values()) { + clearTimeout(timer); + } + + this.__keypressTimers.clear(); + } + } + + getCanvas() { + return this.stage.getCanvas(); + } + +} + + + + +/***/ }), + +/***/ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/application/Component.mjs": +/*!*********************************************************************************************************!*\ + !*** ./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/application/Component.mjs ***! + \*********************************************************************************************************/ +/*! exports provided: default */ +/***/ (function(__webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return Component; }); +/* harmony import */ var _tree_Element_mjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../tree/Element.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/tree/Element.mjs"); +/* harmony import */ var _tree_Utils_mjs__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../tree/Utils.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/tree/Utils.mjs"); +/* harmony import */ var _StateMachine_mjs__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./StateMachine.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/application/StateMachine.mjs"); +/* + * If not stated otherwise in this file or this component's LICENSE file the + * following copyright and licenses apply: + * + * Copyright 2020 Metrological + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + + + +/** + * @extends StateMachine + */ +class Component extends _tree_Element_mjs__WEBPACK_IMPORTED_MODULE_0__["default"] { + + constructor(stage, properties) { + super(stage); + + // Encapsulate tags to prevent leaking. + this.tagRoot = true; + + if (_tree_Utils_mjs__WEBPACK_IMPORTED_MODULE_1__["default"].isObjectLiteral(properties)) { + Object.assign(this, properties); + } + + this.__initialized = false; + this.__firstActive = false; + this.__firstEnable = false; + + this.__signals = undefined; + + this.__passSignals = undefined; + + this.__construct(); + + // Quick-apply template. + const func = this.constructor.getTemplateFunc(this); + func.f(this, func.a); + + this._build(); + } + + __start() { + _StateMachine_mjs__WEBPACK_IMPORTED_MODULE_2__["default"].setupStateMachine(this); + this._onStateChange = Component.prototype.__onStateChange; + } + + get state() { + return this._getState(); + } + + __onStateChange() { + /* FIXME: Workaround for case, where application was shut but component still lives */ + if (this.application) { + this.application.updateFocusPath(); + } + } + + _refocus() { + /* FIXME: Workaround for case, where application was shut but component still lives */ + if (this.application) { + this.application.updateFocusPath(); + } + } + + static bindProp(name, func = null) { + return {__propertyBinding: true, __name: name, __func: func}; + } + + __bindProperty(propObj, targetObj, targetProp) { + // 1. find binding position: find object and property name to be bound + const obj = targetObj; + const prop = targetProp; + const propDependencies = Array.isArray(propObj.__name) ? propObj.__name : [propObj.__name]; + + // 2. create setters for every given dependency + for (let i = 0; i < propDependencies.length; i++) { + const propName = propDependencies[i]; + const func = propObj.__func ? propObj.__func : (context) => context[propName]; + + if (!this.hasOwnProperty(propName)) { + this[`__prop_bindings_${propName}`] = [{__obj: obj, __prop: prop, __func: func}]; + Object.defineProperty(this, propName, { + set: (value) => { + this[`__prop_${propName}`] = value; + for (const {__obj, __prop, __func} of this[`__prop_bindings_${propName}`]) { + __obj[__prop] = __func(this); + } + }, + get: () => this[`__prop_${propName}`] + }); + } else { + this[`__prop_bindings_${propName}`].push({__obj: obj, __prop: prop, __func: func}); + } + } + } + + /** + * Returns a high-performance template patcher. + */ + static getTemplateFunc(ctx) { + // We need a different template function per patch id. + const name = "_templateFunc"; + + // Be careful with class-based static inheritance. + const hasName = '__has' + name; + if (this[hasName] !== this) { + this[hasName] = this; + this[name] = this.parseTemplate(this._template(ctx)); + } + return this[name]; + } + + static parseTemplate(obj) { + const context = { + loc: [], + store: [], + rid: 0 + }; + + this.parseTemplateRec(obj, context, "element"); + + const code = context.loc.join(";\n"); + const f = new Function("element", "store", code); + return {f: f, a: context.store}; + } + + static parseTemplateRec(obj, context, cursor) { + const store = context.store; + const loc = context.loc; + const keys = Object.keys(obj); + keys.forEach(key => { + let value = obj[key]; + if (_tree_Utils_mjs__WEBPACK_IMPORTED_MODULE_1__["default"].isUcChar(key.charCodeAt(0))) { + // Value must be expanded as well. + if (_tree_Utils_mjs__WEBPACK_IMPORTED_MODULE_1__["default"].isObjectLiteral(value)) { + // Ref. + const childCursor = `r${key.replace(/[^a-z0-9]/gi, "") + context.rid}`; + let type = value.type ? value.type : _tree_Element_mjs__WEBPACK_IMPORTED_MODULE_0__["default"]; + if (type === _tree_Element_mjs__WEBPACK_IMPORTED_MODULE_0__["default"]) { + loc.push(`var ${childCursor} = element.stage.createElement()`); + } else { + store.push(type); + loc.push(`var ${childCursor} = new store[${store.length - 1}](${cursor}.stage)`); + } + loc.push(`${childCursor}.ref = "${key}"`); + context.rid++; + + // Enter sub. + this.parseTemplateRec(value, context, childCursor); + + loc.push(`${cursor}.childList.add(${childCursor})`); + } else if (_tree_Utils_mjs__WEBPACK_IMPORTED_MODULE_1__["default"].isObject(value)) { + // Dynamic assignment. + store.push(value); + loc.push(`${cursor}.childList.add(store[${store.length - 1}])`); + } + } else { + if (key === "text") { + const propKey = cursor + "__text"; + loc.push(`var ${propKey} = ${cursor}.enableTextTexture()`); + if (value.__propertyBinding === true) { + // Allow binding entire objects to text property + store.push(value); + loc.push(`element.__bindProperty(store[${store.length - 1}], ${cursor}, "${key}")`); + } else { + this.parseTemplatePropRec(value, context, propKey); + } + } else if (key === "shader" && _tree_Utils_mjs__WEBPACK_IMPORTED_MODULE_1__["default"].isObjectLiteral(value)) { + const shaderCursor = `${cursor}["shader"]` + store.push(value); + loc.push(`${cursor}["${key}"] = store[${store.length - 1}]`); + this.parsePropertyBindings(value, context, shaderCursor); + } else if (key === "texture" && _tree_Utils_mjs__WEBPACK_IMPORTED_MODULE_1__["default"].isObjectLiteral(value)) { + const propKey = cursor + "__texture"; + const type = value.type; + if (type) { + store.push(type); + loc.push(`var ${propKey} = new store[${store.length - 1}](${cursor}.stage)`); + this.parseTemplatePropRec(value, context, propKey); + loc.push(`${cursor}["${key}"] = ${propKey}`); + } else { + loc.push(`${propKey} = ${cursor}.texture`); + this.parseTemplatePropRec(value, context, propKey); + } + } else if (_tree_Utils_mjs__WEBPACK_IMPORTED_MODULE_1__["default"].isObjectLiteral(value) && value.__propertyBinding === true) { + store.push(value); + loc.push(`element.__bindProperty(store[${store.length - 1}], ${cursor}, "${key}")`); + } else { + // Property; + if (_tree_Utils_mjs__WEBPACK_IMPORTED_MODULE_1__["default"].isNumber(value)) { + loc.push(`${cursor}["${key}"] = ${value}`); + } else if (_tree_Utils_mjs__WEBPACK_IMPORTED_MODULE_1__["default"].isBoolean(value)) { + loc.push(`${cursor}["${key}"] = ${value ? "true" : "false"}`); + } else if (_tree_Utils_mjs__WEBPACK_IMPORTED_MODULE_1__["default"].isObject(value) || Array.isArray(value)) { + // Dynamic assignment. + // Because literal objects may contain dynamics, we store the full object. + store.push(value); + loc.push(`${cursor}["${key}"] = store[${store.length - 1}]`); + } else { + // String etc. + loc.push(`${cursor}["${key}"] = ${JSON.stringify(value)}`); + } + } + } + }); + } + + static parseTemplatePropRec(obj, context, cursor) { + const store = context.store; + const loc = context.loc; + const keys = Object.keys(obj); + keys.forEach(key => { + if (key !== "type") { + const value = obj[key]; + if (_tree_Utils_mjs__WEBPACK_IMPORTED_MODULE_1__["default"].isNumber(value)) { + loc.push(`${cursor}["${key}"] = ${value}`); + } else if (_tree_Utils_mjs__WEBPACK_IMPORTED_MODULE_1__["default"].isBoolean(value)) { + loc.push(`${cursor}["${key}"] = ${value ? "true" : "false"}`); + } else if (_tree_Utils_mjs__WEBPACK_IMPORTED_MODULE_1__["default"].isObject(value) && value.__propertyBinding === true) { + store.push(value); + loc.push(`element.__bindProperty(store[${store.length - 1}], ${cursor}, "${key}")`); + } else if (_tree_Utils_mjs__WEBPACK_IMPORTED_MODULE_1__["default"].isObject(value) || Array.isArray(value)) { + // Dynamic assignment. + // Because literal objects may contain dynamics, we store the full object. + store.push(value); + loc.push(`${cursor}["${key}"] = store[${store.length - 1}]`); + } else { + // String etc. + loc.push(`${cursor}["${key}"] = ${JSON.stringify(value)}`); + } + } + }); + } + + static parsePropertyBindings(obj, context, cursor) { + const store = context.store; + const loc = context.loc; + const keys = Object.keys(obj); + keys.forEach(key => { + if (key !== "type") { + const value = obj[key]; + if (_tree_Utils_mjs__WEBPACK_IMPORTED_MODULE_1__["default"].isObjectLiteral(value) && value.__propertyBinding === true) { + store.push(value); + loc.push(`element.__bindProperty(store[${store.length - 1}], ${cursor}, "${key}")`); + } + } + }); + } + + _onSetup() { + if (!this.__initialized) { + this._setup(); + } + } + + _setup() { + } + + _onAttach() { + if (!this.__initialized) { + this.__init(); + this.__initialized = true; + } + + this._attach(); + } + + _attach() { + } + + _onDetach() { + this._detach(); + } + + _detach() { + } + + _onEnabled() { + if (!this.__firstEnable) { + this._firstEnable(); + this.__firstEnable = true; + } + + this._enable(); + } + + _firstEnable() { + } + + _enable() { + } + + _onDisabled() { + this._disable(); + } + + _disable() { + } + + _onActive() { + if (!this.__firstActive) { + this._firstActive(); + this.__firstActive = true; + } + + this._active(); + } + + _firstActive() { + } + + _active() { + } + + _onInactive() { + this._inactive(); + } + + _inactive() { + } + + get application() { + return this.stage.application; + } + + __construct() { + this._construct(); + } + + _construct() { + } + + _build() { + } + + __init() { + this._init(); + } + + _init() { + } + + _focus(newTarget, prevTarget) { + } + + _unfocus(newTarget) { + } + + _focusChange(target, newTarget) { + } + + _getFocused() { + // Override to delegate focus to child components. + return this; + } + + _setFocusSettings(settings) { + // Override to add custom settings. See Application._handleFocusSettings(). + } + + _handleFocusSettings(settings) { + // Override to react on custom settings. See Application._handleFocusSettings(). + } + + static _template() { + return {}; + } + + hasFinalFocus() { + let path = this.application._focusPath; + return path && path.length && path[path.length - 1] === this; + } + + hasFocus() { + let path = this.application._focusPath; + return path && (path.indexOf(this) >= 0); + } + + get cparent() { + return Component.getParent(this); + } + + seekAncestorByType(type) { + let c = this.cparent; + while (c) { + if (c.constructor === type) { + return c; + } + c = c.cparent; + } + } + + getSharedAncestorComponent(element) { + let ancestor = this.getSharedAncestor(element); + while (ancestor && !ancestor.isComponent) { + ancestor = ancestor.parent; + } + return ancestor; + } + + get signals() { + return this.__signals; + } + + set signals(v) { + if (!_tree_Utils_mjs__WEBPACK_IMPORTED_MODULE_1__["default"].isObjectLiteral(v)) { + this._throwError("Signals: specify an object with signal-to-fire mappings"); + } + this.__signals = v; + } + + set alterSignals(v) { + if (!_tree_Utils_mjs__WEBPACK_IMPORTED_MODULE_1__["default"].isObjectLiteral(v)) { + this._throwError("Signals: specify an object with signal-to-fire mappings"); + } + if (!this.__signals) { + this.__signals = {}; + } + for (let key in v) { + const d = v[key]; + if (d === undefined) { + delete this.__signals[key]; + } else { + this.__signals[key] = v; + } + } + } + + get passSignals() { + return this.__passSignals || {}; + } + + set passSignals(v) { + this.__passSignals = Object.assign(this.__passSignals || {}, v); + } + + set alterPassSignals(v) { + if (!_tree_Utils_mjs__WEBPACK_IMPORTED_MODULE_1__["default"].isObjectLiteral(v)) { + this._throwError("Signals: specify an object with signal-to-fire mappings"); + } + if (!this.__passSignals) { + this.__passSignals = {}; + } + for (let key in v) { + const d = v[key]; + if (d === undefined) { + delete this.__passSignals[key]; + } else { + this.__passSignals[key] = v; + } + } + } + + /** + * Signals the parent of the specified event. + * A parent/ancestor that wishes to handle the signal should set the 'signals' property on this component. + * @param {string} event + * @param {...*} args + */ + signal(event, ...args) { + return this._signal(event, args); + } + + _signal(event, args) { + const signalParent = this._getParentSignalHandler(); + if (signalParent) { + if (this.__signals) { + let fireEvent = this.__signals[event]; + if (fireEvent === false) { + // Ignore event. + return; + } + if (fireEvent) { + if (fireEvent === true) { + fireEvent = event; + } + + if (_tree_Utils_mjs__WEBPACK_IMPORTED_MODULE_1__["default"].isFunction(fireEvent)) { + return fireEvent(...args); + } + + if (signalParent._hasMethod(fireEvent)) { + return signalParent[fireEvent](...args); + } + } + } + + let passSignal = (this.__passSignals && this.__passSignals[event]); + if (passSignal) { + // Bubble up. + if (passSignal && passSignal !== true) { + // Replace signal name. + event = passSignal; + } + + return signalParent._signal(event, args); + } + } + } + + _getParentSignalHandler() { + return this.cparent ? this.cparent._getSignalHandler() : null; + } + + _getSignalHandler() { + if (this._signalProxy) { + return this.cparent ? this.cparent._getSignalHandler() : null; + } + return this; + } + + get _signalProxy() { + return false; + } + + fireAncestors(name, ...args) { + if (!name.startsWith('$')) { + throw new Error("Ancestor event name must be prefixed by dollar sign."); + } + + const parent = this._getParentSignalHandler(); + if (parent) { + return parent._doFireAncestors(name, args); + } + } + + _doFireAncestors(name, args) { + if (this._hasMethod(name)) { + return this.fire(name, ...args); + } else { + const signalParent = this._getParentSignalHandler(); + if (signalParent) { + return signalParent._doFireAncestors(name, args); + } + } + } + + static collectSubComponents(subs, element) { + if (element.hasChildren()) { + const childList = element.__childList; + for (let i = 0, n = childList.length; i < n; i++) { + const child = childList.getAt(i); + if (child.isComponent) { + subs.push(child); + } else { + Component.collectSubComponents(subs, child); + } + } + } + } + + static getComponent(element) { + let parent = element; + while (parent && !parent.isComponent) { + parent = parent.parent; + } + return parent; + } + + static getParent(element) { + return Component.getComponent(element.parent); + } +} + +Component.prototype.isComponent = true; + + +/***/ }), + +/***/ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/application/StateMachine.mjs": +/*!************************************************************************************************************!*\ + !*** ./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/application/StateMachine.mjs ***! + \************************************************************************************************************/ +/*! exports provided: default */ +/***/ (function(__webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return StateMachine; }); +/* + * If not stated otherwise in this file or this component's LICENSE file the + * following copyright and licenses apply: + * + * Copyright 2020 Metrological + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +class StateMachine { + + constructor() { + StateMachine.setupStateMachine(this); + } + + static setupStateMachine(target) { + const targetConstructor = target.constructor; + const router = StateMachine.create(targetConstructor); + Object.setPrototypeOf(target, router.prototype); + target.constructor = targetConstructor; + target._initStateMachine(); + } + + /** + * Creates a state machine implementation. + * It extends the original type and should be used when creating new instances. + * The original type is available as static property 'original', and it must be used when subclassing as follows: + * const type = StateMachine.create(class YourNewStateMachineClass extends YourBaseStateMachineClass.original { }) + * @param {Class} type + * @returns {StateMachine} + */ + static create(type) { + if (!type.hasOwnProperty('_sm')) { + // Only need to run once. + const stateMachineType = new StateMachineType(type); + type._sm = stateMachineType; + } + + return type._sm.router; + } + + /** + * Calls the specified method if it exists. + * @param {string} event + * @param {*...} args + */ + fire(event, ...args) { + if (this._hasMethod(event)) { + return this[event](...args); + } + } + + /** + * Returns the current state path (for example "Initialized.Loading"). + * @returns {string} + * @protected + */ + _getState() { + return this._state.__path; + } + + /** + * Returns true iff statePath is (an ancestor of) currentStatePath. + * @param {string} statePath + * @param {string} currentStatePath + * @returns {Boolean} + * @protected + */ + _inState(statePath, currentStatePath = this._state.__path) { + const state = this._sm.getStateByPath(statePath); + const currentState = this._sm.getStateByPath(currentStatePath); + const level = state.__level; + const stateAtLevel = StateMachine._getStateAtLevel(currentState, level); + return (stateAtLevel === state); + } + + /** + * Returns true if the specified class member is defined for the currently set state. + * @param {string} name + * @returns {boolean} + * @protected + */ + _hasMember(name) { + return !!this.constructor.prototype[name]; + } + + /** + * Returns true if the specified class member is a method for the currently set state. + * @param {string} name + * @returns {boolean} + * @protected + */ + _hasMethod(name) { + const member = this.constructor.prototype[name]; + return !!member && (typeof member === "function") + } + + /** + * Switches to the specified state. + * @param {string} statePath + * Substates are seperated by a underscores (for example "Initialized.Loading"). + * @param {*[]} [args] + * Args that are supplied in $enter and $exit events. + * @protected + */ + _setState(statePath, args) { + const setStateId = ++this._setStateCounter; + this._setStateId = setStateId; + + if (this._state.__path !== statePath) { + // Performance optimization. + let newState = this._sm._stateMap[statePath]; + if (!newState) { + // Check for super state. + newState = this._sm.getStateByPath(statePath); + } + + const prevState = this._state; + + const hasDifferentEnterMethod = (newState.prototype.$enter !== this._state.prototype.$enter); + const hasDifferentExitMethod = (newState.prototype.$exit !== this._state.prototype.$exit); + if (hasDifferentEnterMethod || hasDifferentExitMethod) { + const sharedState = StateMachine._getSharedState(this._state, newState); + const context = { + newState: newState.__path, + prevState: prevState.__path, + sharedState: sharedState.__path + }; + const sharedLevel = sharedState.__level; + + if (hasDifferentExitMethod) { + const exitStates = StateMachine._getStatesUntilLevel(this._state, sharedLevel); + for (let i = 0, n = exitStates.length; i < n; i++) { + this.__setState(exitStates[i]); + this._callExit(this._state, args, context); + const stateChangeOverridden = (this._setStateId !== setStateId); + if (stateChangeOverridden) { + return; + } + } + } + + if (hasDifferentEnterMethod) { + const enterStates = StateMachine._getStatesUntilLevel(newState, sharedLevel).reverse(); + for (let i = 0, n = enterStates.length; i < n; i++) { + this.__setState(enterStates[i]); + this._callEnter(this._state, args, context); + const stateChangeOverridden = (this._setStateId !== setStateId); + if (stateChangeOverridden) { + return; + } + } + } + + } + + this.__setState(newState); + + if (this._changedState) { + const context = { + newState: newState.__path, + prevState: prevState.__path + }; + + if (args) { + this._changedState(context, ...args); + } else { + this._changedState(context); + } + } + + if (this._onStateChange) { + const context = { + newState: newState.__path, + prevState: prevState.__path + }; + this._onStateChange(context); + } + + } + } + + _callEnter(state, args = [], context) { + const hasParent = !!state.__parent; + if (state.prototype.$enter) { + if (!hasParent || (state.__parent.prototype.$enter !== state.prototype.$enter)) { + state.prototype.$enter.apply(this, [context, ...args]); + } + } + } + + _callExit(state, args = [], context) { + const hasParent = !!state.__parent; + if (state.prototype.$exit) { + if (!hasParent || (state.__parent.prototype.$exit !== state.prototype.$exit)) { + state.prototype.$exit.apply(this, [context, ...args]); + } + } + } + + __setState(state) { + this._state = state; + this._stateIndex = state.__index; + this.constructor = state; + } + + _initStateMachine() { + this._state = null; + this._stateIndex = 0; + this._setStateCounter = 0; + this._sm = this._routedType._sm; + this.__setState(this._sm.getStateByPath("")); + const context = {newState: "", prevState: undefined, sharedState: undefined}; + this._callEnter(this._state, [], context); + this._onStateChange = undefined; + } + + /** + * Between multiple member names, select the one specified in the deepest state. + * If multiple member names are specified in the same deepest state, the first one in the array is returned. + * @param {string[]} memberNames + * @returns {string|undefined} + * @protected + */ + _getMostSpecificHandledMember(memberNames) { + let cur = this._state; + do { + for (let i = 0, n = memberNames.length; i < n; i++) { + const memberName = memberNames[i]; + if (!cur.__parent) { + if (cur.prototype[memberName]) { + return memberName; + } + } else { + const alias = StateMachineType.getStateMemberAlias(cur.__path, memberName); + if (this[alias]) { + return memberName; + } + } + } + cur = cur.__parent; + } while (cur); + } + + static _getStatesUntilLevel(state, level) { + const states = []; + while (state.__level > level) { + states.push(state); + state = state.__parent; + } + return states; + } + + static _getSharedState(state1, state2) { + const state1Array = StateMachine._getAncestorStates(state1); + const state2Array = StateMachine._getAncestorStates(state2); + const n = Math.min(state1Array.length, state2Array.length); + for (let i = 0; i < n; i++) { + if (state1Array[i] !== state2Array[i]) { + return state1Array[i - 1]; + } + } + return state1Array[n - 1]; + } + + static _getAncestorStates(state) { + const result = []; + do { + result.push(state); + } while(state = state.__parent); + return result.reverse(); + } + + static _getStateAtLevel(state, level) { + if (level > state.__level) { + return undefined; + } + + while(level < state.__level) { + state = state.__parent; + } + return state; + } +} + +class StateMachineType { + + constructor(type) { + this._type = type; + this._router = null; + + this.init(); + } + + get router() { + return this._router; + } + + init() { + this._router = this._createRouter(); + + this._stateMap = this._getStateMap(); + + this._addStateMemberDelegatorsToRouter(); + + } + + _createRouter() { + const type = this._type; + + const router = class StateMachineRouter extends type { + constructor() { + super(...arguments); + if (!this.constructor.hasOwnProperty('_isRouter')) { + throw new Error(`You need to extend ${type.name}.original instead of ${type.name}.`); + } + } + }; + router._isRouter = true; + router.prototype._routedType = type; + router.original = type; + + this._mixinStateMachineMethods(router); + + return router; + } + + _mixinStateMachineMethods(router) { + // Mixin the state machine methods, so that we reuse the methods instead of re-creating them. + const names = Object.getOwnPropertyNames(StateMachine.prototype); + for (let i = 0, n = names.length; i < n; i++) { + const name = names[i]; + if (name !== "constructor") { + const descriptor = Object.getOwnPropertyDescriptor(StateMachine.prototype, name); + Object.defineProperty(router.prototype, name, descriptor); + } + } + } + + _addStateMemberDelegatorsToRouter() { + const members = this._getAllMemberNames(); + + members.forEach(member => { + this._addMemberRouter(member); + }); + } + + /** + * @note We are generating code because it yields much better performance. + */ + _addMemberRouter(member) { + const statePaths = Object.keys(this._stateMap); + const descriptors = []; + const aliases = []; + statePaths.forEach((statePath, index) => { + const state = this._stateMap[statePath]; + const descriptor = this._getDescriptor(state, member); + if (descriptor) { + descriptors[index] = descriptor; + + // Add to prototype. + const alias = StateMachineType.getStateMemberAlias(descriptor._source.__path, member); + aliases[index] = alias; + + if (!this._router.prototype.hasOwnProperty(alias)) { + Object.defineProperty(this._router.prototype, alias, descriptor); + } + } else { + descriptors[index] = null; + aliases[index] = null; + } + }); + + let type = undefined; + descriptors.forEach(descriptor => { + if (descriptor) { + const descType = this._getDescriptorType(descriptor); + if (type && (type !== descType)) { + console.warn(`[Lightning] Member ${member} in ${this._type.name} has inconsistent types.`); + return; + } + type = descType; + } + }); + + switch(type) { + case "method": + this._addMethodRouter(member, descriptors, aliases); + break; + case "getter": + this._addGetterSetterRouters(member); + break; + case "property": + console.warn("[Lightning] Fixed properties are not supported; please use a getter instead!") + break; + } + } + + _getDescriptor(state, member, isValid = () => true) { + let type = state; + let curState = state; + + do { + const descriptor = Object.getOwnPropertyDescriptor(type.prototype, member); + if (descriptor) { + if (isValid(descriptor)) { + descriptor._source = curState; + return descriptor; + } + } + type = Object.getPrototypeOf(type); + if (type && type.hasOwnProperty('__state')) { + curState = type; + } + } while(type && type.prototype); + return undefined; + } + + _getDescriptorType(descriptor) { + if (descriptor.get || descriptor.set) { + return 'getter'; + } else { + if (typeof descriptor.value === "function") { + return 'method'; + } else { + return 'property'; + } + } + } + + static _supportsSpread() { + if (this.__supportsSpread === undefined) { + this.__supportsSpread = false; + try { + const func = new Function("return [].concat(...arguments);"); + func(); + this.__supportsSpread = true; + } catch(e) {} + } + return this.__supportsSpread; + } + + _addMethodRouter(member, descriptors, aliases) { + const code = [ + // The line ensures that, while debugging, your IDE won't open many tabs. + "//@ sourceURL=StateMachineRouter.js", + "var i = this._stateIndex;" + ]; + let cur = aliases[0]; + const supportsSpread = StateMachineType._supportsSpread(); + for (let i = 1, n = aliases.length; i < n; i++) { + const alias = aliases[i]; + if (alias !== cur) { + if (cur) { + if (supportsSpread) { + code.push(`if (i < ${i}) return this["${cur}"](...arguments); else`); + } else { + code.push(`if (i < ${i}) return this["${cur}"].apply(this, arguments); else`); + } + } else { + code.push(`if (i < ${i}) return ; else`); + } + } + cur = alias; + } + if (cur) { + if (supportsSpread) { + code.push(`return this["${cur}"](...arguments);`); + } else { + code.push(`return this["${cur}"].apply(this, arguments);`); + } + } else { + code.push(`;`); + } + const functionBody = code.join("\n"); + const router = new Function([], functionBody); + + const descriptor = {value: router}; + Object.defineProperty(this._router.prototype, member, descriptor); + } + + _addGetterSetterRouters(member) { + const getter = this._getGetterRouter(member); + const setter = this._getSetterRouter(member); + const descriptor = { + get: getter, + set: setter + }; + Object.defineProperty(this._router.prototype, member, descriptor); + } + + _getGetterRouter(member) { + const statePaths = Object.keys(this._stateMap); + const descriptors = []; + const aliases = []; + statePaths.forEach((statePath, index) => { + const state = this._stateMap[statePath]; + const descriptor = this._getDescriptor(state, member, (descriptor => descriptor.get)); + if (descriptor) { + descriptors[index] = descriptor; + + // Add to prototype. + const alias = StateMachineType.getStateMemberAlias(descriptor._source.__path, member); + aliases[index] = alias; + + if (!this._router.prototype.hasOwnProperty(alias)) { + Object.defineProperty(this._router.prototype, alias, descriptor); + } + } else { + descriptors[index] = null; + aliases[index] = null; + } + }); + + const code = [ + // The line ensures that, while debugging, your IDE won't open many tabs. + "//@ sourceURL=StateMachineRouter.js", + "var i = this._stateIndex;" + ]; + let cur = aliases[0]; + for (let i = 1, n = aliases.length; i < n; i++) { + const alias = aliases[i]; + if (alias !== cur) { + if (cur) { + code.push(`if (i < ${i}) return this["${cur}"]; else`); + } else { + code.push(`if (i < ${i}) return ; else`); + } + } + cur = alias; + } + if (cur) { + code.push(`return this["${cur}"];`); + } else { + code.push(`;`); + } + const functionBody = code.join("\n"); + const router = new Function([], functionBody); + return router; + } + + _getSetterRouter(member) { + const statePaths = Object.keys(this._stateMap); + const descriptors = []; + const aliases = []; + statePaths.forEach((statePath, index) => { + const state = this._stateMap[statePath]; + const descriptor = this._getDescriptor(state, member, (descriptor => descriptor.set)); + if (descriptor) { + descriptors[index] = descriptor; + + // Add to prototype. + const alias = StateMachineType.getStateMemberAlias(descriptor._source.__path, member); + aliases[index] = alias; + + if (!this._router.prototype.hasOwnProperty(alias)) { + Object.defineProperty(this._router.prototype, alias, descriptor); + } + } else { + descriptors[index] = null; + aliases[index] = null; + } + }); + + const code = [ + // The line ensures that, while debugging, your IDE won't open many tabs. + "//@ sourceURL=StateMachineRouter.js", + "var i = this._stateIndex;" + ]; + let cur = aliases[0]; + for (let i = 1, n = aliases.length; i < n; i++) { + const alias = aliases[i]; + if (alias !== cur) { + if (cur) { + code.push(`if (i < ${i}) this["${cur}"] = arg; else`); + } else { + code.push(`if (i < ${i}) ; else`); + } + } + cur = alias; + } + if (cur) { + code.push(`this["${cur}"] = arg;`); + } else { + code.push(`;`); + } + const functionBody = code.join("\n"); + const router = new Function(["arg"], functionBody); + return router; + } + + static getStateMemberAlias(path, member) { + return "$" + (path ? path + "." : "") + member; + } + + _getAllMemberNames() { + const stateMap = this._stateMap; + const map = Object.keys(stateMap); + let members = new Set(); + map.forEach(statePath => { + if (statePath === "") { + // Root state can be skipped: if the method only occurs in the root state, we don't need to re-delegate it based on state. + return; + } + const state = stateMap[statePath]; + const names = this._getStateMemberNames(state); + names.forEach(name => { + members.add(name); + }) + }); + return [...members]; + } + + _getStateMemberNames(state) { + let type = state; + let members = new Set(); + const isRoot = this._type === state; + do { + const names = this._getStateMemberNamesForType(type); + names.forEach(name => { + members.add(name) + }); + + type = Object.getPrototypeOf(type); + } while(type && type.prototype && (!type.hasOwnProperty("__state") || isRoot)); + + return members; + } + + _getStateMemberNamesForType(type) { + const memberNames = Object.getOwnPropertyNames(type.prototype); + return memberNames.filter(memberName => { + return (memberName !== "constructor") && !StateMachineType._isStateLocalMember(memberName); + }); + } + + static _isStateLocalMember(memberName) { + return (memberName === "$enter") || (memberName === "$exit"); + } + + getStateByPath(statePath) { + if (this._stateMap[statePath]) { + return this._stateMap[statePath]; + } + + // Search for closest match. + const parts = statePath.split("."); + while(parts.pop()) { + const statePath = parts.join("."); + if (this._stateMap[statePath]) { + return this._stateMap[statePath]; + } + } + } + + _getStateMap() { + if (!this._stateMap) { + this._stateMap = this._createStateMap(); + } + return this._stateMap; + } + + _createStateMap() { + const stateMap = {}; + this._addState(this._type, null, "", stateMap); + return stateMap; + } + + _addState(state, parentState, name, stateMap) { + state.__state = true; + state.__name = name; + + this._addStaticStateProperty(state, parentState); + + const parentPath = (parentState ? parentState.__path : ""); + let path = (parentPath ? parentPath + "." : "") + name; + state.__path = path; + state.__level = parentState ? parentState.__level + 1 : 0; + state.__parent = parentState; + state.__index = Object.keys(stateMap).length; + stateMap[path] = state; + + const states = state._states; + if (states) { + const isInheritedFromParent = (parentState && parentState._states === states); + if (!isInheritedFromParent) { + const subStates = state._states(); + subStates.forEach(subState => { + const stateName = StateMachineType._getStateName(subState); + this._addState(subState, state, stateName, stateMap); + }); + } + } + } + + static _getStateName(state) { + const name = state.name; + + const index = name.indexOf('$'); + if (index > 0) { + // Strip off rollup name suffix. + return name.substr(0, index); + } + + return name; + } + + _addStaticStateProperty(state, parentState) { + if (parentState) { + const isClassStateLevel = parentState && !parentState.__parent; + if (isClassStateLevel) { + this._router[state.__name] = state; + } else { + parentState[state.__name] = state; + } + } + } + +} + + +/***/ }), + +/***/ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/components/BloomComponent.mjs": +/*!*************************************************************************************************************!*\ + !*** ./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/components/BloomComponent.mjs ***! + \*************************************************************************************************************/ +/*! exports provided: default */ +/***/ (function(__webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return BloomComponent; }); +/* harmony import */ var _application_Component_mjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../application/Component.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/application/Component.mjs"); +/* harmony import */ var _renderer_webgl_shaders_LinearBlurShader_mjs__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../renderer/webgl/shaders/LinearBlurShader.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/renderer/webgl/shaders/LinearBlurShader.mjs"); +/* harmony import */ var _renderer_webgl_shaders_BoxBlurShader_mjs__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../renderer/webgl/shaders/BoxBlurShader.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/renderer/webgl/shaders/BoxBlurShader.mjs"); +/* harmony import */ var _renderer_webgl_shaders_DefaultShader_mjs__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../renderer/webgl/shaders/DefaultShader.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/renderer/webgl/shaders/DefaultShader.mjs"); +/* + * If not stated otherwise in this file or this component's LICENSE file the + * following copyright and licenses apply: + * + * Copyright 2020 Metrological + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + + + + +class BloomComponent extends _application_Component_mjs__WEBPACK_IMPORTED_MODULE_0__["default"] { + + static _template() { + const onUpdate = function(element, elementCore) { + if ((elementCore._recalc & (2 + 128))) { + const w = elementCore.w; + const h = elementCore.h; + let cur = elementCore; + do { + cur = cur._children[0]; + cur._element.w = w; + cur._element.h = h; + } while(cur._children); + } + }; + + return { + Textwrap: {rtt: true, forceZIndexContext: true, renderOffscreen: true, + BloomBase: {shader: {type: BloomBaseShader}, + Content: {} + } + }, + Layers: { + L0: {rtt: true, onUpdate: onUpdate, scale: 2, pivot: 0, visible: false, Content: {shader: {type: _renderer_webgl_shaders_BoxBlurShader_mjs__WEBPACK_IMPORTED_MODULE_2__["default"]}}}, + L1: {rtt: true, onUpdate: onUpdate, scale: 4, pivot: 0, visible: false, Content: {shader: {type: _renderer_webgl_shaders_BoxBlurShader_mjs__WEBPACK_IMPORTED_MODULE_2__["default"]}}}, + L2: {rtt: true, onUpdate: onUpdate, scale: 8, pivot: 0, visible: false, Content: {shader: {type: _renderer_webgl_shaders_BoxBlurShader_mjs__WEBPACK_IMPORTED_MODULE_2__["default"]}}}, + L3: {rtt: true, onUpdate: onUpdate, scale: 16, pivot: 0, visible: false, Content: {shader: {type: _renderer_webgl_shaders_BoxBlurShader_mjs__WEBPACK_IMPORTED_MODULE_2__["default"]}}} + } + } + } + + get _signalProxy() { + return true; + } + + constructor(stage) { + super(stage); + this._textwrap = this.sel("Textwrap"); + this._wrapper = this.sel("Textwrap.Content"); + this._layers = this.sel("Layers"); + + this._amount = 0; + this._paddingX = 0; + this._paddingY = 0; + } + + _build() { + const filterShaderSettings = [{x:1,y:0,kernelRadius:3},{x:0,y:1,kernelRadius:3},{x:1.5,y:0,kernelRadius:3},{x:0,y:1.5,kernelRadius:3}]; + const filterShaders = filterShaderSettings.map(s => { + const shader = this.stage.createShader(Object.assign({type: _renderer_webgl_shaders_LinearBlurShader_mjs__WEBPACK_IMPORTED_MODULE_1__["default"]}, s)); + return shader; + }); + + this._setLayerTexture(this.getLayerContents(0), this._textwrap.getTexture(), []); + this._setLayerTexture(this.getLayerContents(1), this.getLayer(0).getTexture(), [filterShaders[0], filterShaders[1]]); + + // Notice that 1.5 filters should be applied before 1.0 filters. + this._setLayerTexture(this.getLayerContents(2), this.getLayer(1).getTexture(), [filterShaders[0], filterShaders[1], filterShaders[2], filterShaders[3]]); + this._setLayerTexture(this.getLayerContents(3), this.getLayer(2).getTexture(), [filterShaders[0], filterShaders[1], filterShaders[2], filterShaders[3]]); + } + + _setLayerTexture(element, texture, steps) { + if (!steps.length) { + element.texture = texture; + } else { + const step = steps.pop(); + const child = element.stage.c({rtt: true, shader: step}); + + // Recurse. + this._setLayerTexture(child, texture, steps); + + element.childList.add(child); + } + return element; + } + + get content() { + return this.sel('Textwrap.Content'); + } + + set content(v) { + this.sel('Textwrap.Content').patch(v); + } + + set padding(v) { + this._paddingX = v; + this._paddingY = v; + this._updateBlurSize(); + } + + set paddingX(v) { + this._paddingX = v; + this._updateBlurSize(); + } + + set paddingY(v) { + this._paddingY = v; + this._updateBlurSize(); + } + + getLayer(i) { + return this._layers.sel("L" + i); + } + + getLayerContents(i) { + return this.getLayer(i).sel("Content"); + } + + _onResize() { + this._updateBlurSize(); + } + + _updateBlurSize() { + let w = this.renderWidth; + let h = this.renderHeight; + + let paddingX = this._paddingX; + let paddingY = this._paddingY; + + let fw = w + paddingX * 2; + let fh = h + paddingY * 2; + this._textwrap.w = fw; + this._wrapper.x = paddingX; + this.getLayer(0).w = this.getLayerContents(0).w = fw / 2; + this.getLayer(1).w = this.getLayerContents(1).w = fw / 4; + this.getLayer(2).w = this.getLayerContents(2).w = fw / 8; + this.getLayer(3).w = this.getLayerContents(3).w = fw / 16; + this._textwrap.x = -paddingX; + + this._textwrap.h = fh; + this._wrapper.y = paddingY; + this.getLayer(0).h = this.getLayerContents(0).h = fh / 2; + this.getLayer(1).h = this.getLayerContents(1).h = fh / 4; + this.getLayer(2).h = this.getLayerContents(2).h = fh / 8; + this.getLayer(3).h = this.getLayerContents(3).h = fh / 16; + this._textwrap.y = -paddingY; + + this.w = w; + this.h = h; + } + + /** + * Sets the amount of blur. A value between 0 and 4. Goes up exponentially for blur. + * Best results for non-fractional values. + * @param v; + */ + set amount(v) { + this._amount = v; + this._update(); + } + + get amount() { + return this._amount; + } + + _update() { + let v = Math.min(4, Math.max(0, this._amount)); + if (v > 0) { + this.getLayer(0).visible = (v > 0); + this.getLayer(1).visible = (v > 1); + this.getLayer(2).visible = (v > 2); + this.getLayer(3).visible = (v > 3); + } + } + + set shader(s) { + super.shader = s; + if (!this.renderToTexture) { + console.warn("[Lightning] Please enable renderToTexture to use with a shader."); + } + } + + _firstActive() { + this._build(); + } + +} + +class BloomBaseShader extends _renderer_webgl_shaders_DefaultShader_mjs__WEBPACK_IMPORTED_MODULE_3__["default"] { +} + +BloomBaseShader.fragmentShaderSource = ` + #ifdef GL_ES + # ifdef GL_FRAGMENT_PRECISION_HIGH + precision highp float; + # else + precision lowp float; + # endif + #endif + varying vec2 vTextureCoord; + varying vec4 vColor; + uniform sampler2D uSampler; + void main(void){ + vec4 color = texture2D(uSampler, vTextureCoord) * vColor; + float m = max(max(color.r, color.g), color.b); + float c = max(0.0, (m - 0.80)) * 5.0; + color = color * c; + gl_FragColor = color; + } +`; + + +/***/ }), + +/***/ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/components/BorderComponent.mjs": +/*!**************************************************************************************************************!*\ + !*** ./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/components/BorderComponent.mjs ***! + \**************************************************************************************************************/ +/*! exports provided: default */ +/***/ (function(__webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return BorderComponent; }); +/* harmony import */ var _application_Component_mjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../application/Component.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/application/Component.mjs"); +/* + * If not stated otherwise in this file or this component's LICENSE file the + * following copyright and licenses apply: + * + * Copyright 2020 Metrological + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + +class BorderComponent extends _application_Component_mjs__WEBPACK_IMPORTED_MODULE_0__["default"] { + + static _template() { + return { + Content: {}, + Borders: { + Top: {rect: true, visible: false, mountY: 1}, + Right: {rect: true, visible: false}, + Bottom: {rect: true, visible: false}, + Left: {rect: true, visible: false, mountX: 1} + } + }; + } + + get _signalProxy() { + return true; + } + + constructor(stage) { + super(stage); + + this._borderTop = this.tag("Top"); + this._borderRight = this.tag("Right"); + this._borderBottom = this.tag("Bottom"); + this._borderLeft = this.tag("Left"); + + this.onAfterUpdate = function (element) { + const content = element.childList.first; + let w = element.core.w || content.renderWidth; + let h = element.core.h || content.renderHeight; + element._borderTop.w = w; + element._borderBottom.y = h; + element._borderBottom.w = w; + element._borderLeft.h = h + element._borderTop.h + element._borderBottom.h; + element._borderLeft.y = -element._borderTop.h; + element._borderRight.x = w; + element._borderRight.h = h + element._borderTop.h + element._borderBottom.h; + element._borderRight.y = -element._borderTop.h; + }; + + this.borderWidth = 1; + } + + get content() { + return this.sel('Content'); + } + + set content(v) { + this.sel('Content').patch(v, true); + } + + get borderWidth() { + return this.borderWidthTop; + } + + get borderWidthTop() { + return this._borderTop.h; + } + + get borderWidthRight() { + return this._borderRight.w; + } + + get borderWidthBottom() { + return this._borderBottom.h; + } + + get borderWidthLeft() { + return this._borderLeft.w; + } + + set borderWidth(v) { + this.borderWidthTop = v; + this.borderWidthRight = v; + this.borderWidthBottom = v; + this.borderWidthLeft = v; + } + + set borderWidthTop(v) { + this._borderTop.h = v; + this._borderTop.visible = (v > 0); + } + + set borderWidthRight(v) { + this._borderRight.w = v; + this._borderRight.visible = (v > 0); + } + + set borderWidthBottom(v) { + this._borderBottom.h = v; + this._borderBottom.visible = (v > 0); + } + + set borderWidthLeft(v) { + this._borderLeft.w = v; + this._borderLeft.visible = (v > 0); + } + + get colorBorder() { + return this.colorBorderTop; + } + + get colorBorderTop() { + return this._borderTop.color; + } + + get colorBorderRight() { + return this._borderRight.color; + } + + get colorBorderBottom() { + return this._borderBottom.color; + } + + get colorBorderLeft() { + return this._borderLeft.color; + } + + set colorBorder(v) { + this.colorBorderTop = v; + this.colorBorderRight = v; + this.colorBorderBottom = v; + this.colorBorderLeft = v; + } + + set colorBorderTop(v) { + this._borderTop.color = v; + } + + set colorBorderRight(v) { + this._borderRight.color = v; + } + + set colorBorderBottom(v) { + this._borderBottom.color = v; + } + + set colorBorderLeft(v) { + this._borderLeft.color = v; + } + + get borderTop() { + return this._borderTop; + } + + set borderTop(settings) { + this.borderTop.patch(settings); + } + + get borderRight() { + return this._borderRight; + } + + set borderRight(settings) { + this.borderRight.patch(settings); + } + + get borderBottom() { + return this._borderBottom; + } + + set borderBottom(settings) { + this.borderBottom.patch(settings); + } + + get borderLeft() { + return this._borderLeft; + } + + set borderLeft(settings) { + this.borderLeft.patch(settings); + } + + set borders(settings) { + this.borderTop = settings; + this.borderLeft = settings; + this.borderBottom = settings; + this.borderRight = settings; + } + +} + + + +/***/ }), + +/***/ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/components/FastBlurComponent.mjs": +/*!****************************************************************************************************************!*\ + !*** ./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/components/FastBlurComponent.mjs ***! + \****************************************************************************************************************/ +/*! exports provided: default */ +/***/ (function(__webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return FastBlurComponent; }); +/* harmony import */ var _application_Component_mjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../application/Component.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/application/Component.mjs"); +/* harmony import */ var _renderer_webgl_shaders_LinearBlurShader_mjs__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../renderer/webgl/shaders/LinearBlurShader.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/renderer/webgl/shaders/LinearBlurShader.mjs"); +/* harmony import */ var _renderer_webgl_shaders_BoxBlurShader_mjs__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../renderer/webgl/shaders/BoxBlurShader.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/renderer/webgl/shaders/BoxBlurShader.mjs"); +/* harmony import */ var _renderer_webgl_shaders_DefaultShader_mjs__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../renderer/webgl/shaders/DefaultShader.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/renderer/webgl/shaders/DefaultShader.mjs"); +/* harmony import */ var _renderer_c2d_shaders_BlurShader_mjs__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../renderer/c2d/shaders/BlurShader.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/renderer/c2d/shaders/BlurShader.mjs"); +/* harmony import */ var _tree_Shader_mjs__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../tree/Shader.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/tree/Shader.mjs"); +/* harmony import */ var _tools_MultiSpline_mjs__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../tools/MultiSpline.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/tools/MultiSpline.mjs"); +/* + * If not stated otherwise in this file or this component's LICENSE file the + * following copyright and licenses apply: + * + * Copyright 2020 Metrological + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + + + + + + + +class FastBlurComponent extends _application_Component_mjs__WEBPACK_IMPORTED_MODULE_0__["default"] { + static _template() { + return {} + } + + get wrap() { + return this.tag("Wrap"); + } + + set content(v) { + return this.wrap.content = v; + } + + get content() { + return this.wrap.content; + } + + set padding(v) { + this.wrap._paddingX = v; + this.wrap._paddingY = v; + this.wrap._updateBlurSize(); + } + + set paddingX(v) { + this.wrap._paddingX = v; + this.wrap._updateBlurSize(); + } + + set paddingY(v) { + this.wrap._paddingY = v; + this.wrap._updateBlurSize(); + } + + set amount(v) { + return this.wrap.amount = v; + } + + get amount() { + return this.wrap.amount; + } + + _onResize() { + this.wrap.w = this.renderWidth; + this.wrap.h = this.renderHeight; + } + + get _signalProxy() { + return true; + } + + _build() { + this.patch({ + Wrap: {type: this.stage.gl ? WebGLFastBlurComponent : C2dFastBlurComponent} + }); + } + +} + + +class C2dFastBlurComponent extends _application_Component_mjs__WEBPACK_IMPORTED_MODULE_0__["default"] { + + static _template() { + return { + forceZIndexContext: true, + rtt: true, + Textwrap: {shader: {type: _renderer_c2d_shaders_BlurShader_mjs__WEBPACK_IMPORTED_MODULE_4__["default"]}, Content: {}} + } + } + + constructor(stage) { + super(stage); + this._textwrap = this.sel("Textwrap"); + this._wrapper = this.sel("Textwrap>Content"); + + this._amount = 0; + this._paddingX = 0; + this._paddingY = 0; + + } + + static getSpline() { + if (!this._multiSpline) { + this._multiSpline = new _tools_MultiSpline_mjs__WEBPACK_IMPORTED_MODULE_6__["default"](); + this._multiSpline.parse(false, {0: 0, 0.25: 1.5, 0.5: 5.5, 0.75: 18, 1: 39}); + } + return this._multiSpline; + } + + get content() { + return this.sel('Textwrap>Content'); + } + + set content(v) { + this.sel('Textwrap>Content').patch(v, true); + } + + set padding(v) { + this._paddingX = v; + this._paddingY = v; + this._updateBlurSize(); + } + + set paddingX(v) { + this._paddingX = v; + this._updateBlurSize(); + } + + set paddingY(v) { + this._paddingY = v; + this._updateBlurSize(); + } + + _updateBlurSize() { + let w = this.renderWidth; + let h = this.renderHeight; + + let paddingX = this._paddingX; + let paddingY = this._paddingY; + + this._wrapper.x = paddingX; + this._textwrap.x = -paddingX; + + this._wrapper.y = paddingY; + this._textwrap.y = -paddingY; + + this._textwrap.w = w + paddingX * 2; + this._textwrap.h = h + paddingY * 2; + } + + get amount() { + return this._amount; + } + + /** + * Sets the amount of blur. A value between 0 and 4. Goes up exponentially for blur. + * Best results for non-fractional values. + * @param v; + */ + set amount(v) { + this._amount = v; + this._textwrap.shader.kernelRadius = C2dFastBlurComponent._amountToKernelRadius(v); + } + + static _amountToKernelRadius(v) { + return C2dFastBlurComponent.getSpline().getValue(Math.min(1, v * 0.25)); + } + + get _signalProxy() { + return true; + } + +} + +class WebGLFastBlurComponent extends _application_Component_mjs__WEBPACK_IMPORTED_MODULE_0__["default"] { + + static _template() { + const onUpdate = function(element, elementCore) { + if ((elementCore._recalc & (2 + 128))) { + const w = elementCore.w; + const h = elementCore.h; + let cur = elementCore; + do { + cur = cur._children[0]; + cur._element.w = w; + cur._element.h = h; + } while(cur._children); + } + }; + + return { + Textwrap: {rtt: true, forceZIndexContext: true, renderOffscreen: true, Content: {}}, + Layers: { + L0: {rtt: true, onUpdate: onUpdate, renderOffscreen: true, visible: false, Content: {shader: {type: _renderer_webgl_shaders_BoxBlurShader_mjs__WEBPACK_IMPORTED_MODULE_2__["default"]}}}, + L1: {rtt: true, onUpdate: onUpdate, renderOffscreen: true, visible: false, Content: {shader: {type: _renderer_webgl_shaders_BoxBlurShader_mjs__WEBPACK_IMPORTED_MODULE_2__["default"]}}}, + L2: {rtt: true, onUpdate: onUpdate, renderOffscreen: true, visible: false, Content: {shader: {type: _renderer_webgl_shaders_BoxBlurShader_mjs__WEBPACK_IMPORTED_MODULE_2__["default"]}}}, + L3: {rtt: true, onUpdate: onUpdate, renderOffscreen: true, visible: false, Content: {shader: {type: _renderer_webgl_shaders_BoxBlurShader_mjs__WEBPACK_IMPORTED_MODULE_2__["default"]}}} + }, + Result: {shader: {type: FastBlurOutputShader}, visible: false} + } + } + + get _signalProxy() { + return true; + } + + constructor(stage) { + super(stage); + this._textwrap = this.sel("Textwrap"); + this._wrapper = this.sel("Textwrap>Content"); + this._layers = this.sel("Layers"); + this._output = this.sel("Result"); + + this._amount = 0; + this._paddingX = 0; + this._paddingY = 0; + } + + _buildLayers() { + const filterShaderSettings = [{x:1,y:0,kernelRadius:1},{x:0,y:1,kernelRadius:1},{x:1.5,y:0,kernelRadius:1},{x:0,y:1.5,kernelRadius:1}]; + const filterShaders = filterShaderSettings.map(s => { + const shader = _tree_Shader_mjs__WEBPACK_IMPORTED_MODULE_5__["default"].create(this.stage, Object.assign({type: _renderer_webgl_shaders_LinearBlurShader_mjs__WEBPACK_IMPORTED_MODULE_1__["default"]}, s)); + return shader; + }); + + this._setLayerTexture(this.getLayerContents(0), this._textwrap.getTexture(), []); + this._setLayerTexture(this.getLayerContents(1), this.getLayer(0).getTexture(), [filterShaders[0], filterShaders[1]]); + + // Notice that 1.5 filters should be applied before 1.0 filters. + this._setLayerTexture(this.getLayerContents(2), this.getLayer(1).getTexture(), [filterShaders[0], filterShaders[1], filterShaders[2], filterShaders[3]]); + this._setLayerTexture(this.getLayerContents(3), this.getLayer(2).getTexture(), [filterShaders[0], filterShaders[1], filterShaders[2], filterShaders[3]]); + } + + _setLayerTexture(element, texture, steps) { + if (!steps.length) { + element.texture = texture; + } else { + const step = steps.pop(); + const child = element.stage.c({rtt: true, shader: step}); + + // Recurse. + this._setLayerTexture(child, texture, steps); + + element.childList.add(child); + } + return element; + } + + get content() { + return this.sel('Textwrap>Content'); + } + + set content(v) { + this.sel('Textwrap>Content').patch(v, true); + } + + set padding(v) { + this._paddingX = v; + this._paddingY = v; + this._updateBlurSize(); + } + + set paddingX(v) { + this._paddingX = v; + this._updateBlurSize(); + } + + set paddingY(v) { + this._paddingY = v; + this._updateBlurSize(); + } + + getLayer(i) { + return this._layers.sel("L" + i); + } + + getLayerContents(i) { + return this.getLayer(i).sel("Content"); + } + + _onResize() { + this._updateBlurSize(); + } + + _updateBlurSize() { + let w = this.renderWidth; + let h = this.renderHeight; + + let paddingX = this._paddingX; + let paddingY = this._paddingY; + + let fw = w + paddingX * 2; + let fh = h + paddingY * 2; + this._textwrap.w = fw; + this._wrapper.x = paddingX; + this.getLayer(0).w = this.getLayerContents(0).w = fw / 2; + this.getLayer(1).w = this.getLayerContents(1).w = fw / 4; + this.getLayer(2).w = this.getLayerContents(2).w = fw / 8; + this.getLayer(3).w = this.getLayerContents(3).w = fw / 16; + this._output.x = -paddingX; + this._textwrap.x = -paddingX; + this._output.w = fw; + + this._textwrap.h = fh; + this._wrapper.y = paddingY; + this.getLayer(0).h = this.getLayerContents(0).h = fh / 2; + this.getLayer(1).h = this.getLayerContents(1).h = fh / 4; + this.getLayer(2).h = this.getLayerContents(2).h = fh / 8; + this.getLayer(3).h = this.getLayerContents(3).h = fh / 16; + this._output.y = -paddingY; + this._textwrap.y = -paddingY; + this._output.h = fh; + + this.w = w; + this.h = h; + } + + /** + * Sets the amount of blur. A value between 0 and 4. Goes up exponentially for blur. + * Best results for non-fractional values. + * @param v; + */ + set amount(v) { + this._amount = v; + this._update(); + } + + get amount() { + return this._amount; + } + + _update() { + let v = Math.min(4, Math.max(0, this._amount)); + if (v === 0) { + this._textwrap.renderToTexture = false; + this._output.shader.otherTextureSource = null; + this._output.visible = false; + } else { + this._textwrap.renderToTexture = true; + this._output.visible = true; + + this.getLayer(0).visible = (v > 0); + this.getLayer(1).visible = (v > 1); + this.getLayer(2).visible = (v > 2); + this.getLayer(3).visible = (v > 3); + + if (v <= 1) { + this._output.texture = this._textwrap.getTexture(); + this._output.shader.otherTextureSource = this.getLayer(0).getTexture(); + this._output.shader.a = v; + } else if (v <= 2) { + this._output.texture = this.getLayer(0).getTexture(); + this._output.shader.otherTextureSource = this.getLayer(1).getTexture(); + this._output.shader.a = v - 1; + } else if (v <= 3) { + this._output.texture = this.getLayer(1).getTexture(); + this._output.shader.otherTextureSource = this.getLayer(2).getTexture(); + this._output.shader.a = v - 2; + } else if (v <= 4) { + this._output.texture = this.getLayer(2).getTexture(); + this._output.shader.otherTextureSource = this.getLayer(3).getTexture(); + this._output.shader.a = v - 3; + } + } + } + + set shader(s) { + super.shader = s; + if (!this.renderToTexture) { + console.warn("[Lightning] Please enable renderToTexture to use with a shader."); + } + } + + _firstActive() { + this._buildLayers(); + } + +} + +/** + * Shader that combines two textures into one output. + */ +class FastBlurOutputShader extends _renderer_webgl_shaders_DefaultShader_mjs__WEBPACK_IMPORTED_MODULE_3__["default"] { + + constructor(ctx) { + super(ctx); + + this._a = 0; + this._otherTextureSource = null; + } + + get a() { + return this._a; + } + + set a(v) { + this._a = v; + this.redraw(); + } + + set otherTextureSource(v) { + this._otherTextureSource = v; + this.redraw(); + } + + setupUniforms(operation) { + super.setupUniforms(operation); + this._setUniform("a", this._a, this.gl.uniform1f); + this._setUniform("uSampler2", 1, this.gl.uniform1i); + } + + beforeDraw(operation) { + let glTexture = this._otherTextureSource ? this._otherTextureSource.nativeTexture : null; + + let gl = this.gl; + gl.activeTexture(gl.TEXTURE1); + gl.bindTexture(gl.TEXTURE_2D, glTexture); + gl.activeTexture(gl.TEXTURE0); + } +} + +FastBlurOutputShader.fragmentShaderSource = ` + #ifdef GL_ES + # ifdef GL_FRAGMENT_PRECISION_HIGH + precision highp float; + # else + precision lowp float; + # endif + #endif + varying vec2 vTextureCoord; + varying vec4 vColor; + uniform sampler2D uSampler; + uniform sampler2D uSampler2; + uniform float a; + void main(void){ + if (a == 1.0) { + gl_FragColor = texture2D(uSampler2, vTextureCoord) * vColor; + } else { + gl_FragColor = ((1.0 - a) * texture2D(uSampler, vTextureCoord) + (a * texture2D(uSampler2, vTextureCoord))) * vColor; + } + } +`; + + +/***/ }), + +/***/ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/components/ListComponent.mjs": +/*!************************************************************************************************************!*\ + !*** ./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/components/ListComponent.mjs ***! + \************************************************************************************************************/ +/*! exports provided: default */ +/***/ (function(__webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return ListComponent; }); +/* harmony import */ var _application_Component_mjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../application/Component.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/application/Component.mjs"); +/* harmony import */ var _tools_ObjectListWrapper_mjs__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../tools/ObjectListWrapper.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/tools/ObjectListWrapper.mjs"); +/* harmony import */ var _tree_Utils_mjs__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../tree/Utils.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/tree/Utils.mjs"); +/* + * If not stated otherwise in this file or this component's LICENSE file the + * following copyright and licenses apply: + * + * Copyright 2020 Metrological + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + +class ListComponent extends _application_Component_mjs__WEBPACK_IMPORTED_MODULE_0__["default"] { + + constructor(stage) { + super(stage); + + this._wrapper = super._children.a({}); + + this._reloadVisibleElements = false; + + this._visibleItems = new Set(); + + this._index = 0; + + this._started = false; + + /** + * The transition definition that is being used when scrolling the items. + * @type TransitionSettings + */ + this._scrollTransitionSettings = this.stage.transitions.createSettings({}); + + /** + * The scroll area size in pixels per item. + */ + this._itemSize = 100; + + this._viewportScrollOffset = 0; + + this._itemScrollOffset = 0; + + /** + * Should the list jump when scrolling between end to start, or should it be continuous, like a carrousel? + */ + this._roll = false; + + /** + * Allows restricting the start scroll position. + */ + this._rollMin = 0; + + /** + * Allows restricting the end scroll position. + */ + this._rollMax = 0; + + /** + * Definition for a custom animation that is applied when an item is (partially) selected. + * @type AnimationSettings + */ + this._progressAnimation = null; + + /** + * Inverts the scrolling direction. + * @type {boolean} + * @private + */ + this._invertDirection = false; + + /** + * Layout the items horizontally or vertically? + * @type {boolean} + * @private + */ + this._horizontal = true; + + this.itemList = new ListItems(this); + } + + _allowChildrenAccess() { + return false; + } + + get items() { + return this.itemList.get(); + } + + set items(children) { + this.itemList.patch(children); + } + + start() { + this._wrapper.transition(this.property, this._scrollTransitionSettings); + this._scrollTransition = this._wrapper.transition(this.property); + this._scrollTransition.on('progress', p => this.update()); + + this.setIndex(0, true, true); + + this._started = true; + + this.update(); + } + + setIndex(index, immediate = false, closest = false) { + let nElements = this.length; + if (!nElements) return; + + this.emit('unfocus', this.getElement(this.realIndex), this._index, this.realIndex); + + if (closest) { + // Scroll to same offset closest to the index. + let offset = _tree_Utils_mjs__WEBPACK_IMPORTED_MODULE_2__["default"].getModuloIndex(index, nElements); + let o = _tree_Utils_mjs__WEBPACK_IMPORTED_MODULE_2__["default"].getModuloIndex(this.index, nElements); + let diff = offset - o; + if (diff > 0.5 * nElements) { + diff -= nElements; + } else if (diff < -0.5 * nElements) { + diff += nElements; + } + this._index += diff; + } else { + this._index = index; + } + + if (this._roll || (this.viewportSize > this._itemSize * nElements)) { + this._index = _tree_Utils_mjs__WEBPACK_IMPORTED_MODULE_2__["default"].getModuloIndex(this._index, nElements); + } + + let direction = (this._horizontal ^ this._invertDirection ? -1 : 1); + let value = direction * this._index * this._itemSize; + + if (this._roll) { + let min, max, scrollDelta; + if (direction == 1) { + max = (nElements - 1) * this._itemSize; + scrollDelta = this._viewportScrollOffset * this.viewportSize - this._itemScrollOffset * this._itemSize; + + max -= scrollDelta; + + min = this.viewportSize - (this._itemSize + scrollDelta); + + if (this._rollMin) min -= this._rollMin; + if (this._rollMax) max += this._rollMax; + + value = Math.max(Math.min(value, max), min); + } else { + max = (nElements * this._itemSize - this.viewportSize); + scrollDelta = this._viewportScrollOffset * this.viewportSize - this._itemScrollOffset * this._itemSize; + + max += scrollDelta; + + let min = scrollDelta; + + if (this._rollMin) min -= this._rollMin; + if (this._rollMax) max += this._rollMax; + + value = Math.min(Math.max(-max, value), -min); + } + } + + this._scrollTransition.start(value); + + if (immediate) { + this._scrollTransition.finish(); + } + + this.emit('focus', this.getElement(this.realIndex), this._index, this.realIndex); + } + + getAxisPosition() { + let target = -this._scrollTransition._targetValue; + + let direction = (this._horizontal ^ this._invertDirection ? -1 : 1); + let value = -direction * this._index * this._itemSize; + + return this._viewportScrollOffset * this.viewportSize + (value - target); + } + + update() { + if (!this._started) return; + + let nElements = this.length; + if (!nElements) return; + + let direction = (this._horizontal ^ this._invertDirection ? -1 : 1); + + // Map position to index value. + let v = (this._horizontal ? this._wrapper.x : this._wrapper.y); + + let viewportSize = this.viewportSize; + let scrollDelta = this._viewportScrollOffset * viewportSize - this._itemScrollOffset * this._itemSize; + v += scrollDelta; + + let s, e, ps, pe; + if (direction == -1) { + s = Math.floor(-v / this._itemSize); + ps = 1 - ((-v / this._itemSize) - s); + e = Math.floor((viewportSize - v) / this._itemSize); + pe = (((viewportSize - v) / this._itemSize) - e); + } else { + s = Math.ceil(v / this._itemSize); + ps = 1 + (v / this._itemSize) - s; + e = Math.ceil((v - viewportSize) / this._itemSize); + pe = e - ((v - viewportSize) / this._itemSize); + } + if (this._roll || (viewportSize > this._itemSize * nElements)) { + // Don't show additional items. + if (e >= nElements) { + e = nElements - 1; + pe = 1; + } + if (s >= nElements) { + s = nElements - 1; + ps = 1; + } + if (e <= -1) { + e = 0; + pe = 1; + } + if (s <= -1) { + s = 0; + ps = 1; + } + } + + let offset = -direction * s * this._itemSize; + + let item; + for (let index = s; (direction == -1 ? index <= e : index >= e); (direction == -1 ? index++ : index--)) { + let realIndex = _tree_Utils_mjs__WEBPACK_IMPORTED_MODULE_2__["default"].getModuloIndex(index, nElements); + + let element = this.getElement(realIndex); + item = element.parent; + this._visibleItems.delete(item); + if (this._horizontal) { + item.x = offset + scrollDelta; + } else { + item.y = offset + scrollDelta; + } + + let wasVisible = item.visible; + item.visible = true; + + if (!wasVisible || this._reloadVisibleElements) { + // Turned visible. + this.emit('visible', index, realIndex); + } + + + + if (this._progressAnimation) { + let p = 1; + if (index == s) { + p = ps; + } else if (index == e) { + p = pe; + } + + // Use animation to progress. + this._progressAnimation.apply(element, p); + } + + offset += this._itemSize; + } + + // Handle item visibility. + let self = this; + this._visibleItems.forEach(function(invisibleItem) { + invisibleItem.visible = false; + self._visibleItems.delete(invisibleItem); + }); + + for (let index = s; (direction == -1 ? index <= e : index >= e); (direction == -1 ? index++ : index--)) { + let realIndex = _tree_Utils_mjs__WEBPACK_IMPORTED_MODULE_2__["default"].getModuloIndex(index, nElements); + this._visibleItems.add(this.getWrapper(realIndex)); + } + + this._reloadVisibleElements = false; + } + + setPrevious() { + this.setIndex(this._index - 1); + } + + setNext() { + this.setIndex(this._index + 1); + } + + getWrapper(index) { + return this._wrapper.children[index]; + } + + getElement(index) { + let e = this._wrapper.children[index]; + return e ? e.children[0] : null; + } + + reload() { + this._reloadVisibleElements = true; + this.update(); + } + + get element() { + let e = this._wrapper.children[this.realIndex]; + return e ? e.children[0] : null; + } + + get length() { + return this._wrapper.children.length; + } + + get property() { + return this._horizontal ? 'x' : 'y'; + } + + get viewportSize() { + return this._horizontal ? this.w : this.h; + } + + get index() { + return this._index; + } + + get realIndex() { + return _tree_Utils_mjs__WEBPACK_IMPORTED_MODULE_2__["default"].getModuloIndex(this._index, this.length); + } + + get itemSize() { + return this._itemSize; + } + + set itemSize(v) { + this._itemSize = v; + this.update(); + } + + get viewportScrollOffset() { + return this._viewportScrollOffset; + } + + set viewportScrollOffset(v) { + this._viewportScrollOffset = v; + this.update(); + } + + get itemScrollOffset() { + return this._itemScrollOffset; + } + + set itemScrollOffset(v) { + this._itemScrollOffset = v; + this.update(); + } + + get scrollTransitionSettings() { + return this._scrollTransitionSettings; + } + + set scrollTransitionSettings(v) { + this._scrollTransitionSettings.patch(v); + } + + set scrollTransition(v) { + this._scrollTransitionSettings.patch(v); + } + + get scrollTransition() { + return this._scrollTransition; + } + + get progressAnimation() { + return this._progressAnimation; + } + + set progressAnimation(v) { + if (_tree_Utils_mjs__WEBPACK_IMPORTED_MODULE_2__["default"].isObjectLiteral(v)) { + this._progressAnimation = this.stage.animations.createSettings(v); + } else { + this._progressAnimation = v; + } + this.update(); + } + + get roll() { + return this._roll; + } + + set roll(v) { + this._roll = v; + this.update(); + } + + get rollMin() { + return this._rollMin; + } + + set rollMin(v) { + this._rollMin = v; + this.update(); + } + + get rollMax() { + return this._rollMax; + } + + set rollMax(v) { + this._rollMax = v; + this.update(); + } + + get invertDirection() { + return this._invertDirection; + } + + set invertDirection(v) { + if (!this._started) { + this._invertDirection = v; + } + } + + get horizontal() { + return this._horizontal; + } + + set horizontal(v) { + if (v !== this._horizontal) { + if (!this._started) { + this._horizontal = v; + } + } + } + +} + + +class ListItems extends _tools_ObjectListWrapper_mjs__WEBPACK_IMPORTED_MODULE_1__["default"] { + constructor(list) { + let wrap = (item => { + let parent = item.stage.createElement(); + parent.add(item); + parent.visible = false; + return parent; + }) + + super(list._wrapper._children, wrap); + this.list = list; + } + + onAdd(item, index) { + super.onAdd(item, index); + this.checkStarted(index); + } + + checkStarted(index) { + this.list._reloadVisibleElements = true; + if (!this.list._started) { + this.list.start(); + } else { + if (this.list.length === 1) { + this.list.setIndex(0, true, true); + } else { + if (this.list._index >= this.list.length) { + this.list.setIndex(0); + } + } + this.list.update(); + } + } + + onRemove(item, index) { + super.onRemove(item, index); + let ri = this.list.realIndex; + if (ri === index) { + if (ri === this.list.length) { + ri--; + } + if (ri >= 0) { + this.list.setIndex(ri); + } + } else if (ri > index) { + this.list.setIndex(ri - 1); + } + + this.list._reloadVisibleElements = true; + } + + onSet(item, index) { + super.onSet(item, index); + this.checkStarted(index); + } + + onSync(removed, added, order) { + super.onSync(removed, added, order); + this.checkStarted(0); + } + + get _signalProxy() { + return true; + } + +} + + + + +/***/ }), + +/***/ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/components/SmoothScaleComponent.mjs": +/*!*******************************************************************************************************************!*\ + !*** ./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/components/SmoothScaleComponent.mjs ***! + \*******************************************************************************************************************/ +/*! exports provided: default */ +/***/ (function(__webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return SmoothScaleComponent; }); +/* harmony import */ var _application_Component_mjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../application/Component.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/application/Component.mjs"); +/* + * If not stated otherwise in this file or this component's LICENSE file the + * following copyright and licenses apply: + * + * Copyright 2020 Metrological + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + +class SmoothScaleComponent extends _application_Component_mjs__WEBPACK_IMPORTED_MODULE_0__["default"] { + + static _template() { + return { + ContentWrap: {renderOffscreen: true, forceZIndexContext: true, onAfterUpdate: SmoothScaleComponent._updateDimensions, + Content: {} + }, + Scale: {visible: false} + } + } + + constructor(stage) { + super(stage); + + this._smoothScale = 1; + this._iterations = 0; + } + + get content() { + return this.tag('Content'); + } + + set content(v) { + this.tag('Content').patch(v, true); + } + + get smoothScale() { + return this._smoothScale; + } + + set smoothScale(v) { + if (this._smoothScale !== v) { + let its = 0; + while(v < 0.5 && its < 12) { + its++; + v = v * 2; + } + + this.scale = v; + this._setIterations(its); + + this._smoothScale = v; + } + } + + _setIterations(its) { + if (this._iterations !== its) { + const scalers = this.sel("Scale").childList; + const content = this.sel("ContentWrap"); + while (scalers.length < its) { + const first = scalers.length === 0; + const texture = (first ? content.getTexture() : scalers.last.getTexture()); + scalers.a({rtt: true, renderOffscreen: true, texture: texture}); + } + + SmoothScaleComponent._updateDimensions(this.tag("ContentWrap"), true); + + const useScalers = (its > 0); + this.patch({ + ContentWrap: {renderToTexture: useScalers}, + Scale: {visible: useScalers} + }); + + for (let i = 0, n = scalers.length; i < n; i++) { + scalers.getAt(i).patch({ + visible: i < its, + renderOffscreen: i !== its - 1 + }); + } + this._iterations = its; + } + } + + static _updateDimensions(contentWrap, force) { + const content = contentWrap.children[0]; + let w = content.renderWidth; + let h = content.renderHeight; + if (w !== contentWrap.w || h !== contentWrap.h || force) { + contentWrap.w = w; + contentWrap.h = h; + + const scalers = contentWrap.parent.tag("Scale").children; + for (let i = 0, n = scalers.length; i < n; i++) { + w = w * 0.5; + h = h * 0.5; + scalers[i].w = w; + scalers[i].h = h; + } + } + } + + get _signalProxy() { + return true; + } + +} + + +/***/ }), + +/***/ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/flex/FlexContainer.mjs": +/*!******************************************************************************************************!*\ + !*** ./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/flex/FlexContainer.mjs ***! + \******************************************************************************************************/ +/*! exports provided: default */ +/***/ (function(__webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return FlexContainer; }); +/* harmony import */ var _tree_Base_mjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../tree/Base.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/tree/Base.mjs"); +/* harmony import */ var _layout_FlexLayout_mjs__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./layout/FlexLayout.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/flex/layout/FlexLayout.mjs"); +/* + * If not stated otherwise in this file or this component's LICENSE file the + * following copyright and licenses apply: + * + * Copyright 2020 Metrological + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + + +class FlexContainer { + + + constructor(item) { + this._item = item; + + this._layout = new _layout_FlexLayout_mjs__WEBPACK_IMPORTED_MODULE_1__["default"](this); + this._horizontal = true; + this._reverse = false; + this._wrap = false; + this._alignItems = 'stretch'; + this._justifyContent = 'flex-start'; + this._alignContent = 'flex-start'; + + this._paddingLeft = 0; + this._paddingTop = 0; + this._paddingRight = 0; + this._paddingBottom = 0; + } + + get item() { + return this._item; + } + + _changedDimensions() { + this._item.changedDimensions(); + } + + _changedContents() { + this._item.changedContents(); + } + + get direction() { + return (this._horizontal ? "row" : "column") + (this._reverse ? "-reverse" : ""); + } + + set direction(f) { + if (this.direction === f) return; + + this._horizontal = (f === 'row' || f === 'row-reverse'); + this._reverse = (f === 'row-reverse' || f === 'column-reverse'); + + this._changedContents(); + } + + set wrap(v) { + this._wrap = v; + this._changedContents(); + } + + get wrap() { + return this._wrap; + } + + get alignItems() { + return this._alignItems; + } + + set alignItems(v) { + if (this._alignItems === v) return; + if (FlexContainer.ALIGN_ITEMS.indexOf(v) === -1) { + throw new Error("Unknown alignItems, options: " + FlexContainer.ALIGN_ITEMS.join(",")); + } + this._alignItems = v; + + this._changedContents(); + } + + get alignContent() { + return this._alignContent; + } + + set alignContent(v) { + if (this._alignContent === v) return; + if (FlexContainer.ALIGN_CONTENT.indexOf(v) === -1) { + throw new Error("Unknown alignContent, options: " + FlexContainer.ALIGN_CONTENT.join(",")); + } + this._alignContent = v; + + this._changedContents(); + } + + get justifyContent() { + return this._justifyContent; + } + + set justifyContent(v) { + if (this._justifyContent === v) return; + + if (FlexContainer.JUSTIFY_CONTENT.indexOf(v) === -1) { + throw new Error("Unknown justifyContent, options: " + FlexContainer.JUSTIFY_CONTENT.join(",")); + } + this._justifyContent = v; + + this._changedContents(); + } + + set padding(v) { + this.paddingLeft = v; + this.paddingTop = v; + this.paddingRight = v; + this.paddingBottom = v; + } + + get padding() { + return this.paddingLeft; + } + + set paddingLeft(v) { + this._paddingLeft = v; + this._changedDimensions(); + } + + get paddingLeft() { + return this._paddingLeft; + } + + set paddingTop(v) { + this._paddingTop = v; + this._changedDimensions(); + } + + get paddingTop() { + return this._paddingTop; + } + + set paddingRight(v) { + this._paddingRight = v; + this._changedDimensions(); + } + + get paddingRight() { + return this._paddingRight; + } + + set paddingBottom(v) { + this._paddingBottom = v; + this._changedDimensions(); + } + + get paddingBottom() { + return this._paddingBottom; + } + + patch(settings) { + _tree_Base_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].patchObject(this, settings); + } + +} + +FlexContainer.ALIGN_ITEMS = ["flex-start", "flex-end", "center", "stretch"]; +FlexContainer.ALIGN_CONTENT = ["flex-start", "flex-end", "center", "space-between", "space-around", "space-evenly", "stretch"]; +FlexContainer.JUSTIFY_CONTENT = ["flex-start", "flex-end", "center", "space-between", "space-around", "space-evenly"]; + + +/***/ }), + +/***/ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/flex/FlexItem.mjs": +/*!*************************************************************************************************!*\ + !*** ./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/flex/FlexItem.mjs ***! + \*************************************************************************************************/ +/*! exports provided: default */ +/***/ (function(__webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return FlexItem; }); +/* harmony import */ var _tree_Base_mjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../tree/Base.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/tree/Base.mjs"); +/* harmony import */ var _FlexUtils_mjs__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./FlexUtils.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/flex/FlexUtils.mjs"); +/* harmony import */ var _FlexContainer_mjs__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./FlexContainer.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/flex/FlexContainer.mjs"); +/* + * If not stated otherwise in this file or this component's LICENSE file the + * following copyright and licenses apply: + * + * Copyright 2020 Metrological + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + + + +class FlexItem { + + constructor(item) { + this._ctr = null; + this._item = item; + this._grow = 0; + this._shrink = FlexItem.SHRINK_AUTO; + this._alignSelf = undefined; + this._minWidth = 0; + this._minHeight = 0; + this._maxWidth = 0; + this._maxHeight = 0; + + this._marginLeft = 0; + this._marginTop = 0; + this._marginRight = 0; + this._marginBottom = 0; + } + + get item() { + return this._item; + } + + get grow() { + return this._grow; + } + + set grow(v) { + if (this._grow === v) return; + + this._grow = parseInt(v) || 0; + + this._changed(); + } + + get shrink() { + if (this._shrink === FlexItem.SHRINK_AUTO) { + return this._getDefaultShrink(); + } + return this._shrink; + } + + _getDefaultShrink() { + if (this.item.isFlexEnabled()) { + return 1; + } else { + // All non-flex containers are absolutely positioned items with fixed dimensions, and by default not shrinkable. + return 0; + } + } + + set shrink(v) { + if (this._shrink === v) return; + + this._shrink = parseInt(v) || 0; + + this._changed(); + } + + get alignSelf() { + return this._alignSelf; + } + + set alignSelf(v) { + if (this._alignSelf === v) return; + + if (v === undefined) { + this._alignSelf = undefined; + } else { + if (_FlexContainer_mjs__WEBPACK_IMPORTED_MODULE_2__["default"].ALIGN_ITEMS.indexOf(v) === -1) { + throw new Error("Unknown alignSelf, options: " + _FlexContainer_mjs__WEBPACK_IMPORTED_MODULE_2__["default"].ALIGN_ITEMS.join(",")); + } + this._alignSelf = v; + } + + this._changed(); + } + + get minWidth() { + return this._minWidth; + } + + set minWidth(v) { + this._minWidth = Math.max(0, v); + this._item.changedDimensions(true, false); + } + + get minHeight() { + return this._minHeight; + } + + set minHeight(v) { + this._minHeight = Math.max(0, v); + this._item.changedDimensions(false, true); + } + + get maxWidth() { + return this._maxWidth; + } + + set maxWidth(v) { + this._maxWidth = Math.max(0, v); + this._item.changedDimensions(true, false); + } + + get maxHeight() { + return this._maxHeight; + } + + set maxHeight(v) { + this._maxHeight = Math.max(0, v); + this._item.changedDimensions(false, true); + } + + /** + * @note margins behave slightly different than in HTML with regard to shrinking. + * In HTML, (outer) margins can be removed when shrinking. In this engine, they will not shrink at all. + */ + set margin(v) { + this.marginLeft = v; + this.marginTop = v; + this.marginRight = v; + this.marginBottom = v; + } + + get margin() { + return this.marginLeft; + } + + set marginLeft(v) { + this._marginLeft = v; + this._changed(); + } + + get marginLeft() { + return this._marginLeft; + } + + set marginTop(v) { + this._marginTop = v; + this._changed(); + } + + get marginTop() { + return this._marginTop; + } + + set marginRight(v) { + this._marginRight = v; + this._changed(); + } + + get marginRight() { + return this._marginRight; + } + + set marginBottom(v) { + this._marginBottom = v; + this._changed(); + } + + get marginBottom() { + return this._marginBottom; + } + + _changed() { + if (this.ctr) this.ctr._changedContents(); + } + + set ctr(v) { + this._ctr = v; + } + + get ctr() { + return this._ctr; + } + + patch(settings) { + _tree_Base_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].patchObject(this, settings); + } + + _resetLayoutSize() { + this._resetHorizontalAxisLayoutSize(); + this._resetVerticalAxisLayoutSize(); + } + + _resetCrossAxisLayoutSize() { + if (this.ctr._horizontal) { + this._resetVerticalAxisLayoutSize(); + } else { + this._resetHorizontalAxisLayoutSize(); + } + } + + _resetHorizontalAxisLayoutSize() { + let w = _FlexUtils_mjs__WEBPACK_IMPORTED_MODULE_1__["default"].getRelAxisSize(this.item, true); + if (this._minWidth) { + w = Math.max(this._minWidth, w); + } + if (this._maxWidth) { + w = Math.min(this._maxWidth, w); + } + _FlexUtils_mjs__WEBPACK_IMPORTED_MODULE_1__["default"].setAxisLayoutSize(this.item, true, w); + } + + _resetVerticalAxisLayoutSize() { + let h = _FlexUtils_mjs__WEBPACK_IMPORTED_MODULE_1__["default"].getRelAxisSize(this.item, false); + if (this._minHeight) { + h = Math.max(this._minHeight, h); + } + if (this._maxHeight) { + h = Math.min(this._maxHeight, h); + } + _FlexUtils_mjs__WEBPACK_IMPORTED_MODULE_1__["default"].setAxisLayoutSize(this.item, false, h); + } + + _getCrossAxisMinSizeSetting() { + return this._getMinSizeSetting(!this.ctr._horizontal); + } + + _getCrossAxisMaxSizeSetting() { + return this._getMaxSizeSetting(!this.ctr._horizontal); + } + + _getMainAxisMaxSizeSetting() { + return this._getMaxSizeSetting(this.ctr._horizontal); + } + + _getMinSizeSetting(horizontal) { + if (horizontal) { + return this._minWidth; + } else { + return this._minHeight; + } + } + + _getMaxSizeSetting(horizontal) { + if (horizontal) { + return this._maxWidth; + } else { + return this._maxHeight; + } + } + + _getMainAxisMinSize() { + return _FlexUtils_mjs__WEBPACK_IMPORTED_MODULE_1__["default"].getAxisMinSize(this.item, this.ctr._horizontal); + } + + _getCrossAxisMinSize() { + return _FlexUtils_mjs__WEBPACK_IMPORTED_MODULE_1__["default"].getAxisMinSize(this.item, !this.ctr._horizontal); + } + + _getMainAxisLayoutSize() { + return _FlexUtils_mjs__WEBPACK_IMPORTED_MODULE_1__["default"].getAxisLayoutSize(this.item, this.ctr._horizontal); + } + + _getMainAxisLayoutPos() { + return _FlexUtils_mjs__WEBPACK_IMPORTED_MODULE_1__["default"].getAxisLayoutPos(this.item, this.ctr._horizontal); + } + + _setMainAxisLayoutPos(pos) { + return _FlexUtils_mjs__WEBPACK_IMPORTED_MODULE_1__["default"].setAxisLayoutPos(this.item, this.ctr._horizontal, pos); + } + + _setCrossAxisLayoutPos(pos) { + return _FlexUtils_mjs__WEBPACK_IMPORTED_MODULE_1__["default"].setAxisLayoutPos(this.item, !this.ctr._horizontal, pos); + } + + _getCrossAxisLayoutSize() { + return _FlexUtils_mjs__WEBPACK_IMPORTED_MODULE_1__["default"].getAxisLayoutSize(this.item, !this.ctr._horizontal); + } + + _resizeCrossAxis(size) { + return _FlexUtils_mjs__WEBPACK_IMPORTED_MODULE_1__["default"].resizeAxis(this.item, !this.ctr._horizontal, size); + } + + _resizeMainAxis(size) { + return _FlexUtils_mjs__WEBPACK_IMPORTED_MODULE_1__["default"].resizeAxis(this.item, this.ctr._horizontal, size); + } + + _getMainAxisPadding() { + return _FlexUtils_mjs__WEBPACK_IMPORTED_MODULE_1__["default"].getTotalPadding(this.item, this.ctr._horizontal); + } + + _getCrossAxisPadding() { + return _FlexUtils_mjs__WEBPACK_IMPORTED_MODULE_1__["default"].getTotalPadding(this.item, !this.ctr._horizontal); + } + + _getMainAxisMargin() { + return _FlexUtils_mjs__WEBPACK_IMPORTED_MODULE_1__["default"].getTotalMargin(this.item, this.ctr._horizontal); + } + + _getCrossAxisMargin() { + return _FlexUtils_mjs__WEBPACK_IMPORTED_MODULE_1__["default"].getTotalMargin(this.item, !this.ctr._horizontal); + } + + _getHorizontalMarginOffset() { + return _FlexUtils_mjs__WEBPACK_IMPORTED_MODULE_1__["default"].getMarginOffset(this.item, true); + } + + _getVerticalMarginOffset() { + return _FlexUtils_mjs__WEBPACK_IMPORTED_MODULE_1__["default"].getMarginOffset(this.item, false); + } + + _getMainAxisMinSizeWithPaddingAndMargin() { + return this._getMainAxisMinSize() + this._getMainAxisPadding() + this._getMainAxisMargin(); + } + + _getCrossAxisMinSizeWithPaddingAndMargin() { + return this._getCrossAxisMinSize() + this._getCrossAxisPadding() + this._getCrossAxisMargin(); + } + + _getMainAxisLayoutSizeWithPaddingAndMargin() { + return this._getMainAxisLayoutSize() + this._getMainAxisPadding() + this._getMainAxisMargin(); + } + + _getCrossAxisLayoutSizeWithPaddingAndMargin() { + return this._getCrossAxisLayoutSize() + this._getCrossAxisPadding() + this._getCrossAxisMargin(); + } + + _hasFixedCrossAxisSize() { + return !_FlexUtils_mjs__WEBPACK_IMPORTED_MODULE_1__["default"].isZeroAxisSize(this.item, !this.ctr._horizontal); + } + + _hasRelCrossAxisSize() { + return !!(this.ctr._horizontal ? this.item.funcH : this.item.funcW); + } + +} + + +FlexItem.SHRINK_AUTO = -1; + + +/***/ }), + +/***/ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/flex/FlexTarget.mjs": +/*!***************************************************************************************************!*\ + !*** ./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/flex/FlexTarget.mjs ***! + \***************************************************************************************************/ +/*! exports provided: default */ +/***/ (function(__webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return FlexTarget; }); +/* harmony import */ var _FlexContainer_mjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./FlexContainer.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/flex/FlexContainer.mjs"); +/* harmony import */ var _FlexItem_mjs__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./FlexItem.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/flex/FlexItem.mjs"); +/* harmony import */ var _FlexUtils_mjs__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./FlexUtils.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/flex/FlexUtils.mjs"); +/* + * If not stated otherwise in this file or this component's LICENSE file the + * following copyright and licenses apply: + * + * Copyright 2020 Metrological + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + + + +/** + * This is the connection between the render tree with the layout tree of this flex container/item. + */ +class FlexTarget { + + constructor(target) { + this._target = target; + + /** + * Possible values (only in case of container): + * bit 0: has changed or contains items with changes + * bit 1: width changed + * bit 2: height changed + */ + this._recalc = 0; + + this._enabled = false; + + this.x = 0; + this.y = 0; + this.w = 0; + this.h = 0; + + this._originalX = 0; + this._originalY = 0; + this._originalWidth = 0; + this._originalHeight = 0; + + this._flex = null; + this._flexItem = null; + this._flexItemDisabled = false; + + this._items = null; + } + + get flexLayout() { + return this.flex ? this.flex._layout : null; + } + + layoutFlexTree() { + if (this.isFlexEnabled() && this.isChanged()) { + this.flexLayout.layoutTree(); + } + } + + get target() { + return this._target; + } + + get flex() { + return this._flex; + } + + set flex(v) { + if (!v) { + if (this.isFlexEnabled()) { + this._disableFlex(); + } + } else { + if (!this.isFlexEnabled()) { + this._enableFlex(); + } + this._flex.patch(v); + } + } + + get flexItem() { + if (this._flexItemDisabled) { + return false; + } + this._ensureFlexItem(); + return this._flexItem; + } + + set flexItem(v) { + if (v === false) { + if (!this._flexItemDisabled) { + const parent = this.flexParent; + this._flexItemDisabled = true; + this._checkEnabled(); + if (parent) { + parent._clearFlexItemsCache(); + parent.changedContents(); + } + } + } else { + this._ensureFlexItem(); + + this._flexItem.patch(v); + + if (this._flexItemDisabled) { + this._flexItemDisabled = false; + this._checkEnabled(); + const parent = this.flexParent; + if (parent) { + parent._clearFlexItemsCache(); + parent.changedContents(); + } + } + } + } + + _enableFlex() { + this._flex = new _FlexContainer_mjs__WEBPACK_IMPORTED_MODULE_0__["default"](this); + this._checkEnabled(); + this.changedDimensions(); + this._enableChildrenAsFlexItems(); + } + + _disableFlex() { + this.changedDimensions(); + this._flex = null; + this._checkEnabled(); + this._disableChildrenAsFlexItems(); + } + + _enableChildrenAsFlexItems() { + const children = this._target._children; + if (children) { + for (let i = 0, n = children.length; i < n; i++) { + const child = children[i]; + child.layout._enableFlexItem(); + } + } + } + + _disableChildrenAsFlexItems() { + const children = this._target._children; + if (children) { + for (let i = 0, n = children.length; i < n; i++) { + const child = children[i]; + child.layout._disableFlexItem(); + } + } + } + + _enableFlexItem() { + this._ensureFlexItem(); + const flexParent = this._target._parent._layout; + this._flexItem.ctr = flexParent._flex; + flexParent.changedContents(); + this._checkEnabled(); + } + + _disableFlexItem() { + if (this._flexItem) { + this._flexItem.ctr = null; + } + + // We keep the flexItem object because it may contain custom settings. + this._checkEnabled(); + + // Offsets have been changed. We can't recover them, so we'll just clear them instead. + this._resetOffsets(); + } + + _resetOffsets() { + this.x = 0; + this.y = 0; + } + + _ensureFlexItem() { + if (!this._flexItem) { + this._flexItem = new _FlexItem_mjs__WEBPACK_IMPORTED_MODULE_1__["default"](this); + } + } + + _checkEnabled() { + const enabled = this.isEnabled(); + if (this._enabled !== enabled) { + if (enabled) { + this._enable(); + } else { + this._disable(); + } + this._enabled = enabled; + } + } + + _enable() { + this._setupTargetForFlex(); + this._target.enableFlexLayout(); + } + + _disable() { + this._restoreTargetToNonFlex(); + this._target.disableFlexLayout(); + } + + isEnabled() { + return this.isFlexEnabled() || this.isFlexItemEnabled(); + } + + isFlexEnabled() { + return this._flex !== null; + } + + isFlexItemEnabled() { + return this.flexParent !== null; + } + + _restoreTargetToNonFlex() { + const target = this._target; + target.x = this._originalX; + target.y = this._originalY; + target.setDimensions(this._originalWidth, this._originalHeight); + } + + _setupTargetForFlex() { + const target = this._target; + this._originalX = target._x; + this._originalY = target._y; + this._originalWidth = target._w; + this._originalHeight = target._h; + } + + setParent(from, to) { + if (from && from.isFlexContainer()) { + from._layout._changedChildren(); + } + + if (to && to.isFlexContainer()) { + this._enableFlexItem(); + to._layout._changedChildren(); + } + this._checkEnabled(); + } + + get flexParent() { + if (this._flexItemDisabled) { + return null; + } + + const parent = this._target._parent; + if (parent && parent.isFlexContainer()) { + return parent._layout; + } + return null; + } + + setVisible(v) { + const parent = this.flexParent; + if (parent) { + parent._changedChildren(); + } + } + + get items() { + if (!this._items) { + this._items = this._getFlexItems(); + } + return this._items; + } + + _getFlexItems() { + const items = []; + const children = this._target._children; + if (children) { + for (let i = 0, n = children.length; i < n; i++) { + const item = children[i]; + if (item.visible) { + if (item.isFlexItem()) { + items.push(item.layout); + } + } + } + } + return items; + } + + _changedChildren() { + this._clearFlexItemsCache(); + this.changedContents(); + } + + _clearFlexItemsCache() { + this._items = null; + } + + setLayout(x, y, w, h) { + let originalX = this._originalX; + let originalY = this._originalY; + if (this.funcX) { + originalX = this.funcX(_FlexUtils_mjs__WEBPACK_IMPORTED_MODULE_2__["default"].getParentAxisSizeWithPadding(this, true)); + } + if (this.funcY) { + originalY = this.funcY(_FlexUtils_mjs__WEBPACK_IMPORTED_MODULE_2__["default"].getParentAxisSizeWithPadding(this, false)); + } + + if (this.isFlexItemEnabled()) { + this.target.setLayout(x + originalX, y + originalY, w, h); + } else { + // Reuse the x,y 'settings'. + this.target.setLayout(originalX, originalY, w, h); + } + } + + changedDimensions(changeWidth = true, changeHeight = true) { + this._updateRecalc(changeWidth, changeHeight); + } + + changedContents() { + this._updateRecalc(); + } + + forceLayout() { + this._updateRecalc(); + } + + isChanged() { + return this._recalc > 0; + } + + _updateRecalc(changeExternalWidth = false, changeExternalHeight = false) { + if (this.isFlexEnabled()) { + const layout = this._flex._layout; + + // When something internal changes, it can have effect on the external dimensions. + changeExternalWidth = changeExternalWidth || layout.isAxisFitToContents(true); + changeExternalHeight = changeExternalHeight || layout.isAxisFitToContents(false); + } + + const recalc = 1 + (changeExternalWidth ? 2 : 0) + (changeExternalHeight ? 4 : 0); + const newRecalcFlags = this.getNewRecalcFlags(recalc); + this._recalc |= recalc; + if (newRecalcFlags > 1) { + if (this.flexParent) { + this.flexParent._updateRecalcBottomUp(recalc); + } else { + this._target.triggerLayout(); + } + } else { + this._target.triggerLayout(); + } + } + + getNewRecalcFlags(flags) { + return (7 - this._recalc) & flags; + } + + _updateRecalcBottomUp(childRecalc) { + const newRecalc = this._getRecalcFromChangedChildRecalc(childRecalc); + const newRecalcFlags = this.getNewRecalcFlags(newRecalc); + this._recalc |= newRecalc; + if (newRecalcFlags > 1) { + const flexParent = this.flexParent; + if (flexParent) { + flexParent._updateRecalcBottomUp(newRecalc); + } else { + this._target.triggerLayout(); + } + } else { + this._target.triggerLayout(); + } + } + + _getRecalcFromChangedChildRecalc(childRecalc) { + const layout = this._flex._layout; + + const mainAxisRecalcFlag = layout._horizontal ? 1 : 2; + const crossAxisRecalcFlag = layout._horizontal ? 2 : 1; + + const crossAxisDimensionsChangedInChild = (childRecalc & crossAxisRecalcFlag); + if (!crossAxisDimensionsChangedInChild) { + const mainAxisDimensionsChangedInChild = (childRecalc & mainAxisRecalcFlag); + if (mainAxisDimensionsChangedInChild) { + const mainAxisIsWrapping = layout.isWrapping(); + if (mainAxisIsWrapping) { + const crossAxisIsFitToContents = layout.isCrossAxisFitToContents(); + if (crossAxisIsFitToContents) { + // Special case: due to wrapping, the cross axis size may be changed. + childRecalc += crossAxisRecalcFlag; + } + } + } + } + + let isWidthDynamic = layout.isAxisFitToContents(true); + let isHeightDynamic = layout.isAxisFitToContents(false); + + if (layout.shrunk) { + // If during previous layout this container was 'shrunk', any changes may change the 'min axis size' of the + // contents, leading to a different axis size on this container even when it was not 'fit to contents'. + if (layout._horizontal) { + isWidthDynamic = true; + } else { + isHeightDynamic = true; + } + } + + const localRecalc = 1 + (isWidthDynamic ? 2 : 0) + (isHeightDynamic ? 4 : 0); + + const combinedRecalc = childRecalc & localRecalc; + return combinedRecalc; + } + + get recalc() { + return this._recalc; + } + + clearRecalcFlag() { + this._recalc = 0; + } + + enableLocalRecalcFlag() { + this._recalc = 1; + } + + get originalX() { + return this._originalX; + } + + setOriginalXWithoutUpdatingLayout(v) { + this._originalX = v; + } + + get originalY() { + return this._originalY; + } + + setOriginalYWithoutUpdatingLayout(v) { + this._originalY = v; + } + + get originalWidth() { + return this._originalWidth; + } + + set originalWidth(v) { + if (this._originalWidth !== v) { + this._originalWidth = v; + this.changedDimensions(true, false); + } + } + + get originalHeight() { + return this._originalHeight; + } + + set originalHeight(v) { + if (this._originalHeight !== v) { + this._originalHeight = v; + this.changedDimensions(false, true); + } + } + + get funcX() { + return this._target.funcX; + } + + get funcY() { + return this._target.funcY; + } + + get funcW() { + return this._target.funcW; + } + + get funcH() { + return this._target.funcH; + } +} + + +/***/ }), + +/***/ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/flex/FlexUtils.mjs": +/*!**************************************************************************************************!*\ + !*** ./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/flex/FlexUtils.mjs ***! + \**************************************************************************************************/ +/*! exports provided: default */ +/***/ (function(__webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return FlexUtils; }); +/* + * If not stated otherwise in this file or this component's LICENSE file the + * following copyright and licenses apply: + * + * Copyright 2020 Metrological + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +class FlexUtils { + + static getParentAxisSizeWithPadding(item, horizontal) { + const target = item.target; + const parent = target.getParent(); + if (!parent) { + return 0; + } else { + const flexParent = item.flexParent; + if (flexParent) { + // Use pending layout size. + return this.getAxisLayoutSize(flexParent, horizontal) + this.getTotalPadding(flexParent, horizontal); + } else { + // Use 'absolute' size. + return horizontal ? parent.w : parent.h; + } + } + } + + static getRelAxisSize(item, horizontal) { + if (horizontal) { + if (item.funcW) { + if (this._allowRelAxisSizeFunction(item, true)) { + return item.funcW(this.getParentAxisSizeWithPadding(item, true)); + } else { + return 0; + } + } else { + return item.originalWidth; + } + } else { + if (item.funcH) { + if (this._allowRelAxisSizeFunction(item, false)) { + return item.funcH(this.getParentAxisSizeWithPadding(item, false)); + } else { + return 0; + } + } else { + return item.originalHeight; + } + } + } + + static _allowRelAxisSizeFunction(item, horizontal) { + const flexParent = item.flexParent; + if (flexParent && flexParent._flex._layout.isAxisFitToContents(horizontal)) { + // We don't allow relative width on fit-to-contents because it leads to conflicts. + return false; + } + return true; + } + + static isZeroAxisSize(item, horizontal) { + if (horizontal) { + return !item.originalWidth && !item.funcW; + } else { + return !item.originalHeight && !item.funcH; + } + } + + static getAxisLayoutPos(item, horizontal) { + return horizontal ? item.x : item.y; + } + + static getAxisLayoutSize(item, horizontal) { + return horizontal ? item.w : item.h; + } + + static setAxisLayoutPos(item, horizontal, pos) { + if (horizontal) { + item.x = pos; + } else { + item.y = pos; + } + } + + static setAxisLayoutSize(item, horizontal, size) { + if (horizontal) { + item.w = size; + } else { + item.h = size; + } + } + + static getAxisMinSize(item, horizontal) { + let minSize = this.getPlainAxisMinSize(item, horizontal); + + let flexItemMinSize = 0; + if (item.isFlexItemEnabled()) { + flexItemMinSize = item._flexItem._getMinSizeSetting(horizontal); + } + + const hasLimitedMinSize = (flexItemMinSize > 0); + if (hasLimitedMinSize) { + minSize = Math.max(minSize, flexItemMinSize); + } + return minSize; + } + + static getPlainAxisMinSize(item, horizontal) { + if (item.isFlexEnabled()) { + return item._flex._layout.getAxisMinSize(horizontal); + } else { + const isShrinkable = (item.flexItem.shrink !== 0); + if (isShrinkable) { + return 0; + } else { + return this.getRelAxisSize(item, horizontal); + } + } + } + + static resizeAxis(item, horizontal, size) { + if (item.isFlexEnabled()) { + const isMainAxis = (item._flex._horizontal === horizontal); + if (isMainAxis) { + item._flex._layout.resizeMainAxis(size); + } else { + item._flex._layout.resizeCrossAxis(size); + } + } else { + this.setAxisLayoutSize(item, horizontal, size); + } + } + + + static getPaddingOffset(item, horizontal) { + if (item.isFlexEnabled()) { + const flex = item._flex; + if (horizontal) { + return flex.paddingLeft; + } else { + return flex.paddingTop; + } + } else { + return 0; + } + } + + static getTotalPadding(item, horizontal) { + if (item.isFlexEnabled()) { + const flex = item._flex; + if (horizontal) { + return flex.paddingRight + flex.paddingLeft; + } else { + return flex.paddingTop + flex.paddingBottom; + } + } else { + return 0; + } + } + + static getMarginOffset(item, horizontal) { + const flexItem = item.flexItem; + if (flexItem) { + if (horizontal) { + return flexItem.marginLeft; + } else { + return flexItem.marginTop; + } + } else { + return 0; + } + } + + static getTotalMargin(item, horizontal) { + const flexItem = item.flexItem; + if (flexItem) { + if (horizontal) { + return flexItem.marginRight + flexItem.marginLeft; + } else { + return flexItem.marginTop + flexItem.marginBottom; + } + } else { + return 0; + } + } + +} + + +/***/ }), + +/***/ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/flex/layout/ContentAligner.mjs": +/*!**************************************************************************************************************!*\ + !*** ./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/flex/layout/ContentAligner.mjs ***! + \**************************************************************************************************************/ +/*! exports provided: default */ +/***/ (function(__webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return ContentAligner; }); +/* harmony import */ var _SpacingCalculator_mjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./SpacingCalculator.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/flex/layout/SpacingCalculator.mjs"); +/* + * If not stated otherwise in this file or this component's LICENSE file the + * following copyright and licenses apply: + * + * Copyright 2020 Metrological + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + +class ContentAligner { + + constructor(layout) { + this._layout = layout; + this._totalCrossAxisSize = 0; + } + + get _lines() { + return this._layout._lines; + } + + init() { + this._totalCrossAxisSize = this._getTotalCrossAxisSize(); + } + + align() { + const crossAxisSize = this._layout.crossAxisSize; + const remainingSpace = crossAxisSize - this._totalCrossAxisSize; + + const {spacingBefore, spacingBetween} = this._getSpacing(remainingSpace); + + const lines = this._lines; + + const mode = this._layout._flexContainer.alignContent; + let growSize = 0; + if (mode === "stretch" && lines.length && (remainingSpace > 0)) { + growSize = remainingSpace / lines.length; + } + + let currentPos = spacingBefore; + for (let i = 0, n = lines.length; i < n; i++) { + const crossAxisLayoutOffset = currentPos; + const aligner = lines[i].createItemAligner(); + + let finalCrossAxisLayoutSize = lines[i].crossAxisLayoutSize + growSize; + + aligner.setCrossAxisLayoutSize(finalCrossAxisLayoutSize); + aligner.setCrossAxisLayoutOffset(crossAxisLayoutOffset); + + aligner.align(); + + if (aligner.recursiveResizeOccured) { + lines[i].setItemPositions(); + } + + currentPos += finalCrossAxisLayoutSize; + currentPos += spacingBetween; + } + } + + get totalCrossAxisSize() { + return this._totalCrossAxisSize; + } + + _getTotalCrossAxisSize() { + const lines = this._lines; + let total = 0; + for (let i = 0, n = lines.length; i < n; i++) { + const line = lines[i]; + total += line.crossAxisLayoutSize; + } + return total; + } + + _getSpacing(remainingSpace) { + const mode = this._layout._flexContainer.alignContent; + const numberOfItems = this._lines.length; + return _SpacingCalculator_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].getSpacing(mode, numberOfItems, remainingSpace); + } + +} + + +/***/ }), + +/***/ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/flex/layout/FlexLayout.mjs": +/*!**********************************************************************************************************!*\ + !*** ./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/flex/layout/FlexLayout.mjs ***! + \**********************************************************************************************************/ +/*! exports provided: default */ +/***/ (function(__webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return FlexLayout; }); +/* harmony import */ var _ContentAligner_mjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./ContentAligner.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/flex/layout/ContentAligner.mjs"); +/* harmony import */ var _FlexUtils_mjs__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../FlexUtils.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/flex/FlexUtils.mjs"); +/* harmony import */ var _LineLayouter_mjs__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./LineLayouter.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/flex/layout/LineLayouter.mjs"); +/* harmony import */ var _ItemCoordinatesUpdater_mjs__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./ItemCoordinatesUpdater.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/flex/layout/ItemCoordinatesUpdater.mjs"); +/* + * If not stated otherwise in this file or this component's LICENSE file the + * following copyright and licenses apply: + * + * Copyright 2020 Metrological + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + + + + +/** + * Layouts a flex container (and descendants). + */ +class FlexLayout { + + constructor(flexContainer) { + this._flexContainer = flexContainer; + + this._lineLayouter = new _LineLayouter_mjs__WEBPACK_IMPORTED_MODULE_2__["default"](this); + + this._resizingMainAxis = false; + this._resizingCrossAxis = false; + + this._cachedMainAxisSizeAfterLayout = 0; + this._cachedCrossAxisSizeAfterLayout = 0; + + this._shrunk = false; + } + + get shrunk() { + return this._shrunk; + } + + get recalc() { + return this.item.recalc; + } + + layoutTree() { + const isSubTree = (this.item.flexParent !== null); + if (isSubTree) { + // Use the dimensions set by the parent flex tree. + this._updateSubTreeLayout(); + } else { + this.updateTreeLayout(); + } + this.updateItemCoords(); + } + + updateTreeLayout() { + if (this.recalc) { + this._performUpdateLayoutTree(); + } else { + this._performUpdateLayoutTreeFromCache(); + } + } + + _performUpdateLayoutTree() { + this._setInitialAxisSizes(); + this._layoutAxes(); + this._refreshLayoutCache(); + } + + _refreshLayoutCache() { + this._cachedMainAxisSizeAfterLayout = this.mainAxisSize; + this._cachedCrossAxisSizeAfterLayout = this.crossAxisSize; + } + + _performUpdateLayoutTreeFromCache() { + const sizeMightHaveChanged = (this.item.funcW || this.item.funcH); + if (sizeMightHaveChanged) { + // Update after all. + this.item.enableLocalRecalcFlag(); + this._performUpdateLayoutTree(); + } else { + this.mainAxisSize = this._cachedMainAxisSizeAfterLayout; + this.crossAxisSize = this._cachedCrossAxisSizeAfterLayout; + } + } + + updateItemCoords() { + const updater = new _ItemCoordinatesUpdater_mjs__WEBPACK_IMPORTED_MODULE_3__["default"](this); + updater.finalize(); + } + + _updateSubTreeLayout() { + // The dimensions of this container are guaranteed not to have changed. + // That's why we can safely 'reuse' those and re-layout the contents. + const crossAxisSize = this.crossAxisSize; + this._layoutMainAxis(); + this.performResizeCrossAxis(crossAxisSize); + } + + _setInitialAxisSizes() { + if (this.item.isFlexItemEnabled()) { + this.item.flexItem._resetLayoutSize(); + } else { + this.mainAxisSize = this._getMainAxisBasis(); + this.crossAxisSize = this._getCrossAxisBasis(); + } + this._resizingMainAxis = false; + this._resizingCrossAxis = false; + this._shrunk = false; + } + + _layoutAxes() { + this._layoutMainAxis(); + this._layoutCrossAxis(); + } + + /** + * @pre mainAxisSize should exclude padding. + */ + _layoutMainAxis() { + this._layoutLines(); + this._fitMainAxisSizeToContents(); + } + + _layoutLines() { + this._lineLayouter.layoutLines(); + } + + get _lines() { + return this._lineLayouter.lines; + } + + _fitMainAxisSizeToContents() { + if (!this._resizingMainAxis) { + if (this.isMainAxisFitToContents()) { + this.mainAxisSize = this._lineLayouter.mainAxisContentSize; + } + } + } + + /** + * @pre crossAxisSize should exclude padding. + */ + _layoutCrossAxis() { + const aligner = new _ContentAligner_mjs__WEBPACK_IMPORTED_MODULE_0__["default"](this); + aligner.init(); + this._totalCrossAxisSize = aligner.totalCrossAxisSize; + this._fitCrossAxisSizeToContents(); + aligner.align(); + } + + _fitCrossAxisSizeToContents() { + if (!this._resizingCrossAxis) { + if (this.isCrossAxisFitToContents()) { + this.crossAxisSize = this._totalCrossAxisSize; + } + } + } + + isWrapping() { + return this._flexContainer.wrap; + } + + isAxisFitToContents(horizontal) { + if (this._horizontal === horizontal) { + return this.isMainAxisFitToContents(); + } else { + return this.isCrossAxisFitToContents(); + } + } + + isMainAxisFitToContents() { + return !this.isWrapping() && !this._hasFixedMainAxisBasis(); + } + + isCrossAxisFitToContents() { + return !this._hasFixedCrossAxisBasis(); + } + + _hasFixedMainAxisBasis() { + return !_FlexUtils_mjs__WEBPACK_IMPORTED_MODULE_1__["default"].isZeroAxisSize(this.item, this._horizontal); + } + + _hasFixedCrossAxisBasis() { + return !_FlexUtils_mjs__WEBPACK_IMPORTED_MODULE_1__["default"].isZeroAxisSize(this.item, !this._horizontal); + } + + getAxisMinSize(horizontal) { + if (this._horizontal === horizontal) { + return this._getMainAxisMinSize(); + } else { + return this._getCrossAxisMinSize(); + } + } + + _getMainAxisMinSize() { + return this._lineLayouter.mainAxisMinSize; + } + + _getCrossAxisMinSize() { + return this._lineLayouter.crossAxisMinSize; + } + + resizeMainAxis(size) { + if (this.mainAxisSize !== size) { + if (this.recalc > 0) { + this.performResizeMainAxis(size); + } else { + if (this._checkValidCacheMainAxisResize()) { + this.mainAxisSize = size; + this._fitCrossAxisSizeToContents(); + } else { + // Cache miss. + this.item.enableLocalRecalcFlag(); + this.performResizeMainAxis(size); + } + } + } + } + + _checkValidCacheMainAxisResize(size) { + const isFinalMainAxisSize = (size === this.targetMainAxisSize); + if (isFinalMainAxisSize) { + return true; + } + const canIgnoreCacheMiss = !this.isCrossAxisFitToContents(); + if (canIgnoreCacheMiss) { + // Allow other main axis resizes and check if final resize matches the target main axis size + // (ItemCoordinatesUpdater). + return true; + } + return false; + } + + performResizeMainAxis(size) { + const isShrinking = (size < this.mainAxisSize); + this._shrunk = isShrinking; + + this.mainAxisSize = size; + + this._resizingMainAxis = true; + this._layoutAxes(); + this._resizingMainAxis = false; + } + + resizeCrossAxis(size) { + if (this.crossAxisSize !== size) { + if (this.recalc > 0) { + this.performResizeCrossAxis(size); + } else { + this.crossAxisSize = size; + } + } + } + + performResizeCrossAxis(size) { + this.crossAxisSize = size; + + this._resizingCrossAxis = true; + this._layoutCrossAxis(); + this._resizingCrossAxis = false; + } + + get targetMainAxisSize() { + return this._horizontal ? this.item.target.w : this.item.target.h; + } + + get targetCrossAxisSize() { + return this._horizontal ? this.item.target.h : this.item.target.w; + } + + getParentFlexContainer() { + return this.item.isFlexItemEnabled() ? this.item.flexItem.ctr : null; + } + + _getHorizontalPadding() { + return _FlexUtils_mjs__WEBPACK_IMPORTED_MODULE_1__["default"].getTotalPadding(this.item, true); + } + + _getVerticalPadding() { + return _FlexUtils_mjs__WEBPACK_IMPORTED_MODULE_1__["default"].getTotalPadding(this.item, false); + } + + _getHorizontalPaddingOffset() { + return _FlexUtils_mjs__WEBPACK_IMPORTED_MODULE_1__["default"].getPaddingOffset(this.item, true); + } + + _getVerticalPaddingOffset() { + return _FlexUtils_mjs__WEBPACK_IMPORTED_MODULE_1__["default"].getPaddingOffset(this.item, false); + } + + _getMainAxisBasis() { + return _FlexUtils_mjs__WEBPACK_IMPORTED_MODULE_1__["default"].getRelAxisSize(this.item, this._horizontal); + } + + _getCrossAxisBasis() { + return _FlexUtils_mjs__WEBPACK_IMPORTED_MODULE_1__["default"].getRelAxisSize(this.item, !this._horizontal); + } + + get _horizontal() { + return this._flexContainer._horizontal; + } + + get _reverse() { + return this._flexContainer._reverse; + } + + get item() { + return this._flexContainer.item; + } + + get items() { + return this.item.items; + } + + get resizingMainAxis() { + return this._resizingMainAxis; + } + + get resizingCrossAxis() { + return this._resizingCrossAxis; + } + + get numberOfItems() { + return this.items.length; + } + + get mainAxisSize() { + return _FlexUtils_mjs__WEBPACK_IMPORTED_MODULE_1__["default"].getAxisLayoutSize(this.item, this._horizontal); + } + + get crossAxisSize() { + return _FlexUtils_mjs__WEBPACK_IMPORTED_MODULE_1__["default"].getAxisLayoutSize(this.item, !this._horizontal); + } + + set mainAxisSize(v) { + _FlexUtils_mjs__WEBPACK_IMPORTED_MODULE_1__["default"].setAxisLayoutSize(this.item, this._horizontal, v); + } + + set crossAxisSize(v) { + _FlexUtils_mjs__WEBPACK_IMPORTED_MODULE_1__["default"].setAxisLayoutSize(this.item, !this._horizontal, v); + } + +} + + +/***/ }), + +/***/ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/flex/layout/ItemCoordinatesUpdater.mjs": +/*!**********************************************************************************************************************!*\ + !*** ./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/flex/layout/ItemCoordinatesUpdater.mjs ***! + \**********************************************************************************************************************/ +/*! exports provided: default */ +/***/ (function(__webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return ItemCoordinatesUpdater; }); +/* harmony import */ var _FlexUtils_mjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../FlexUtils.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/flex/FlexUtils.mjs"); +/* + * If not stated otherwise in this file or this component's LICENSE file the + * following copyright and licenses apply: + * + * Copyright 2020 Metrological + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + +class ItemCoordinatesUpdater { + + constructor(layout) { + this._layout = layout; + this._isReverse = this._flexContainer._reverse; + this._horizontalPaddingOffset = this._layout._getHorizontalPaddingOffset(); + this._verticalPaddingOffset = this._layout._getVerticalPaddingOffset(); + } + + get _flexContainer() { + return this._layout._flexContainer; + } + + finalize() { + const parentFlex = this._layout.getParentFlexContainer(); + if (parentFlex) { + // We must update it from the parent to set padding offsets and reverse position. + const updater = new ItemCoordinatesUpdater(parentFlex._layout); + updater._finalizeItemAndChildren(this._flexContainer.item); + } else { + this._finalizeRoot(); + this._finalizeItems(); + } + } + + _finalizeRoot() { + const item = this._flexContainer.item; + let x = _FlexUtils_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].getAxisLayoutPos(item, true); + let y = _FlexUtils_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].getAxisLayoutPos(item, false); + let w = _FlexUtils_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].getAxisLayoutSize(item, true); + let h = _FlexUtils_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].getAxisLayoutSize(item, false); + + w += this._layout._getHorizontalPadding(); + h += this._layout._getVerticalPadding(); + + item.clearRecalcFlag(); + + item.setLayout(x, y, w, h); + } + + _finalizeItems() { + const items = this._layout.items; + for (let i = 0, n = items.length; i < n; i++) { + const item = items[i]; + const validCache = this._validateItemCache(item); + + // Notice that we must also finalize a cached items, as it's coordinates may have changed. + this._finalizeItem(item); + + if (!validCache) { + this._finalizeItemChildren(item); + } + } + } + + _validateItemCache(item) { + if (item.recalc === 0) { + if (item.isFlexEnabled()) { + const layout = item._flex._layout; + + const dimensionsMatchPreviousResult = (item.w === item.target.w && item.h === item.target.h); + if (dimensionsMatchPreviousResult) { + // Cache is valid. + return true; + } else { + const crossAxisSize = layout.crossAxisSize; + layout.performResizeMainAxis(layout.mainAxisSize); + layout.performResizeCrossAxis(crossAxisSize); + } + } + } + return false; + } + + _finalizeItemAndChildren(item) { + this._finalizeItem(item); + this._finalizeItemChildren(item); + } + + _finalizeItem(item) { + if (this._isReverse) { + this._reverseMainAxisLayoutPos(item); + } + + let x = _FlexUtils_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].getAxisLayoutPos(item, true); + let y = _FlexUtils_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].getAxisLayoutPos(item, false); + let w = _FlexUtils_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].getAxisLayoutSize(item, true); + let h = _FlexUtils_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].getAxisLayoutSize(item, false); + + x += this._horizontalPaddingOffset; + y += this._verticalPaddingOffset; + + const flex = item.flex; + if (flex) { + w += item._flex._layout._getHorizontalPadding(); + h += item._flex._layout._getVerticalPadding(); + } + + const flexItem = item.flexItem; + if (flexItem) { + x += flexItem._getHorizontalMarginOffset(); + y += flexItem._getVerticalMarginOffset(); + } + + item.clearRecalcFlag(); + item.setLayout(x, y, w, h); + } + + _finalizeItemChildren(item) { + const flex = item._flex; + if (flex) { + const updater = new ItemCoordinatesUpdater(flex._layout); + updater._finalizeItems(); + } + } + + _reverseMainAxisLayoutPos(item) { + const endPos = (item.flexItem._getMainAxisLayoutPos() + item.flexItem._getMainAxisLayoutSizeWithPaddingAndMargin()); + const reversedPos = this._layout.mainAxisSize - endPos; + item.flexItem._setMainAxisLayoutPos(reversedPos); + } + +} + + +/***/ }), + +/***/ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/flex/layout/LineLayouter.mjs": +/*!************************************************************************************************************!*\ + !*** ./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/flex/layout/LineLayouter.mjs ***! + \************************************************************************************************************/ +/*! exports provided: default */ +/***/ (function(__webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return LineLayouter; }); +/* harmony import */ var _line_LineLayout_mjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./line/LineLayout.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/flex/layout/line/LineLayout.mjs"); +/* + * If not stated otherwise in this file or this component's LICENSE file the + * following copyright and licenses apply: + * + * Copyright 2020 Metrological + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + +/** + * Distributes items over layout lines. + */ +class LineLayouter { + + constructor(layout) { + this._layout = layout; + this._mainAxisMinSize = -1; + this._crossAxisMinSize = -1; + this._mainAxisContentSize = 0; + } + + get lines() { + return this._lines; + } + + get mainAxisMinSize() { + if (this._mainAxisMinSize === -1) { + this._mainAxisMinSize = this._getMainAxisMinSize(); + } + return this._mainAxisMinSize; + } + + get crossAxisMinSize() { + if (this._crossAxisMinSize === -1) { + this._crossAxisMinSize = this._getCrossAxisMinSize(); + } + return this._crossAxisMinSize; + } + + get mainAxisContentSize() { + return this._mainAxisContentSize; + } + + layoutLines() { + this._setup(); + const items = this._layout.items; + const wrap = this._layout.isWrapping(); + + let startIndex = 0; + let i; + const n = items.length; + for (i = 0; i < n; i++) { + const item = items[i]; + + this._layoutFlexItem(item); + + // Get predicted main axis size. + const itemMainAxisSize = item.flexItem._getMainAxisLayoutSizeWithPaddingAndMargin(); + + if (wrap && (i > startIndex)) { + const isOverflowing = (this._curMainAxisPos + itemMainAxisSize > this._mainAxisSize); + if (isOverflowing) { + this._layoutLine(startIndex, i - 1); + this._curMainAxisPos = 0; + startIndex = i; + } + } + + this._addToMainAxisPos(itemMainAxisSize); + } + + if (startIndex < i) { + this._layoutLine(startIndex, i - 1); + } + } + + _layoutFlexItem(item) { + if (item.isFlexEnabled()) { + item.flexLayout.updateTreeLayout(); + } else { + item.flexItem._resetLayoutSize(); + } + } + + _setup() { + this._mainAxisSize = this._layout.mainAxisSize; + this._curMainAxisPos = 0; + this._maxMainAxisPos = 0; + this._lines = []; + + this._mainAxisMinSize = -1; + this._crossAxisMinSize = -1; + this._mainAxisContentSize = 0; + } + + _addToMainAxisPos(itemMainAxisSize) { + this._curMainAxisPos += itemMainAxisSize; + if (this._curMainAxisPos > this._maxMainAxisPos) { + this._maxMainAxisPos = this._curMainAxisPos; + } + } + + _layoutLine(startIndex, endIndex) { + const availableSpace = this._getAvailableMainAxisLayoutSpace(); + const line = new _line_LineLayout_mjs__WEBPACK_IMPORTED_MODULE_0__["default"](this._layout, startIndex, endIndex, availableSpace); + line.performLayout(); + this._lines.push(line); + + if (this._mainAxisContentSize === 0 || (this._curMainAxisPos > this._mainAxisContentSize)) { + this._mainAxisContentSize = this._curMainAxisPos; + } + } + + _getAvailableMainAxisLayoutSpace() { + if (!this._layout.resizingMainAxis && this._layout.isMainAxisFitToContents()) { + return 0; + } else { + return this._mainAxisSize - this._curMainAxisPos; + } + } + + _getCrossAxisMinSize() { + let crossAxisMinSize = 0; + const items = this._layout.items; + for (let i = 0, n = items.length; i < n; i++) { + const item = items[i]; + const itemCrossAxisMinSize = item.flexItem._getCrossAxisMinSizeWithPaddingAndMargin(); + crossAxisMinSize = Math.max(crossAxisMinSize, itemCrossAxisMinSize); + } + return crossAxisMinSize; + } + + _getMainAxisMinSize() { + if (this._lines.length === 1) { + return this._lines[0].getMainAxisMinSize(); + } else { + // Wrapping lines: specified width is used as min width (in accordance to W3C flexbox). + return this._layout.mainAxisSize; + } + } + +} + + +/***/ }), + +/***/ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/flex/layout/SpacingCalculator.mjs": +/*!*****************************************************************************************************************!*\ + !*** ./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/flex/layout/SpacingCalculator.mjs ***! + \*****************************************************************************************************************/ +/*! exports provided: default */ +/***/ (function(__webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return SpacingCalculator; }); +/* + * If not stated otherwise in this file or this component's LICENSE file the + * following copyright and licenses apply: + * + * Copyright 2020 Metrological + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +class SpacingCalculator { + + static getSpacing(mode, numberOfItems, remainingSpace) { + const itemGaps = (numberOfItems - 1); + let spacePerGap; + + let spacingBefore, spacingBetween; + + switch(mode) { + case "flex-start": + spacingBefore = 0; + spacingBetween = 0; + break; + case "flex-end": + spacingBefore = remainingSpace; + spacingBetween = 0; + break; + case "center": + spacingBefore = remainingSpace / 2; + spacingBetween = 0; + break; + case "space-between": + spacingBefore = 0; + spacingBetween = Math.max(0, remainingSpace) / itemGaps; + break; + case "space-around": + if (remainingSpace < 0) { + return this.getSpacing("center", numberOfItems, remainingSpace); + } else { + spacePerGap = remainingSpace / (itemGaps + 1); + spacingBefore = 0.5 * spacePerGap; + spacingBetween = spacePerGap; + } + break; + case "space-evenly": + if (remainingSpace < 0) { + return this.getSpacing("center", numberOfItems, remainingSpace); + } else { + spacePerGap = remainingSpace / (itemGaps + 2); + spacingBefore = spacePerGap; + spacingBetween = spacePerGap; + } + break; + case "stretch": + spacingBefore = 0; + spacingBetween = 0; + break; + default: + throw new Error("Unknown mode: " + mode); + } + + return {spacingBefore, spacingBetween} + } + +} + + +/***/ }), + +/***/ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/flex/layout/line/ItemAligner.mjs": +/*!****************************************************************************************************************!*\ + !*** ./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/flex/layout/line/ItemAligner.mjs ***! + \****************************************************************************************************************/ +/*! exports provided: default */ +/***/ (function(__webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return ItemAligner; }); +/* + * If not stated otherwise in this file or this component's LICENSE file the + * following copyright and licenses apply: + * + * Copyright 2020 Metrological + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +class ItemAligner { + + constructor(line) { + this._line = line; + this._crossAxisLayoutSize = 0; + this._crossAxisLayoutOffset = 0; + this._alignItemsSetting = null; + this._recursiveResizeOccured = false; + this._isCrossAxisFitToContents = false; + } + + get _layout() { + return this._line._layout; + } + + get _flexContainer() { + return this._layout._flexContainer; + } + + setCrossAxisLayoutSize(size) { + this._crossAxisLayoutSize = size; + } + + setCrossAxisLayoutOffset(offset) { + this._crossAxisLayoutOffset = offset; + } + + align() { + this._alignItemsSetting = this._flexContainer.alignItems; + + this._isCrossAxisFitToContents = this._layout.isAxisFitToContents(!this._flexContainer._horizontal); + + this._recursiveResizeOccured = false; + const items = this._line.items; + for (let i = this._line.startIndex; i <= this._line.endIndex; i++) { + const item = items[i]; + this._alignItem(item); + } + } + + get recursiveResizeOccured() { + return this._recursiveResizeOccured; + } + + _alignItem(item) { + const flexItem = item.flexItem; + let align = flexItem.alignSelf || this._alignItemsSetting; + + if (align === "stretch" && this._preventStretch(flexItem)) { + align = "flex-start"; + } + + if (align !== "stretch" && !this._isCrossAxisFitToContents) { + if (flexItem._hasRelCrossAxisSize()) { + // As cross axis size might have changed, we need to recalc the relative flex item's size. + flexItem._resetCrossAxisLayoutSize(); + } + } + + switch(align) { + case "flex-start": + this._alignItemFlexStart(flexItem); + break; + case "flex-end": + this._alignItemFlexEnd(flexItem); + break; + case "center": + this._alignItemFlexCenter(flexItem); + break; + case "stretch": + this._alignItemStretch(flexItem); + break; + } + } + + _alignItemFlexStart(flexItem) { + flexItem._setCrossAxisLayoutPos(this._crossAxisLayoutOffset); + } + + _alignItemFlexEnd(flexItem) { + const itemCrossAxisSize = flexItem._getCrossAxisLayoutSizeWithPaddingAndMargin(); + flexItem._setCrossAxisLayoutPos(this._crossAxisLayoutOffset + (this._crossAxisLayoutSize - itemCrossAxisSize)); + } + + _alignItemFlexCenter(flexItem) { + const itemCrossAxisSize = flexItem._getCrossAxisLayoutSizeWithPaddingAndMargin(); + const center = (this._crossAxisLayoutSize - itemCrossAxisSize) / 2; + flexItem._setCrossAxisLayoutPos(this._crossAxisLayoutOffset + center); + } + + _alignItemStretch(flexItem) { + flexItem._setCrossAxisLayoutPos(this._crossAxisLayoutOffset); + + const mainAxisLayoutSizeBeforeResize = flexItem._getMainAxisLayoutSize(); + let size = this._crossAxisLayoutSize - flexItem._getCrossAxisMargin() - flexItem._getCrossAxisPadding(); + + const crossAxisMinSizeSetting = flexItem._getCrossAxisMinSizeSetting(); + if (crossAxisMinSizeSetting > 0) { + size = Math.max(size, crossAxisMinSizeSetting); + } + + const crossAxisMaxSizeSetting = flexItem._getCrossAxisMaxSizeSetting(); + const crossAxisMaxSizeSettingEnabled = (crossAxisMaxSizeSetting > 0); + if (crossAxisMaxSizeSettingEnabled) { + size = Math.min(size, crossAxisMaxSizeSetting); + } + + flexItem._resizeCrossAxis(size); + const mainAxisLayoutSizeAfterResize = flexItem._getMainAxisLayoutSize(); + + const recursiveResize = (mainAxisLayoutSizeAfterResize !== mainAxisLayoutSizeBeforeResize); + if (recursiveResize) { + // Recursive resize can happen when this flex item has the opposite direction than the container + // and is wrapping and auto-sizing. Due to item/content stretching the main axis size of the flex + // item may decrease. If it does so, we must re-justify-content the complete line. + // Notice that we don't account for changes to the (if autosized) main axis size caused by recursive + // resize, which may cause the container's main axis to not shrink to the contents properly. + // This is by design, because if we had re-run the main axis layout, we could run into issues such + // as slow layout or endless loops. + this._recursiveResizeOccured = true; + } + } + + _preventStretch(flexItem) { + const hasFixedCrossAxisSize = flexItem._hasFixedCrossAxisSize(); + const forceStretch = (flexItem.alignSelf === "stretch"); + return hasFixedCrossAxisSize && !forceStretch; + } + +} + + +/***/ }), + +/***/ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/flex/layout/line/ItemPositioner.mjs": +/*!*******************************************************************************************************************!*\ + !*** ./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/flex/layout/line/ItemPositioner.mjs ***! + \*******************************************************************************************************************/ +/*! exports provided: default */ +/***/ (function(__webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return ItemPositioner; }); +/* harmony import */ var _SpacingCalculator_mjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../SpacingCalculator.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/flex/layout/SpacingCalculator.mjs"); +/* + * If not stated otherwise in this file or this component's LICENSE file the + * following copyright and licenses apply: + * + * Copyright 2020 Metrological + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + +class ItemPositioner { + + constructor(lineLayout) { + this._line = lineLayout; + } + + get _layout() { + return this._line._layout; + } + + position() { + const {spacingBefore, spacingBetween} = this._getSpacing(); + + let currentPos = spacingBefore; + + const items = this._line.items; + for (let i = this._line.startIndex; i <= this._line.endIndex; i++) { + const item = items[i]; + + item.flexItem._setMainAxisLayoutPos(currentPos); + currentPos += item.flexItem._getMainAxisLayoutSizeWithPaddingAndMargin(); + currentPos += spacingBetween; + } + } + + _getSpacing() { + const remainingSpace = this._line._availableSpace; + let mode = this._layout._flexContainer.justifyContent; + const numberOfItems = this._line.numberOfItems; + + return _SpacingCalculator_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].getSpacing(mode, numberOfItems, remainingSpace); + } + +} + + +/***/ }), + +/***/ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/flex/layout/line/LineLayout.mjs": +/*!***************************************************************************************************************!*\ + !*** ./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/flex/layout/line/LineLayout.mjs ***! + \***************************************************************************************************************/ +/*! exports provided: default */ +/***/ (function(__webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return LineLayout; }); +/* harmony import */ var _SizeShrinker_mjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./SizeShrinker.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/flex/layout/line/SizeShrinker.mjs"); +/* harmony import */ var _SizeGrower_mjs__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./SizeGrower.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/flex/layout/line/SizeGrower.mjs"); +/* harmony import */ var _ItemPositioner_mjs__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./ItemPositioner.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/flex/layout/line/ItemPositioner.mjs"); +/* harmony import */ var _ItemAligner_mjs__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./ItemAligner.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/flex/layout/line/ItemAligner.mjs"); +/* + * If not stated otherwise in this file or this component's LICENSE file the + * following copyright and licenses apply: + * + * Copyright 2020 Metrological + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + + + + +class LineLayout { + + constructor(layout, startIndex, endIndex, availableSpace) { + this._layout = layout; + this.items = layout.items; + this.startIndex = startIndex; + this.endIndex = endIndex; + this._availableSpace = availableSpace; + } + + performLayout() { + this._setItemSizes(); + this.setItemPositions(); + this._calcLayoutInfo(); + } + + _setItemSizes() { + if (this._availableSpace > 0) { + this._growItemSizes(this._availableSpace); + } else if (this._availableSpace < 0) { + this._shrinkItemSizes(-this._availableSpace); + } + } + + _growItemSizes(amount) { + const grower = new _SizeGrower_mjs__WEBPACK_IMPORTED_MODULE_1__["default"](this); + grower.grow(amount); + this._availableSpace -= grower.getGrownSize(); + } + + _shrinkItemSizes(amount) { + const shrinker = new _SizeShrinker_mjs__WEBPACK_IMPORTED_MODULE_0__["default"](this); + shrinker.shrink(amount); + this._availableSpace += shrinker.getShrunkSize(); + } + + setItemPositions() { + const positioner = new _ItemPositioner_mjs__WEBPACK_IMPORTED_MODULE_2__["default"](this); + positioner.position(); + } + + createItemAligner() { + return new _ItemAligner_mjs__WEBPACK_IMPORTED_MODULE_3__["default"](this); + } + + _calcLayoutInfo() { + this._calcCrossAxisMaxLayoutSize(); + } + + getMainAxisMinSize() { + let mainAxisMinSize = 0; + for (let i = this.startIndex; i <= this.endIndex; i++) { + const item = this.items[i]; + mainAxisMinSize += item.flexItem._getMainAxisMinSizeWithPaddingAndMargin(); + } + return mainAxisMinSize; + } + + get numberOfItems() { + return this.endIndex - this.startIndex + 1; + } + + get crossAxisLayoutSize() { + const noSpecifiedCrossAxisSize = (this._layout.isCrossAxisFitToContents() && !this._layout.resizingCrossAxis); + const shouldFitToContents = (this._layout.isWrapping() || noSpecifiedCrossAxisSize); + if (shouldFitToContents) { + return this._crossAxisMaxLayoutSize; + } else { + return this._layout.crossAxisSize; + } + } + + _calcCrossAxisMaxLayoutSize() { + this._crossAxisMaxLayoutSize = this._getCrossAxisMaxLayoutSize(); + } + + _getCrossAxisMaxLayoutSize() { + let crossAxisMaxSize = 0; + for (let i = this.startIndex; i <= this.endIndex; i++) { + const item = this.items[i]; + crossAxisMaxSize = Math.max(crossAxisMaxSize, item.flexItem._getCrossAxisLayoutSizeWithPaddingAndMargin()); + } + return crossAxisMaxSize; + } + + +} + + +/***/ }), + +/***/ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/flex/layout/line/SizeGrower.mjs": +/*!***************************************************************************************************************!*\ + !*** ./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/flex/layout/line/SizeGrower.mjs ***! + \***************************************************************************************************************/ +/*! exports provided: default */ +/***/ (function(__webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return SizeGrower; }); +/* + * If not stated otherwise in this file or this component's LICENSE file the + * following copyright and licenses apply: + * + * Copyright 2020 Metrological + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +class SizeGrower { + + constructor(line) { + this._line = line; + this._amountRemaining = 0; + this._grownSize = 0; + } + + grow(amount) { + this._grownSize = 0; + + this._amountRemaining = amount; + let totalGrowAmount = this._getTotalGrowAmount(); + if (totalGrowAmount) { + const items = this._line.items; + do { + let amountPerGrow = this._amountRemaining / totalGrowAmount; + for (let i = this._line.startIndex; i <= this._line.endIndex; i++) { + const item = items[i]; + const flexItem = item.flexItem; + const growAmount = flexItem.grow; + const isGrowableItem = (growAmount > 0); + if (isGrowableItem) { + let grow = growAmount * amountPerGrow; + const maxSize = flexItem._getMainAxisMaxSizeSetting(); + const size = flexItem._getMainAxisLayoutSize(); + if (maxSize > 0) { + if (size >= maxSize) { + // Already fully grown. + grow = 0; + } else { + const maxGrow = maxSize - size; + const isFullyGrown = (grow >= maxGrow); + if (isFullyGrown) { + grow = maxGrow; + + // Destribute remaining amount over the other flex items. + totalGrowAmount -= growAmount; + } + } + } + + if (grow > 0) { + const finalSize = size + grow; + flexItem._resizeMainAxis(finalSize); + + this._grownSize += grow; + this._amountRemaining -= grow; + + if (Math.abs(this._amountRemaining) < 10e-6) { + return; + } + } + } + } + } while(totalGrowAmount && (Math.abs(this._amountRemaining) > 10e-6)); + } + } + + _getTotalGrowAmount() { + let total = 0; + const items = this._line.items; + for (let i = this._line.startIndex; i <= this._line.endIndex; i++) { + const item = items[i]; + const flexItem = item.flexItem; + + if (flexItem.grow) { + const maxSize = flexItem._getMainAxisMaxSizeSetting(); + const size = flexItem._getMainAxisLayoutSize(); + + // Exclude those already fully grown. + if (maxSize === 0 || size < maxSize) { + total += flexItem.grow; + } + } + } + return total; + } + + getGrownSize() { + return this._grownSize; + } + +} + + +/***/ }), + +/***/ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/flex/layout/line/SizeShrinker.mjs": +/*!*****************************************************************************************************************!*\ + !*** ./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/flex/layout/line/SizeShrinker.mjs ***! + \*****************************************************************************************************************/ +/*! exports provided: default */ +/***/ (function(__webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return SizeShrinker; }); +/* + * If not stated otherwise in this file or this component's LICENSE file the + * following copyright and licenses apply: + * + * Copyright 2020 Metrological + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +class SizeShrinker { + + constructor(line) { + this._line = line; + this._amountRemaining = 0; + this._shrunkSize = 0; + } + + shrink(amount) { + this._shrunkSize = 0; + + this._amountRemaining = amount; + let totalShrinkAmount = this._getTotalShrinkAmount(); + if (totalShrinkAmount) { + const items = this._line.items; + do { + let amountPerShrink = this._amountRemaining / totalShrinkAmount; + for (let i = this._line.startIndex; i <= this._line.endIndex; i++) { + const item = items[i]; + const flexItem = item.flexItem; + const shrinkAmount = flexItem.shrink; + const isShrinkableItem = (shrinkAmount > 0); + if (isShrinkableItem) { + let shrink = shrinkAmount * amountPerShrink; + const minSize = flexItem._getMainAxisMinSize(); + const size = flexItem._getMainAxisLayoutSize(); + if (size > minSize) { + const maxShrink = size - minSize; + const isFullyShrunk = (shrink >= maxShrink); + if (isFullyShrunk) { + shrink = maxShrink; + + // Destribute remaining amount over the other flex items. + totalShrinkAmount -= shrinkAmount; + } + + const finalSize = size - shrink; + flexItem._resizeMainAxis(finalSize); + + this._shrunkSize += shrink; + this._amountRemaining -= shrink; + + if (Math.abs(this._amountRemaining) < 10e-6) { + return; + } + } + } + } + } while(totalShrinkAmount && (Math.abs(this._amountRemaining) > 10e-6)); + } + } + + _getTotalShrinkAmount() { + let total = 0; + const items = this._line.items; + for (let i = this._line.startIndex; i <= this._line.endIndex; i++) { + const item = items[i]; + const flexItem = item.flexItem; + + if (flexItem.shrink) { + const minSize = flexItem._getMainAxisMinSize(); + const size = flexItem._getMainAxisLayoutSize(); + + // Exclude those already fully shrunk. + if (size > minSize) { + total += flexItem.shrink; + } + } + } + return total; + } + + getShrunkSize() { + return this._shrunkSize; + } + +} + + +/***/ }), + +/***/ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/index.js": +/*!****************************************************************************************!*\ + !*** ./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/index.js ***! + \****************************************************************************************/ +/*! exports provided: default, Application, Component, Base, Utils, StageUtils, Element, Tools, Stage, ElementCore, ElementTexturizer, Texture, EventEmitter, WebGLGrayscaleShader, BoxBlurShader, DitheringShader, CircularPushShader, InversionShader, LinearBlurShader, OutlineShader, PixelateShader, RadialFilterShader, RoundedRectangleShader, SpinnerShader2, FadeOutShader, HoleShader, VignetteShader, SpinnerShader, RadialGradientShader, Light3dShader, PerspectiveShader, MagnifierShader, WebGLShader, WebGLDefaultShader, C2dShader, C2dDefaultShader, C2dGrayscaleShader, C2dBlurShader, RectangleTexture, NoiseTexture, TextTexture, ImageTexture, HtmlTexture, StaticTexture, StaticCanvasTexture, SourceTexture, FastBlurComponent, BloomComponent, SmoothScaleComponent, BorderComponent, ListComponent, ObjMerger, ObjectListProxy, ObjectListWrapper */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var _application_Application_mjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./application/Application.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/application/Application.mjs"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Application", function() { return _application_Application_mjs__WEBPACK_IMPORTED_MODULE_0__["default"]; }); + +/* harmony import */ var _application_Component_mjs__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./application/Component.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/application/Component.mjs"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Component", function() { return _application_Component_mjs__WEBPACK_IMPORTED_MODULE_1__["default"]; }); + +/* harmony import */ var _tree_Base_mjs__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./tree/Base.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/tree/Base.mjs"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Base", function() { return _tree_Base_mjs__WEBPACK_IMPORTED_MODULE_2__["default"]; }); + +/* harmony import */ var _tree_Utils_mjs__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./tree/Utils.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/tree/Utils.mjs"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Utils", function() { return _tree_Utils_mjs__WEBPACK_IMPORTED_MODULE_3__["default"]; }); + +/* harmony import */ var _tree_StageUtils_mjs__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./tree/StageUtils.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/tree/StageUtils.mjs"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "StageUtils", function() { return _tree_StageUtils_mjs__WEBPACK_IMPORTED_MODULE_4__["default"]; }); + +/* harmony import */ var _tree_Element_mjs__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./tree/Element.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/tree/Element.mjs"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Element", function() { return _tree_Element_mjs__WEBPACK_IMPORTED_MODULE_5__["default"]; }); + +/* harmony import */ var _tree_core_ElementCore_mjs__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./tree/core/ElementCore.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/tree/core/ElementCore.mjs"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ElementCore", function() { return _tree_core_ElementCore_mjs__WEBPACK_IMPORTED_MODULE_6__["default"]; }); + +/* harmony import */ var _tree_core_ElementTexturizer_mjs__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./tree/core/ElementTexturizer.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/tree/core/ElementTexturizer.mjs"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ElementTexturizer", function() { return _tree_core_ElementTexturizer_mjs__WEBPACK_IMPORTED_MODULE_7__["default"]; }); + +/* harmony import */ var _tree_Texture_mjs__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./tree/Texture.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/tree/Texture.mjs"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Texture", function() { return _tree_Texture_mjs__WEBPACK_IMPORTED_MODULE_8__["default"]; }); + +/* harmony import */ var _tools_Tools_mjs__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./tools/Tools.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/tools/Tools.mjs"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Tools", function() { return _tools_Tools_mjs__WEBPACK_IMPORTED_MODULE_9__["default"]; }); + +/* harmony import */ var _tools_ObjMerger_mjs__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./tools/ObjMerger.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/tools/ObjMerger.mjs"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ObjMerger", function() { return _tools_ObjMerger_mjs__WEBPACK_IMPORTED_MODULE_10__["default"]; }); + +/* harmony import */ var _tools_ObjectListProxy_mjs__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ./tools/ObjectListProxy.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/tools/ObjectListProxy.mjs"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ObjectListProxy", function() { return _tools_ObjectListProxy_mjs__WEBPACK_IMPORTED_MODULE_11__["default"]; }); + +/* harmony import */ var _tools_ObjectListWrapper_mjs__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ./tools/ObjectListWrapper.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/tools/ObjectListWrapper.mjs"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ObjectListWrapper", function() { return _tools_ObjectListWrapper_mjs__WEBPACK_IMPORTED_MODULE_12__["default"]; }); + +/* harmony import */ var _textures_RectangleTexture_mjs__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ./textures/RectangleTexture.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/textures/RectangleTexture.mjs"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "RectangleTexture", function() { return _textures_RectangleTexture_mjs__WEBPACK_IMPORTED_MODULE_13__["default"]; }); + +/* harmony import */ var _textures_NoiseTexture_mjs__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ./textures/NoiseTexture.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/textures/NoiseTexture.mjs"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "NoiseTexture", function() { return _textures_NoiseTexture_mjs__WEBPACK_IMPORTED_MODULE_14__["default"]; }); + +/* harmony import */ var _textures_TextTexture_mjs__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ./textures/TextTexture.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/textures/TextTexture.mjs"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "TextTexture", function() { return _textures_TextTexture_mjs__WEBPACK_IMPORTED_MODULE_15__["default"]; }); + +/* harmony import */ var _textures_ImageTexture_mjs__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(/*! ./textures/ImageTexture.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/textures/ImageTexture.mjs"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ImageTexture", function() { return _textures_ImageTexture_mjs__WEBPACK_IMPORTED_MODULE_16__["default"]; }); + +/* harmony import */ var _textures_HtmlTexture_mjs__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(/*! ./textures/HtmlTexture.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/textures/HtmlTexture.mjs"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "HtmlTexture", function() { return _textures_HtmlTexture_mjs__WEBPACK_IMPORTED_MODULE_17__["default"]; }); + +/* harmony import */ var _textures_StaticTexture_mjs__WEBPACK_IMPORTED_MODULE_18__ = __webpack_require__(/*! ./textures/StaticTexture.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/textures/StaticTexture.mjs"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "StaticTexture", function() { return _textures_StaticTexture_mjs__WEBPACK_IMPORTED_MODULE_18__["default"]; }); + +/* harmony import */ var _textures_StaticCanvasTexture_mjs__WEBPACK_IMPORTED_MODULE_19__ = __webpack_require__(/*! ./textures/StaticCanvasTexture.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/textures/StaticCanvasTexture.mjs"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "StaticCanvasTexture", function() { return _textures_StaticCanvasTexture_mjs__WEBPACK_IMPORTED_MODULE_19__["default"]; }); + +/* harmony import */ var _textures_SourceTexture_mjs__WEBPACK_IMPORTED_MODULE_20__ = __webpack_require__(/*! ./textures/SourceTexture.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/textures/SourceTexture.mjs"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SourceTexture", function() { return _textures_SourceTexture_mjs__WEBPACK_IMPORTED_MODULE_20__["default"]; }); + +/* harmony import */ var _components_ListComponent_mjs__WEBPACK_IMPORTED_MODULE_21__ = __webpack_require__(/*! ./components/ListComponent.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/components/ListComponent.mjs"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ListComponent", function() { return _components_ListComponent_mjs__WEBPACK_IMPORTED_MODULE_21__["default"]; }); + +/* harmony import */ var _components_FastBlurComponent_mjs__WEBPACK_IMPORTED_MODULE_22__ = __webpack_require__(/*! ./components/FastBlurComponent.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/components/FastBlurComponent.mjs"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FastBlurComponent", function() { return _components_FastBlurComponent_mjs__WEBPACK_IMPORTED_MODULE_22__["default"]; }); + +/* harmony import */ var _components_BloomComponent_mjs__WEBPACK_IMPORTED_MODULE_23__ = __webpack_require__(/*! ./components/BloomComponent.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/components/BloomComponent.mjs"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "BloomComponent", function() { return _components_BloomComponent_mjs__WEBPACK_IMPORTED_MODULE_23__["default"]; }); + +/* harmony import */ var _components_SmoothScaleComponent_mjs__WEBPACK_IMPORTED_MODULE_24__ = __webpack_require__(/*! ./components/SmoothScaleComponent.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/components/SmoothScaleComponent.mjs"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SmoothScaleComponent", function() { return _components_SmoothScaleComponent_mjs__WEBPACK_IMPORTED_MODULE_24__["default"]; }); + +/* harmony import */ var _components_BorderComponent_mjs__WEBPACK_IMPORTED_MODULE_25__ = __webpack_require__(/*! ./components/BorderComponent.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/components/BorderComponent.mjs"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "BorderComponent", function() { return _components_BorderComponent_mjs__WEBPACK_IMPORTED_MODULE_25__["default"]; }); + +/* harmony import */ var _EventEmitter_mjs__WEBPACK_IMPORTED_MODULE_26__ = __webpack_require__(/*! ./EventEmitter.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/EventEmitter.mjs"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "EventEmitter", function() { return _EventEmitter_mjs__WEBPACK_IMPORTED_MODULE_26__["default"]; }); + +/* harmony import */ var _renderer_webgl_WebGLShader_mjs__WEBPACK_IMPORTED_MODULE_27__ = __webpack_require__(/*! ./renderer/webgl/WebGLShader.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/renderer/webgl/WebGLShader.mjs"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "WebGLShader", function() { return _renderer_webgl_WebGLShader_mjs__WEBPACK_IMPORTED_MODULE_27__["default"]; }); + +/* harmony import */ var _renderer_webgl_shaders_DefaultShader_mjs__WEBPACK_IMPORTED_MODULE_28__ = __webpack_require__(/*! ./renderer/webgl/shaders/DefaultShader.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/renderer/webgl/shaders/DefaultShader.mjs"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "WebGLDefaultShader", function() { return _renderer_webgl_shaders_DefaultShader_mjs__WEBPACK_IMPORTED_MODULE_28__["default"]; }); + +/* harmony import */ var _renderer_common_shaders_GrayscaleShader_mjs__WEBPACK_IMPORTED_MODULE_29__ = __webpack_require__(/*! ./renderer/common/shaders/GrayscaleShader.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/renderer/common/shaders/GrayscaleShader.mjs"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "WebGLGrayscaleShader", function() { return _renderer_common_shaders_GrayscaleShader_mjs__WEBPACK_IMPORTED_MODULE_29__["WebGLGrayscaleShader"]; }); + +/* harmony import */ var _renderer_webgl_shaders_BoxBlurShader_mjs__WEBPACK_IMPORTED_MODULE_30__ = __webpack_require__(/*! ./renderer/webgl/shaders/BoxBlurShader.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/renderer/webgl/shaders/BoxBlurShader.mjs"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "BoxBlurShader", function() { return _renderer_webgl_shaders_BoxBlurShader_mjs__WEBPACK_IMPORTED_MODULE_30__["default"]; }); + +/* harmony import */ var _renderer_webgl_shaders_DitheringShader_mjs__WEBPACK_IMPORTED_MODULE_31__ = __webpack_require__(/*! ./renderer/webgl/shaders/DitheringShader.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/renderer/webgl/shaders/DitheringShader.mjs"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "DitheringShader", function() { return _renderer_webgl_shaders_DitheringShader_mjs__WEBPACK_IMPORTED_MODULE_31__["default"]; }); + +/* harmony import */ var _renderer_webgl_shaders_CircularPushShader_mjs__WEBPACK_IMPORTED_MODULE_32__ = __webpack_require__(/*! ./renderer/webgl/shaders/CircularPushShader.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/renderer/webgl/shaders/CircularPushShader.mjs"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "CircularPushShader", function() { return _renderer_webgl_shaders_CircularPushShader_mjs__WEBPACK_IMPORTED_MODULE_32__["default"]; }); + +/* harmony import */ var _renderer_webgl_shaders_InversionShader_mjs__WEBPACK_IMPORTED_MODULE_33__ = __webpack_require__(/*! ./renderer/webgl/shaders/InversionShader.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/renderer/webgl/shaders/InversionShader.mjs"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "InversionShader", function() { return _renderer_webgl_shaders_InversionShader_mjs__WEBPACK_IMPORTED_MODULE_33__["default"]; }); + +/* harmony import */ var _renderer_webgl_shaders_LinearBlurShader_mjs__WEBPACK_IMPORTED_MODULE_34__ = __webpack_require__(/*! ./renderer/webgl/shaders/LinearBlurShader.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/renderer/webgl/shaders/LinearBlurShader.mjs"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "LinearBlurShader", function() { return _renderer_webgl_shaders_LinearBlurShader_mjs__WEBPACK_IMPORTED_MODULE_34__["default"]; }); + +/* harmony import */ var _renderer_webgl_shaders_OutlineShader_mjs__WEBPACK_IMPORTED_MODULE_35__ = __webpack_require__(/*! ./renderer/webgl/shaders/OutlineShader.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/renderer/webgl/shaders/OutlineShader.mjs"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "OutlineShader", function() { return _renderer_webgl_shaders_OutlineShader_mjs__WEBPACK_IMPORTED_MODULE_35__["default"]; }); + +/* harmony import */ var _renderer_webgl_shaders_PixelateShader_mjs__WEBPACK_IMPORTED_MODULE_36__ = __webpack_require__(/*! ./renderer/webgl/shaders/PixelateShader.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/renderer/webgl/shaders/PixelateShader.mjs"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PixelateShader", function() { return _renderer_webgl_shaders_PixelateShader_mjs__WEBPACK_IMPORTED_MODULE_36__["default"]; }); + +/* harmony import */ var _renderer_webgl_shaders_RadialFilterShader_mjs__WEBPACK_IMPORTED_MODULE_37__ = __webpack_require__(/*! ./renderer/webgl/shaders/RadialFilterShader.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/renderer/webgl/shaders/RadialFilterShader.mjs"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "RadialFilterShader", function() { return _renderer_webgl_shaders_RadialFilterShader_mjs__WEBPACK_IMPORTED_MODULE_37__["default"]; }); + +/* harmony import */ var _renderer_webgl_shaders_RoundedRectangleShader_mjs__WEBPACK_IMPORTED_MODULE_38__ = __webpack_require__(/*! ./renderer/webgl/shaders/RoundedRectangleShader.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/renderer/webgl/shaders/RoundedRectangleShader.mjs"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "RoundedRectangleShader", function() { return _renderer_webgl_shaders_RoundedRectangleShader_mjs__WEBPACK_IMPORTED_MODULE_38__["default"]; }); + +/* harmony import */ var _renderer_webgl_shaders_FadeOutShader_mjs__WEBPACK_IMPORTED_MODULE_39__ = __webpack_require__(/*! ./renderer/webgl/shaders/FadeOutShader.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/renderer/webgl/shaders/FadeOutShader.mjs"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FadeOutShader", function() { return _renderer_webgl_shaders_FadeOutShader_mjs__WEBPACK_IMPORTED_MODULE_39__["default"]; }); + +/* harmony import */ var _renderer_webgl_shaders_VignetteShader_mjs__WEBPACK_IMPORTED_MODULE_40__ = __webpack_require__(/*! ./renderer/webgl/shaders/VignetteShader.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/renderer/webgl/shaders/VignetteShader.mjs"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "VignetteShader", function() { return _renderer_webgl_shaders_VignetteShader_mjs__WEBPACK_IMPORTED_MODULE_40__["default"]; }); + +/* harmony import */ var _renderer_webgl_shaders_SpinnerShader_mjs__WEBPACK_IMPORTED_MODULE_41__ = __webpack_require__(/*! ./renderer/webgl/shaders/SpinnerShader.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/renderer/webgl/shaders/SpinnerShader.mjs"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SpinnerShader", function() { return _renderer_webgl_shaders_SpinnerShader_mjs__WEBPACK_IMPORTED_MODULE_41__["default"]; }); + +/* harmony import */ var _renderer_webgl_shaders_HoleShader_mjs__WEBPACK_IMPORTED_MODULE_42__ = __webpack_require__(/*! ./renderer/webgl/shaders/HoleShader.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/renderer/webgl/shaders/HoleShader.mjs"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "HoleShader", function() { return _renderer_webgl_shaders_HoleShader_mjs__WEBPACK_IMPORTED_MODULE_42__["default"]; }); + +/* harmony import */ var _renderer_webgl_shaders_RadialGradientShader_mjs__WEBPACK_IMPORTED_MODULE_43__ = __webpack_require__(/*! ./renderer/webgl/shaders/RadialGradientShader.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/renderer/webgl/shaders/RadialGradientShader.mjs"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "RadialGradientShader", function() { return _renderer_webgl_shaders_RadialGradientShader_mjs__WEBPACK_IMPORTED_MODULE_43__["default"]; }); + +/* harmony import */ var _renderer_webgl_shaders_Light3dShader_mjs__WEBPACK_IMPORTED_MODULE_44__ = __webpack_require__(/*! ./renderer/webgl/shaders/Light3dShader.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/renderer/webgl/shaders/Light3dShader.mjs"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Light3dShader", function() { return _renderer_webgl_shaders_Light3dShader_mjs__WEBPACK_IMPORTED_MODULE_44__["default"]; }); + +/* harmony import */ var _renderer_webgl_shaders_PerspectiveShader_mjs__WEBPACK_IMPORTED_MODULE_45__ = __webpack_require__(/*! ./renderer/webgl/shaders/PerspectiveShader.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/renderer/webgl/shaders/PerspectiveShader.mjs"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PerspectiveShader", function() { return _renderer_webgl_shaders_PerspectiveShader_mjs__WEBPACK_IMPORTED_MODULE_45__["default"]; }); + +/* harmony import */ var _renderer_webgl_shaders_MagnifierShader_mjs__WEBPACK_IMPORTED_MODULE_46__ = __webpack_require__(/*! ./renderer/webgl/shaders/MagnifierShader.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/renderer/webgl/shaders/MagnifierShader.mjs"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "MagnifierShader", function() { return _renderer_webgl_shaders_MagnifierShader_mjs__WEBPACK_IMPORTED_MODULE_46__["default"]; }); + +/* harmony import */ var _renderer_c2d_C2dShader_mjs__WEBPACK_IMPORTED_MODULE_47__ = __webpack_require__(/*! ./renderer/c2d/C2dShader.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/renderer/c2d/C2dShader.mjs"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "C2dShader", function() { return _renderer_c2d_C2dShader_mjs__WEBPACK_IMPORTED_MODULE_47__["default"]; }); + +/* harmony import */ var _renderer_c2d_shaders_DefaultShader_mjs__WEBPACK_IMPORTED_MODULE_48__ = __webpack_require__(/*! ./renderer/c2d/shaders/DefaultShader.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/renderer/c2d/shaders/DefaultShader.mjs"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "C2dDefaultShader", function() { return _renderer_c2d_shaders_DefaultShader_mjs__WEBPACK_IMPORTED_MODULE_48__["default"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "C2dGrayscaleShader", function() { return _renderer_common_shaders_GrayscaleShader_mjs__WEBPACK_IMPORTED_MODULE_29__["C2dGrayscaleShader"]; }); + +/* harmony import */ var _renderer_c2d_shaders_BlurShader_mjs__WEBPACK_IMPORTED_MODULE_49__ = __webpack_require__(/*! ./renderer/c2d/shaders/BlurShader.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/renderer/c2d/shaders/BlurShader.mjs"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "C2dBlurShader", function() { return _renderer_c2d_shaders_BlurShader_mjs__WEBPACK_IMPORTED_MODULE_49__["default"]; }); + +/* harmony import */ var _renderer_webgl_shaders_SpinnerShader2_mjs__WEBPACK_IMPORTED_MODULE_50__ = __webpack_require__(/*! ./renderer/webgl/shaders/SpinnerShader2.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/renderer/webgl/shaders/SpinnerShader2.mjs"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SpinnerShader2", function() { return _renderer_webgl_shaders_SpinnerShader2_mjs__WEBPACK_IMPORTED_MODULE_50__["default"]; }); + +/* harmony import */ var _tree_Stage_mjs__WEBPACK_IMPORTED_MODULE_51__ = __webpack_require__(/*! ./tree/Stage.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/tree/Stage.mjs"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Stage", function() { return _tree_Stage_mjs__WEBPACK_IMPORTED_MODULE_51__["default"]; }); + +/* harmony import */ var _lightning_mjs__WEBPACK_IMPORTED_MODULE_52__ = __webpack_require__(/*! ./lightning.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/lightning.mjs"); +/* + * If not stated otherwise in this file or this component's LICENSE file the + * following copyright and licenses apply: + * + * Copyright 2023 Metrological + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +// full export (no tree-shaking) + +/* harmony default export */ __webpack_exports__["default"] = (_lightning_mjs__WEBPACK_IMPORTED_MODULE_52__["default"]); +// tree-shakeable exports + +//# sourceMappingURL=index.js.map + +/***/ }), + +/***/ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/lightning.mjs": +/*!*********************************************************************************************!*\ + !*** ./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/lightning.mjs ***! + \*********************************************************************************************/ +/*! exports provided: default */ +/***/ (function(__webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var _application_Application_mjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./application/Application.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/application/Application.mjs"); +/* harmony import */ var _application_Component_mjs__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./application/Component.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/application/Component.mjs"); +/* harmony import */ var _tree_Base_mjs__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./tree/Base.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/tree/Base.mjs"); +/* harmony import */ var _tree_Utils_mjs__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./tree/Utils.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/tree/Utils.mjs"); +/* harmony import */ var _tree_StageUtils_mjs__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./tree/StageUtils.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/tree/StageUtils.mjs"); +/* harmony import */ var _tree_Element_mjs__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./tree/Element.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/tree/Element.mjs"); +/* harmony import */ var _tree_core_ElementCore_mjs__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./tree/core/ElementCore.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/tree/core/ElementCore.mjs"); +/* harmony import */ var _tree_core_ElementTexturizer_mjs__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./tree/core/ElementTexturizer.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/tree/core/ElementTexturizer.mjs"); +/* harmony import */ var _tree_Texture_mjs__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./tree/Texture.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/tree/Texture.mjs"); +/* harmony import */ var _tools_Tools_mjs__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./tools/Tools.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/tools/Tools.mjs"); +/* harmony import */ var _tools_ObjMerger_mjs__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./tools/ObjMerger.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/tools/ObjMerger.mjs"); +/* harmony import */ var _tools_ObjectListProxy_mjs__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ./tools/ObjectListProxy.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/tools/ObjectListProxy.mjs"); +/* harmony import */ var _tools_ObjectListWrapper_mjs__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ./tools/ObjectListWrapper.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/tools/ObjectListWrapper.mjs"); +/* harmony import */ var _textures_RectangleTexture_mjs__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ./textures/RectangleTexture.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/textures/RectangleTexture.mjs"); +/* harmony import */ var _textures_NoiseTexture_mjs__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ./textures/NoiseTexture.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/textures/NoiseTexture.mjs"); +/* harmony import */ var _textures_TextTexture_mjs__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ./textures/TextTexture.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/textures/TextTexture.mjs"); +/* harmony import */ var _textures_ImageTexture_mjs__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(/*! ./textures/ImageTexture.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/textures/ImageTexture.mjs"); +/* harmony import */ var _textures_HtmlTexture_mjs__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(/*! ./textures/HtmlTexture.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/textures/HtmlTexture.mjs"); +/* harmony import */ var _textures_StaticTexture_mjs__WEBPACK_IMPORTED_MODULE_18__ = __webpack_require__(/*! ./textures/StaticTexture.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/textures/StaticTexture.mjs"); +/* harmony import */ var _textures_StaticCanvasTexture_mjs__WEBPACK_IMPORTED_MODULE_19__ = __webpack_require__(/*! ./textures/StaticCanvasTexture.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/textures/StaticCanvasTexture.mjs"); +/* harmony import */ var _textures_SourceTexture_mjs__WEBPACK_IMPORTED_MODULE_20__ = __webpack_require__(/*! ./textures/SourceTexture.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/textures/SourceTexture.mjs"); +/* harmony import */ var _components_ListComponent_mjs__WEBPACK_IMPORTED_MODULE_21__ = __webpack_require__(/*! ./components/ListComponent.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/components/ListComponent.mjs"); +/* harmony import */ var _components_FastBlurComponent_mjs__WEBPACK_IMPORTED_MODULE_22__ = __webpack_require__(/*! ./components/FastBlurComponent.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/components/FastBlurComponent.mjs"); +/* harmony import */ var _components_BloomComponent_mjs__WEBPACK_IMPORTED_MODULE_23__ = __webpack_require__(/*! ./components/BloomComponent.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/components/BloomComponent.mjs"); +/* harmony import */ var _components_SmoothScaleComponent_mjs__WEBPACK_IMPORTED_MODULE_24__ = __webpack_require__(/*! ./components/SmoothScaleComponent.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/components/SmoothScaleComponent.mjs"); +/* harmony import */ var _components_BorderComponent_mjs__WEBPACK_IMPORTED_MODULE_25__ = __webpack_require__(/*! ./components/BorderComponent.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/components/BorderComponent.mjs"); +/* harmony import */ var _EventEmitter_mjs__WEBPACK_IMPORTED_MODULE_26__ = __webpack_require__(/*! ./EventEmitter.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/EventEmitter.mjs"); +/* harmony import */ var _renderer_webgl_WebGLShader_mjs__WEBPACK_IMPORTED_MODULE_27__ = __webpack_require__(/*! ./renderer/webgl/WebGLShader.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/renderer/webgl/WebGLShader.mjs"); +/* harmony import */ var _renderer_webgl_shaders_DefaultShader_mjs__WEBPACK_IMPORTED_MODULE_28__ = __webpack_require__(/*! ./renderer/webgl/shaders/DefaultShader.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/renderer/webgl/shaders/DefaultShader.mjs"); +/* harmony import */ var _renderer_common_shaders_GrayscaleShader_mjs__WEBPACK_IMPORTED_MODULE_29__ = __webpack_require__(/*! ./renderer/common/shaders/GrayscaleShader.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/renderer/common/shaders/GrayscaleShader.mjs"); +/* harmony import */ var _renderer_webgl_shaders_BoxBlurShader_mjs__WEBPACK_IMPORTED_MODULE_30__ = __webpack_require__(/*! ./renderer/webgl/shaders/BoxBlurShader.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/renderer/webgl/shaders/BoxBlurShader.mjs"); +/* harmony import */ var _renderer_webgl_shaders_DitheringShader_mjs__WEBPACK_IMPORTED_MODULE_31__ = __webpack_require__(/*! ./renderer/webgl/shaders/DitheringShader.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/renderer/webgl/shaders/DitheringShader.mjs"); +/* harmony import */ var _renderer_webgl_shaders_CircularPushShader_mjs__WEBPACK_IMPORTED_MODULE_32__ = __webpack_require__(/*! ./renderer/webgl/shaders/CircularPushShader.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/renderer/webgl/shaders/CircularPushShader.mjs"); +/* harmony import */ var _renderer_webgl_shaders_InversionShader_mjs__WEBPACK_IMPORTED_MODULE_33__ = __webpack_require__(/*! ./renderer/webgl/shaders/InversionShader.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/renderer/webgl/shaders/InversionShader.mjs"); +/* harmony import */ var _renderer_webgl_shaders_LinearBlurShader_mjs__WEBPACK_IMPORTED_MODULE_34__ = __webpack_require__(/*! ./renderer/webgl/shaders/LinearBlurShader.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/renderer/webgl/shaders/LinearBlurShader.mjs"); +/* harmony import */ var _renderer_webgl_shaders_OutlineShader_mjs__WEBPACK_IMPORTED_MODULE_35__ = __webpack_require__(/*! ./renderer/webgl/shaders/OutlineShader.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/renderer/webgl/shaders/OutlineShader.mjs"); +/* harmony import */ var _renderer_webgl_shaders_PixelateShader_mjs__WEBPACK_IMPORTED_MODULE_36__ = __webpack_require__(/*! ./renderer/webgl/shaders/PixelateShader.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/renderer/webgl/shaders/PixelateShader.mjs"); +/* harmony import */ var _renderer_webgl_shaders_RadialFilterShader_mjs__WEBPACK_IMPORTED_MODULE_37__ = __webpack_require__(/*! ./renderer/webgl/shaders/RadialFilterShader.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/renderer/webgl/shaders/RadialFilterShader.mjs"); +/* harmony import */ var _renderer_webgl_shaders_RoundedRectangleShader_mjs__WEBPACK_IMPORTED_MODULE_38__ = __webpack_require__(/*! ./renderer/webgl/shaders/RoundedRectangleShader.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/renderer/webgl/shaders/RoundedRectangleShader.mjs"); +/* harmony import */ var _renderer_webgl_shaders_FadeOutShader_mjs__WEBPACK_IMPORTED_MODULE_39__ = __webpack_require__(/*! ./renderer/webgl/shaders/FadeOutShader.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/renderer/webgl/shaders/FadeOutShader.mjs"); +/* harmony import */ var _renderer_webgl_shaders_VignetteShader_mjs__WEBPACK_IMPORTED_MODULE_40__ = __webpack_require__(/*! ./renderer/webgl/shaders/VignetteShader.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/renderer/webgl/shaders/VignetteShader.mjs"); +/* harmony import */ var _renderer_webgl_shaders_SpinnerShader_mjs__WEBPACK_IMPORTED_MODULE_41__ = __webpack_require__(/*! ./renderer/webgl/shaders/SpinnerShader.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/renderer/webgl/shaders/SpinnerShader.mjs"); +/* harmony import */ var _renderer_webgl_shaders_HoleShader_mjs__WEBPACK_IMPORTED_MODULE_42__ = __webpack_require__(/*! ./renderer/webgl/shaders/HoleShader.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/renderer/webgl/shaders/HoleShader.mjs"); +/* harmony import */ var _renderer_webgl_shaders_RadialGradientShader_mjs__WEBPACK_IMPORTED_MODULE_43__ = __webpack_require__(/*! ./renderer/webgl/shaders/RadialGradientShader.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/renderer/webgl/shaders/RadialGradientShader.mjs"); +/* harmony import */ var _renderer_webgl_shaders_Light3dShader_mjs__WEBPACK_IMPORTED_MODULE_44__ = __webpack_require__(/*! ./renderer/webgl/shaders/Light3dShader.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/renderer/webgl/shaders/Light3dShader.mjs"); +/* harmony import */ var _renderer_webgl_shaders_PerspectiveShader_mjs__WEBPACK_IMPORTED_MODULE_45__ = __webpack_require__(/*! ./renderer/webgl/shaders/PerspectiveShader.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/renderer/webgl/shaders/PerspectiveShader.mjs"); +/* harmony import */ var _renderer_webgl_shaders_MagnifierShader_mjs__WEBPACK_IMPORTED_MODULE_46__ = __webpack_require__(/*! ./renderer/webgl/shaders/MagnifierShader.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/renderer/webgl/shaders/MagnifierShader.mjs"); +/* harmony import */ var _renderer_c2d_C2dShader_mjs__WEBPACK_IMPORTED_MODULE_47__ = __webpack_require__(/*! ./renderer/c2d/C2dShader.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/renderer/c2d/C2dShader.mjs"); +/* harmony import */ var _renderer_c2d_shaders_DefaultShader_mjs__WEBPACK_IMPORTED_MODULE_48__ = __webpack_require__(/*! ./renderer/c2d/shaders/DefaultShader.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/renderer/c2d/shaders/DefaultShader.mjs"); +/* harmony import */ var _renderer_c2d_shaders_BlurShader_mjs__WEBPACK_IMPORTED_MODULE_49__ = __webpack_require__(/*! ./renderer/c2d/shaders/BlurShader.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/renderer/c2d/shaders/BlurShader.mjs"); +/* harmony import */ var _tree_Stage_mjs__WEBPACK_IMPORTED_MODULE_50__ = __webpack_require__(/*! ./tree/Stage.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/tree/Stage.mjs"); +/* harmony import */ var _renderer_webgl_shaders_SpinnerShader2_mjs__WEBPACK_IMPORTED_MODULE_51__ = __webpack_require__(/*! ./renderer/webgl/shaders/SpinnerShader2.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/renderer/webgl/shaders/SpinnerShader2.mjs"); +/* + * If not stated otherwise in this file or this component's LICENSE file the + * following copyright and licenses apply: + * + * Copyright 2020 Metrological + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +const lightning = { + Application: _application_Application_mjs__WEBPACK_IMPORTED_MODULE_0__["default"], + Component: _application_Component_mjs__WEBPACK_IMPORTED_MODULE_1__["default"], + Base: _tree_Base_mjs__WEBPACK_IMPORTED_MODULE_2__["default"], + Utils: _tree_Utils_mjs__WEBPACK_IMPORTED_MODULE_3__["default"], + StageUtils: _tree_StageUtils_mjs__WEBPACK_IMPORTED_MODULE_4__["default"], + Element: _tree_Element_mjs__WEBPACK_IMPORTED_MODULE_5__["default"], + Tools: _tools_Tools_mjs__WEBPACK_IMPORTED_MODULE_9__["default"], + Stage: _tree_Stage_mjs__WEBPACK_IMPORTED_MODULE_50__["default"], + ElementCore: _tree_core_ElementCore_mjs__WEBPACK_IMPORTED_MODULE_6__["default"], + ElementTexturizer: _tree_core_ElementTexturizer_mjs__WEBPACK_IMPORTED_MODULE_7__["default"], + Texture: _tree_Texture_mjs__WEBPACK_IMPORTED_MODULE_8__["default"], + EventEmitter: _EventEmitter_mjs__WEBPACK_IMPORTED_MODULE_26__["default"], + shaders: { + Grayscale: _renderer_common_shaders_GrayscaleShader_mjs__WEBPACK_IMPORTED_MODULE_29__["WebGLGrayscaleShader"], + BoxBlur: _renderer_webgl_shaders_BoxBlurShader_mjs__WEBPACK_IMPORTED_MODULE_30__["default"], + Dithering: _renderer_webgl_shaders_DitheringShader_mjs__WEBPACK_IMPORTED_MODULE_31__["default"], + CircularPush: _renderer_webgl_shaders_CircularPushShader_mjs__WEBPACK_IMPORTED_MODULE_32__["default"], + Inversion: _renderer_webgl_shaders_InversionShader_mjs__WEBPACK_IMPORTED_MODULE_33__["default"], + LinearBlur: _renderer_webgl_shaders_LinearBlurShader_mjs__WEBPACK_IMPORTED_MODULE_34__["default"], + Outline: _renderer_webgl_shaders_OutlineShader_mjs__WEBPACK_IMPORTED_MODULE_35__["default"], + Pixelate: _renderer_webgl_shaders_PixelateShader_mjs__WEBPACK_IMPORTED_MODULE_36__["default"], + RadialFilter: _renderer_webgl_shaders_RadialFilterShader_mjs__WEBPACK_IMPORTED_MODULE_37__["default"], + RoundedRectangle: _renderer_webgl_shaders_RoundedRectangleShader_mjs__WEBPACK_IMPORTED_MODULE_38__["default"], + Spinner2: _renderer_webgl_shaders_SpinnerShader2_mjs__WEBPACK_IMPORTED_MODULE_51__["default"], + FadeOut: _renderer_webgl_shaders_FadeOutShader_mjs__WEBPACK_IMPORTED_MODULE_39__["default"], + Hole: _renderer_webgl_shaders_HoleShader_mjs__WEBPACK_IMPORTED_MODULE_42__["default"], + Vignette: _renderer_webgl_shaders_VignetteShader_mjs__WEBPACK_IMPORTED_MODULE_40__["default"], + Spinner: _renderer_webgl_shaders_SpinnerShader_mjs__WEBPACK_IMPORTED_MODULE_41__["default"], + RadialGradient: _renderer_webgl_shaders_RadialGradientShader_mjs__WEBPACK_IMPORTED_MODULE_43__["default"], + Light3d: _renderer_webgl_shaders_Light3dShader_mjs__WEBPACK_IMPORTED_MODULE_44__["default"], + Perspective: _renderer_webgl_shaders_PerspectiveShader_mjs__WEBPACK_IMPORTED_MODULE_45__["default"], + Magnifier: _renderer_webgl_shaders_MagnifierShader_mjs__WEBPACK_IMPORTED_MODULE_46__["default"], + WebGLShader: _renderer_webgl_WebGLShader_mjs__WEBPACK_IMPORTED_MODULE_27__["default"], + WebGLDefaultShader: _renderer_webgl_shaders_DefaultShader_mjs__WEBPACK_IMPORTED_MODULE_28__["default"], + C2dShader: _renderer_c2d_C2dShader_mjs__WEBPACK_IMPORTED_MODULE_47__["default"], + C2dDefaultShader: _renderer_c2d_shaders_DefaultShader_mjs__WEBPACK_IMPORTED_MODULE_48__["default"], + c2d: { + Grayscale: _renderer_common_shaders_GrayscaleShader_mjs__WEBPACK_IMPORTED_MODULE_29__["C2dGrayscaleShader"], + Blur: _renderer_c2d_shaders_BlurShader_mjs__WEBPACK_IMPORTED_MODULE_49__["default"] + } + }, + textures: { + RectangleTexture: _textures_RectangleTexture_mjs__WEBPACK_IMPORTED_MODULE_13__["default"], + NoiseTexture: _textures_NoiseTexture_mjs__WEBPACK_IMPORTED_MODULE_14__["default"], + TextTexture: _textures_TextTexture_mjs__WEBPACK_IMPORTED_MODULE_15__["default"], + ImageTexture: _textures_ImageTexture_mjs__WEBPACK_IMPORTED_MODULE_16__["default"], + HtmlTexture: _textures_HtmlTexture_mjs__WEBPACK_IMPORTED_MODULE_17__["default"], + StaticTexture: _textures_StaticTexture_mjs__WEBPACK_IMPORTED_MODULE_18__["default"], + StaticCanvasTexture: _textures_StaticCanvasTexture_mjs__WEBPACK_IMPORTED_MODULE_19__["default"], + SourceTexture: _textures_SourceTexture_mjs__WEBPACK_IMPORTED_MODULE_20__["default"] + }, + components: { + FastBlurComponent: _components_FastBlurComponent_mjs__WEBPACK_IMPORTED_MODULE_22__["default"], + BloomComponent: _components_BloomComponent_mjs__WEBPACK_IMPORTED_MODULE_23__["default"], + SmoothScaleComponent: _components_SmoothScaleComponent_mjs__WEBPACK_IMPORTED_MODULE_24__["default"], + BorderComponent: _components_BorderComponent_mjs__WEBPACK_IMPORTED_MODULE_25__["default"], + ListComponent: _components_ListComponent_mjs__WEBPACK_IMPORTED_MODULE_21__["default"] + }, + tools: { + ObjMerger: _tools_ObjMerger_mjs__WEBPACK_IMPORTED_MODULE_10__["default"], + ObjectListProxy: _tools_ObjectListProxy_mjs__WEBPACK_IMPORTED_MODULE_11__["default"], + ObjectListWrapper: _tools_ObjectListWrapper_mjs__WEBPACK_IMPORTED_MODULE_12__["default"] + } +}; + +if (_tree_Utils_mjs__WEBPACK_IMPORTED_MODULE_3__["default"].isWeb) { + window.lng = lightning; +} + +/* harmony default export */ __webpack_exports__["default"] = (lightning); + + +/***/ }), + +/***/ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/platforms/PlatformLoader.mjs": +/*!************************************************************************************************************!*\ + !*** ./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/platforms/PlatformLoader.mjs ***! + \************************************************************************************************************/ +/*! exports provided: default */ +/***/ (function(__webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return PlatformLoader; }); +/* harmony import */ var _browser_WebPlatform_mjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./browser/WebPlatform.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/platforms/browser/WebPlatform.mjs"); +/* + * If not stated otherwise in this file or this component's LICENSE file the + * following copyright and licenses apply: + * + * Copyright 2020 Metrological + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + +class PlatformLoader { + static load(options) { + if (options.platform) { + return options.platform; + } else { + return _browser_WebPlatform_mjs__WEBPACK_IMPORTED_MODULE_0__["default"]; + } + } +} + + +/***/ }), + +/***/ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/platforms/browser/ImageWorker.mjs": +/*!*****************************************************************************************************************!*\ + !*** ./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/platforms/browser/ImageWorker.mjs ***! + \*****************************************************************************************************************/ +/*! exports provided: default */ +/***/ (function(__webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return ImageWorker; }); +/* + * If not stated otherwise in this file or this component's LICENSE file the + * following copyright and licenses apply: + * + * Copyright 2020 Metrological + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +class ImageWorker { + + constructor(options = {}) { + this._items = new Map(); + this._id = 0; + + this._initWorker(); + } + + destroy() { + if (this._worker) { + this._worker.terminate(); + } + + this._items = null; + this._worker = null; + + delete this._items; + delete this._worker; + } + + _initWorker() { + const code = `(${createWorker.toString()})()`; + const blob = new Blob([code.replace('"use strict";', '')]); // firefox adds "use strict"; to any function which might block worker execution so knock it off + const blobURL = (window.URL ? URL : webkitURL).createObjectURL(blob, { + type: 'application/javascript; charset=utf-8' + }); + this._worker = new Worker(blobURL); + + this._worker.postMessage({type: 'config', config: {path: window.location.href, protocol: window.location.protocol}}); + + this._worker.onmessage = (e) => { + if (e.data && e.data.id) { + const id = e.data.id; + const item = this._items.get(id); + if (item) { + if (e.data.type == 'data') { + this.finish(item, e.data.info); + } else { + this.error(item, e.data.info); + } + } + } + } + } + + create(src) { + const id = ++this._id; + const item = new ImageWorkerImage(this, id, src); + this._items.set(id, item); + this._worker.postMessage({type: "add", id: id, src: src}); + return item; + } + + cancel(image) { + this._worker.postMessage({type: "cancel", id: image.id}); + this._items.delete(image.id); + } + + error(image, info) { + image.error(info); + this._items.delete(image.id); + } + + finish(image, info) { + image.load(info); + this._items.delete(image.id); + } + +} + +class ImageWorkerImage { + + constructor(manager, id, src) { + this._manager = manager; + this._id = id; + this._src = src; + this._onError = null; + this._onLoad = null; + } + + get id() { + return this._id; + } + + get src() { + return this._src; + } + + set onError(f) { + this._onError = f; + } + + set onLoad(f) { + this._onLoad = f; + } + + cancel() { + this._manager.cancel(this); + } + + load(info) { + if (this._onLoad) { + this._onLoad(info); + } + } + + error(info) { + if (this._onError) { + this._onError(info); + } + } + +} + +/** + * Notice that, within the createWorker function, we must only use ES5 code to keep it ES5-valid after babelifying, as + * the converted code of this section is converted to a blob and used as the js of the web worker thread. + */ +const createWorker = function() { + + function ImageWorkerServer() { + + this.items = new Map(); + + var t = this; + onmessage = function(e) { + t._receiveMessage(e); + } + + } + + ImageWorkerServer.isPathAbsolute = function(path) { + return /^(?:\/|[a-z]+:\/\/)/.test(path) || path.substr(0, 5) == 'data:'; + }; + + ImageWorkerServer.prototype._receiveMessage = function(e) { + if (e.data.type === 'config') { + this.config = e.data.config; + + var base = this.config.path; + // the constructing of the basepath fails + // if location.hash contains a slash + var hasHashPath = /#.*?\//; + if(hasHashPath.test(base)){ + base = base.replace(/#.*$/,''); + } + + var parts = base.split("/"); + parts.pop(); + this._relativeBase = parts.join("/") + "/"; + + } else if (e.data.type === 'add') { + this.add(e.data.id, e.data.src); + } else if (e.data.type === 'cancel') { + this.cancel(e.data.id); + } + }; + + ImageWorkerServer.prototype.add = function(id, src) { + // Convert relative URLs. + if (!ImageWorkerServer.isPathAbsolute(src)) { + src = this._relativeBase + src; + } + + if (src.substr(0,2) === "//") { + // This doesn't work for image workers. + src = this.config.protocol + src; + } + + var item = new ImageWorkerServerItem(id, src); + var t = this; + item.onFinish = function(result) { + t.finish(item, result); + }; + item.onError = function(info) { + t.error(item, info); + }; + this.items.set(id, item); + item.start(); + }; + + ImageWorkerServer.prototype.cancel = function(id) { + var item = this.items.get(id); + if (item) { + item.cancel(); + this.items.delete(id); + } + } + + ImageWorkerServer.prototype.finish = function(item, {imageBitmap, hasAlphaChannel}) { + postMessage({ + type: "data", + id: item.id, + info: { + imageBitmap, + hasAlphaChannel + } + }, [imageBitmap]); + this.items.delete(item.id); + }; + + ImageWorkerServer.prototype.error = function(item, {type, message}) { + postMessage({ + type: "error", + id: item.id, + info: { + type, + message + } + }); + this.items.delete(item.id); + }; + + ImageWorkerServer.isWPEBrowser = function() { + return (navigator.userAgent.indexOf("WPE") !== -1); + }; + + function ImageWorkerServerItem(id, src) { + + this._onError = undefined; + this._onFinish = undefined; + this._id = id; + this._src = src; + this._xhr = undefined; + this._mimeType = undefined; + this._canceled = false; + + } + + Object.defineProperty(ImageWorkerServerItem.prototype, 'id', { + get: function() { + return this._id; + } + }); + + Object.defineProperty(ImageWorkerServerItem.prototype, 'onFinish', { + get: function() { + return this._onFinish; + }, + set: function(f) { + this._onFinish = f; + } + }); + + Object.defineProperty(ImageWorkerServerItem.prototype, 'onError', { + get: function() { + return this._onError; + }, + set: function(f) { + this._onError = f; + } + }); + + ImageWorkerServerItem.prototype.start = function() { + this._xhr = new XMLHttpRequest(); + this._xhr.open("GET", this._src, true); + this._xhr.responseType = "blob"; + + var t = this; + this._xhr.onerror = function(oEvent) { + t.error({type: "connection", message: "Connection error"}); + }; + + this._xhr.onload = function(oEvent) { + var blob = t._xhr.response; + t._mimeType = blob.type; + + t._createImageBitmap(blob); + }; + + this._xhr.send(); + }; + + ImageWorkerServerItem.prototype._createImageBitmap = function(blob) { + var t = this; + createImageBitmap(blob, {premultiplyAlpha: 'premultiply', colorSpaceConversion: 'none', imageOrientation: 'none'}).then(function(imageBitmap) { + t.finish({ + imageBitmap, + hasAlphaChannel: t._hasAlphaChannel() + }); + }).catch(function(e) { + t.error({type: "parse", message: "Error parsing image data"}); + }); + }; + + ImageWorkerServerItem.prototype._hasAlphaChannel = function() { + if (ImageWorkerServer.isWPEBrowser()) { + // When using unaccelerated rendering image (https://github.com/WebPlatformForEmbedded/WPEWebKit/blob/wpe-20170728/Source/WebCore/html/ImageBitmap.cpp#L52), + // everything including JPG images are in RGBA format. Upload is way faster when using an alpha channel. + // @todo: after hardware acceleration is fixed and re-enabled, JPG should be uploaded in RGB to get the best possible performance and memory usage. + return true; + } else { + return (this._mimeType.indexOf("image/png") !== -1); + } + }; + + ImageWorkerServerItem.prototype.cancel = function() { + if (this._canceled) return; + if (this._xhr) { + this._xhr.abort(); + } + this._canceled = true; + }; + + ImageWorkerServerItem.prototype.error = function(type, message) { + if (!this._canceled && this._onError) { + this._onError({type, message}); + } + }; + + ImageWorkerServerItem.prototype.finish = function(info) { + if (!this._canceled && this._onFinish) { + this._onFinish(info); + } + }; + + var worker = new ImageWorkerServer(); +}; + + +/***/ }), + +/***/ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/platforms/browser/WebPlatform.mjs": +/*!*****************************************************************************************************************!*\ + !*** ./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/platforms/browser/WebPlatform.mjs ***! + \*****************************************************************************************************************/ +/*! exports provided: default */ +/***/ (function(__webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return WebPlatform; }); +/* harmony import */ var _tree_Utils_mjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../tree/Utils.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/tree/Utils.mjs"); +/* harmony import */ var _ImageWorker_mjs__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./ImageWorker.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/platforms/browser/ImageWorker.mjs"); +/* + * If not stated otherwise in this file or this component's LICENSE file the + * following copyright and licenses apply: + * + * Copyright 2020 Metrological + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + + +/** + * Platform-specific functionality. + */ +class WebPlatform { + + init(stage) { + this.stage = stage; + this._looping = false; + this._awaitingLoop = false; + + // Alternative handler to avoid RAF when idle + this._loopHandler = null; + this._idleLoopCounter = 0; + this._idleLoopDelay = 60; + this._onIdle = false; + + if (this.stage.getOption("useImageWorker")) { + if (!window.createImageBitmap || !window.Worker) { + console.warn("[Lightning] Can't use image worker because browser does not have createImageBitmap and Web Worker support"); + } else { + this._imageWorker = new _ImageWorker_mjs__WEBPACK_IMPORTED_MODULE_1__["default"](); + } + } + + this._registerVisibilityChangeHandler(); + } + + destroy() { + if (this._imageWorker) { + this._imageWorker.destroy(); + } + + clearInterval(this._loopHandler); + + this._removeKeyHandler(); + this._removeClickHandler(); + this._removeHoverHandler(); + this._removeScrollWheelHandler(); + this._removeVisibilityChangeHandler(); + + this.stage = null; + delete this.stage; + } + + startLoop() { + this._looping = true; + if (!this._awaitingLoop) { + this.loop(); + } + } + + stopLoop() { + this._looping = false; + } + + switchLoop() { + if (this._onIdle === false) { + this._onIdle = true; + this.stage.onIdle(); + } + + if (this._idleLoopCounter < this._idleLoopDelay) { + this._idleLoopCounter++; + return; + } + if (!this.stage.ctx.hasRenderUpdates()) { + this.stopLoop(); + this._loopHandler = setInterval(() => { + this.stage.updateFrame(); + this.stage.idleFrame(); + if (this.stage.ctx.hasRenderUpdates()) { + clearInterval(this._loopHandler); + this.startLoop(); + }; + }, 1000 / 60); + } else { + this._idleLoopCounter = 0; + } + } + + loop() { + let self = this; + let lp = function () { + self._awaitingLoop = false; + self._onIdle = false; + if (self._looping) { + self.stage.updateFrame(); + if (self.stage.getOption("pauseRafLoopOnIdle")) { + self.switchLoop(); + } + self.stage.renderFrame(); + requestAnimationFrame(lp); + self._awaitingLoop = true; + } + } + requestAnimationFrame(lp); + } + + uploadCompressedGlTexture(gl, textureSource, source, options) { + const view = !source.pvr ? new DataView(source.mipmaps[0]) : source.mipmaps[0]; + gl.compressedTexImage2D( + gl.TEXTURE_2D, + 0, + source.glInternalFormat, + source.pixelWidth, + source.pixelHeight, + 0, + view, + ) + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR); + } + + uploadGlTexture(gl, textureSource, source, options) { + if (source instanceof ImageData || source instanceof HTMLImageElement || source instanceof HTMLVideoElement || (window.ImageBitmap && source instanceof ImageBitmap)) { + // Web-specific data types. + gl.texImage2D(gl.TEXTURE_2D, 0, options.internalFormat, options.format, options.type, source); + } else if (source instanceof HTMLCanvasElement) { + if (_tree_Utils_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].isZiggo || this.stage.getOption("forceTxCanvasSource")) { + // Ziggo EOS and Selene have issues with getImageData implementation causing artifacts. + gl.texImage2D(gl.TEXTURE_2D, 0, options.internalFormat, options.format, options.type, source); + } else if (source.width > 0 && source.height > 0) { + // Workaround for some browsers (e.g. Tizen) as they do not convert canvas data to texture correctly, sometimes causing artifacts. + // Width/Height check added because of https://github.com/rdkcentral/Lightning/issues/412 + const ctx = source.getContext('2d'); + gl.texImage2D(gl.TEXTURE_2D, 0, options.internalFormat, options.format, options.type, ctx.getImageData(0, 0, source.width, source.height)); + } + } else { + gl.texImage2D(gl.TEXTURE_2D, 0, options.internalFormat, textureSource.w, textureSource.h, 0, options.format, options.type, source); + } + } + + /** + * KTX File format specification + * https://www.khronos.org/registry/KTX/specs/1.0/ktxspec_v1.html + **/ + handleKtxLoad(cb, src) { + var self = this; + return function () { + var arraybuffer = this.response; + var view = new DataView(arraybuffer); + + // identifier, big endian + var targetIdentifier = 3632701469 + if (targetIdentifier !== (view.getUint32(0) + view.getUint32(4) + view.getUint32(8))) { + cb('Parsing failed: identifier ktx mismatch:', src) + } + + var littleEndian = (view.getUint32(12) === 16909060) ? true : false; + var data = { + glType: view.getUint32(16, littleEndian), + glTypeSize: view.getUint32(20, littleEndian), + glFormat: view.getUint32(24, littleEndian), + glInternalFormat: view.getUint32(28, littleEndian), + glBaseInternalFormat: view.getUint32(32, littleEndian), + pixelWidth: view.getUint32(36, littleEndian), + pixelHeight: view.getUint32(40, littleEndian), + pixelDepth: view.getUint32(44, littleEndian), + numberOfArrayElements: view.getUint32(48, littleEndian), + numberOfFaces: view.getUint32(52, littleEndian), + numberOfMipmapLevels: view.getUint32(56, littleEndian), + bytesOfKeyValueData: view.getUint32(60, littleEndian), + kvps: [], + mipmaps: [], + get width() { return this.pixelWidth }, + get height() { return this.pixelHeight }, + }; + + const props = (obj) => { + const p = []; + for (let v in obj) { + p.push(obj[v]); + } + return p; + } + + const formats = Object.values(self.stage.renderer.getCompressedTextureExtensions()) + .filter((obj) => obj != null) + .map((obj) => props(obj)) + .reduce((prev, current) => prev.concat(current)); + + if (!formats.includes(data.glInternalFormat)) { + console.warn("[Lightning] Unrecognized texture extension format:", src, data.glInternalFormat, self.stage.renderer.getCompressedTextureExtensions()); + } + + var offset = 64 + // Key Value Pairs of data start at byte offset 64 + // But the only known kvp is the API version, so skipping parsing. + offset += data.bytesOfKeyValueData; + + for (var i = 0; i < data.numberOfMipmapLevels; i++) { + var imageSize = view.getUint32(offset); + offset += 4; + data.mipmaps.push(view.buffer.slice(offset, imageSize)); + offset += imageSize + } + + cb(null, { + source: data, + renderInfo: { src: src, compressed: true }, + }) + } + } + + handlePvrLoad(cb, src) { + return function () { + // pvr header length in 32 bits + const pvrHeaderLength = 13; + // for now only we only support: COMPRESSED_RGB_ETC1_WEBGL + const pvrFormatEtc1 = 0x8D64; + const pvrWidth = 7; + const pvrHeight = 6; + const pvrMipmapCount = 11; + const pvrMetadata = 12; + const arrayBuffer = this.response; + const header = new Int32Array(arrayBuffer, 0, pvrHeaderLength); + const dataOffset = header[pvrMetadata] + 52; + const pvrtcData = new Uint8Array(arrayBuffer, dataOffset); + + var data = { + glInternalFormat: pvrFormatEtc1, + pixelWidth: header[pvrWidth], + pixelHeight: header[pvrHeight], + numberOfMipmapLevels: header[pvrMipmapCount], + mipmaps: [], + pvr: true, + get width() { return this.pixelWidth }, + get height() { return this.pixelHeight }, + }; + + let offset = 0 + let width = data.pixelWidth; + let height = data.pixelHeight; + + for (var i = 0; i < data.numberOfMipmapLevels; i++) { + const level = ((width + 3) >> 2) * ((height + 3) >> 2) * 8; + const view = new Uint8Array(arrayBuffer, pvrtcData.byteOffset + offset, level); + data.mipmaps.push(view); + offset += level; + width = width >> 1; + height = height >> 1; + } + + cb(null, { + source: data, + renderInfo: { src: src, compressed: true }, + }) + } + } + + loadSrcTexture({ src, hasAlpha }, cb) { + let cancelCb = undefined; + let isPng = (src.toLowerCase().indexOf(".png") >= 0) || src.substr(0, 21) == 'data:image/png;base64'; + let isKtx = src.indexOf('.ktx') >= 0; + let isPvr = src.indexOf('.pvr') >= 0; + if (isKtx || isPvr) { + let request = new XMLHttpRequest(); + request.addEventListener( + "load", isKtx ? this.handleKtxLoad(cb, src) : this.handlePvrLoad(cb, src) + ); + request.open("GET", src); + request.responseType = "arraybuffer"; + request.send(); + cancelCb = function () { + request.abort(); + } + } else if (this._imageWorker) { + // WPE-specific image parser. + const image = this._imageWorker.create(src); + image.onError = function (err) { + return cb("Image load error"); + }; + image.onLoad = function ({ imageBitmap, hasAlphaChannel }) { + cb(null, { + source: imageBitmap, + renderInfo: { src: src, compressed: false }, + hasAlpha: hasAlphaChannel, + premultiplyAlpha: true + }); + }; + cancelCb = function () { + image.cancel(); + } + } else { + let image = new Image(); + + // On the PS4 platform setting the `crossOrigin` attribute on + // images can cause CORS failures. + if (!(src.substr(0, 5) == "data:") && !_tree_Utils_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].isPS4) { + // Base64. + image.crossOrigin = "Anonymous"; + } + image.onerror = function (err) { + // Ignore error message when cancelled. + if (image.src) { + return cb("Image load error"); + } + }; + image.onload = function () { + cb(null, { + source: image, + renderInfo: { src: src, compressed: false }, + hasAlpha: isPng || hasAlpha + }); + }; + image.src = src; + + cancelCb = function () { + image.onerror = null; + image.onload = null; + image.removeAttribute('src'); + } + } + + return cancelCb; + } + + createWebGLContext(w, h) { + let canvas = this.stage.getOption('canvas') || document.createElement('canvas'); + + if (w && h) { + canvas.width = w; + canvas.height = h; + } + + let opts = { + alpha: true, + antialias: false, + premultipliedAlpha: true, + stencil: true, + preserveDrawingBuffer: false + }; + + let gl = canvas.getContext('webgl', opts) || canvas.getContext('experimental-webgl', opts) || canvas.getContext('webgl2', opts); + + if (!gl) { + throw new Error('This browser does not support webGL.'); + } + + return gl; + } + + createCanvasContext(w, h) { + let canvas = this.stage.getOption('canvas') || document.createElement('canvas'); + + if (w && h) { + canvas.width = w; + canvas.height = h; + } + + let c2d = canvas.getContext('2d'); + if (!c2d) { + throw new Error('This browser does not support 2d canvas.'); + } + + return c2d; + } + + getHrTime() { + return window.performance ? window.performance.now() : (new Date()).getTime(); + } + + getDrawingCanvas() { + // We can't reuse this canvas because textures may load async. + return document.createElement('canvas'); + } + + getTextureOptionsForDrawingCanvas(canvas) { + let options = {}; + options.source = canvas; + return options; + } + + nextFrame(changes) { + /* WebGL blits automatically */ + } + + registerKeydownHandler(keyhandler) { + this._keydownListener = (e) => { + keyhandler(e); + }; + window.addEventListener('keydown', this._keydownListener); + } + + registerKeyupHandler(keyhandler) { + this._keyupListener = (e) => { + keyhandler(e); + }; + window.addEventListener('keyup', this._keyupListener); + } + + _removeKeyHandler() { + if (this._keydownListener) { + window.removeEventListener('keydown', this._keydownListener); + } + + if (this._keyupListener) { + window.removeEventListener('keyup', this._keyupListener); + } + } + + registerClickHandler(clickHandler) { + this._clickListener = e => { + clickHandler(e); + }; + window.addEventListener('mousedown', this._clickListener); + } + + _removeClickHandler() { + if (this._clickListener) { + window.removeEventListener('mousedown', this._clickListener); + } + } + + registerHoverHandler(hoverHandler) { + this._hoverListener = e => { + hoverHandler(e); + }; + window.addEventListener('mousemove', this._hoverListener); + } + + _removeHoverHandler() { + if (this._hoverListener) { + window.removeEventListener('mousemove', this._hoverListener); + } + } + + registerScrollWheelHandler(registerScrollWheelHandler) { + this._scrollWheelListener = e => { + registerScrollWheelHandler(e); + } + window.addEventListener('wheel', this._scrollWheelListener); + } + + _removeScrollWheelHandler() { + if (this._scrollWheelListener) { + window.removeEventListener('wheel', this._scrollWheelListener); + } + } + + /** + * Fix for issue reported at: https://github.com/WebPlatformForEmbedded/WPEWebKit/issues/882 + */ + _registerVisibilityChangeHandler() { + this._visibilityChangeHandler = () => { + if (document.visibilityState === 'visible') { + this.stage.root.core.setHasRenderUpdates(2); + this.stage.renderFrame(); + } + } + document.addEventListener('visibilitychange', this._visibilityChangeHandler); + } + + _removeVisibilityChangeHandler() { + if (this._visibilityChangeHandler) { + document.removeEventListener('visibilitychange', this._visibilityChangeHandler); + } + } +} + + +/***/ }), + +/***/ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/renderer/Renderer.mjs": +/*!*****************************************************************************************************!*\ + !*** ./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/renderer/Renderer.mjs ***! + \*****************************************************************************************************/ +/*! exports provided: default */ +/***/ (function(__webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return Renderer; }); +/* harmony import */ var _tree_Base_mjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../tree/Base.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/tree/Base.mjs"); +/* + * If not stated otherwise in this file or this component's LICENSE file the + * following copyright and licenses apply: + * + * Copyright 2020 Metrological + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +class Renderer { + + constructor(stage) { + this.stage = stage; + this._defaultShader = undefined; + } + + gc(aggressive) { + } + + destroy() { + } + + getDefaultShader(ctx = this.stage.ctx) { + if (!this._defaultShader) { + this._defaultShader = this._createDefaultShader(ctx); + } + return this._defaultShader; + } + + _createDefaultShader(ctx) { + } + + isValidShaderType(shaderType) { + return (shaderType.prototype instanceof this._getShaderBaseType()); + } + + createShader(ctx, settings) { + const shaderType = settings.type; + // If shader type is not correct, use a different platform. + if (!this.isValidShaderType(shaderType)) { + const convertedShaderType = this._getShaderAlternative(shaderType); + if (!convertedShaderType) { + console.warn("[Lightning] Shader has no implementation for render target: " + shaderType.name); + return this._createDefaultShader(ctx); + } + return new convertedShaderType(ctx); + } else { + const shader = new shaderType(ctx); + _tree_Base_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].patchObject(this, settings); + return shader; + } + } + + _getShaderBaseType() { + } + + _getShaderAlternative(shaderType) { + return this.getDefaultShader(); + } + + copyRenderTexture(renderTexture, nativeTexture, options) { + console.warn('[Lightning] copyRenderTexture not supported by renderer'); + } +} + + + + +/***/ }), + +/***/ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/renderer/c2d/C2dCoreQuadList.mjs": +/*!****************************************************************************************************************!*\ + !*** ./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/renderer/c2d/C2dCoreQuadList.mjs ***! + \****************************************************************************************************************/ +/*! exports provided: default */ +/***/ (function(__webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return C2dCoreQuadList; }); +/* harmony import */ var _tree_core_CoreQuadList_mjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../tree/core/CoreQuadList.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/tree/core/CoreQuadList.mjs"); +/* + * If not stated otherwise in this file or this component's LICENSE file the + * following copyright and licenses apply: + * + * Copyright 2020 Metrological + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + +class C2dCoreQuadList extends _tree_core_CoreQuadList_mjs__WEBPACK_IMPORTED_MODULE_0__["default"] { + + constructor(ctx) { + super(ctx); + + this.renderContexts = []; + this.modes = []; + } + + setRenderContext(index, v) { + this.renderContexts[index] = v; + } + + setSimpleTc(index, v) { + if (v) { + this.modes[index] |= 1; + } else { + this.modes[index] -= (this.modes[index] & 1); + } + } + + setWhite(index, v) { + if (v) { + this.modes[index] |= 2; + } else { + this.modes[index] -= (this.modes[index] & 2); + } + } + + getRenderContext(index) { + return this.renderContexts[index]; + } + + getSimpleTc(index) { + return (this.modes[index] & 1); + } + + getWhite(index) { + return (this.modes[index] & 2); + } + +} + + +/***/ }), + +/***/ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/renderer/c2d/C2dCoreQuadOperation.mjs": +/*!*********************************************************************************************************************!*\ + !*** ./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/renderer/c2d/C2dCoreQuadOperation.mjs ***! + \*********************************************************************************************************************/ +/*! exports provided: default */ +/***/ (function(__webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return C2dCoreQuadOperation; }); +/* harmony import */ var _tree_core_CoreQuadOperation_mjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../tree/core/CoreQuadOperation.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/tree/core/CoreQuadOperation.mjs"); +/* + * If not stated otherwise in this file or this component's LICENSE file the + * following copyright and licenses apply: + * + * Copyright 2020 Metrological + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + +class C2dCoreQuadOperation extends _tree_core_CoreQuadOperation_mjs__WEBPACK_IMPORTED_MODULE_0__["default"] { + + getRenderContext(index) { + return this.quads.getRenderContext(this.index + index); + } + + getSimpleTc(index) { + return this.quads.getSimpleTc(this.index + index); + } + + getWhite(index) { + return this.quads.getWhite(this.index + index); + } + +} + + +/***/ }), + +/***/ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/renderer/c2d/C2dCoreRenderExecutor.mjs": +/*!**********************************************************************************************************************!*\ + !*** ./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/renderer/c2d/C2dCoreRenderExecutor.mjs ***! + \**********************************************************************************************************************/ +/*! exports provided: default */ +/***/ (function(__webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return C2dCoreRenderExecutor; }); +/* harmony import */ var _tree_core_CoreRenderExecutor_mjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../tree/core/CoreRenderExecutor.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/tree/core/CoreRenderExecutor.mjs"); +/* harmony import */ var _tree_StageUtils_mjs__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../tree/StageUtils.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/tree/StageUtils.mjs"); +/* harmony import */ var _tree_Utils_mjs__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../tree/Utils.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/tree/Utils.mjs"); +/* + * If not stated otherwise in this file or this component's LICENSE file the + * following copyright and licenses apply: + * + * Copyright 2020 Metrological + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + + + +class C2dCoreRenderExecutor extends _tree_core_CoreRenderExecutor_mjs__WEBPACK_IMPORTED_MODULE_0__["default"] { + + init() { + this._mainRenderTexture = this.ctx.stage.getCanvas(); + } + + _renderQuadOperation(op) { + let shader = op.shader; + + if (op.length || op.shader.addEmpty()) { + const target = this._renderTexture || this._mainRenderTexture; + shader.beforeDraw(op, target); + shader.draw(op, target); + shader.afterDraw(op, target); + } + } + + _clearRenderTexture() { + const ctx = this._getContext(); + + let clearColor = [0, 0, 0, 0]; + if (this._mainRenderTexture.ctx === ctx) { + clearColor = this.ctx.stage.getClearColor(); + } + + const renderTexture = ctx.canvas; + ctx.setTransform(1, 0, 0, 1, 0, 0); + if (!clearColor[0] && !clearColor[1] && !clearColor[2] && !clearColor[3]) { + ctx.clearRect(0, 0, renderTexture.width, renderTexture.height); + } else { + ctx.fillStyle = _tree_StageUtils_mjs__WEBPACK_IMPORTED_MODULE_1__["default"].getRgbaStringFromArray(clearColor); + // Do not use fillRect because it produces artifacts. + ctx.globalCompositeOperation = 'copy'; + ctx.beginPath(); + ctx.rect(0, 0, renderTexture.width, renderTexture.height); + ctx.closePath(); + ctx.fill(); + ctx.globalCompositeOperation = 'source-over'; + } + } + + _getContext() { + if (this._renderTexture) { + return this._renderTexture.ctx; + } else { + return this._mainRenderTexture.ctx; + } + } + + _restoreContext() { + const ctx = this._getContext(); + ctx.restore(); + ctx.save(); + ctx._scissor = null; + } + + _setScissor(area) { + const ctx = this._getContext(); + + if (!C2dCoreRenderExecutor._equalScissorAreas(ctx.canvas, ctx._scissor, area)) { + // Clipping is stored in the canvas context state. + // We can't reset clipping alone so we need to restore the full context. + this._restoreContext(); + + let precision = this.ctx.stage.getRenderPrecision(); + if (area) { + ctx.beginPath(); + ctx.rect(Math.round(area[0] * precision), Math.round(area[1] * precision), Math.round(area[2] * precision), Math.round(area[3] * precision)); + ctx.closePath(); + ctx.clip(); + } + ctx._scissor = area; + } + } + + static _equalScissorAreas(canvas, area, current) { + if (!area) { + area = [0, 0, canvas.width, canvas.height] + } + if (!current) { + current = [0, 0, canvas.width, canvas.height] + } + return _tree_Utils_mjs__WEBPACK_IMPORTED_MODULE_2__["default"].equalValues(area, current) + } + +} + + +/***/ }), + +/***/ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/renderer/c2d/C2dRenderer.mjs": +/*!************************************************************************************************************!*\ + !*** ./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/renderer/c2d/C2dRenderer.mjs ***! + \************************************************************************************************************/ +/*! exports provided: default */ +/***/ (function(__webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return C2dRenderer; }); +/* harmony import */ var _C2dCoreQuadList_mjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./C2dCoreQuadList.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/renderer/c2d/C2dCoreQuadList.mjs"); +/* harmony import */ var _C2dCoreQuadOperation_mjs__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./C2dCoreQuadOperation.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/renderer/c2d/C2dCoreQuadOperation.mjs"); +/* harmony import */ var _C2dCoreRenderExecutor_mjs__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./C2dCoreRenderExecutor.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/renderer/c2d/C2dCoreRenderExecutor.mjs"); +/* harmony import */ var _tree_core_CoreRenderState_mjs__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../tree/core/CoreRenderState.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/tree/core/CoreRenderState.mjs"); +/* harmony import */ var _shaders_DefaultShader_mjs__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./shaders/DefaultShader.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/renderer/c2d/shaders/DefaultShader.mjs"); +/* harmony import */ var _C2dShader_mjs__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./C2dShader.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/renderer/c2d/C2dShader.mjs"); +/* harmony import */ var _Renderer_mjs__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../Renderer.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/renderer/Renderer.mjs"); +/* harmony import */ var _C2dTextureTintManager_mjs__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./C2dTextureTintManager.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/renderer/c2d/C2dTextureTintManager.mjs"); +/* + * If not stated otherwise in this file or this component's LICENSE file the + * following copyright and licenses apply: + * + * Copyright 2020 Metrological + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + + + + + + + + +class C2dRenderer extends _Renderer_mjs__WEBPACK_IMPORTED_MODULE_6__["default"] { + + constructor(stage) { + super(stage); + + this.tintManager = new _C2dTextureTintManager_mjs__WEBPACK_IMPORTED_MODULE_7__["default"](stage); + + this.setupC2d(this.stage.c2d.canvas); + } + + destroy() { + this.tintManager.destroy(); + + this.tintManager = null; + delete this.tintManager; + } + + _createDefaultShader(ctx) { + return new _shaders_DefaultShader_mjs__WEBPACK_IMPORTED_MODULE_4__["default"](ctx); + } + + _getShaderBaseType() { + return _C2dShader_mjs__WEBPACK_IMPORTED_MODULE_5__["default"] + } + + _getShaderAlternative(shaderType) { + return shaderType.getC2d && shaderType.getC2d(); + } + + createCoreQuadList(ctx) { + return new _C2dCoreQuadList_mjs__WEBPACK_IMPORTED_MODULE_0__["default"](ctx); + } + + createCoreQuadOperation(ctx, shader, shaderOwner, renderTextureInfo, scissor, index) { + return new _C2dCoreQuadOperation_mjs__WEBPACK_IMPORTED_MODULE_1__["default"](ctx, shader, shaderOwner, renderTextureInfo, scissor, index); + } + + createCoreRenderExecutor(ctx) { + return new _C2dCoreRenderExecutor_mjs__WEBPACK_IMPORTED_MODULE_2__["default"](ctx); + } + + createCoreRenderState(ctx) { + return new _tree_core_CoreRenderState_mjs__WEBPACK_IMPORTED_MODULE_3__["default"](ctx); + } + + createRenderTexture(w, h, pw, ph) { + const canvas = document.createElement('canvas'); + canvas.width = pw; + canvas.height = ph; + this.setupC2d(canvas); + return canvas; + } + + freeRenderTexture(nativeTexture) { + this.tintManager.delete(nativeTexture); + } + + gc(aggressive) { + this.tintManager.gc(aggressive); + } + + uploadTextureSource(textureSource, options) { + // For canvas, we do not need to upload. + if (options.source.buffer) { + // Convert RGBA buffer to canvas. + const canvas = document.createElement('canvas'); + canvas.width = options.w; + canvas.height = options.h; + + const imageData = new ImageData(new Uint8ClampedArray(options.source.buffer), options.w, options.h); + canvas.getContext('2d').putImageData(imageData, 0, 0); + return canvas; + } + + return options.source; + } + + freeTextureSource(textureSource) { + this.tintManager.delete(textureSource.nativeTexture); + } + + addQuad(renderState, quads, index) { + // Render context changes while traversing so we save it by ref. + const elementCore = quads.quadElements[index]; + quads.setRenderContext(index, elementCore._renderContext); + quads.setWhite(index, elementCore.isWhite()); + quads.setSimpleTc(index, elementCore.hasSimpleTexCoords()); + } + + isRenderTextureReusable(renderState, renderTextureInfo) { + // @todo: check render coords/matrix, maybe move this to core? + return false; + } + + finishRenderState(renderState) { + } + + setupC2d(canvas) { + const ctx = canvas.getContext('2d'); + canvas.ctx = ctx; + + ctx._scissor = null; + + // Save base state so we can restore the defaults later. + canvas.ctx.save(); + } + +} + + +/***/ }), + +/***/ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/renderer/c2d/C2dShader.mjs": +/*!**********************************************************************************************************!*\ + !*** ./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/renderer/c2d/C2dShader.mjs ***! + \**********************************************************************************************************/ +/*! exports provided: default */ +/***/ (function(__webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return C2dShader; }); +/* harmony import */ var _tree_Shader_mjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../tree/Shader.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/tree/Shader.mjs"); +/* + * If not stated otherwise in this file or this component's LICENSE file the + * following copyright and licenses apply: + * + * Copyright 2020 Metrological + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + +class C2dShader extends _tree_Shader_mjs__WEBPACK_IMPORTED_MODULE_0__["default"] { + + beforeDraw(operation) { + } + + draw(operation) { + } + + afterDraw(operation) { + } + +} + + +/***/ }), + +/***/ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/renderer/c2d/C2dTextureTintManager.mjs": +/*!**********************************************************************************************************************!*\ + !*** ./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/renderer/c2d/C2dTextureTintManager.mjs ***! + \**********************************************************************************************************************/ +/*! exports provided: default */ +/***/ (function(__webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return C2dTextureTintManager; }); +/* + * If not stated otherwise in this file or this component's LICENSE file the + * following copyright and licenses apply: + * + * Copyright 2020 Metrological + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +class C2dTextureTintManager { + + constructor(stage) { + this.stage = stage; + this._usedMemory = 0; + this._cachedNativeTextures = new Set(); + } + + destroy() { + this.gc(true); + + this.stage = null; + delete this.stage; + } + + _addMemoryUsage(delta) { + this._usedMemory += delta; + + this.stage.addMemoryUsage(delta); + } + + delete(nativeTexture) { + // Should be called when native texture is cleaned up. + if (this._hasCache(nativeTexture)) { + const cache = this._getCache(nativeTexture); + const prevMemUsage = cache.memoryUsage; + cache.clear(); + this._cachedNativeTextures.delete(nativeTexture); + this._addMemoryUsage(cache.memoryUsage - prevMemUsage); + } + } + + getTintTexture(nativeTexture, color) { + const frame = this.stage.frameCounter; + + this._cachedNativeTextures.add(nativeTexture); + + const cache = this._getCache(nativeTexture); + + const item = cache.get(color); + item.lf = frame; + + if (item.tx) { + if (nativeTexture.update > item.u) { + // Native texture was updated in the mean time: renew. + this._tintTexture(item.tx, nativeTexture, color) + } + + return item.tx; + } else { + const before = cache.memoryUsage; + + // Find blanco tint texture. + let target = cache.reuseTexture(frame); + if (target) { + target.ctx.clearRect(0, 0, target.width, target.height); + } else { + // Allocate new. + target = document.createElement('canvas'); + target.width = nativeTexture.w; + target.height = nativeTexture.h; + target.ctx = target.getContext('2d'); + } + + this._tintTexture(target, nativeTexture, color); + cache.set(color, target, frame); + + const after = cache.memoryUsage; + + if (after !== before) { + this._addMemoryUsage(after - before); + } + + return target; + } + } + + _tintTexture(target, source, color) { + let col = color.toString(16); + while (col.length < 6) { + col = "0" + col; + } + target.ctx.fillStyle = '#' + col; + target.ctx.globalCompositeOperation = 'copy'; + target.ctx.fillRect(0, 0, source.w, source.h); + target.ctx.globalCompositeOperation = 'multiply'; + target.ctx.drawImage(source, 0, 0, source.w, source.h, 0, 0, target.width, target.height); + + // Alpha-mix the texture. + target.ctx.globalCompositeOperation = 'destination-in'; + target.ctx.drawImage(source, 0, 0, source.w, source.h, 0, 0, target.width, target.height); + } + + _hasCache(nativeTexture) { + return !!nativeTexture._tintCache; + } + + _getCache(nativeTexture) { + if (!nativeTexture._tintCache) { + nativeTexture._tintCache = new C2dTintCache(nativeTexture); + } + return nativeTexture._tintCache; + } + + gc(aggressive = false) { + const frame = this.stage.frameCounter; + let delta = 0; + this._cachedNativeTextures.forEach(texture => { + const cache = this._getCache(texture); + if (aggressive) { + delta += cache.memoryUsage; + cache.clear(); + } else { + const before = cache.memoryUsage; + cache.cleanup(frame); + cache.releaseBlancoTextures(); + delta += (cache.memoryUsage - before); + } + }); + + if (aggressive) { + this._cachedNativeTextures.clear(); + } + + if (delta) { + this._addMemoryUsage(delta); + } + } + +} + +class C2dTintCache { + + constructor(nativeTexture) { + this._tx = nativeTexture; + this._colors = new Map(); + this._blancoTextures = null; + this._lastCleanupFrame = 0; + this._memTextures = 0; + } + + get memoryUsage() { + return this._memTextures * this._tx.w * this._tx.h; + } + + releaseBlancoTextures() { + this._memTextures -= this._blancoTextures.length; + this._blancoTextures = []; + } + + clear() { + // Dereference the textures. + this._blancoTextures = null; + this._colors.clear(); + this._memTextures = 0; + } + + get(color) { + let item = this._colors.get(color); + if (!item) { + item = {lf: -1, tx: undefined, u: -1}; + this._colors.set(color, item); + } + return item; + } + + set(color, texture, frame) { + const item = this.get(color); + item.lf = frame; + item.tx = texture; + item.u = frame; + this._memTextures++; + } + + cleanup(frame) { + // We only need to clean up once per frame. + if (this._lastCleanupFrame !== frame) { + + // We limit blanco textures reuse to one frame only to prevent memory usage growth. + this._blancoTextures = []; + + this._colors.forEach((item, color) => { + // Clean up entries that were not used last frame. + if (item.lf < frame - 1) { + if (item.tx) { + // Keep as reusable blanco texture. + this._blancoTextures.push(item.tx); + } + this._colors.delete(color); + } + }); + + this._lastCleanupFrame = frame; + } + } + + reuseTexture(frame) { + // Try to reuse textures, because creating them every frame is expensive. + this.cleanup(frame); + if (this._blancoTextures && this._blancoTextures.length) { + this._memTextures--; + return this._blancoTextures.pop(); + } + } + +} + + + +/***/ }), + +/***/ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/renderer/c2d/shaders/BlurShader.mjs": +/*!*******************************************************************************************************************!*\ + !*** ./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/renderer/c2d/shaders/BlurShader.mjs ***! + \*******************************************************************************************************************/ +/*! exports provided: default */ +/***/ (function(__webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return BlurShader; }); +/* harmony import */ var _DefaultShader_mjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./DefaultShader.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/renderer/c2d/shaders/DefaultShader.mjs"); +/* + * If not stated otherwise in this file or this component's LICENSE file the + * following copyright and licenses apply: + * + * Copyright 2020 Metrological + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + +class BlurShader extends _DefaultShader_mjs__WEBPACK_IMPORTED_MODULE_0__["default"] { + + constructor(context) { + super(context); + this._kernelRadius = 1; + } + + get kernelRadius() { + return this._kernelRadius; + } + + set kernelRadius(v) { + this._kernelRadius = v; + this.redraw(); + } + + useDefault() { + return this._amount === 0; + } + + _beforeDrawEl({target}) { + target.ctx.filter = "blur(" + this._kernelRadius + "px)"; + } + + _afterDrawEl({target}) { + target.ctx.filter = "none"; + } + +} + + + +/***/ }), + +/***/ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/renderer/c2d/shaders/DefaultShader.mjs": +/*!**********************************************************************************************************************!*\ + !*** ./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/renderer/c2d/shaders/DefaultShader.mjs ***! + \**********************************************************************************************************************/ +/*! exports provided: default */ +/***/ (function(__webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return DefaultShader; }); +/* harmony import */ var _C2dShader_mjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../C2dShader.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/renderer/c2d/C2dShader.mjs"); +/* harmony import */ var _tree_StageUtils_mjs__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../../tree/StageUtils.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/tree/StageUtils.mjs"); +/* + * If not stated otherwise in this file or this component's LICENSE file the + * following copyright and licenses apply: + * + * Copyright 2020 Metrological + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + + +class DefaultShader extends _C2dShader_mjs__WEBPACK_IMPORTED_MODULE_0__["default"] { + + constructor(ctx) { + super(ctx); + this._rectangleTexture = ctx.stage.rectangleTexture.source.nativeTexture; + this._tintManager = this.ctx.stage.renderer.tintManager; + } + + draw(operation, target) { + const ctx = target.ctx; + let length = operation.length; + for (let i = 0; i < length; i++) { + const tx = operation.getTexture(i); + const vc = operation.getElementCore(i); + const rc = operation.getRenderContext(i); + const white = operation.getWhite(i); + const stc = operation.getSimpleTc(i); + + //@todo: try to optimize out per-draw transform setting. split translate, transform. + const precision = this.ctx.stage.getRenderPrecision(); + ctx.setTransform(rc.ta * precision, rc.tc * precision, rc.tb * precision, rc.td * precision, rc.px * precision, rc.py * precision); + + const rect = (tx === this._rectangleTexture); + const info = {operation, target, index: i, rect}; + + if (rect) { + // Check for gradient. + if (white) { + ctx.fillStyle = 'white'; + } else { + this._setColorGradient(ctx, vc); + } + + ctx.globalAlpha = rc.alpha; + this._beforeDrawEl(info); + ctx.fillRect(0, 0, vc.w, vc.h); + this._afterDrawEl(info); + ctx.globalAlpha = 1.0; + } else { + // @todo: set image smoothing based on the texture. + + // @todo: optimize by registering whether identity texcoords are used. + ctx.globalAlpha = rc.alpha; + this._beforeDrawEl(info); + + // @todo: test if rounding yields better performance. + + // Notice that simple texture coords can be turned on even though vc._ulx etc are not simple, because + // we are rendering a render-to-texture (texcoords were stashed). Same is true for 'white' color btw. + const sourceX = stc ? 0 : (vc._ulx * tx.w); + const sourceY = stc ? 0 : (vc._uly * tx.h); + const sourceW = (stc ? 1 : (vc._brx - vc._ulx)) * tx.w; + const sourceH = (stc ? 1 : (vc._bry - vc._uly)) * tx.h; + + let colorize = !white; + if (colorize) { + // @todo: cache the tint texture for better performance. + + // Draw to intermediate texture with background color/gradient. + // This prevents us from having to create a lot of render texture canvases. + + // Notice that we don't support (non-rect) gradients, only color tinting for c2d. We'll just take the average color. + let color = vc._colorUl; + if (vc._colorUl !== vc._colorUr || vc._colorUr !== vc._colorBl || vc._colorBr !== vc._colorBl) { + color = _tree_StageUtils_mjs__WEBPACK_IMPORTED_MODULE_1__["default"].mergeMultiColorsEqual([vc._colorUl, vc._colorUr, vc._colorBl, vc._colorBr]); + } + + const alpha = ((color / 16777216) | 0) / 255.0; + ctx.globalAlpha *= alpha; + + const rgb = color & 0x00FFFFFF; + const tintTexture = this._tintManager.getTintTexture(tx, rgb); + + // Actually draw result. + ctx.fillStyle = 'white'; + ctx.drawImage(tintTexture, sourceX, sourceY, sourceW, sourceH, 0, 0, vc.w, vc.h); + } else { + ctx.fillStyle = 'white'; + ctx.drawImage(tx, sourceX, sourceY, sourceW, sourceH, 0, 0, vc.w, vc.h); + } + this._afterDrawEl(info); + ctx.globalAlpha = 1.0; + } + } + } + + _setColorGradient(ctx, vc, w = vc.w, h = vc.h, transparency = true) { + let color = vc._colorUl; + let gradient; + //@todo: quick single color check. + //@todo: cache gradient/fill style (if possible, probably context-specific). + + if (vc._colorUl === vc._colorUr) { + if (vc._colorBl === vc._colorBr) { + if (vc._colorUl === vc.colorBl) { + // Single color. + } else { + // Vertical gradient. + gradient = ctx.createLinearGradient(0, 0, 0, h); + if (transparency) { + gradient.addColorStop(0, _tree_StageUtils_mjs__WEBPACK_IMPORTED_MODULE_1__["default"].getRgbaString(vc._colorUl)); + gradient.addColorStop(1, _tree_StageUtils_mjs__WEBPACK_IMPORTED_MODULE_1__["default"].getRgbaString(vc._colorBl)); + } else { + gradient.addColorStop(0, _tree_StageUtils_mjs__WEBPACK_IMPORTED_MODULE_1__["default"].getRgbString(vc._colorUl)); + gradient.addColorStop(1, _tree_StageUtils_mjs__WEBPACK_IMPORTED_MODULE_1__["default"].getRgbString(vc._colorBl)); + + } + } + } else { + // Not supported gradient. + } + } else { + if (vc._colorUl === vc._colorBl && vc._colorUr === vc._colorBr) { + // Horizontal gradient. + gradient = ctx.createLinearGradient(0, 0, w, 0); + if (transparency) { + gradient.addColorStop(0, _tree_StageUtils_mjs__WEBPACK_IMPORTED_MODULE_1__["default"].getRgbaString(vc._colorUl)); + gradient.addColorStop(1, _tree_StageUtils_mjs__WEBPACK_IMPORTED_MODULE_1__["default"].getRgbaString(vc._colorBr)); + } else { + gradient.addColorStop(0, _tree_StageUtils_mjs__WEBPACK_IMPORTED_MODULE_1__["default"].getRgbString(vc._colorUl)); + gradient.addColorStop(1, _tree_StageUtils_mjs__WEBPACK_IMPORTED_MODULE_1__["default"].getRgbString(vc._colorBr)); + } + } + } + + if (gradient) { + ctx.fillStyle = gradient; + } else { + ctx.fillStyle = transparency ? _tree_StageUtils_mjs__WEBPACK_IMPORTED_MODULE_1__["default"].getRgbaString(color) : _tree_StageUtils_mjs__WEBPACK_IMPORTED_MODULE_1__["default"].getRgbString(color); + } + } + + _beforeDrawEl(info) { + } + + _afterDrawEl(info) { + } + +} + + +/***/ }), + +/***/ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/renderer/common/shaders/GrayscaleShader.mjs": +/*!***************************************************************************************************************************!*\ + !*** ./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/renderer/common/shaders/GrayscaleShader.mjs ***! + \***************************************************************************************************************************/ +/*! exports provided: WebGLGrayscaleShader, C2dGrayscaleShader */ +/***/ (function(__webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "WebGLGrayscaleShader", function() { return WebGLGrayscaleShader; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "C2dGrayscaleShader", function() { return C2dGrayscaleShader; }); +/* harmony import */ var _c2d_shaders_DefaultShader_mjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../c2d/shaders/DefaultShader.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/renderer/c2d/shaders/DefaultShader.mjs"); +/* harmony import */ var _webgl_shaders_DefaultShader_mjs__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../webgl/shaders/DefaultShader.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/renderer/webgl/shaders/DefaultShader.mjs"); +/* + * If not stated otherwise in this file or this component's LICENSE file the + * following copyright and licenses apply: + * + * Copyright 2020 Metrological + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + + +class WebGLGrayscaleShader extends _webgl_shaders_DefaultShader_mjs__WEBPACK_IMPORTED_MODULE_1__["default"] { + + constructor(context) { + super(context); + this._amount = 1; + } + + static getC2d() { + return C2dGrayscaleShader; + } + + + set amount(v) { + this._amount = v; + this.redraw(); + } + + get amount() { + return this._amount; + } + + useDefault() { + return this._amount === 0; + } + + setupUniforms(operation) { + super.setupUniforms(operation); + this._setUniform("amount", this._amount, this.gl.uniform1f); + } + +} + +WebGLGrayscaleShader.fragmentShaderSource = ` + #ifdef GL_ES + # ifdef GL_FRAGMENT_PRECISION_HIGH + precision highp float; + # else + precision lowp float; + # endif + #endif + varying vec2 vTextureCoord; + varying vec4 vColor; + uniform sampler2D uSampler; + uniform float amount; + void main(void){ + vec4 color = texture2D(uSampler, vTextureCoord) * vColor; + float grayness = 0.2 * color.r + 0.6 * color.g + 0.2 * color.b; + gl_FragColor = vec4(amount * vec3(grayness, grayness, grayness) + (1.0 - amount) * color.rgb, color.a); + } +`; + +class C2dGrayscaleShader extends _c2d_shaders_DefaultShader_mjs__WEBPACK_IMPORTED_MODULE_0__["default"] { + + constructor(context) { + super(context); + this._amount = 1; + } + + static getWebGL() { + return WebGLGrayscaleShader; + } + + + set amount(v) { + this._amount = v; + this.redraw(); + } + + get amount() { + return this._amount; + } + + useDefault() { + return this._amount === 0; + } + + _beforeDrawEl({target}) { + target.ctx.filter = "grayscale(" + this._amount + ")"; + } + + _afterDrawEl({target}) { + target.ctx.filter = "none"; + } + +} + + +/***/ }), + +/***/ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/renderer/spark/SparkRenderer.mjs": +/*!****************************************************************************************************************!*\ + !*** ./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/renderer/spark/SparkRenderer.mjs ***! + \****************************************************************************************************************/ +/*! exports provided: default */ +/***/ (function(__webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return SparkRenderer; }); +/* harmony import */ var _webgl_WebGLRenderer_mjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../webgl/WebGLRenderer.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/renderer/webgl/WebGLRenderer.mjs"); +/* harmony import */ var _shaders_SparkShader_mjs__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./shaders/SparkShader.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/renderer/spark/shaders/SparkShader.mjs"); +/* + * If not stated otherwise in this file or this component's LICENSE file the + * following copyright and licenses apply: + * + * Copyright 2020 Metrological + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + + +class SparkRenderer extends _webgl_WebGLRenderer_mjs__WEBPACK_IMPORTED_MODULE_0__["default"] { + + constructor(stage) { + super(stage); + } + + _createDefaultShader(ctx) { + return new _shaders_SparkShader_mjs__WEBPACK_IMPORTED_MODULE_1__["default"](ctx); + } + + createCoreRenderExecutor(ctx) { + global.beginDrawing(); + let ret = super.createCoreRenderExecutor(ctx); + global.endDrawing(); + return ret; + } +} + + +/***/ }), + +/***/ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/renderer/spark/shaders/SparkShader.mjs": +/*!**********************************************************************************************************************!*\ + !*** ./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/renderer/spark/shaders/SparkShader.mjs ***! + \**********************************************************************************************************************/ +/*! exports provided: default */ +/***/ (function(__webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return SparkShader; }); +/* harmony import */ var _webgl_WebGLShader_mjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../webgl/WebGLShader.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/renderer/webgl/WebGLShader.mjs"); +/* + * If not stated otherwise in this file or this component's LICENSE file the + * following copyright and licenses apply: + * + * Copyright 2020 Metrological + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + +class SparkShader extends _webgl_WebGLShader_mjs__WEBPACK_IMPORTED_MODULE_0__["default"] { + + enableAttribs() { + // Enables the attribs in the shader program. + let gl = this.gl; + gl.vertexAttribPointer(this._attrib("aVertexPosition"), 2, gl.FLOAT, false, 20, 0); + gl.enableVertexAttribArray(this._attrib("aVertexPosition")); + + if (this._attrib("aTextureCoord") !== -1) { + gl.vertexAttribPointer(this._attrib("aTextureCoord"), 2, gl.FLOAT, false, 20, 2 * 4); + gl.enableVertexAttribArray(this._attrib("aTextureCoord")); + } + + if (this._attrib("aColor") !== -1) { + // Some shaders may ignore the color. + gl.vertexAttribPointer(this._attrib("aColor"), 4, gl.UNSIGNED_BYTE, true, 20, 4 * 4); + gl.enableVertexAttribArray(this._attrib("aColor")); + } + } + + disableAttribs() { + // Disables the attribs in the shader program. + let gl = this.gl; + gl.disableVertexAttribArray(this._attrib("aVertexPosition")); + + if (this._attrib("aTextureCoord") !== -1) { + gl.disableVertexAttribArray(this._attrib("aTextureCoord")); + } + + if (this._attrib("aColor") !== -1) { + gl.disableVertexAttribArray(this._attrib("aColor")); + } + } + + setupUniforms(operation) { + this._setUniform("projection", this._getProjection(operation), this.gl.uniform2fv, false); + } + + draw(operation) { + let gl = this.gl; + + let length = operation.length; + + if (length) { + let glTexture = operation.getTexture(0); + let pos = 0; + for (let i = 0; i < length; i++) { + let tx = operation.getTexture(i); + if (glTexture !== tx) { + if (glTexture.options && glTexture.options.imageRef) { + let elementPostion = (i > 0) ? (i - 1) : i; + const precision = this.ctx.stage.getOption('precision'); + let vc = operation.getElementCore(elementPostion); + this.ctx.stage.platform.paint(gl, glTexture.options.imageRef, vc._worldContext.px*precision, vc._worldContext.py*precision, vc._colorUl, vc); + } else { + gl.bindTexture(gl.TEXTURE_2D, glTexture); + gl.drawElements(gl.TRIANGLES, 6 * (i - pos), gl.UNSIGNED_SHORT, (pos + operation.index) * 6 * 2); + } + glTexture = tx; + pos = i; + } + } + if (pos < length) { + if (glTexture.options && glTexture.options.imageRef) { + const precision = this.ctx.stage.getOption('precision'); + let vc = operation.getElementCore(pos); + this.ctx.stage.platform.paint(gl, glTexture.options.imageRef, vc._worldContext.px*precision, vc._worldContext.py*precision, vc._colorUl, vc); + } else { + gl.bindTexture(gl.TEXTURE_2D, glTexture); + gl.drawElements(gl.TRIANGLES, 6 * (length - pos), gl.UNSIGNED_SHORT, (pos + operation.index) * 6 * 2); + } + } + } + } + +} + +SparkShader.vertexShaderSource = ` + #ifdef GL_ES + # ifdef GL_FRAGMENT_PRECISION_HIGH + precision highp float; + # else + precision lowp float; + # endif + #endif + attribute vec2 aVertexPosition; + attribute vec2 aTextureCoord; + attribute vec4 aColor; + uniform vec2 projection; + varying vec2 vTextureCoord; + varying vec4 vColor; + void main(void){ + gl_Position = vec4(aVertexPosition.x * projection.x - 1.0, aVertexPosition.y * -abs(projection.y) + 1.0, 0.0, 1.0); + vTextureCoord = aTextureCoord; + vColor = aColor; + gl_Position.y = -sign(projection.y) * gl_Position.y; + } +`; + +SparkShader.fragmentShaderSource = ` + #ifdef GL_ES + # ifdef GL_FRAGMENT_PRECISION_HIGH + precision highp float; + # else + precision lowp float; + # endif + #endif + varying vec2 vTextureCoord; + varying vec4 vColor; + uniform sampler2D uSampler; + void main(void){ + gl_FragColor = texture2D(uSampler, vTextureCoord) * vColor; + } +`; + + + +/***/ }), + +/***/ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/renderer/webgl/WebGLCoreQuadList.mjs": +/*!********************************************************************************************************************!*\ + !*** ./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/renderer/webgl/WebGLCoreQuadList.mjs ***! + \********************************************************************************************************************/ +/*! exports provided: default */ +/***/ (function(__webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return WebGLCoreQuadList; }); +/* harmony import */ var _tree_core_CoreQuadList_mjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../tree/core/CoreQuadList.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/tree/core/CoreQuadList.mjs"); +/* + * If not stated otherwise in this file or this component's LICENSE file the + * following copyright and licenses apply: + * + * Copyright 2020 Metrological + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + +class WebGLCoreQuadList extends _tree_core_CoreQuadList_mjs__WEBPACK_IMPORTED_MODULE_0__["default"] { + + constructor(ctx) { + super(ctx); + + // Allocate a fairly big chunk of memory that should be enough to support ~100000 (default) quads. + // We do not (want to) handle memory overflow. + const byteSize = ctx.stage.getOption('bufferMemory'); + + this.dataLength = 0; + + this.data = new ArrayBuffer(byteSize); + this.floats = new Float32Array(this.data); + this.uints = new Uint32Array(this.data); + } + + getAttribsDataByteOffset(index) { + // Where this quad can be found in the attribs buffer. + return index * 80; + } + + getQuadContents() { + // Debug: log contents of quad buffer. + let floats = this.floats; + let uints = this.uints; + let lines = []; + for (let i = 1; i <= this.length; i++) { + let str = 'entry ' + i + ': '; + for (let j = 0; j < 4; j++) { + let b = i * 20 + j * 4; + str += floats[b] + ',' + floats[b+1] + ':' + floats[b+2] + ',' + floats[b+3] + '[' + uints[b+4].toString(16) + '] '; + } + lines.push(str); + } + + return lines; + } + + +} + + +/***/ }), + +/***/ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/renderer/webgl/WebGLCoreQuadOperation.mjs": +/*!*************************************************************************************************************************!*\ + !*** ./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/renderer/webgl/WebGLCoreQuadOperation.mjs ***! + \*************************************************************************************************************************/ +/*! exports provided: default */ +/***/ (function(__webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return WebGLCoreQuadOperation; }); +/* harmony import */ var _tree_core_CoreQuadOperation_mjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../tree/core/CoreQuadOperation.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/tree/core/CoreQuadOperation.mjs"); +/* + * If not stated otherwise in this file or this component's LICENSE file the + * following copyright and licenses apply: + * + * Copyright 2020 Metrological + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + +class WebGLCoreQuadOperation extends _tree_core_CoreQuadOperation_mjs__WEBPACK_IMPORTED_MODULE_0__["default"] { + + constructor(ctx, shader, shaderOwner, renderTextureInfo, scissor, index) { + super(ctx, shader, shaderOwner, renderTextureInfo, scissor, index); + + this.extraAttribsDataByteOffset = 0; + } + + getAttribsDataByteOffset(index) { + // Where this quad can be found in the attribs buffer. + return this.quads.getAttribsDataByteOffset(this.index + index); + } + + /** + * Returns the relative pixel coordinates in the shader owner to gl position coordinates in the render texture. + * @param x + * @param y + * @return {number[]} + */ + getNormalRenderTextureCoords(x, y) { + let coords = this.shaderOwner.getRenderTextureCoords(x, y); + coords[0] /= this.getRenderWidth(); + coords[1] /= this.getRenderHeight(); + coords[0] = coords[0] * 2 - 1; + coords[1] = 1 - coords[1] * 2; + return coords; + } + + getProjection() { + if (this.renderTextureInfo === null) { + return this.ctx.renderExec._projection; + } else { + return this.renderTextureInfo.nativeTexture.projection; + } + } + +} + + +/***/ }), + +/***/ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/renderer/webgl/WebGLCoreRenderExecutor.mjs": +/*!**************************************************************************************************************************!*\ + !*** ./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/renderer/webgl/WebGLCoreRenderExecutor.mjs ***! + \**************************************************************************************************************************/ +/*! exports provided: default */ +/***/ (function(__webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return WebGLCoreRenderExecutor; }); +/* harmony import */ var _tree_core_CoreRenderExecutor_mjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../tree/core/CoreRenderExecutor.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/tree/core/CoreRenderExecutor.mjs"); +/* + * If not stated otherwise in this file or this component's LICENSE file the + * following copyright and licenses apply: + * + * Copyright 2020 Metrological + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + +class WebGLCoreRenderExecutor extends _tree_core_CoreRenderExecutor_mjs__WEBPACK_IMPORTED_MODULE_0__["default"] { + + constructor(ctx) { + super(ctx) + + this.gl = this.ctx.stage.gl; + + this.init(); + } + + init() { + let gl = this.gl; + + // Create new sharable buffer for params. + this._attribsBuffer = gl.createBuffer(); + + let maxQuads = Math.floor(this.renderState.quads.data.byteLength / 80); + + // Init webgl arrays. + let allIndices = new Uint16Array(maxQuads * 6); + + // fill the indices with the quads to draw. + for (let i = 0, j = 0; i < maxQuads; i += 6, j += 4) { + allIndices[i] = j; + allIndices[i + 1] = j + 1; + allIndices[i + 2] = j + 2; + allIndices[i + 3] = j; + allIndices[i + 4] = j + 2; + allIndices[i + 5] = j + 3; + } + + // The quads buffer can be (re)used to draw a range of quads. + this._quadsBuffer = gl.createBuffer(); + gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this._quadsBuffer); + gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, allIndices, gl.STATIC_DRAW); + + // The matrix that causes the [0,0 - W,H] box to map to [-1,-1 - 1,1] in the end results. + this._projection = new Float32Array([2/this.ctx.stage.coordsWidth, -2/this.ctx.stage.coordsHeight]); + + } + + destroy() { + super.destroy(); + this.gl.deleteBuffer(this._attribsBuffer); + this.gl.deleteBuffer(this._quadsBuffer); + + this.gl = null; + delete this.gl; + } + + _reset() { + super._reset(); + + let gl = this.gl; + gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA); + gl.enable(gl.BLEND); + gl.disable(gl.DEPTH_TEST); + + this._stopShaderProgram(); + this._setupBuffers(); + } + + _setupBuffers() { + let gl = this.gl; + gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this._quadsBuffer); + let element = new Float32Array(this.renderState.quads.data, 0, this.renderState.quads.dataLength); + gl.bindBuffer(gl.ARRAY_BUFFER, this._attribsBuffer); + gl.bufferData(gl.ARRAY_BUFFER, element, gl.DYNAMIC_DRAW); + } + + _setupQuadOperation(quadOperation) { + super._setupQuadOperation(quadOperation); + this._useShaderProgram(quadOperation.shader, quadOperation); + } + + _renderQuadOperation(op) { + let shader = op.shader; + + if (op.length || op.shader.addEmpty()) { + shader.beforeDraw(op); + shader.draw(op); + shader.afterDraw(op); + } + } + + /** + * @param {WebGLShader} shader; + * @param {CoreQuadOperation} operation; + */ + _useShaderProgram(shader, operation) { + if (!shader.hasSameProgram(this._currentShaderProgram)) { + if (this._currentShaderProgram) { + this._currentShaderProgram.stopProgram(); + } + shader.useProgram(); + this._currentShaderProgram = shader; + } + shader.setupUniforms(operation); + } + + _stopShaderProgram() { + if (this._currentShaderProgram) { + // The currently used shader program should be stopped gracefully. + this._currentShaderProgram.stopProgram(); + this._currentShaderProgram = null; + } + } + + _bindRenderTexture(renderTexture) { + super._bindRenderTexture(renderTexture); + + let gl = this.gl; + if (!this._renderTexture) { + gl.bindFramebuffer(gl.FRAMEBUFFER, null); + gl.viewport(0,0,this.ctx.stage.w,this.ctx.stage.h); + } else { + gl.bindFramebuffer(gl.FRAMEBUFFER, this._renderTexture.framebuffer); + gl.viewport(0,0,this._renderTexture.w, this._renderTexture.h); + } + } + + _clearRenderTexture() { + super._clearRenderTexture(); + let gl = this.gl; + if (!this._renderTexture) { + let glClearColor = this.ctx.stage.getClearColor(); + if (glClearColor) { + gl.clearColor(glClearColor[0] * glClearColor[3], glClearColor[1] * glClearColor[3], glClearColor[2] * glClearColor[3], glClearColor[3]); + gl.clear(gl.COLOR_BUFFER_BIT); + } + } else { + // Clear texture. + gl.clearColor(0, 0, 0, 0); + gl.clear(gl.COLOR_BUFFER_BIT); + } + } + + _setScissor(area) { + super._setScissor(area); + + if (this._scissor === area) { + return; + } + this._scissor = area; + + let gl = this.gl; + if (!area) { + gl.disable(gl.SCISSOR_TEST); + } else { + gl.enable(gl.SCISSOR_TEST); + let precision = this.ctx.stage.getRenderPrecision(); + let y = area[1]; + if (this._renderTexture === null) { + // Flip. + y = (this.ctx.stage.h / precision - (area[1] + area[3])); + } + gl.scissor(Math.round(area[0] * precision), Math.round(y * precision), Math.round(area[2] * precision), Math.round(area[3] * precision)); + } + } + +} + + +/***/ }), + +/***/ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/renderer/webgl/WebGLRenderer.mjs": +/*!****************************************************************************************************************!*\ + !*** ./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/renderer/webgl/WebGLRenderer.mjs ***! + \****************************************************************************************************************/ +/*! exports provided: default */ +/***/ (function(__webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return WebGLRenderer; }); +/* harmony import */ var _tree_Utils_mjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../tree/Utils.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/tree/Utils.mjs"); +/* harmony import */ var _tree_StageUtils_mjs__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../tree/StageUtils.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/tree/StageUtils.mjs"); +/* harmony import */ var _WebGLCoreQuadList_mjs__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./WebGLCoreQuadList.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/renderer/webgl/WebGLCoreQuadList.mjs"); +/* harmony import */ var _WebGLCoreQuadOperation_mjs__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./WebGLCoreQuadOperation.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/renderer/webgl/WebGLCoreQuadOperation.mjs"); +/* harmony import */ var _WebGLCoreRenderExecutor_mjs__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./WebGLCoreRenderExecutor.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/renderer/webgl/WebGLCoreRenderExecutor.mjs"); +/* harmony import */ var _tree_core_CoreRenderState_mjs__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../../tree/core/CoreRenderState.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/tree/core/CoreRenderState.mjs"); +/* harmony import */ var _shaders_DefaultShader_mjs__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./shaders/DefaultShader.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/renderer/webgl/shaders/DefaultShader.mjs"); +/* harmony import */ var _WebGLShader_mjs__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./WebGLShader.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/renderer/webgl/WebGLShader.mjs"); +/* harmony import */ var _Renderer_mjs__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../Renderer.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/renderer/Renderer.mjs"); +/* + * If not stated otherwise in this file or this component's LICENSE file the + * following copyright and licenses apply: + * + * Copyright 2020 Metrological + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + + + + + + + + + +class WebGLRenderer extends _Renderer_mjs__WEBPACK_IMPORTED_MODULE_8__["default"] { + + constructor(stage) { + super(stage); + this.shaderPrograms = new Map(); + this._compressedTextureExtensions = { + astc: stage.gl.getExtension('WEBGL_compressed_texture_astc'), + etc1: stage.gl.getExtension('WEBGL_compressed_texture_etc1'), + s3tc: stage.gl.getExtension('WEBGL_compressed_texture_s3tc'), + pvrtc: stage.gl.getExtension('WEBGL_compressed_texture_pvrtc'), + } + } + + getCompressedTextureExtensions() { + return this._compressedTextureExtensions + } + + destroy() { + this.shaderPrograms.forEach(shaderProgram => shaderProgram.destroy()); + + this.shaderPrograms = null; + this._compressedTextureExtensions = null; + + delete this.shaderPrograms; + delete this._compressedTextureExtensions; + } + + _createDefaultShader(ctx) { + return new _shaders_DefaultShader_mjs__WEBPACK_IMPORTED_MODULE_6__["default"](ctx); + } + + _getShaderBaseType() { + return _WebGLShader_mjs__WEBPACK_IMPORTED_MODULE_7__["default"] + } + + _getShaderAlternative(shaderType) { + return shaderType.getWebGL && shaderType.getWebGL(); + } + + createCoreQuadList(ctx) { + return new _WebGLCoreQuadList_mjs__WEBPACK_IMPORTED_MODULE_2__["default"](ctx); + } + + createCoreQuadOperation(ctx, shader, shaderOwner, renderTextureInfo, scissor, index) { + return new _WebGLCoreQuadOperation_mjs__WEBPACK_IMPORTED_MODULE_3__["default"](ctx, shader, shaderOwner, renderTextureInfo, scissor, index); + } + + createCoreRenderExecutor(ctx) { + return new _WebGLCoreRenderExecutor_mjs__WEBPACK_IMPORTED_MODULE_4__["default"](ctx); + } + + createCoreRenderState(ctx) { + return new _tree_core_CoreRenderState_mjs__WEBPACK_IMPORTED_MODULE_5__["default"](ctx); + } + + createRenderTexture(w, h, pw, ph) { + const gl = this.stage.gl; + const glTexture = gl.createTexture(); + gl.bindTexture(gl.TEXTURE_2D, glTexture); + + gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, pw, ph, 0, gl.RGBA, gl.UNSIGNED_BYTE, null); + + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); + + glTexture.params = {}; + glTexture.params[gl.TEXTURE_MAG_FILTER] = gl.LINEAR; + glTexture.params[gl.TEXTURE_MIN_FILTER] = gl.LINEAR; + glTexture.params[gl.TEXTURE_WRAP_S] = gl.CLAMP_TO_EDGE; + glTexture.params[gl.TEXTURE_WRAP_T] = gl.CLAMP_TO_EDGE; + glTexture.options = { format: gl.RGBA, internalFormat: gl.RGBA, type: gl.UNSIGNED_BYTE }; + + // We need a specific framebuffer for every render texture. + glTexture.framebuffer = gl.createFramebuffer(); + glTexture.projection = new Float32Array([2 / w, 2 / h]); + + gl.bindFramebuffer(gl.FRAMEBUFFER, glTexture.framebuffer); + gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, glTexture, 0); + + return glTexture; + } + + freeRenderTexture(glTexture) { + let gl = this.stage.gl; + gl.deleteFramebuffer(glTexture.framebuffer); + gl.deleteTexture(glTexture); + } + + _getBytesPerPixel(fmt, type) { + const gl = this.stage.gl; + + if (fmt === gl.RGBA) { + switch (type) { + case gl.UNSIGNED_BYTE: + return 4; + + case gl.UNSIGNED_SHORT_4_4_4_4: + return 2; + + case gl.UNSIGNED_SHORT_5_5_5_1: + return 2; + + default: + throw new Error('Invalid type specified for GL_RGBA format'); + } + } + else if (fmt === gl.RGB) { + switch (type) { + case gl.UNSIGNED_BYTE: + return 3; + + case gl.UNSIGNED_BYTE_5_6_5: + return 2; + + default: + throw new Error('Invalid type specified for GL_RGB format'); + } + } + else { + throw new Error('Invalid format specified in call to _getBytesPerPixel()'); + } + } + + uploadTextureSource(textureSource, options) { + const gl = this.stage.gl; + + const source = options.source; + let compressed = false; + if (options.renderInfo) { + compressed = options.renderInfo.compressed || false + } + + const format = { + premultiplyAlpha: true, + hasAlpha: true + }; + + if (options && options.hasOwnProperty('premultiplyAlpha')) { + format.premultiplyAlpha = options.premultiplyAlpha; + } + + if (options && options.hasOwnProperty('flipBlueRed')) { + format.flipBlueRed = options.flipBlueRed; + } + + if (options && options.hasOwnProperty('hasAlpha')) { + format.hasAlpha = options.hasAlpha; + } + + if (!format.hasAlpha) { + format.premultiplyAlpha = false; + } + + format.texParams = options.texParams || {} + format.texOptions = options.texOptions || {} + + let glTexture = gl.createTexture(); + gl.bindTexture(gl.TEXTURE_2D, glTexture); + + gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, format.premultiplyAlpha); + + if (_tree_Utils_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].isNode) { + gl.pixelStorei(gl.UNPACK_FLIP_BLUE_RED, !!format.flipBlueRed); + } + + const texParams = format.texParams; + if (!texParams[gl.TEXTURE_MAG_FILTER]) texParams[gl.TEXTURE_MAG_FILTER] = gl.LINEAR; + if (!texParams[gl.TEXTURE_MIN_FILTER]) texParams[gl.TEXTURE_MIN_FILTER] = gl.LINEAR; + if (!texParams[gl.TEXTURE_WRAP_S]) texParams[gl.TEXTURE_WRAP_S] = gl.CLAMP_TO_EDGE; + if (!texParams[gl.TEXTURE_WRAP_T]) texParams[gl.TEXTURE_WRAP_T] = gl.CLAMP_TO_EDGE; + + Object.keys(texParams).forEach(key => { + const value = texParams[key]; + gl.texParameteri(gl.TEXTURE_2D, parseInt(key), value); + }); + + if (compressed) { + this.stage.platform.uploadCompressedGlTexture(gl, textureSource, source); + return glTexture; + } + + const texOptions = format.texOptions; + texOptions.format = texOptions.format || (format.hasAlpha ? gl.RGBA : gl.RGB); + texOptions.type = texOptions.type || gl.UNSIGNED_BYTE; + texOptions.internalFormat = texOptions.internalFormat || texOptions.format; + if (options && options.imageRef) { + texOptions.imageRef = options.imageRef; + } + + this.stage.platform.uploadGlTexture(gl, textureSource, source, texOptions); + + glTexture.params = _tree_Utils_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].cloneObjShallow(texParams); + glTexture.options = _tree_Utils_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].cloneObjShallow(texOptions); + + // calculate bytes per pixel for vram usage tracking + glTexture.bytesPerPixel = this._getBytesPerPixel(texOptions.format, texOptions.type); + + return glTexture; + } + + freeTextureSource(textureSource) { + this.stage.gl.deleteTexture(textureSource.nativeTexture); + } + + addQuad(renderState, quads, index) { + let offset = (index * 20); + const elementCore = quads.quadElements[index]; + + let r = elementCore._renderContext; + + let floats = renderState.quads.floats; + let uints = renderState.quads.uints; + const mca = _tree_StageUtils_mjs__WEBPACK_IMPORTED_MODULE_1__["default"].mergeColorAlpha; + + if (r.tb !== 0 || r.tc !== 0) { + floats[offset++] = r.px; + floats[offset++] = r.py; + floats[offset++] = elementCore._ulx; + floats[offset++] = elementCore._uly; + uints[offset++] = mca(elementCore._colorUl, r.alpha); + floats[offset++] = r.px + elementCore._w * r.ta; + floats[offset++] = r.py + elementCore._w * r.tc; + floats[offset++] = elementCore._brx; + floats[offset++] = elementCore._uly; + uints[offset++] = mca(elementCore._colorUr, r.alpha); + floats[offset++] = r.px + elementCore._w * r.ta + elementCore._h * r.tb; + floats[offset++] = r.py + elementCore._w * r.tc + elementCore._h * r.td; + floats[offset++] = elementCore._brx; + floats[offset++] = elementCore._bry; + uints[offset++] = mca(elementCore._colorBr, r.alpha); + floats[offset++] = r.px + elementCore._h * r.tb; + floats[offset++] = r.py + elementCore._h * r.td; + floats[offset++] = elementCore._ulx; + floats[offset++] = elementCore._bry; + uints[offset] = mca(elementCore._colorBl, r.alpha); + } else { + // Simple. + let cx = r.px + elementCore._w * r.ta; + let cy = r.py + elementCore._h * r.td; + + floats[offset++] = r.px; + floats[offset++] = r.py; + floats[offset++] = elementCore._ulx; + floats[offset++] = elementCore._uly; + uints[offset++] = mca(elementCore._colorUl, r.alpha); + floats[offset++] = cx; + floats[offset++] = r.py; + floats[offset++] = elementCore._brx; + floats[offset++] = elementCore._uly; + uints[offset++] = mca(elementCore._colorUr, r.alpha); + floats[offset++] = cx; + floats[offset++] = cy; + floats[offset++] = elementCore._brx; + floats[offset++] = elementCore._bry; + uints[offset++] = mca(elementCore._colorBr, r.alpha); + floats[offset++] = r.px; + floats[offset++] = cy; + floats[offset++] = elementCore._ulx; + floats[offset++] = elementCore._bry; + uints[offset] = mca(elementCore._colorBl, r.alpha); + } + } + + isRenderTextureReusable(renderState, renderTextureInfo) { + let offset = (renderState._renderTextureInfo.offset * 80) / 4; + let floats = renderState.quads.floats; + let uints = renderState.quads.uints; + return ((floats[offset] === 0) && + (floats[offset + 1] === 0) && + (floats[offset + 2] === 0) && + (floats[offset + 3] === 0) && + (uints[offset + 4] === 0xFFFFFFFF) && + (floats[offset + 5] === renderTextureInfo.w) && + (floats[offset + 6] === 0) && + (floats[offset + 7] === 1) && + (floats[offset + 8] === 0) && + (uints[offset + 9] === 0xFFFFFFFF) && + (floats[offset + 10] === renderTextureInfo.w) && + (floats[offset + 11] === renderTextureInfo.h) && + (floats[offset + 12] === 1) && + (floats[offset + 13] === 1) && + (uints[offset + 14] === 0xFFFFFFFF) && + (floats[offset + 15] === 0) && + (floats[offset + 16] === renderTextureInfo.h) && + (floats[offset + 17] === 0) && + (floats[offset + 18] === 1) && + (uints[offset + 19] === 0xFFFFFFFF)); + } + + finishRenderState(renderState) { + // Set extra shader attribute data. + let offset = renderState.length * 80; + for (let i = 0, n = renderState.quadOperations.length; i < n; i++) { + renderState.quadOperations[i].extraAttribsDataByteOffset = offset; + let extra = renderState.quadOperations[i].shader.getExtraAttribBytesPerVertex() * 4 * renderState.quadOperations[i].length; + offset += extra; + if (extra) { + renderState.quadOperations[i].shader.setExtraAttribsInBuffer(renderState.quadOperations[i], renderState.quads); + } + } + renderState.quads.dataLength = offset; + } + + copyRenderTexture(renderTexture, nativeTexture, options) { + const gl = this.stage.gl; + gl.bindTexture(gl.TEXTURE_2D, nativeTexture); + gl.bindFramebuffer(gl.FRAMEBUFFER, renderTexture.framebuffer); + const precision = renderTexture.precision; + gl.copyTexSubImage2D( + gl.TEXTURE_2D, + 0, + precision * (options.sx || 0), + precision * (options.sy || 0), + precision * (options.x || 0), + precision * (options.y || 0), + precision * (options.w || renderTexture.ow), + precision * (options.h || renderTexture.oh)); + } + +} + + +/***/ }), + +/***/ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/renderer/webgl/WebGLShader.mjs": +/*!**************************************************************************************************************!*\ + !*** ./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/renderer/webgl/WebGLShader.mjs ***! + \**************************************************************************************************************/ +/*! exports provided: default */ +/***/ (function(__webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return WebGLShader; }); +/* harmony import */ var _WebGLShaderProgram_mjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./WebGLShaderProgram.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/renderer/webgl/WebGLShaderProgram.mjs"); +/* harmony import */ var _tree_Shader_mjs__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../tree/Shader.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/tree/Shader.mjs"); +/* + * If not stated otherwise in this file or this component's LICENSE file the + * following copyright and licenses apply: + * + * Copyright 2020 Metrological + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + + +class WebGLShader extends _tree_Shader_mjs__WEBPACK_IMPORTED_MODULE_1__["default"] { + + constructor(ctx) { + super(ctx); + + const stage = ctx.stage; + + this._program = stage.renderer.shaderPrograms.get(this.constructor); + if (!this._program) { + this._program = new _WebGLShaderProgram_mjs__WEBPACK_IMPORTED_MODULE_0__["default"](this.constructor.vertexShaderSource, this.constructor.fragmentShaderSource); + + // Let the vbo context perform garbage collection. + stage.renderer.shaderPrograms.set(this.constructor, this._program); + } + + this.gl = stage.gl; + } + + get glProgram() { + return this._program.glProgram; + } + + _init() { + if (!this._initialized) { + this.initialize(); + this._initialized = true; + } + } + + initialize() { + this._program.compile(this.gl); + } + + get initialized() { + return this._initialized; + } + + _uniform(name) { + return this._program.getUniformLocation(name); + } + + _attrib(name) { + return this._program.getAttribLocation(name); + } + + _setUniform(name, value, glFunction) { + this._program.setUniformValue(name, value, glFunction); + } + + useProgram() { + this._init(); + this.gl.useProgram(this.glProgram); + this.beforeUsage(); + this.enableAttribs(); + } + + stopProgram() { + this.afterUsage(); + this.disableAttribs(); + } + + hasSameProgram(other) { + // For performance reasons, we first check for identical references. + return (other && ((other === this) || (other._program === this._program))); + } + + beforeUsage() { + // Override to set settings other than the default settings (blend mode etc). + } + + afterUsage() { + // All settings changed in beforeUsage should be reset here. + } + + enableAttribs() { + + } + + disableAttribs() { + + } + + getExtraAttribBytesPerVertex() { + return 0; + } + + getVertexAttribPointerOffset(operation) { + return operation.extraAttribsDataByteOffset - operation.index * 4 * this.getExtraAttribBytesPerVertex(); + } + + setExtraAttribsInBuffer(operation) { + // Set extra attrib data in in operation.quads.data/floats/uints, starting from + // operation.extraAttribsBufferByteOffset. + } + + setupUniforms(operation) { + // Set all shader-specific uniforms. + // Notice that all uniforms should be set, even if they have not been changed within this shader instance. + // The uniforms are shared by all shaders that have the same type (and shader program). + } + + _getProjection(operation) { + return operation.getProjection(); + } + + getFlipY(operation) { + return this._getProjection(operation)[1] < 0; + } + + beforeDraw(operation) { + } + + draw(operation) { + } + + afterDraw(operation) { + } + + cleanup() { + this._initialized = false; + // Program takes little resources, so it is only destroyed when the full stage is destroyed. + } + +} + + +/***/ }), + +/***/ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/renderer/webgl/WebGLShaderProgram.mjs": +/*!*********************************************************************************************************************!*\ + !*** ./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/renderer/webgl/WebGLShaderProgram.mjs ***! + \*********************************************************************************************************************/ +/*! exports provided: default */ +/***/ (function(__webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return WebGLShaderProgram; }); +/* + * If not stated otherwise in this file or this component's LICENSE file the + * following copyright and licenses apply: + * + * Copyright 2020 Metrological + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * Base functionality for shader setup/destroy. + */ +class WebGLShaderProgram { + + constructor(vertexShaderSource, fragmentShaderSource) { + + this.vertexShaderSource = vertexShaderSource; + this.fragmentShaderSource = fragmentShaderSource; + + this._program = null; + this.gl = null; + + this._uniformLocations = new Map(); + this._attributeLocations = new Map(); + + this._currentUniformValues = {}; + } + + compile(gl) { + if (this._program) return; + + this.gl = gl; + + this._program = gl.createProgram(); + + let glVertShader = this._glCompile(gl.VERTEX_SHADER, this.vertexShaderSource); + let glFragShader = this._glCompile(gl.FRAGMENT_SHADER, this.fragmentShaderSource); + + gl.attachShader(this._program, glVertShader); + gl.attachShader(this._program, glFragShader); + gl.linkProgram(this._program); + + // if linking fails, then log and cleanup + if (!gl.getProgramParameter(this._program, gl.LINK_STATUS)) { + console.error('[Lightning] Error: Could not initialize shader.'); + console.error('[Lightning] gl.VALIDATE_STATUS', gl.getProgramParameter(this._program, gl.VALIDATE_STATUS)); + console.error('[Lightning] gl.getError()', gl.getError()); + + // if there is a program info log, log it + if (gl.getProgramInfoLog(this._program) !== '') { + console.warn('[Lightning] Warning: gl.getProgramInfoLog()', gl.getProgramInfoLog(this._program)); + } + + gl.deleteProgram(this._program); + this._program = null; + } + + // clean up some shaders + gl.deleteShader(glVertShader); + gl.deleteShader(glFragShader); + } + + _glCompile(type, src) { + let shader = this.gl.createShader(type); + + this.gl.shaderSource(shader, src); + this.gl.compileShader(shader); + + if (!this.gl.getShaderParameter(shader, this.gl.COMPILE_STATUS)) { + console.error('[Lightning]', this.constructor.name, 'Type: ' + (type === this.gl.VERTEX_SHADER ? 'vertex shader' : 'fragment shader') ); + console.error('[Lightning]', this.gl.getShaderInfoLog(shader)); + let idx = 0; + console.error('[Lightning]', "========== source ==========\n" + src.split("\n").map(line => "" + (++idx) + ": " + line).join("\n")); + return null; + } + + return shader; + } + + getUniformLocation(name) { + let location = this._uniformLocations.get(name); + if (location === undefined) { + location = this.gl.getUniformLocation(this._program, name); + this._uniformLocations.set(name, location); + } + + return location; + } + + getAttribLocation(name) { + let location = this._attributeLocations.get(name); + if (location === undefined) { + location = this.gl.getAttribLocation(this._program, name); + this._attributeLocations.set(name, location); + } + + return location; + } + + destroy() { + if (this._program) { + this.gl.deleteProgram(this._program); + } + + this._attributeLocations = null; + this._currentUniformValues = null; + this.fragmentShaderSource = null; + this._program = null; + this.gl = null; + this._uniformLocations = null; + this.vertexShaderSource = null; + + delete this.vertexShaderSource; + delete this._program; + delete this._currentUniformValues; + delete this.fragmentShaderSource; + delete this.gl; + delete this._uniformLocations; + delete this._attributeLocations; + + } + + get glProgram() { + return this._program; + } + + get compiled() { + return !!this._program; + } + + _valueEquals(v1, v2) { + // Uniform value is either a typed array or a numeric value. + if (v1.length && v2.length) { + for (let i = 0, n = v1.length; i < n; i++) { + if (v1[i] !== v2[i]) return false; + } + return true; + } else { + return (v1 === v2); + } + } + + _valueClone(v) { + if (v.length) { + return v.slice(0); + } else { + return v; + } + } + + setUniformValue(name, value, glFunction) { + let v = this._currentUniformValues[name]; + if (v === undefined || !this._valueEquals(v, value)) { + let clonedValue = this._valueClone(value); + this._currentUniformValues[name] = clonedValue; + + let loc = this.getUniformLocation(name); + if (loc) { + let isMatrix = (glFunction === this.gl.uniformMatrix2fv || glFunction === this.gl.uniformMatrix3fv || glFunction === this.gl.uniformMatrix4fv); + if (isMatrix) { + glFunction.call(this.gl, loc, false, clonedValue); + } else { + glFunction.call(this.gl, loc, clonedValue); + } + } + } + } + +} + + +/***/ }), + +/***/ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/renderer/webgl/shaders/BoxBlurShader.mjs": +/*!************************************************************************************************************************!*\ + !*** ./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/renderer/webgl/shaders/BoxBlurShader.mjs ***! + \************************************************************************************************************************/ +/*! exports provided: default */ +/***/ (function(__webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return BoxBlurShader; }); +/* harmony import */ var _DefaultShader_mjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./DefaultShader.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/renderer/webgl/shaders/DefaultShader.mjs"); +/* + * If not stated otherwise in this file or this component's LICENSE file the + * following copyright and licenses apply: + * + * Copyright 2020 Metrological + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + +/** + * 4x4 box blur shader which works in conjunction with a 50% rescale. + */ +class BoxBlurShader extends _DefaultShader_mjs__WEBPACK_IMPORTED_MODULE_0__["default"] { + + setupUniforms(operation) { + super.setupUniforms(operation); + const dx = 1.0 / operation.getTextureWidth(0); + const dy = 1.0 / operation.getTextureHeight(0); + this._setUniform("stepTextureCoord", new Float32Array([dx, dy]), this.gl.uniform2fv); + } + +} + +BoxBlurShader.vertexShaderSource = ` + #ifdef GL_ES + # ifdef GL_FRAGMENT_PRECISION_HIGH + precision highp float; + # else + precision lowp float; + # endif + #endif + uniform vec2 stepTextureCoord; + attribute vec2 aVertexPosition; + attribute vec2 aTextureCoord; + attribute vec4 aColor; + uniform vec2 projection; + varying vec4 vColor; + varying vec2 vTextureCoordUl; + varying vec2 vTextureCoordUr; + varying vec2 vTextureCoordBl; + varying vec2 vTextureCoordBr; + void main(void){ + gl_Position = vec4(aVertexPosition.x * projection.x - 1.0, aVertexPosition.y * -abs(projection.y) + 1.0, 0.0, 1.0); + vTextureCoordUl = aTextureCoord - stepTextureCoord; + vTextureCoordBr = aTextureCoord + stepTextureCoord; + vTextureCoordUr = vec2(vTextureCoordBr.x, vTextureCoordUl.y); + vTextureCoordBl = vec2(vTextureCoordUl.x, vTextureCoordBr.y); + vColor = aColor; + gl_Position.y = -sign(projection.y) * gl_Position.y; + } +`; + +BoxBlurShader.fragmentShaderSource = ` + #ifdef GL_ES + # ifdef GL_FRAGMENT_PRECISION_HIGH + precision highp float; + # else + precision lowp float; + # endif + #endif + varying vec2 vTextureCoordUl; + varying vec2 vTextureCoordUr; + varying vec2 vTextureCoordBl; + varying vec2 vTextureCoordBr; + varying vec4 vColor; + uniform sampler2D uSampler; + void main(void){ + vec4 color = 0.25 * (texture2D(uSampler, vTextureCoordUl) + texture2D(uSampler, vTextureCoordUr) + texture2D(uSampler, vTextureCoordBl) + texture2D(uSampler, vTextureCoordBr)); + gl_FragColor = color * vColor; + } +`; + + + +/***/ }), + +/***/ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/renderer/webgl/shaders/CircularPushShader.mjs": +/*!*****************************************************************************************************************************!*\ + !*** ./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/renderer/webgl/shaders/CircularPushShader.mjs ***! + \*****************************************************************************************************************************/ +/*! exports provided: default */ +/***/ (function(__webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return CircularPushShader; }); +/* harmony import */ var _tree_Utils_mjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../../tree/Utils.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/tree/Utils.mjs"); +/* harmony import */ var _DefaultShader_mjs__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./DefaultShader.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/renderer/webgl/shaders/DefaultShader.mjs"); +/* + * If not stated otherwise in this file or this component's LICENSE file the + * following copyright and licenses apply: + * + * Copyright 2020 Metrological + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + + +class CircularPushShader extends _DefaultShader_mjs__WEBPACK_IMPORTED_MODULE_1__["default"] { + + constructor(ctx) { + super(ctx); + + this._inputValue = 0; + + this._maxDerivative = 0.01; + + this._normalizedValue = 0; + + // The offset between buckets. A value between 0 and 1. + this._offset = 0; + + this._amount = 0.1; + + this._aspectRatio = 1; + + this._offsetX = 0; + + this._offsetY = 0; + + this.buckets = 100; + } + + get aspectRatio() { + return this._aspectRatio; + } + + set aspectRatio(v) { + this._aspectRatio = v; + this.redraw(); + } + + get offsetX() { + return this._offsetX; + } + + set offsetX(v) { + this._offsetX = v; + this.redraw(); + } + + get offsetY() { + return this._offsetY; + } + + set offsetY(v) { + this._offsetY = v; + this.redraw(); + } + + set amount(v) { + this._amount = v; + this.redraw(); + } + + get amount() { + return this._amount; + } + + set inputValue(v) { + this._inputValue = v; + } + + get inputValue() { + return this._inputValue; + } + + set maxDerivative(v) { + this._maxDerivative = v; + } + + get maxDerivative() { + return this._maxDerivative; + } + + set buckets(v) { + if (v > 100) { + console.warn("[Lightning] CircularPushShader: supports max 100 buckets"); + v = 100; + } + + // This should be set before starting. + this._buckets = v; + + // Init values array in the correct length. + this._values = new Uint8Array(this._getValues(v)); + + this.redraw(); + } + + get buckets() { + return this._buckets; + } + + _getValues(n) { + const v = []; + for (let i = 0; i < n; i++) { + v.push(this._inputValue); + } + return v; + } + + /** + * Progresses the shader with the specified (fractional) number of buckets. + * @param {number} o; + * A number from 0 to 1 (1 = all buckets). + */ + progress(o) { + this._offset += o * this._buckets; + const full = Math.floor(this._offset); + this._offset -= full; + this._shiftBuckets(full); + this.redraw(); + } + + _shiftBuckets(n) { + for (let i = this._buckets - 1; i >= 0; i--) { + const targetIndex = i - n; + if (targetIndex < 0) { + this._normalizedValue = Math.min(this._normalizedValue + this._maxDerivative, Math.max(this._normalizedValue - this._maxDerivative, this._inputValue)); + this._values[i] = 255 * this._normalizedValue; + } else { + this._values[i] = this._values[targetIndex]; + } + } + } + + set offset(v) { + this._offset = v; + this.redraw(); + } + + setupUniforms(operation) { + super.setupUniforms(operation); + this._setUniform("aspectRatio", this._aspectRatio, this.gl.uniform1f); + this._setUniform("offsetX", this._offsetX, this.gl.uniform1f); + this._setUniform("offsetY", this._offsetY, this.gl.uniform1f); + this._setUniform("amount", this._amount, this.gl.uniform1f); + this._setUniform("offset", this._offset, this.gl.uniform1f); + this._setUniform("buckets", this._buckets, this.gl.uniform1f); + this._setUniform("uValueSampler", 1, this.gl.uniform1i); + } + + useDefault() { + return this._amount === 0; + } + + beforeDraw(operation) { + const gl = this.gl; + gl.activeTexture(gl.TEXTURE1); + if (!this._valuesTexture) { + this._valuesTexture = gl.createTexture(); + gl.bindTexture(gl.TEXTURE_2D, this._valuesTexture); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); + if (_tree_Utils_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].isNode) { + gl.pixelStorei(gl.UNPACK_FLIP_BLUE_RED, false); + } + gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false); + } else { + gl.bindTexture(gl.TEXTURE_2D, this._valuesTexture); + } + + // Upload new values. + gl.texImage2D(gl.TEXTURE_2D, 0, gl.ALPHA, this._buckets, 1, 0, gl.ALPHA, gl.UNSIGNED_BYTE, this._values); + gl.activeTexture(gl.TEXTURE0); + } + + cleanup() { + if (this._valuesTexture) { + this.gl.deleteTexture(this._valuesTexture); + } + } + + +} + +CircularPushShader.vertexShaderSource = ` + #ifdef GL_ES + # ifdef GL_FRAGMENT_PRECISION_HIGH + precision highp float; + # else + precision lowp float; + # endif + #endif + attribute vec2 aVertexPosition; + attribute vec2 aTextureCoord; + attribute vec4 aColor; + uniform vec2 projection; + uniform float offsetX; + uniform float offsetY; + uniform float aspectRatio; + varying vec2 vTextureCoord; + varying vec2 vPos; + varying vec4 vColor; + void main(void){ + gl_Position = vec4(aVertexPosition.x * projection.x - 1.0, aVertexPosition.y * -abs(projection.y) + 1.0, 0.0, 1.0); + vTextureCoord = aTextureCoord; + vPos = vTextureCoord * 2.0 - 1.0; + vPos.y = vPos.y * aspectRatio; + vPos.y = vPos.y + offsetY; + vPos.x = vPos.x + offsetX; + vColor = aColor; + gl_Position.y = -sign(projection.y) * gl_Position.y; + } +`; + +CircularPushShader.fragmentShaderSource = ` + #ifdef GL_ES + # ifdef GL_FRAGMENT_PRECISION_HIGH + precision highp float; + # else + precision lowp float; + # endif + #endif + varying vec2 vTextureCoord; + varying vec4 vColor; + varying vec2 vPos; + uniform float amount; + uniform float offset; + uniform float values[100]; + uniform float buckets; + uniform sampler2D uSampler; + uniform sampler2D uValueSampler; + void main(void){ + float l = length(vPos); + float m = (l * buckets * 0.678 - offset) / buckets; + float f = texture2D(uValueSampler, vec2(m, 0.0)).a * amount; + vec2 unit = vPos / l; + gl_FragColor = texture2D(uSampler, vTextureCoord - f * unit) * vColor; + } +`; + + + + +/***/ }), + +/***/ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/renderer/webgl/shaders/DefaultShader.mjs": +/*!************************************************************************************************************************!*\ + !*** ./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/renderer/webgl/shaders/DefaultShader.mjs ***! + \************************************************************************************************************************/ +/*! exports provided: default */ +/***/ (function(__webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return DefaultShader; }); +/* harmony import */ var _WebGLShader_mjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../WebGLShader.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/renderer/webgl/WebGLShader.mjs"); +/* + * If not stated otherwise in this file or this component's LICENSE file the + * following copyright and licenses apply: + * + * Copyright 2020 Metrological + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + +class DefaultShader extends _WebGLShader_mjs__WEBPACK_IMPORTED_MODULE_0__["default"] { + + enableAttribs() { + // Enables the attribs in the shader program. + let gl = this.gl; + gl.vertexAttribPointer(this._attrib("aVertexPosition"), 2, gl.FLOAT, false, 20, 0); + gl.enableVertexAttribArray(this._attrib("aVertexPosition")); + + if (this._attrib("aTextureCoord") !== -1) { + gl.vertexAttribPointer(this._attrib("aTextureCoord"), 2, gl.FLOAT, false, 20, 2 * 4); + gl.enableVertexAttribArray(this._attrib("aTextureCoord")); + } + + if (this._attrib("aColor") !== -1) { + // Some shaders may ignore the color. + gl.vertexAttribPointer(this._attrib("aColor"), 4, gl.UNSIGNED_BYTE, true, 20, 4 * 4); + gl.enableVertexAttribArray(this._attrib("aColor")); + } + } + + disableAttribs() { + // Disables the attribs in the shader program. + let gl = this.gl; + gl.disableVertexAttribArray(this._attrib("aVertexPosition")); + + if (this._attrib("aTextureCoord") !== -1) { + gl.disableVertexAttribArray(this._attrib("aTextureCoord")); + } + + if (this._attrib("aColor") !== -1) { + gl.disableVertexAttribArray(this._attrib("aColor")); + } + } + + setupUniforms(operation) { + this._setUniform("projection", this._getProjection(operation), this.gl.uniform2fv, false); + } + + draw(operation) { + let gl = this.gl; + + let length = operation.length; + + if (length) { + let glTexture = operation.getTexture(0); + let pos = 0; + for (let i = 0; i < length; i++) { + let tx = operation.getTexture(i); + if (glTexture !== tx) { + gl.bindTexture(gl.TEXTURE_2D, glTexture); + gl.drawElements(gl.TRIANGLES, 6 * (i - pos), gl.UNSIGNED_SHORT, (pos + operation.index) * 6 * 2); + glTexture = tx; + pos = i; + } + } + + gl.bindTexture(gl.TEXTURE_2D, glTexture); + gl.drawElements(gl.TRIANGLES, 6 * (length - pos), gl.UNSIGNED_SHORT, (pos + operation.index) * 6 * 2); + } + } + +} + +DefaultShader.vertexShaderSource = ` + #ifdef GL_ES + # ifdef GL_FRAGMENT_PRECISION_HIGH + precision highp float; + # else + precision lowp float; + # endif + #endif + attribute vec2 aVertexPosition; + attribute vec2 aTextureCoord; + attribute vec4 aColor; + uniform vec2 projection; + varying vec2 vTextureCoord; + varying vec4 vColor; + void main(void){ + gl_Position = vec4(aVertexPosition.x * projection.x - 1.0, aVertexPosition.y * -abs(projection.y) + 1.0, 0.0, 1.0); + vTextureCoord = aTextureCoord; + vColor = aColor; + gl_Position.y = -sign(projection.y) * gl_Position.y; + } +`; + +DefaultShader.fragmentShaderSource = ` + #ifdef GL_ES + # ifdef GL_FRAGMENT_PRECISION_HIGH + precision highp float; + # else + precision lowp float; + # endif + #endif + varying vec2 vTextureCoord; + varying vec4 vColor; + uniform sampler2D uSampler; + void main(void){ + gl_FragColor = texture2D(uSampler, vTextureCoord) * vColor; + } +`; + + + +/***/ }), + +/***/ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/renderer/webgl/shaders/DitheringShader.mjs": +/*!**************************************************************************************************************************!*\ + !*** ./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/renderer/webgl/shaders/DitheringShader.mjs ***! + \**************************************************************************************************************************/ +/*! exports provided: default */ +/***/ (function(__webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return DitheringShader; }); +/* harmony import */ var _textures_NoiseTexture_mjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../../textures/NoiseTexture.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/textures/NoiseTexture.mjs"); +/* harmony import */ var _DefaultShader_mjs__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./DefaultShader.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/renderer/webgl/shaders/DefaultShader.mjs"); +/* + * If not stated otherwise in this file or this component's LICENSE file the + * following copyright and licenses apply: + * + * Copyright 2020 Metrological + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + + +/** + * This shader can be used to fix a problem that is known as 'gradient banding'. + */ +class DitheringShader extends _DefaultShader_mjs__WEBPACK_IMPORTED_MODULE_1__["default"] { + + constructor(ctx) { + super(ctx); + + this._noiseTexture = new _textures_NoiseTexture_mjs__WEBPACK_IMPORTED_MODULE_0__["default"](ctx.stage); + + this._graining = 1/256; + + this._random = false; + } + + set graining(v) { + this._graining = v; + this.redraw(); + } + + set random(v) { + this._random = v; + this.redraw(); + } + + setExtraAttribsInBuffer(operation) { + // Make sure that the noise texture is uploaded to the GPU. + this._noiseTexture.load(); + + let offset = operation.extraAttribsDataByteOffset / 4; + let floats = operation.quads.floats; + + let length = operation.length; + + for (let i = 0; i < length; i++) { + + // Calculate noise texture coordinates so that it spans the full element. + let brx = operation.getElementWidth(i) / this._noiseTexture.getRenderWidth(); + let bry = operation.getElementHeight(i) / this._noiseTexture.getRenderHeight(); + + let ulx = 0; + let uly = 0; + if (this._random) { + ulx = Math.random(); + uly = Math.random(); + + brx += ulx; + bry += uly; + + if (Math.random() < 0.5) { + // Flip for more randomness. + const t = ulx; + ulx = brx; + brx = t; + } + + if (Math.random() < 0.5) { + // Flip for more randomness. + const t = uly; + uly = bry; + bry = t; + } + } + + // Specify all corner points. + floats[offset] = ulx; + floats[offset + 1] = uly; + + floats[offset + 2] = brx; + floats[offset + 3] = uly; + + floats[offset + 4] = brx; + floats[offset + 5] = bry; + + floats[offset + 6] = ulx; + floats[offset + 7] = bry; + + offset += 8; + } + } + + beforeDraw(operation) { + let gl = this.gl; + gl.vertexAttribPointer(this._attrib("aNoiseTextureCoord"), 2, gl.FLOAT, false, 8, this.getVertexAttribPointerOffset(operation)); + + let glTexture = this._noiseTexture.source.nativeTexture; + gl.activeTexture(gl.TEXTURE1); + gl.bindTexture(gl.TEXTURE_2D, glTexture); + gl.activeTexture(gl.TEXTURE0); + } + + getExtraAttribBytesPerVertex() { + return 8; + } + + setupUniforms(operation) { + super.setupUniforms(operation); + this._setUniform("uNoiseSampler", 1, this.gl.uniform1i); + this._setUniform("graining", 2 * this._graining, this.gl.uniform1f); + } + + enableAttribs() { + super.enableAttribs(); + let gl = this.gl; + gl.enableVertexAttribArray(this._attrib("aNoiseTextureCoord")); + } + + disableAttribs() { + super.disableAttribs(); + let gl = this.gl; + gl.disableVertexAttribArray(this._attrib("aNoiseTextureCoord")); + } + + useDefault() { + return this._graining === 0; + } + + afterDraw(operation) { + if (this._random) { + this.redraw(); + } + } + +} + +DitheringShader.vertexShaderSource = ` + #ifdef GL_ES + # ifdef GL_FRAGMENT_PRECISION_HIGH + precision highp float; + # else + precision lowp float; + # endif + #endif + attribute vec2 aVertexPosition; + attribute vec2 aTextureCoord; + attribute vec2 aNoiseTextureCoord; + attribute vec4 aColor; + uniform vec2 projection; + varying vec2 vTextureCoord; + varying vec2 vNoiseTextureCoord; + varying vec4 vColor; + void main(void){ + gl_Position = vec4(aVertexPosition.x * projection.x - 1.0, aVertexPosition.y * -abs(projection.y) + 1.0, 0.0, 1.0); + vTextureCoord = aTextureCoord; + vNoiseTextureCoord = aNoiseTextureCoord; + vColor = aColor; + gl_Position.y = -sign(projection.y) * gl_Position.y; + } +`; + +DitheringShader.fragmentShaderSource = ` + #ifdef GL_ES + # ifdef GL_FRAGMENT_PRECISION_HIGH + precision highp float; + # else + precision lowp float; + # endif + #endif + varying vec2 vTextureCoord; + varying vec2 vNoiseTextureCoord; + varying vec4 vColor; + uniform sampler2D uSampler; + uniform sampler2D uNoiseSampler; + uniform float graining; + void main(void){ + vec4 noise = texture2D(uNoiseSampler, vNoiseTextureCoord); + vec4 color = texture2D(uSampler, vTextureCoord); + gl_FragColor = (color * vColor) + graining * (noise.r - 0.5); + } +`; + + +/***/ }), + +/***/ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/renderer/webgl/shaders/FadeOutShader.mjs": +/*!************************************************************************************************************************!*\ + !*** ./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/renderer/webgl/shaders/FadeOutShader.mjs ***! + \************************************************************************************************************************/ +/*! exports provided: default */ +/***/ (function(__webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return FadeOutShader; }); +/* harmony import */ var _DefaultShader_mjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./DefaultShader.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/renderer/webgl/shaders/DefaultShader.mjs"); +/* + * If not stated otherwise in this file or this component's LICENSE file the + * following copyright and licenses apply: + * + * Copyright 2020 Metrological + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + +class FadeOutShader extends _DefaultShader_mjs__WEBPACK_IMPORTED_MODULE_0__["default"] { + constructor(context) { + super(context); + this._fade = [0, 0, 0, 0]; + } + + set top(num) { + this._fade[0] = num; + this.redraw(); + } + + get top() { + return this._fade[0]; + } + + set right(num) { + this._fade[1] = num; + this.redraw(); + } + + get right() { + return this._fade[1]; + } + + set bottom(num) { + this._fade[2] = num; + this.redraw(); + } + + get bottom() { + return this._fade[2]; + } + + set left(num) { + this._fade[3] = num; + this.redraw(); + } + + get left() { + return this._fade[3]; + } + + set fade(v) { + if(Array.isArray(v)) { + if(v.length === 2) { + this._fade = [v[0], v[1], v[0], v[1]]; + } + else if(v.length === 3) { + this._fade = [v[0], v[1], v[2], this._fade[3]]; + } + else if (v.length === 4) { + this._fade = v; + } + else { + this._fade = [v[0], v[0], v[0], v[0]]; + } + } + else { + this._fade = [v, v, v, v]; + } + this.redraw(); + } + + get fade() { + return this._fade; + } + + setupUniforms(operation) { + super.setupUniforms(operation); + const owner = operation.shaderOwner; + + const renderPrecision = this.ctx.stage.getRenderPrecision(); + const fade = this._fade.map((f) => f * renderPrecision); + this._setUniform('fade', new Float32Array(fade), this.gl.uniform4fv); + this._setUniform('resolution', new Float32Array([owner._w * renderPrecision, owner._h * renderPrecision]), this.gl.uniform2fv); + } +} + +FadeOutShader.fragmentShaderSource = ` + #ifdef GL_ES + # ifdef GL_FRAGMENT_PRECISION_HIGH + precision highp float; + # else + precision lowp float; + # endif + #endif + varying vec2 vTextureCoord; + varying vec4 vColor; + uniform sampler2D uSampler; + uniform vec2 resolution; + uniform vec4 fade; + + void main() { + vec4 color = texture2D(uSampler, vTextureCoord) * vColor; + vec2 halfRes = 0.5 * resolution.xy; + vec2 point = vTextureCoord.xy * resolution.xy; + + vec2 pos1; + vec2 pos2; + vec2 d; + float c; + float t = 0.0; + + if(fade[0] > 0.0) { + pos1 = vec2(point.x, point.y); + pos2 = vec2(point.x, point.y + fade[0]); + d = pos2 - pos1; + c = dot(pos1, d) / dot(d, d); + t = smoothstep(0.0, 1.0, clamp(c, 0.0, 1.0)); + color = mix(vec4(0.0), color, t); + } + + if(fade[1] > 0.0) { + vec2 pos1 = vec2(point.x - resolution.x - fade[1], vTextureCoord.y); + vec2 pos2 = vec2(point.x - resolution.x, vTextureCoord.y); + d = pos1 - pos2; + c = dot(pos2, d) / dot(d, d); + t = smoothstep(0.0, 1.0, clamp(c, 0.0, 1.0)); + color = mix(vec4(0.0), color, t); + } + + if(fade[2] > 0.0) { + vec2 pos1 = vec2(vTextureCoord.x, point.y - resolution.y - fade[2]); + vec2 pos2 = vec2(vTextureCoord.x, point.y - resolution.y); + d = pos1 - pos2; + c = dot(pos2, d) / dot(d, d); + t = smoothstep(0.0, 1.0, clamp(c, 0.0, 1.0)); + color = mix(vec4(0.0), color, t); + } + + if(fade[3] > 0.0) { + pos1 = vec2(point.x, point.y); + pos2 = vec2(point.x + fade[3], point.y); + d = pos2 - pos1; + c = dot(pos1, d) / dot(d, d); + t = smoothstep(0.0, 1.0, clamp(c, 0.0, 1.0)); + color = mix(vec4(0.0), color, t); + } + + gl_FragColor = color; + } +`; + + +/***/ }), + +/***/ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/renderer/webgl/shaders/HoleShader.mjs": +/*!*********************************************************************************************************************!*\ + !*** ./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/renderer/webgl/shaders/HoleShader.mjs ***! + \*********************************************************************************************************************/ +/*! exports provided: default */ +/***/ (function(__webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return HoleShader; }); +/* harmony import */ var _DefaultShader_mjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./DefaultShader.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/renderer/webgl/shaders/DefaultShader.mjs"); +/* + * If not stated otherwise in this file or this component's LICENSE file the + * following copyright and licenses apply: + * + * Copyright 2020 Metrological + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + +class HoleShader extends _DefaultShader_mjs__WEBPACK_IMPORTED_MODULE_0__["default"] { + + constructor(context) { + super(context); + this._x = 0; + this._y = 0; + this._w = 0; + this._h = 0; + this._radius = 0; + } + + get x() { + return this._x; + } + + set x(v) { + this._x = v; + this.redraw(); + } + + get y() { + return this._y; + } + + set y(v) { + this._y = v; + this.redraw(); + } + + get w() { + return this._w; + } + + set w(v) { + this._w = v; + this.redraw(); + } + + get h() { + return this._h; + } + + set h(v) { + this._h = v; + this.redraw(); + } + + get radius() { + return this._radius; + } + + set radius(v) { + this._radius = v; + this.redraw(); + } + + setupUniforms(operation) { + super.setupUniforms(operation); + + const owner = operation.shaderOwner; + const renderPrecision = this.ctx.stage.getRenderPrecision() + + this._setUniform("x", this._x * renderPrecision, this.gl.uniform1f); + this._setUniform("y", this._y * renderPrecision, this.gl.uniform1f); + this._setUniform("w", this._w * renderPrecision, this.gl.uniform1f); + this._setUniform("h", this._h * renderPrecision, this.gl.uniform1f); + this._setUniform('radius', (this._radius + .5) * renderPrecision, this.gl.uniform1f); + this._setUniform('resolution', new Float32Array([owner._w * renderPrecision, owner._h * renderPrecision]), this.gl.uniform2fv); + } + + useDefault() { + return (this._x === 0 && this._y === 0 && this._w === 0 && this._h === 0) + } +} + +HoleShader.vertexShaderSource = _DefaultShader_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].vertexShaderSource; + +HoleShader.fragmentShaderSource = ` + #ifdef GL_ES + # ifdef GL_FRAGMENT_PRECISION_HIGH + precision highp float; + # else + precision lowp float; + # endif + #endif + varying vec2 vTextureCoord; + varying vec4 vColor; + uniform sampler2D uSampler; + uniform float x; + uniform float y; + uniform float w; + uniform float h; + uniform vec2 resolution; + uniform float radius; + + float roundBox(vec2 p, vec2 b, float r) { + float d = length(max(abs(p)-b+r, 0.1))-r; + return smoothstep(1.0, 0.0, d); + } + + void main(void){ + vec4 color = texture2D(uSampler, vTextureCoord); + vec2 pos = vTextureCoord.xy * resolution - vec2(x, y) - vec2(w, h) / 2.0; + vec2 size = vec2(w, h) / 2.0; + float b = roundBox(pos, size, radius); + gl_FragColor = mix(color, vec4(0.0), b) * vColor; + } +`; + + +/***/ }), + +/***/ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/renderer/webgl/shaders/InversionShader.mjs": +/*!**************************************************************************************************************************!*\ + !*** ./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/renderer/webgl/shaders/InversionShader.mjs ***! + \**************************************************************************************************************************/ +/*! exports provided: default */ +/***/ (function(__webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return InversionShader; }); +/* harmony import */ var _DefaultShader_mjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./DefaultShader.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/renderer/webgl/shaders/DefaultShader.mjs"); +/* + * If not stated otherwise in this file or this component's LICENSE file the + * following copyright and licenses apply: + * + * Copyright 2020 Metrological + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + +class InversionShader extends _DefaultShader_mjs__WEBPACK_IMPORTED_MODULE_0__["default"] { + + constructor(context) { + super(context); + this._amount = 1; + } + + set amount(v) { + this._amount = v; + this.redraw(); + } + + get amount() { + return this._amount; + } + + useDefault() { + return this._amount === 0; + } + + setupUniforms(operation) { + super.setupUniforms(operation); + this._setUniform("amount", this._amount, this.gl.uniform1f); + } + +} + +InversionShader.fragmentShaderSource = ` + #ifdef GL_ES + # ifdef GL_FRAGMENT_PRECISION_HIGH + precision highp float; + # else + precision lowp float; + # endif + #endif + varying vec2 vTextureCoord; + varying vec4 vColor; + uniform sampler2D uSampler; + uniform float amount; + void main(void){ + vec4 color = texture2D(uSampler, vTextureCoord); + color.rgb = color.rgb * (1.0 - amount) + amount * (1.0 * color.a - color.rgb); + gl_FragColor = color * vColor; + } +`; + + + +/***/ }), + +/***/ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/renderer/webgl/shaders/Light3dShader.mjs": +/*!************************************************************************************************************************!*\ + !*** ./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/renderer/webgl/shaders/Light3dShader.mjs ***! + \************************************************************************************************************************/ +/*! exports provided: default */ +/***/ (function(__webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return Light3dShader; }); +/* harmony import */ var _DefaultShader_mjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./DefaultShader.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/renderer/webgl/shaders/DefaultShader.mjs"); +/* + * If not stated otherwise in this file or this component's LICENSE file the + * following copyright and licenses apply: + * + * Copyright 2020 Metrological + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + +class Light3dShader extends _DefaultShader_mjs__WEBPACK_IMPORTED_MODULE_0__["default"] { + + constructor(ctx) { + super(ctx); + + this._strength = 0.5; + this._ambient = 0.5; + this._fudge = 0.4; + + this._rx = 0; + this._ry = 0; + + this._z = 0; + this._pivotX = NaN; + this._pivotY = NaN; + this._pivotZ = 0; + + this._lightY = 0; + this._lightZ = 0; + } + + setupUniforms(operation) { + super.setupUniforms(operation); + + let vr = operation.shaderOwner; + let element = vr.element; + + let pivotX = isNaN(this._pivotX) ? element.pivotX * vr.w : this._pivotX; + let pivotY = isNaN(this._pivotY) ? element.pivotY * vr.h : this._pivotY; + let coords = vr.getRenderTextureCoords(pivotX, pivotY); + + // Counter normal rotation. + + let rz = -Math.atan2(vr._renderContext.tc, vr._renderContext.ta); + + let gl = this.gl; + this._setUniform("pivot", new Float32Array([coords[0], coords[1], this._pivotZ]), gl.uniform3fv); + this._setUniform("rot", new Float32Array([this._rx, this._ry, rz]), gl.uniform3fv); + + this._setUniform("z", this._z, gl.uniform1f); + this._setUniform("lightY", this.lightY, gl.uniform1f); + this._setUniform("lightZ", this.lightZ, gl.uniform1f); + this._setUniform("strength", this._strength, gl.uniform1f); + this._setUniform("ambient", this._ambient, gl.uniform1f); + this._setUniform("fudge", this._fudge, gl.uniform1f); + } + + set strength(v) { + this._strength = v; + this.redraw(); + } + + get strength() { + return this._strength; + } + + set ambient(v) { + this._ambient = v; + this.redraw(); + } + + get ambient() { + return this._ambient; + } + + set fudge(v) { + this._fudge = v; + this.redraw(); + } + + get fudge() { + return this._fudge; + } + + get rx() { + return this._rx; + } + + set rx(v) { + this._rx = v; + this.redraw(); + } + + get ry() { + return this._ry; + } + + set ry(v) { + this._ry = v; + this.redraw(); + } + + get z() { + return this._z; + } + + set z(v) { + this._z = v; + this.redraw(); + } + + get pivotX() { + return this._pivotX; + } + + set pivotX(v) { + this._pivotX = v + 1; + this.redraw(); + } + + get pivotY() { + return this._pivotY; + } + + set pivotY(v) { + this._pivotY = v + 1; + this.redraw(); + } + + get lightY() { + return this._lightY; + } + + set lightY(v) { + this._lightY = v; + this.redraw(); + } + + get pivotZ() { + return this._pivotZ; + } + + set pivotZ(v) { + this._pivotZ = v; + this.redraw(); + } + + get lightZ() { + return this._lightZ; + } + + set lightZ(v) { + this._lightZ = v; + this.redraw(); + } + + useDefault() { + return (this._rx === 0 && this._ry === 0 && this._z === 0 && this._strength === 0 && this._ambient === 1); + } + +} + +Light3dShader.vertexShaderSource = ` + #ifdef GL_ES + # ifdef GL_FRAGMENT_PRECISION_HIGH + precision highp float; + # else + precision lowp float; + # endif + #endif + attribute vec2 aVertexPosition; + attribute vec2 aTextureCoord; + attribute vec4 aColor; + uniform vec2 projection; + varying vec2 vTextureCoord; + varying vec4 vColor; + + uniform float fudge; + uniform float strength; + uniform float ambient; + uniform float z; + uniform float lightY; + uniform float lightZ; + uniform vec3 pivot; + uniform vec3 rot; + varying vec3 pos; + + void main(void) { + pos = vec3(aVertexPosition.xy, z); + + pos -= pivot; + + // Undo XY rotation + mat2 iRotXy = mat2( cos(rot.z), sin(rot.z), + -sin(rot.z), cos(rot.z)); + pos.xy = iRotXy * pos.xy; + + // Perform 3d rotations + gl_Position.x = cos(rot.x) * pos.x - sin(rot.x) * pos.z; + gl_Position.y = pos.y; + gl_Position.z = sin(rot.x) * pos.x + cos(rot.x) * pos.z; + + pos.x = gl_Position.x; + pos.y = cos(rot.y) * gl_Position.y - sin(rot.y) * gl_Position.z; + pos.z = sin(rot.y) * gl_Position.y + cos(rot.y) * gl_Position.z; + + // Redo XY rotation + iRotXy[0][1] = -iRotXy[0][1]; + iRotXy[1][0] = -iRotXy[1][0]; + pos.xy = iRotXy * pos.xy; + + // Undo translate to pivot position + pos.xyz += pivot; + + pos = vec3(pos.x * projection.x - 1.0, pos.y * -abs(projection.y) + 1.0, pos.z * projection.x); + + // Set depth perspective + float perspective = 1.0 + fudge * pos.z; + + pos.z += lightZ * projection.x; + + // Map coords to gl coordinate space. + // Set z to 0 because we don't want to perform z-clipping + gl_Position = vec4(pos.xy, 0.0, perspective); + + // Correct light source position. + pos.y += lightY * abs(projection.y); + + vTextureCoord = aTextureCoord; + vColor = aColor; + + gl_Position.y = -sign(projection.y) * gl_Position.y; + } +`; + +Light3dShader.fragmentShaderSource = ` + #ifdef GL_ES + # ifdef GL_FRAGMENT_PRECISION_HIGH + precision highp float; + # else + precision lowp float; + # endif + #endif + varying vec2 vTextureCoord; + varying vec4 vColor; + varying vec3 pos; + uniform sampler2D uSampler; + uniform float ambient; + uniform float strength; + void main(void){ + vec4 rgba = texture2D(uSampler, vTextureCoord); + float d = length(pos); + float n = 1.0 / max(0.1, d); + rgba.rgb = rgba.rgb * (strength * n + ambient); + gl_FragColor = rgba * vColor; + } +`; + + + +/***/ }), + +/***/ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/renderer/webgl/shaders/LinearBlurShader.mjs": +/*!***************************************************************************************************************************!*\ + !*** ./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/renderer/webgl/shaders/LinearBlurShader.mjs ***! + \***************************************************************************************************************************/ +/*! exports provided: default */ +/***/ (function(__webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return LinearBlurShader; }); +/* harmony import */ var _DefaultShader_mjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./DefaultShader.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/renderer/webgl/shaders/DefaultShader.mjs"); +/* + * If not stated otherwise in this file or this component's LICENSE file the + * following copyright and licenses apply: + * + * Copyright 2020 Metrological + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + +class LinearBlurShader extends _DefaultShader_mjs__WEBPACK_IMPORTED_MODULE_0__["default"] { + + constructor(context) { + super(context); + + this._direction = new Float32Array([1, 0]); + this._kernelRadius = 1; + } + + get x() { + return this._direction[0]; + } + + set x(v) { + this._direction[0] = v; + this.redraw(); + } + + get y() { + return this._direction[1]; + } + + set y(v) { + this._direction[1] = v; + this.redraw(); + } + + get kernelRadius() { + return this._kernelRadius; + } + + set kernelRadius(v) { + this._kernelRadius = v; + this.redraw(); + } + + + useDefault() { + return (this._kernelRadius === 0); + } + + setupUniforms(operation) { + super.setupUniforms(operation); + this._setUniform("direction", this._direction, this.gl.uniform2fv); + this._setUniform("kernelRadius", this._kernelRadius, this.gl.uniform1i); + + const w = operation.getRenderWidth(); + const h = operation.getRenderHeight(); + this._setUniform("resolution", new Float32Array([w, h]), this.gl.uniform2fv); + } +} + +LinearBlurShader.fragmentShaderSource = ` + #ifdef GL_ES + # ifdef GL_FRAGMENT_PRECISION_HIGH + precision highp float; + # else + precision lowp float; + # endif + #endif + uniform vec2 resolution; + varying vec2 vTextureCoord; + varying vec4 vColor; + uniform sampler2D uSampler; + uniform vec2 direction; + uniform int kernelRadius; + + vec4 blur1(sampler2D image, vec2 uv, vec2 resolution, vec2 direction) { + vec4 color = vec4(0.0); + vec2 off1 = vec2(1.3333333333333333) * direction; + color += texture2D(image, uv) * 0.29411764705882354; + color += texture2D(image, uv + (off1 / resolution)) * 0.35294117647058826; + color += texture2D(image, uv - (off1 / resolution)) * 0.35294117647058826; + return color; + } + + vec4 blur2(sampler2D image, vec2 uv, vec2 resolution, vec2 direction) { + vec4 color = vec4(0.0); + vec2 off1 = vec2(1.3846153846) * direction; + vec2 off2 = vec2(3.2307692308) * direction; + color += texture2D(image, uv) * 0.2270270270; + color += texture2D(image, uv + (off1 / resolution)) * 0.3162162162; + color += texture2D(image, uv - (off1 / resolution)) * 0.3162162162; + color += texture2D(image, uv + (off2 / resolution)) * 0.0702702703; + color += texture2D(image, uv - (off2 / resolution)) * 0.0702702703; + return color; + } + + vec4 blur3(sampler2D image, vec2 uv, vec2 resolution, vec2 direction) { + vec4 color = vec4(0.0); + vec2 off1 = vec2(1.411764705882353) * direction; + vec2 off2 = vec2(3.2941176470588234) * direction; + vec2 off3 = vec2(5.176470588235294) * direction; + color += texture2D(image, uv) * 0.1964825501511404; + color += texture2D(image, uv + (off1 / resolution)) * 0.2969069646728344; + color += texture2D(image, uv - (off1 / resolution)) * 0.2969069646728344; + color += texture2D(image, uv + (off2 / resolution)) * 0.09447039785044732; + color += texture2D(image, uv - (off2 / resolution)) * 0.09447039785044732; + color += texture2D(image, uv + (off3 / resolution)) * 0.010381362401148057; + color += texture2D(image, uv - (off3 / resolution)) * 0.010381362401148057; + return color; + } + + void main(void){ + if (kernelRadius == 1) { + gl_FragColor = blur1(uSampler, vTextureCoord, resolution, direction) * vColor; + } else if (kernelRadius == 2) { + gl_FragColor = blur2(uSampler, vTextureCoord, resolution, direction) * vColor; + } else { + gl_FragColor = blur3(uSampler, vTextureCoord, resolution, direction) * vColor; + } + } +`; + + +/***/ }), + +/***/ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/renderer/webgl/shaders/MagnifierShader.mjs": +/*!**************************************************************************************************************************!*\ + !*** ./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/renderer/webgl/shaders/MagnifierShader.mjs ***! + \**************************************************************************************************************************/ +/*! exports provided: default */ +/***/ (function(__webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return MagnifierShader; }); +/* harmony import */ var _DefaultShader_mjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./DefaultShader.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/renderer/webgl/shaders/DefaultShader.mjs"); +/* + * If not stated otherwise in this file or this component's LICENSE file the + * following copyright and licenses apply: + * + * Copyright 2020 Metrological + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + +class MagnifierShader extends _DefaultShader_mjs__WEBPACK_IMPORTED_MODULE_0__["default"] { + constructor(context) { + super(context); + this._x = 0; + this._y = 0; + this._w = 0; + this._h = 0; + this._radius = 0; + this._magnification = 0.6; + } + + get x() { + return this._x; + } + + set x(v) { + this._x = v; + this.redraw(); + } + + get y() { + return this._y; + } + + set y(v) { + this._y = v; + this.redraw(); + } + + get w() { + return this._w; + } + + set w(v) { + this._w = v; + this.redraw(); + } + + get h() { + return this._h; + } + + set h(v) { + this._h = v; + this.redraw(); + } + + get magnification() { + return this._magnification; + } + + set magnification(v) { + this._magnification = v; + this.redraw(); + } + + get radius() { + return this._radius; + } + + set radius(v) { + this._radius = v; + this.redraw(); + } + + setupUniforms(operation) { + super.setupUniforms(operation); + + const owner = operation.shaderOwner; + const renderPrecision = this.ctx.stage.getRenderPrecision(); + this._setUniform('x', this._x * renderPrecision, this.gl.uniform1f); + this._setUniform('y', this._y * renderPrecision, this.gl.uniform1f); + this._setUniform('w', this._w * renderPrecision, this.gl.uniform1f); + this._setUniform('h', this._h * renderPrecision, this.gl.uniform1f); + this._setUniform('magnification', this._magnification, this.gl.uniform1f); + this._setUniform( + 'radius', + (this._radius + 0.5) * renderPrecision, + this.gl.uniform1f + ); + this._setUniform( + 'resolution', + new Float32Array([ + owner._w * renderPrecision, + owner._h * renderPrecision + ]), + this.gl.uniform2fv + ); + } + + useDefault() { + return this._w === 0 && this._h === 0; + } + } + + MagnifierShader.vertexShaderSource = _DefaultShader_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].vertexShaderSource; + + MagnifierShader.fragmentShaderSource = ` + #ifdef GL_ES + # ifdef GL_FRAGMENT_PRECISION_HIGH + precision highp float; + # else + precision lowp float; + # endif + #endif + + varying vec2 vTextureCoord; + varying vec4 vColor; + uniform sampler2D uSampler; + uniform float x; + uniform float y; + uniform float w; + uniform float h; + uniform vec2 resolution; + uniform float radius; + uniform float magnification; + + float roundBox(vec2 p, vec2 b, float r) { + float d = length(max(abs(p)-b+r, 0.1))-r; + return smoothstep(1.0, 0.0, d); + } + + float inside(vec2 v) { + vec2 s = step(vec2(0.0, 0.0), v) - step(vec2(1.0, 1.0), v); + return s.x * s.y; + } + + void main(void) { + vec4 color = texture2D(uSampler, vTextureCoord); + vec2 pos = vTextureCoord.xy * resolution - vec2(x, y) - vec2(w, h) / 2.0; + vec2 size = vec2(w, h) / 2.0; + float b = roundBox(pos, size, radius); + vec2 pos2 = (vTextureCoord.xy * magnification * resolution + vec2(x, y) * magnification) / resolution; + gl_FragColor = mix(color, texture2D(uSampler, pos2) * inside(pos2), b) * vColor; + } + `; + + +/***/ }), + +/***/ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/renderer/webgl/shaders/OutlineShader.mjs": +/*!************************************************************************************************************************!*\ + !*** ./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/renderer/webgl/shaders/OutlineShader.mjs ***! + \************************************************************************************************************************/ +/*! exports provided: default */ +/***/ (function(__webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return OutlineShader; }); +/* harmony import */ var _tree_StageUtils_mjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../../tree/StageUtils.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/tree/StageUtils.mjs"); +/* harmony import */ var _DefaultShader_mjs__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./DefaultShader.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/renderer/webgl/shaders/DefaultShader.mjs"); +/* + * If not stated otherwise in this file or this component's LICENSE file the + * following copyright and licenses apply: + * + * Copyright 2020 Metrological + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + + +class OutlineShader extends _DefaultShader_mjs__WEBPACK_IMPORTED_MODULE_1__["default"] { + + constructor(ctx) { + super(ctx); + this._width = 5; + this._col = 0xFFFFFFFF; + this._color = [1,1,1,1]; + } + + set width(v) { + this._width = v; + this.redraw(); + } + + get color() { + return this._col; + } + + set color(v) { + if (this._col !== v) { + const col = _tree_StageUtils_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].getRgbaComponentsNormalized(v); + col[0] = col[0] * col[3]; + col[1] = col[1] * col[3]; + col[2] = col[2] * col[3]; + + this._color = col; + + this.redraw(); + + this._col = v; + } + } + + useDefault() { + return (this._width === 0 || this._col[3] === 0); + } + + setupUniforms(operation) { + super.setupUniforms(operation); + let gl = this.gl; + this._setUniform("color", new Float32Array(this._color), gl.uniform4fv); + } + + enableAttribs() { + super.enableAttribs(); + this.gl.enableVertexAttribArray(this._attrib("aCorner")); + } + + disableAttribs() { + super.disableAttribs(); + this.gl.disableVertexAttribArray(this._attrib("aCorner")); + } + + setExtraAttribsInBuffer(operation) { + let offset = operation.extraAttribsDataByteOffset / 4; + let floats = operation.quads.floats; + + let length = operation.length; + + for (let i = 0; i < length; i++) { + + const elementCore = operation.getElementCore(i); + + // We are setting attributes such that if the value is < 0 or > 1, a border should be drawn. + const ddw = this._width / elementCore.w; + const dw = ddw / (1 - 2 * ddw); + const ddh = this._width / elementCore.h; + const dh = ddh / (1 - 2 * ddh); + + // Specify all corner points. + floats[offset] = -dw; + floats[offset + 1] = -dh; + + floats[offset + 2] = 1 + dw; + floats[offset + 3] = -dh; + + floats[offset + 4] = 1 + dw; + floats[offset + 5] = 1 + dh; + + floats[offset + 6] = -dw; + floats[offset + 7] = 1 + dh; + + offset += 8; + } + } + + beforeDraw(operation) { + let gl = this.gl; + gl.vertexAttribPointer(this._attrib("aCorner"), 2, gl.FLOAT, false, 8, this.getVertexAttribPointerOffset(operation)); + } + + getExtraAttribBytesPerVertex() { + return 8; + } + +} + +OutlineShader.vertexShaderSource = ` + #ifdef GL_ES + # ifdef GL_FRAGMENT_PRECISION_HIGH + precision highp float; + # else + precision lowp float; + # endif + #endif + attribute vec2 aVertexPosition; + attribute vec2 aTextureCoord; + attribute vec4 aColor; + attribute vec2 aCorner; + uniform vec2 projection; + varying vec2 vTextureCoord; + varying vec2 vCorner; + varying vec4 vColor; + void main(void){ + gl_Position = vec4(aVertexPosition.x * projection.x - 1.0, aVertexPosition.y * -abs(projection.y) + 1.0, 0.0, 1.0); + vTextureCoord = aTextureCoord; + vCorner = aCorner; + vColor = aColor; + gl_Position.y = -sign(projection.y) * gl_Position.y; + } +`; + +OutlineShader.fragmentShaderSource = ` + #ifdef GL_ES + # ifdef GL_FRAGMENT_PRECISION_HIGH + precision highp float; + # else + precision lowp float; + # endif + #endif + varying vec2 vTextureCoord; + varying vec4 vColor; + varying vec2 vCorner; + uniform vec4 color; + uniform sampler2D uSampler; + void main(void){ + vec2 m = min(vCorner, 1.0 - vCorner); + float value = step(0.0, min(m.x, m.y)); + gl_FragColor = mix(color, texture2D(uSampler, vTextureCoord) * vColor, value); + } +`; + + + +/***/ }), + +/***/ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/renderer/webgl/shaders/PerspectiveShader.mjs": +/*!****************************************************************************************************************************!*\ + !*** ./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/renderer/webgl/shaders/PerspectiveShader.mjs ***! + \****************************************************************************************************************************/ +/*! exports provided: default */ +/***/ (function(__webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return PerspectiveShader; }); +/* harmony import */ var _DefaultShader_mjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./DefaultShader.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/renderer/webgl/shaders/DefaultShader.mjs"); +/* + * If not stated otherwise in this file or this component's LICENSE file the + * following copyright and licenses apply: + * + * Copyright 2020 Metrological + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + +class PerspectiveShader extends _DefaultShader_mjs__WEBPACK_IMPORTED_MODULE_0__["default"] { + + constructor(ctx) { + super(ctx); + + this._fudge = 0.2; + this._rx = 0; + this._ry = 0; + this._z = 1.0; + } + + setupUniforms(operation) { + super.setupUniforms(operation); + + const vr = operation.shaderOwner; + const element = vr.element; + + const pivotX = element.pivotX * vr.w; + const pivotY = element.pivotY * vr.h; + const coords = vr.getRenderTextureCoords(pivotX, pivotY); + + // Counter normal rotation. + const rz = -Math.atan2(vr._renderContext.tc, vr._renderContext.ta); + + const gl = this.gl; + this._setUniform("pivot", new Float32Array([coords[0], coords[1], 0]), gl.uniform3fv); + this._setUniform("rot", new Float32Array([this._rx, this._ry, rz]), gl.uniform3fv); + this._setUniform("z", this._z, gl.uniform1f); + this._setUniform("fudge", this._fudge, gl.uniform1f); + } + + set fudge(v) { + this._fudge = v; + this.redraw(); + } + + get fudge() { + return this._fudge; + } + + get rx() { + return this._rx; + } + + set rx(v) { + this._rx = v; + this.redraw(); + } + + get ry() { + return this._ry; + } + + set ry(v) { + this._ry = v; + this.redraw(); + } + + get z() { + return this._z; + } + + set z(v) { + this._z = v; + this.redraw(); + } + + useDefault() { + return (this._rx === 0 && this._ry === 0 && this._z === 0); + } + +} + +PerspectiveShader.vertexShaderSource = ` + #ifdef GL_ES + # ifdef GL_FRAGMENT_PRECISION_HIGH + precision highp float; + # else + precision lowp float; + # endif + #endif + attribute vec2 aVertexPosition; + attribute vec2 aTextureCoord; + attribute vec4 aColor; + uniform vec2 projection; + varying vec2 vTextureCoord; + varying vec4 vColor; + + uniform float z; + uniform vec3 pivot; + uniform vec3 rot; + varying vec3 pos; + + void main(void) { + pos = vec3(aVertexPosition.xy, z); + + pos -= pivot; + + // Undo XY rotation + mat2 iRotXy = mat2( cos(rot.z), sin(rot.z), + -sin(rot.z), cos(rot.z)); + pos.xy = iRotXy * pos.xy; + + // Perform 3d rotations + gl_Position.x = cos(rot.x) * pos.x - sin(rot.x) * pos.z; + gl_Position.y = pos.y; + gl_Position.z = sin(rot.x) * pos.x + cos(rot.x) * pos.z; + + pos.x = gl_Position.x; + pos.y = cos(rot.y) * gl_Position.y - sin(rot.y) * gl_Position.z; + pos.z = sin(rot.y) * gl_Position.y + cos(rot.y) * gl_Position.z; + + // Redo XY rotation + iRotXy[0][1] = -iRotXy[0][1]; + iRotXy[1][0] = -iRotXy[1][0]; + pos.xy = iRotXy * pos.xy; + + // Undo translate to pivot position + pos.xyz += pivot; + + pos = vec3(pos.x * projection.x - 1.0, pos.y * -abs(projection.y) + 1.0, pos.z * projection.x); + + // Map coords to gl coordinate space. + // Set z to 0 because we don't want to perform z-clipping + gl_Position = vec4(pos.xy, 0.0, z); + + vTextureCoord = aTextureCoord; + vColor = aColor; + + gl_Position.y = -sign(projection.y) * gl_Position.y; + } +`; + +PerspectiveShader.fragmentShaderSource = ` + #ifdef GL_ES + # ifdef GL_FRAGMENT_PRECISION_HIGH + precision highp float; + # else + precision lowp float; + # endif + #endif + varying vec2 vTextureCoord; + varying vec4 vColor; + uniform sampler2D uSampler; + + uniform vec3 rot; + uniform float fudge; + + void main(void) { + vec2 coords = vTextureCoord; + + coords.xy -= vec2(0.5); + coords.y = coords.y + (sign(rot[0]) * 0.5 - coords.x) * sin(rot[0]) * fudge * coords.y; + coords.x = coords.x + (sign(rot[1]) * 0.5 - coords.y) * sin(rot[1]) * fudge * coords.x; + coords.xy += vec2(0.5); + + if (coords.x < 0.0 || coords.x > 1.0 || coords.y < 0.0 || coords.y > 1.0) { + gl_FragColor = vec4(0.0); + } else { + gl_FragColor = texture2D(uSampler, coords) * vColor; + } + } +`; + + +/***/ }), + +/***/ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/renderer/webgl/shaders/PixelateShader.mjs": +/*!*************************************************************************************************************************!*\ + !*** ./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/renderer/webgl/shaders/PixelateShader.mjs ***! + \*************************************************************************************************************************/ +/*! exports provided: default */ +/***/ (function(__webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return PixelateShader; }); +/* harmony import */ var _DefaultShader_mjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./DefaultShader.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/renderer/webgl/shaders/DefaultShader.mjs"); +/* + * If not stated otherwise in this file or this component's LICENSE file the + * following copyright and licenses apply: + * + * Copyright 2020 Metrological + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + +/** + * @see https://github.com/pixijs/pixi-filters/tree/master/filters/pixelate/src + */ +class PixelateShader extends _DefaultShader_mjs__WEBPACK_IMPORTED_MODULE_0__["default"] { + + constructor(ctx) { + super(ctx); + + this._size = new Float32Array([4, 4]); + } + + get x() { + return this._size[0]; + } + + set x(v) { + this._size[0] = v; + this.redraw(); + } + + get y() { + return this._size[1]; + } + + set y(v) { + this._size[1] = v; + this.redraw(); + } + + get size() { + return this._size[0]; + } + + set size(v) { + this._size[0] = v; + this._size[1] = v; + this.redraw(); + } + + useDefault() { + return ((this._size[0] === 0) && (this._size[1] === 0)); + } + + static getWebGLImpl() { + return WebGLPixelateShaderImpl; + } + + setupUniforms(operation) { + super.setupUniforms(operation); + let gl = this.gl; + this._setUniform("size", new Float32Array(this._size), gl.uniform2fv); + } + + getExtraAttribBytesPerVertex() { + return 8; + } + + enableAttribs() { + super.enableAttribs(); + this.gl.enableVertexAttribArray(this._attrib("aTextureRes")); + } + + disableAttribs() { + super.disableAttribs(); + this.gl.disableVertexAttribArray(this._attrib("aTextureRes")); + } + + setExtraAttribsInBuffer(operation) { + let offset = operation.extraAttribsDataByteOffset / 4; + let floats = operation.quads.floats; + + let length = operation.length; + for (let i = 0; i < length; i++) { + let w = operation.quads.getTextureWidth(operation.index + i); + let h = operation.quads.getTextureHeight(operation.index + i); + + floats[offset] = w; + floats[offset + 1] = h; + floats[offset + 2] = w; + floats[offset + 3] = h; + floats[offset + 4] = w; + floats[offset + 5] = h; + floats[offset + 6] = w; + floats[offset + 7] = h; + + offset += 8; + } + } + + beforeDraw(operation) { + let gl = this.gl; + gl.vertexAttribPointer(this._attrib("aTextureRes"), 2, gl.FLOAT, false, this.getExtraAttribBytesPerVertex(), this.getVertexAttribPointerOffset(operation)); + } +} + +PixelateShader.vertexShaderSource = ` + #ifdef GL_ES + # ifdef GL_FRAGMENT_PRECISION_HIGH + precision highp float; + # else + precision lowp float; + # endif + #endif + attribute vec2 aVertexPosition; + attribute vec2 aTextureCoord; + attribute vec4 aColor; + attribute vec2 aTextureRes; + uniform vec2 projection; + varying vec2 vTextureCoord; + varying vec4 vColor; + varying vec2 vTextureRes; + void main(void){ + gl_Position = vec4(aVertexPosition.x * projection.x - 1.0, aVertexPosition.y * -abs(projection.y) + 1.0, 0.0, 1.0); + vTextureCoord = aTextureCoord; + vColor = aColor; + vTextureRes = aTextureRes; + gl_Position.y = -sign(projection.y) * gl_Position.y; + } +`; + +PixelateShader.fragmentShaderSource = ` + #ifdef GL_ES + # ifdef GL_FRAGMENT_PRECISION_HIGH + precision highp float; + # else + precision lowp float; + # endif + #endif + varying vec2 vTextureCoord; + varying vec4 vColor; + varying vec2 vTextureRes; + + uniform vec2 size; + uniform sampler2D uSampler; + + vec2 mapCoord( vec2 coord ) + { + coord *= vTextureRes.xy; + return coord; + } + + vec2 unmapCoord( vec2 coord ) + { + coord /= vTextureRes.xy; + return coord; + } + + vec2 pixelate(vec2 coord, vec2 size) + { + return floor( coord / size ) * size; + } + + void main(void) + { + vec2 coord = mapCoord(vTextureCoord); + coord = pixelate(coord, size); + coord = unmapCoord(coord); + gl_FragColor = texture2D(uSampler, coord) * vColor; + } +`; + + + +/***/ }), + +/***/ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/renderer/webgl/shaders/RadialFilterShader.mjs": +/*!*****************************************************************************************************************************!*\ + !*** ./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/renderer/webgl/shaders/RadialFilterShader.mjs ***! + \*****************************************************************************************************************************/ +/*! exports provided: default */ +/***/ (function(__webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return RadialFilterShader; }); +/* harmony import */ var _DefaultShader_mjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./DefaultShader.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/renderer/webgl/shaders/DefaultShader.mjs"); +/* + * If not stated otherwise in this file or this component's LICENSE file the + * following copyright and licenses apply: + * + * Copyright 2020 Metrological + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + +class RadialFilterShader extends _DefaultShader_mjs__WEBPACK_IMPORTED_MODULE_0__["default"] { + constructor(context) { + super(context); + this._radius = 0; + this._cutoff = 1; + } + + set radius(v) { + this._radius = v; + this.redraw(); + } + + get radius() { + return this._radius; + } + + set cutoff(v) { + this._cutoff = v; + this.redraw(); + } + + get cutoff() { + return this._cutoff; + } + + useDefault() { + return this._radius === 0; + } + + setupUniforms(operation) { + super.setupUniforms(operation); + // We substract half a pixel to get a better cutoff effect. + this._setUniform("radius", 2 * (this._radius - 0.5) / operation.getRenderWidth(), this.gl.uniform1f); + this._setUniform("cutoff", 0.5 * operation.getRenderWidth() / this._cutoff, this.gl.uniform1f); + } + +} + +RadialFilterShader.vertexShaderSource = ` + #ifdef GL_ES + # ifdef GL_FRAGMENT_PRECISION_HIGH + precision highp float; + # else + precision lowp float; + # endif + #endif + attribute vec2 aVertexPosition; + attribute vec2 aTextureCoord; + attribute vec4 aColor; + uniform vec2 projection; + varying vec2 pos; + varying vec2 vTextureCoord; + varying vec4 vColor; + void main(void){ + gl_Position = vec4(aVertexPosition.x * projection.x - 1.0, aVertexPosition.y * -abs(projection.y) + 1.0, 0.0, 1.0); + vTextureCoord = aTextureCoord; + vColor = aColor; + gl_Position.y = -sign(projection.y) * gl_Position.y; + pos = gl_Position.xy; + } +`; + +RadialFilterShader.fragmentShaderSource = ` + #ifdef GL_ES + # ifdef GL_FRAGMENT_PRECISION_HIGH + precision highp float; + # else + precision lowp float; + # endif + #endif + varying vec2 vTextureCoord; + varying vec2 pos; + varying vec4 vColor; + uniform sampler2D uSampler; + uniform float radius; + uniform float cutoff; + void main(void){ + vec4 color = texture2D(uSampler, vTextureCoord); + float f = max(0.0, min(1.0, 1.0 - (length(pos) - radius) * cutoff)); + gl_FragColor = texture2D(uSampler, vTextureCoord) * vColor * f; + } +`; + + + +/***/ }), + +/***/ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/renderer/webgl/shaders/RadialGradientShader.mjs": +/*!*******************************************************************************************************************************!*\ + !*** ./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/renderer/webgl/shaders/RadialGradientShader.mjs ***! + \*******************************************************************************************************************************/ +/*! exports provided: default */ +/***/ (function(__webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return RadialGradientShader; }); +/* harmony import */ var _DefaultShader_mjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./DefaultShader.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/renderer/webgl/shaders/DefaultShader.mjs"); +/* harmony import */ var _tree_StageUtils_mjs__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../../tree/StageUtils.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/tree/StageUtils.mjs"); +/* + * If not stated otherwise in this file or this component's LICENSE file the + * following copyright and licenses apply: + * + * Copyright 2020 Metrological + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + + +class RadialGradientShader extends _DefaultShader_mjs__WEBPACK_IMPORTED_MODULE_0__["default"] { + constructor(context) { + super(context); + this._pivot = [0, 0]; + this._ic = 0xffffffff; + this._normalizedIC = this._getNormalizedColor(this._ic); + this._oc = 0x00ffffff; + this._normalizedOC = this._getNormalizedColor(this._oc); + this._radius = 0; + } + + set radiusX(v) { + this.radius = v; + } + + get radiusX() { + return this._radius; + } + + set radiusY(v) { + this._radiusY = v; + this.redraw(); + } + + get radiusY() { + return this._radiusY; + } + + set radius(v) { + this._radius = v; + this.redraw(); + } + + set innerColor(argb) { + this._ic = argb; + this._normalizedIC = this._getNormalizedColor(argb); + this.redraw(); + } + + get innerColor() { + return this._ic; + } + + set outerColor(argb) { + this._oc = argb; + this._normalizedOC = this._getNormalizedColor(argb); + this.redraw(); + } + + set color(argb) { + this.innerColor = argb; + } + + get color() { + return this.innerColor; + } + + get outerColor() { + return this._ic; + } + + set x(f) { + this._x = f; + this.redraw(); + } + + set y(f) { + this._y = f; + this.redraw(); + } + + set pivot(v) { + if(Array.isArray(v) && v.length === 2) { + this._pivot = v; + } + else if(Array.isArray(v)) { + this._pivot = [v[0], v[1] || v[0]]; + } + else { + this._pivot = [v, v]; + } + this.redraw(); + } + + get pivot() { + return this._pivot[0]; + } + + set pivotY(f) { + this._pivot[1] = f; + this.redraw(); + } + + get pivotY() { + return this._pivot[1]; + } + + set pivotX(f) { + this._pivot[0] = f; + this.redraw(); + } + + get pivotX() { + return this._pivot[0]; + } + + _getNormalizedColor(color) { + const col = _tree_StageUtils_mjs__WEBPACK_IMPORTED_MODULE_1__["default"].getRgbaComponentsNormalized(color); + col[0] *= col[3]; + col[1] *= col[3]; + col[2] *= col[3]; + return new Float32Array(col); + } + + setupUniforms(operation) { + super.setupUniforms(operation); + const owner = operation.shaderOwner; + + if(this._x) { + this._pivot[0] = this._x / owner.w; + } + if(this._y) { + this._pivot[1] = this._y / owner.h; + } + + if(this._radius === 0) { + this._radius = owner.w * 0.5; + } + + this._setUniform('innerColor', this._normalizedIC, this.gl.uniform4fv); + this._setUniform('fill', _tree_StageUtils_mjs__WEBPACK_IMPORTED_MODULE_1__["default"].getRgbaComponentsNormalized(this._oc)[3], this.gl.uniform1f); + this._setUniform('outerColor', this._normalizedOC, this.gl.uniform4fv); + this._setUniform('pivot', new Float32Array(this._pivot), this.gl.uniform2fv); + this._setUniform('resolution', new Float32Array([owner._w, owner._h]), this.gl.uniform2fv); + this._setUniform('alpha', operation.getElementCore(0).renderContext.alpha, this.gl.uniform1f); + this._setUniform('radius', this._radius, this.gl.uniform1f); + this._setUniform('radiusY', (this._radiusY || this._radius), this.gl.uniform1f); + } +} + +RadialGradientShader.fragmentShaderSource = ` + #ifdef GL_ES + # ifdef GL_FRAGMENT_PRECISION_HIGH + precision highp float; + # else + precision lowp float; + # endif + #endif + + #define PI 3.14159265359 + + varying vec2 vTextureCoord; + varying vec4 vColor; + uniform sampler2D uSampler; + uniform vec2 resolution; + uniform vec2 pivot; + uniform vec4 innerColor; + uniform vec4 outerColor; + uniform float radius; + uniform float radiusY; + uniform float alpha; + uniform float fill; + uniform float aspectRatio; + + void main() { + vec2 point = vTextureCoord.xy * resolution; + vec2 projection = vec2(pivot.x * resolution.x, pivot.y * resolution.y); + float d = length((point - projection) / vec2(radius * 2.0, radiusY * 2.0)); + vec4 color = mix(texture2D(uSampler, vTextureCoord) * vColor, outerColor * alpha, fill); + gl_FragColor = mix(innerColor * alpha, color, smoothstep(0.0, 1.0, d)); + } +`; + + +/***/ }), + +/***/ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/renderer/webgl/shaders/RoundedRectangleShader.mjs": +/*!*********************************************************************************************************************************!*\ + !*** ./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/renderer/webgl/shaders/RoundedRectangleShader.mjs ***! + \*********************************************************************************************************************************/ +/*! exports provided: default */ +/***/ (function(__webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return RoundedRectangleShader; }); +/* harmony import */ var _DefaultShader_mjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./DefaultShader.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/renderer/webgl/shaders/DefaultShader.mjs"); +/* harmony import */ var _tree_StageUtils_mjs__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../../tree/StageUtils.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/tree/StageUtils.mjs"); +/* + * If not stated otherwise in this file or this component's LICENSE file the + * following copyright and licenses apply: + * + * Copyright 2020 Metrological + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + + +class RoundedRectangleShader extends _DefaultShader_mjs__WEBPACK_IMPORTED_MODULE_0__["default"] { + constructor(context) { + super(context); + this._blend = 0; + this._radius = [1, 1, 1, 1]; + this._stroke = 0; + this._fc = 0x00ffffff; + this._fillColor = this._getNormalizedColor(0xffffffff); + this._strokeColor = this._getNormalizedColor(0x00ffffff); + } + + set blend(p) { + this._blend = Math.min(Math.max(p, 0), 1); + } + + get blend() { + return this._blend; + } + + set radius(v) { + if(Array.isArray(v)) { + if(v.length === 2) { + this._radius = [v[0], v[1], v[0], v[1]]; + } + else if(v.length === 3) { + this._radius = [v[0], v[1], v[2], this._radius[3]]; + } + else if (v.length === 4) { + this._radius = v; + } + else { + this._radius = [v[0], v[0], v[0], v[0]]; + } + } + else { + this._radius = [v, v, v, v]; + } + this.redraw(); + } + + get radius() { + return this._radius; + } + + set topLeft(num) { + this._radius[0] = num; + this.redraw(); + } + + get topLeft() { + return this._radius[0]; + } + + set topRight(num) { + this._radius[1] = num; + this.redraw(); + } + + get topRight() { + return this._radius[1]; + } + + set bottomRight(num) { + this._radius[2] = num; + this.redraw(); + } + + get bottomRight() { + return this._radius[2]; + } + + set bottomLeft(num) { + this._radius[3] = num; + this.redraw(); + } + + get bottomLeft() { + return this._radius[3]; + } + + set strokeColor(argb) { + this._sc = argb; + this._strokeColor = this._getNormalizedColor(argb); + this.redraw(); + } + + get strokeColor() { + return this._sc; + } + + set fillColor(argb) { + this._fc = argb; + this._fillColor = this._getNormalizedColor(argb); + this.redraw(); + } + + get fillColor() { + return this._fc; + } + + set stroke(num) { + this._stroke = num; + this.redraw(); + } + + get stroke() { + return this._stroke; + } + + _getNormalizedColor(color) { + const col = _tree_StageUtils_mjs__WEBPACK_IMPORTED_MODULE_1__["default"].getRgbaComponentsNormalized(color); + col[0] *= col[3]; + col[1] *= col[3]; + col[2] *= col[3]; + return new Float32Array(col); + } + + setupUniforms(operation) { + super.setupUniforms(operation); + const owner = operation.shaderOwner; + const renderPrecision = this.ctx.stage.getRenderPrecision(); + const _radius = this._radius.map((r) => (r + 0.5) * renderPrecision) + this._setUniform('radius', new Float32Array(_radius), this.gl.uniform4fv); + this._setUniform('alpha', operation.getElementCore(0).renderContext.alpha, this.gl.uniform1f); + this._setUniform('blend', this._blend, this.gl.uniform1f); + this._setUniform('strokeColor', this._strokeColor, this.gl.uniform4fv); + this._setUniform('fillColor', this._fillColor, this.gl.uniform4fv); + this._setUniform('stroke', this._stroke * renderPrecision, this.gl.uniform1f); + this._setUniform('resolution', new Float32Array([owner._w * renderPrecision, owner._h * renderPrecision]), this.gl.uniform2fv); + } +} + +RoundedRectangleShader.vertexShaderSource = ` + #ifdef GL_ES + # ifdef GL_FRAGMENT_PRECISION_HIGH + precision highp float; + # else + precision lowp float; + # endif + #endif + attribute vec2 aVertexPosition; + attribute vec2 aTextureCoord; + + attribute vec4 aColor; + uniform vec2 projection; + varying vec2 vTextureCoord; + varying vec4 vColor; + + void main(void){ + gl_Position = vec4(aVertexPosition.x * projection.x - 1.0, aVertexPosition.y * -abs(projection.y) + 1.0, 0.0, 1.0); + vTextureCoord = aTextureCoord; + vColor = aColor; + gl_Position.y = -sign(projection.y) * gl_Position.y; + } +`; + +RoundedRectangleShader.fragmentShaderSource = ` + #ifdef GL_ES + # ifdef GL_FRAGMENT_PRECISION_HIGH + precision highp float; + # else + precision lowp float; + # endif + #endif + + #define PI 3.14159265359 + + varying vec2 vTextureCoord; + varying vec4 vColor; + + uniform sampler2D uSampler; + uniform vec2 resolution; + uniform vec4 radius; + uniform float stroke; + uniform vec4 strokeColor; + uniform vec4 fillColor; + uniform float alpha; + uniform float fill; + uniform float blend; + + float boxDist(vec2 p, vec2 size, float radius){ + size -= vec2(radius); + vec2 d = abs(p) - size; + return min(max(d.x, d.y), 0.0) + length(max(d, 0.0)) - radius; + } + + float fillMask(float dist){ + return clamp(-dist, 0.0, 1.0); + } + + float innerBorderMask(float dist, float width){ + float alpha1 = clamp(dist + width, 0.0, 1.0); + float alpha2 = clamp(dist, 0.0, 1.0); + return alpha1 - alpha2; + } + + void main() { + vec2 halfRes = 0.5 * resolution.xy; + float r = 0.0; + if (vTextureCoord.x < 0.5 && vTextureCoord.y < 0.5) { + r = radius[0]; + } else if (vTextureCoord.x >= 0.5 && vTextureCoord.y < 0.5) { + r = radius[1]; + } else if (vTextureCoord.x >= 0.5 && vTextureCoord.y >= 0.5) { + r = radius[2]; + } else { + r = radius[3]; + } + + float b = boxDist(vTextureCoord.xy * resolution - halfRes, halfRes - 0.005, r); + vec4 tex = texture2D(uSampler, vTextureCoord) * vColor; + vec4 blend = mix(vec4(1.0) * alpha, tex, blend); + vec4 layer1 = mix(vec4(0.0), tex * fillColor, fillMask(b)); + gl_FragColor = mix(layer1, blend * strokeColor, innerBorderMask(b + 1.0, stroke)); + } +`; + + +/***/ }), + +/***/ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/renderer/webgl/shaders/SpinnerShader.mjs": +/*!************************************************************************************************************************!*\ + !*** ./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/renderer/webgl/shaders/SpinnerShader.mjs ***! + \************************************************************************************************************************/ +/*! exports provided: default */ +/***/ (function(__webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return SpinnerShader; }); +/* harmony import */ var _DefaultShader_mjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./DefaultShader.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/renderer/webgl/shaders/DefaultShader.mjs"); +/* harmony import */ var _tree_StageUtils_mjs__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../../tree/StageUtils.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/tree/StageUtils.mjs"); +/* + * If not stated otherwise in this file or this component's LICENSE file the + * following copyright and licenses apply: + * + * Copyright 2020 Metrological + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + + +class SpinnerShader extends _DefaultShader_mjs__WEBPACK_IMPORTED_MODULE_0__["default"] { + + constructor(ctx) { + super(ctx); + this._radius = 100; + this._width = 50; + this._period = 1; + this._angle = 0.5; + this._smooth = 0.005; + this._color = 0xffffffff; + this._backgroundColor = 0xff000000; + this._time = Date.now(); + } + + set radius(v) { + this._radius = v; + this.redraw(); + } + + set width(v) { + this._width = v; + this.redraw(); + } + + set period(v) { + this._period = v; + this.redraw(); + } + + set angle(v) { + this._angle = v + this.redraw(); + } + + set smooth(v) { + this._smooth = v; + this.redraw(); + } + + set color(v) { + this._color = v; + this.redraw(); + } + + set backgroundColor(v) { + this._backgroundColor = v; + this.redraw(); + } + + setupUniforms(operation) { + super.setupUniforms(operation); + const owner = operation.shaderOwner + + this._setUniform("iTime", Date.now() - this._time, this.gl.uniform1f); + + const renderPrecision = this.ctx.stage.getRenderPrecision(); + this._setUniform('radius', this._radius * renderPrecision, this.gl.uniform1f); + this._setUniform('width', this._width * renderPrecision, this.gl.uniform1f); + this._setUniform('period', this._period, this.gl.uniform1f); + this._setUniform('angle', this._angle, this.gl.uniform1f); + this._setUniform('smooth', this._smooth, this.gl.uniform1f); + this._setUniform('color', new Float32Array(_tree_StageUtils_mjs__WEBPACK_IMPORTED_MODULE_1__["default"].getRgbaComponentsNormalized(this._color)), this.gl.uniform4fv); + this._setUniform('backgroundColor', new Float32Array(_tree_StageUtils_mjs__WEBPACK_IMPORTED_MODULE_1__["default"].getRgbaComponentsNormalized(this._backgroundColor)), this.gl.uniform4fv); + this._setUniform('resolution', new Float32Array([owner._w * renderPrecision, owner._h * renderPrecision]), this.gl.uniform2fv) + + this.redraw() + } +} + +SpinnerShader.vertexShaderSource = _DefaultShader_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].vertexShaderSource; + +SpinnerShader.fragmentShaderSource = ` + #ifdef GL_ES + # ifdef GL_FRAGMENT_PRECISION_HIGH + precision highp float; + # else + precision lowp float; + # endif + #endif + varying vec2 vTextureCoord; + varying vec4 vColor; + uniform sampler2D uSampler; + + uniform float iTime; + uniform float radius; + uniform float width; + uniform float period; + uniform float angle; + uniform float smooth; + uniform vec2 resolution; + + uniform vec4 color; + uniform vec4 backgroundColor; + + float ratio = resolution.y / resolution.x; + + vec2 transpose_pos(vec2 pos) { + if (ratio < 1.) { + float diff = 0.5 - pos.x; + pos.x = 0.5 - diff / ratio; + } else { + float diff = 0.5 - pos.y; + pos.y = 0.5 - diff * ratio; + } + return pos; + } + + float get_angle(vec2 pos) { + pos = transpose_pos(pos); + float a = atan(pos.y - 0.5, pos.x - 0.5); + a = (1.0+a/3.14159)/2.0; + + return a; + } + + float dist(vec2 pos1, vec2 pos2) { + pos1 = transpose_pos(pos1); + return distance(pos1, pos2); + } + + void main() + { + vec2 fragCoord = vTextureCoord; + vec4 fragColor = vColor; + + vec2 st = vTextureCoord; + float pct = dist(st, vec2(0.5)); + + float a = get_angle(st); + float t = iTime / 1000.0 / period; + + float inner = max((radius - width) / resolution.x, (radius - width) / resolution.y); + float outer = max(radius / resolution.x, radius / resolution.y); + + float x1 = mod(t, 1.0); + float x2 = mod(t + angle, 1.0); + + if (x1 < x2) { + if (a > x1 && a < x2) { + float val = (1.0 - (x2 - a) / angle) * smoothstep(0.0, 3. * smooth, (x2 - a)); + fragColor = mix(backgroundColor, color, val); + } else { + fragColor = backgroundColor; + } + } else { + if (a < x2) { + float val = (1.0 - (x2 - a) / angle) * smoothstep(0.0, 3. * smooth, (x2 - a)); + fragColor = mix(backgroundColor, color, val); + } else if (a > x1) { + float val = (1.0 - (1.0 + x2 - a) / angle) * smoothstep(0.0, 3. * smooth, (1.0 + x2 - a)); + fragColor = mix(backgroundColor, color, val); + } else { + fragColor = backgroundColor; + } + } + + float s = smoothstep(inner, inner + smooth + 0.00001, pct) * (1.0 - smoothstep(outer, outer + smooth + 0.00001, pct)); + gl_FragColor = texture2D(uSampler, fragCoord) * vColor * (1. - s * fragColor.a) + fragColor * s; + } +`; + + +/***/ }), + +/***/ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/renderer/webgl/shaders/SpinnerShader2.mjs": +/*!*************************************************************************************************************************!*\ + !*** ./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/renderer/webgl/shaders/SpinnerShader2.mjs ***! + \*************************************************************************************************************************/ +/*! exports provided: default */ +/***/ (function(__webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return SpinnerShader2; }); +/* harmony import */ var _DefaultShader_mjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./DefaultShader.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/renderer/webgl/shaders/DefaultShader.mjs"); +/* harmony import */ var _tree_StageUtils_mjs__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../../tree/StageUtils.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/tree/StageUtils.mjs"); +/* + * If not stated otherwise in this file or this component's LICENSE file the + * following copyright and licenses apply: + * + * Copyright 2020 Metrological + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + + +class SpinnerShader2 extends _DefaultShader_mjs__WEBPACK_IMPORTED_MODULE_0__["default"] { + constructor(context) { + super(context); + this._period = 1; + this._stroke = 0; + this._showDot = true; + this._clockwise = true; + this._bc = 0xff000000; + this._normalizedBC = this._getNormalizedColor(this._bc); + this._c = 0xffffffff; + this._normalizedC = this._getNormalizedColor(this._c); + } + + set radius(v) { + if(v === 0) { + v = 1; + } + this._radius = v; + } + + set stroke(value) { + this._stroke = Math.abs(value); + } + + get stroke() { + return this._stroke; + } + + set color(argb) { + this._c = argb; + this._normalizedC = this._getNormalizedColor(argb); + } + + get color() { + return this._c; + } + + set backgroundColor(argb) { + this._bc = argb; + this._normalizedBC = this._getNormalizedColor(argb); + } + + get backgroundColor() { + return this._sc; + } + + set showDot(bool) { + this._showDot = bool; + } + + get showDot() { + return this._showDot; + } + + set clockwise(bool) { + this._clockwise = bool; + } + + get clockwise() { + return this._clockwise; + } + + set period(v) { + this._period = v; + } + + get period() { + return this._period; + } + + _getNormalizedColor(color) { + const col = _tree_StageUtils_mjs__WEBPACK_IMPORTED_MODULE_1__["default"].getRgbaComponentsNormalized(color); + col[0] *= col[3]; + col[1] *= col[3]; + col[2] *= col[3]; + return new Float32Array(col); + } + + setupUniforms(operation) { + super.setupUniforms(operation); + const owner = operation.shaderOwner; + const radius = this._radius || (owner._w / 2); + + if(this._stroke === 0) { + this._stroke = radius * 0.33; + } + + this._setUniform('resolution', new Float32Array([owner._w, owner._h]), this.gl.uniform2fv); + this._setUniform('color', this._normalizedC, this.gl.uniform4fv); + this._setUniform('backgroundColor', this._normalizedBC, this.gl.uniform4fv); + this._setUniform('stroke', this._stroke, this.gl.uniform1f); + this._setUniform('radius', radius, this.gl.uniform1f); + this._setUniform('direction', this._clockwise ? -1 : 1, this.gl.uniform1f); + this._setUniform('showDot', !!this._showDot, this.gl.uniform1f); + this._setUniform('time', Date.now() - SpinnerShader2.spinSync, this.gl.uniform1f); + this._setUniform('period', this._period, this.gl.uniform1f); + this._setUniform('alpha', operation.getElementCore(0).renderContext.alpha, this.gl.uniform1f); + + if(this._sc !== this._bc || this._stroke !== radius * 0.5) { + this.redraw(); + } + } +} + +SpinnerShader2.spinSync = Date.now(); + +SpinnerShader2.fragmentShaderSource = ` + #ifdef GL_ES + # ifdef GL_FRAGMENT_PRECISION_HIGH + precision highp float; + # else + precision lowp float; + # endif + #endif + + #define PI 3.14159265359 + + varying vec2 vTextureCoord; + varying vec4 vColor; + + uniform sampler2D uSampler; + uniform vec2 resolution; + uniform vec4 color; + uniform vec4 backgroundColor; + uniform float direction; + uniform float radius; + uniform float time; + uniform float stroke; + uniform float showDot; + uniform float period; + uniform float alpha; + + float circleDist(vec2 p, float radius){ + return length(p) - radius; + } + + float fillMask(float dist){ + return clamp(-dist, 0.0, 1.0); + } + + void main() { + vec2 halfRes = 0.5 * resolution.xy; + vec2 center = vTextureCoord.xy * resolution - halfRes; + + float c = max(-circleDist(center, radius - stroke), circleDist(center, radius)); + float rot = -(time / 1000.0 / period) * 6.0 * direction; + center *= mat2(cos(rot), sin(rot), -sin(rot), cos(rot)); + + float a = direction * atan(center.x, center.y) * PI * 0.05 + 0.45; + + float strokeRad = stroke * 0.5; + a = mix(a, max(a, fillMask(circleDist(vec2(center.x, center.y + (radius - strokeRad)), strokeRad))), showDot); + vec4 base = mix(vec4(0.0), backgroundColor * alpha, fillMask(c)); + gl_FragColor = mix(base, color * alpha, fillMask(c) * a); + } +`; + + +/***/ }), + +/***/ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/renderer/webgl/shaders/VignetteShader.mjs": +/*!*************************************************************************************************************************!*\ + !*** ./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/renderer/webgl/shaders/VignetteShader.mjs ***! + \*************************************************************************************************************************/ +/*! exports provided: default */ +/***/ (function(__webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return VignetteShader; }); +/* harmony import */ var _DefaultShader_mjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./DefaultShader.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/renderer/webgl/shaders/DefaultShader.mjs"); +/* + * If not stated otherwise in this file or this component's LICENSE file the + * following copyright and licenses apply: + * + * Copyright 2020 Metrological + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + +class VignetteShader extends _DefaultShader_mjs__WEBPACK_IMPORTED_MODULE_0__["default"] { + constructor(context) { + super(context); + this._magnitude = 1.3; + this._intensity = 0.7; + this._pivot = [0.5, 0.5]; + } + + setupUniforms(operation) { + super.setupUniforms(operation); + + this._setUniform("magnitude", this._magnitude , this.gl.uniform1f); + this._setUniform("intensity", this._intensity, this.gl.uniform1f); + this._setUniform('pivot', new Float32Array(this._pivot), this.gl.uniform2fv); + this.redraw() + } + + set pivot(v) { + if(Array.isArray(v)) { + this._pivot = v; + } + else { + this._pivot = [v, v]; + } + this.redraw(); + } + + get pivotX() { + return this._pivot[0]; + } + + set pivotX(v) { + this._pivot[0] = v; + this.redraw(); + } + + get pivotY() { + return this._pivot[1]; + } + + set pivotY(v) { + this._pivot[1] = v; + this.redraw(); + } + + get intensity() { + return this._intensity; + } + + set intensity(v) { + this._intensity = v; + this.redraw(); + } + + get magnitude() { + return this._magnitude; + + } + + set magnitude(v) { + this._magnitude = v; + this.redraw(); + } +} + +VignetteShader.vertexShaderSource = _DefaultShader_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].vertexShaderSource; + +VignetteShader.fragmentShaderSource = ` + #ifdef GL_ES + # ifdef GL_FRAGMENT_PRECISION_HIGH + precision highp float; + # else + precision lowp float; + # endif + #endif + varying vec2 vTextureCoord; + varying vec4 vColor; + uniform sampler2D uSampler; + + uniform float magnitude; + uniform float intensity; + uniform vec2 pivot; + + void main() { + vec2 uv = vTextureCoord.xy - pivot + vec2(0.5); + uv.x = clamp(uv.x, 0.0, 1.0); + uv.y = clamp(uv.y, 0.0, 1.0); + + uv *= 1.00 - uv.yx; + float vig = uv.x * uv.y * 25.0 * intensity; + vig = pow(vig, 0.45 * magnitude); + vec4 fragColor = vec4(vig) * vColor; + gl_FragColor = texture2D(uSampler, vTextureCoord) * fragColor; + + } +` + + +/***/ }), + +/***/ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/textures/HtmlTexture.mjs": +/*!********************************************************************************************************!*\ + !*** ./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/textures/HtmlTexture.mjs ***! + \********************************************************************************************************/ +/*! exports provided: default */ +/***/ (function(__webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return HtmlTexture; }); +/* harmony import */ var _tree_Texture_mjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../tree/Texture.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/tree/Texture.mjs"); +/* + * If not stated otherwise in this file or this component's LICENSE file the + * following copyright and licenses apply: + * + * Copyright 2020 Metrological + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + +class HtmlTexture extends _tree_Texture_mjs__WEBPACK_IMPORTED_MODULE_0__["default"] { + + constructor(stage) { + super(stage); + this._htmlElement = undefined; + this._scale = 1; + } + + set htmlElement(v) { + this._htmlElement = v; + this._changed(); + } + + get htmlElement() { + return this._htmlElement; + } + + set scale(v) { + this._scale = v; + this._changed(); + } + + get scale() { + return this._scale; + } + + set html(v) { + if (!v) { + this.htmlElement = undefined; + } else { + const d = document.createElement('div'); + d.innerHTML = "
" + v + "
"; + this.htmlElement = d.firstElementChild; + } + } + + get html() { + return this._htmlElement.innerHTML; + } + + _getIsValid() { + return this.htmlElement; + } + + _getLookupId() { + return this._scale + ":" + this._htmlElement.innerHTML; + } + + _getSourceLoader() { + const htmlElement = this._htmlElement; + const scale = this._scale; + return function(cb) { + if (!window.html2canvas) { + return cb(new Error("Please include html2canvas (https://html2canvas.hertzen.com/)")); + } + + const area = HtmlTexture.getPreloadArea(); + area.appendChild(htmlElement); + + html2canvas(htmlElement, {backgroundColor: null, scale: scale}).then(function(canvas) { + area.removeChild(htmlElement); + if (canvas.height === 0) { + return cb(new Error("Canvas height is 0")); + } + cb(null, {source: canvas, width: canvas.width, height: canvas.height}); + }).catch(e => { + console.error('[Lightning]', e); + }); + } + } + + static getPreloadArea() { + if (!this._preloadArea) { + // Preload area must be included in document body and must be visible to trigger html element rendering. + this._preloadArea = document.createElement('div'); + if (this._preloadArea.attachShadow) { + // Use a shadow DOM if possible to prevent styling from interfering. + this._preloadArea.attachShadow({mode: 'closed'}); + } + this._preloadArea.style.opacity = 0; + this._preloadArea.style.pointerEvents = 'none'; + this._preloadArea.style.position = 'fixed'; + this._preloadArea.style.display = 'block'; + this._preloadArea.style.top = '100vh'; + this._preloadArea.style.overflow = 'hidden'; + document.body.appendChild(this._preloadArea); + } + return this._preloadArea; + } +} + + + +/***/ }), + +/***/ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/textures/ImageTexture.mjs": +/*!*********************************************************************************************************!*\ + !*** ./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/textures/ImageTexture.mjs ***! + \*********************************************************************************************************/ +/*! exports provided: default */ +/***/ (function(__webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return ImageTexture; }); +/* harmony import */ var _tree_Texture_mjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../tree/Texture.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/tree/Texture.mjs"); +/* + * If not stated otherwise in this file or this component's LICENSE file the + * following copyright and licenses apply: + * + * Copyright 2020 Metrological + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + +class ImageTexture extends _tree_Texture_mjs__WEBPACK_IMPORTED_MODULE_0__["default"] { + + constructor(stage) { + super(stage); + + this._src = undefined; + this._hasAlpha = false; + } + + get src() { + return this._src; + } + + set src(v) { + if (this._src !== v) { + this._src = v; + this._changed(); + } + } + + get hasAlpha() { + return this._hasAlpha; + } + + set hasAlpha(v) { + if (this._hasAlpha !== v) { + this._hasAlpha = v; + this._changed(); + } + } + + _getIsValid() { + return !!this._src; + } + + _getLookupId() { + return this._src; + } + + _getSourceLoader() { + let src = this._src; + let hasAlpha = this._hasAlpha; + if (this.stage.getOption('srcBasePath')) { + var fc = src.charCodeAt(0); + if ((src.indexOf("//") === -1) && ((fc >= 65 && fc <= 90) || (fc >= 97 && fc <= 122) || fc == 46)) { + // Alphabetical or dot: prepend base path. + src = this.stage.getOption('srcBasePath') + src; + } + } + + return (cb) => { + return this.stage.platform.loadSrcTexture({src: src, hasAlpha: hasAlpha}, cb); + } + } + + getNonDefaults() { + const obj = super.getNonDefaults(); + if (this._src) { + obj.src = this._src; + } + return obj; + } + +} + + + +/***/ }), + +/***/ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/textures/NoiseTexture.mjs": +/*!*********************************************************************************************************!*\ + !*** ./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/textures/NoiseTexture.mjs ***! + \*********************************************************************************************************/ +/*! exports provided: default */ +/***/ (function(__webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return NoiseTexture; }); +/* harmony import */ var _tree_Texture_mjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../tree/Texture.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/tree/Texture.mjs"); +/* + * If not stated otherwise in this file or this component's LICENSE file the + * following copyright and licenses apply: + * + * Copyright 2020 Metrological + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + +class NoiseTexture extends _tree_Texture_mjs__WEBPACK_IMPORTED_MODULE_0__["default"] { + + _getLookupId() { + return '__noise'; + } + + _getSourceLoader() { + const gl = this.stage.gl; + return function(cb) { + const noise = new Uint8Array(128 * 128 * 4); + for (let i = 0; i < 128 * 128 * 4; i+=4) { + const v = Math.floor(Math.random() * 256); + noise[i] = v; + noise[i+1] = v; + noise[i+2] = v; + noise[i+3] = 255; + } + const texParams = {} + + if (gl) { + texParams[gl.TEXTURE_WRAP_S] = gl.REPEAT; + texParams[gl.TEXTURE_WRAP_T] = gl.REPEAT; + texParams[gl.TEXTURE_MIN_FILTER] = gl.NEAREST; + texParams[gl.TEXTURE_MAG_FILTER] = gl.NEAREST; + } + + cb(null, {source: noise, w: 128, h: 128, texParams: texParams}); + } + } + +} + + +/***/ }), + +/***/ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/textures/RectangleTexture.mjs": +/*!*************************************************************************************************************!*\ + !*** ./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/textures/RectangleTexture.mjs ***! + \*************************************************************************************************************/ +/*! exports provided: default */ +/***/ (function(__webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return RectangleTexture; }); +/* harmony import */ var _tree_Texture_mjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../tree/Texture.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/tree/Texture.mjs"); +/* + * If not stated otherwise in this file or this component's LICENSE file the + * following copyright and licenses apply: + * + * Copyright 2020 Metrological + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + +class RectangleTexture extends _tree_Texture_mjs__WEBPACK_IMPORTED_MODULE_0__["default"] { + + _getLookupId() { + return '__whitepix'; + } + + _getSourceLoader() { + return function(cb) { + var whitePixel = new Uint8Array([255, 255, 255, 255]); + cb(null, {source: whitePixel, w: 1, h: 1, permanent: true}); + } + } + + isAutosizeTexture() { + return false; + } +} + + +/***/ }), + +/***/ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/textures/SourceTexture.mjs": +/*!**********************************************************************************************************!*\ + !*** ./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/textures/SourceTexture.mjs ***! + \**********************************************************************************************************/ +/*! exports provided: default */ +/***/ (function(__webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return SourceTexture; }); +/* harmony import */ var _tree_Texture_mjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../tree/Texture.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/tree/Texture.mjs"); +/* + * If not stated otherwise in this file or this component's LICENSE file the + * following copyright and licenses apply: + * + * Copyright 2020 Metrological + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + +class SourceTexture extends _tree_Texture_mjs__WEBPACK_IMPORTED_MODULE_0__["default"] { + + constructor(stage) { + super(stage); + + this._textureSource = undefined; + } + + get textureSource() { + return this._textureSource; + } + + set textureSource(v) { + if (v !== this._textureSource) { + if (v.isResultTexture) { + // In case of a result texture, automatically inherit the precision. + this._precision = this.stage.getRenderPrecision(); + } + this._textureSource = v; + this._changed(); + } + } + + _getTextureSource() { + return this._textureSource; + } + +} + + +/***/ }), + +/***/ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/textures/StaticCanvasTexture.mjs": +/*!****************************************************************************************************************!*\ + !*** ./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/textures/StaticCanvasTexture.mjs ***! + \****************************************************************************************************************/ +/*! exports provided: default */ +/***/ (function(__webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return StaticCanvasTexture; }); +/* harmony import */ var _tree_Texture_mjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../tree/Texture.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/tree/Texture.mjs"); +/* + * If not stated otherwise in this file or this component's LICENSE file the + * following copyright and licenses apply: + * + * Copyright 2020 Metrological + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + +class StaticCanvasTexture extends _tree_Texture_mjs__WEBPACK_IMPORTED_MODULE_0__["default"] { + + constructor(stage) { + super(stage); + this._factory = undefined; + this._lookupId = undefined; + } + + set content({factory, lookupId = undefined}) { + this._factory = factory; + this._lookupId = lookupId; + this._changed(); + } + + _getIsValid() { + return !!this._factory; + } + + _getLookupId() { + return this._lookupId; + } + + _getSourceLoader() { + const f = this._factory; + return (cb) => { + return f((err, canvas) => { + if (err) { + return cb(err); + } + cb(null, this.stage.platform.getTextureOptionsForDrawingCanvas(canvas)); + }, this.stage); + } + } + +} + + +/***/ }), + +/***/ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/textures/StaticTexture.mjs": +/*!**********************************************************************************************************!*\ + !*** ./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/textures/StaticTexture.mjs ***! + \**********************************************************************************************************/ +/*! exports provided: default */ +/***/ (function(__webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return StaticTexture; }); +/* harmony import */ var _tree_Texture_mjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../tree/Texture.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/tree/Texture.mjs"); +/* + * If not stated otherwise in this file or this component's LICENSE file the + * following copyright and licenses apply: + * + * Copyright 2020 Metrological + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + +class StaticTexture extends _tree_Texture_mjs__WEBPACK_IMPORTED_MODULE_0__["default"] { + + constructor(stage, options) { + super(stage); + + this._options = options; + } + + set options(v) { + if (this._options !== v) { + this._options = v; + this._changed(); + } + } + + get options() { + return this._options; + } + + _getIsValid() { + return !!this._options; + } + + _getSourceLoader() { + return (cb) => { + cb(null, this._options); + } + } +} + + +/***/ }), + +/***/ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/textures/TextTexture.mjs": +/*!********************************************************************************************************!*\ + !*** ./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/textures/TextTexture.mjs ***! + \********************************************************************************************************/ +/*! exports provided: default */ +/***/ (function(__webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return TextTexture; }); +/* harmony import */ var _tree_Texture_mjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../tree/Texture.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/tree/Texture.mjs"); +/* harmony import */ var _tree_Utils_mjs__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../tree/Utils.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/tree/Utils.mjs"); +/* harmony import */ var _TextTextureRenderer_mjs__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./TextTextureRenderer.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/textures/TextTextureRenderer.mjs"); +/* harmony import */ var _TextTextureRendererAdvanced_mjs__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./TextTextureRendererAdvanced.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/textures/TextTextureRendererAdvanced.mjs"); +/* + * If not stated otherwise in this file or this component's LICENSE file the + * following copyright and licenses apply: + * + * Copyright 2020 Metrological + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + + +class TextTexture extends _tree_Texture_mjs__WEBPACK_IMPORTED_MODULE_0__["default"] { + + constructor(stage) { + super(stage); + + // We use the stage precision as the default precision in case of a text texture. + this._precision = this.stage.getOption('precision'); + } + + static renderer(stage, canvas, settings) { + if (this.advancedRenderer) { + return new _TextTextureRendererAdvanced_mjs__WEBPACK_IMPORTED_MODULE_3__["default"](stage, canvas, settings); + } else { + return new _TextTextureRenderer_mjs__WEBPACK_IMPORTED_MODULE_2__["default"](stage, canvas, settings); + } + } + + get text() { + return this._text; + } + + set text(v) { + if (this._text !== v) { + this._text = "" + v; + this._changed(); + } + } + + get w() { + return this._w; + } + + set w(v) { + if (this._w !== v) { + this._w = v; + this._changed(); + } + } + + get h() { + return this._h; + } + + set h(v) { + if (this._h !== v) { + this._h = v; + this._changed(); + } + } + + get fontStyle() { + return this._fontStyle; + } + + set fontStyle(v) { + if (this._fontStyle !== v) { + this._fontStyle = v; + this._changed(); + } + } + + get fontBaselineRatio() { + return this._fontBaselineRatio; + } + + set fontBaselineRatio(v) { + if (this._fontBaselineRatio !== v) { + this._fontBaselineRatio = v; + this._changed(); + } + } + + get fontSize() { + return this._fontSize; + } + + set fontSize(v) { + if (this._fontSize !== v) { + this._fontSize = v; + this._changed(); + } + } + + get fontFace() { + return this._fontFace; + } + + set fontFace(v) { + if (this._fontFace !== v) { + this._fontFace = v; + this._changed(); + } + } + + get wordWrap() { + return this._wordWrap; + } + + set wordWrap(v) { + if (this._wordWrap !== v) { + this._wordWrap = v; + this._changed(); + } + } + + get wordWrapWidth() { + return this._wordWrapWidth; + } + + set wordWrapWidth(v) { + if (this._wordWrapWidth !== v) { + this._wordWrapWidth = v; + this._changed(); + } + } + + get wordBreak() { + return this._wordBreak; + } + + set wordBreak(v) { + if (this._wordBreak !== v) { + this._wordBreak = v; + this._changed(); + } + } + + get textOverflow() { + return this._textOverflow; + } + + set textOverflow(v) { + if (v != this._textOverflow) { + this._textOverflow = v; + this._changed(); + } + } + + get lineHeight() { + return this._lineHeight; + } + + set lineHeight(v) { + if (this._lineHeight !== v) { + this._lineHeight = v; + this._changed(); + } + } + + get textBaseline() { + return this._textBaseline; + } + + set textBaseline(v) { + if (this._textBaseline !== v) { + this._textBaseline = v; + this._changed(); + } + } + + get textAlign() { + return this._textAlign; + } + + set textAlign(v) { + if (this._textAlign !== v) { + this._textAlign = v; + this._changed(); + } + } + + get verticalAlign() { + return this._verticalAlign; + } + + set verticalAlign(v) { + if (this._verticalAlign !== v) { + this._verticalAlign = v; + this._changed(); + } + } + + get offsetY() { + return this._offsetY; + } + + set offsetY(v) { + if (this._offsetY !== v) { + this._offsetY = v; + this._changed(); + } + } + + get maxLines() { + return this._maxLines; + } + + set maxLines(v) { + if (this._maxLines !== v) { + this._maxLines = v; + this._changed(); + } + } + + get maxLinesSuffix() { + return this._maxLinesSuffix; + } + + set maxLinesSuffix(v) { + if (this._maxLinesSuffix !== v) { + this._maxLinesSuffix = v; + this._changed(); + } + } + + get textColor() { + return this._textColor; + } + + set textColor(v) { + if (this._textColor !== v) { + this._textColor = v; + this._changed(); + } + } + + get paddingLeft() { + return this._paddingLeft; + } + + set paddingLeft(v) { + if (this._paddingLeft !== v) { + this._paddingLeft = v; + this._changed(); + } + } + + get paddingRight() { + return this._paddingRight; + } + + set paddingRight(v) { + if (this._paddingRight !== v) { + this._paddingRight = v; + this._changed(); + } + } + + get shadow() { + return this._shadow; + } + + set shadow(v) { + if (this._shadow !== v) { + this._shadow = v; + this._changed(); + } + } + + get shadowColor() { + return this._shadowColor; + } + + set shadowColor(v) { + if (this._shadowColor !== v) { + this._shadowColor = v; + this._changed(); + } + } + + get shadowOffsetX() { + return this._shadowOffsetX; + } + + set shadowOffsetX(v) { + if (this._shadowOffsetX !== v) { + this._shadowOffsetX = v; + this._changed(); + } + } + + get shadowOffsetY() { + return this._shadowOffsetY; + } + + set shadowOffsetY(v) { + if (this._shadowOffsetY !== v) { + this._shadowOffsetY = v; + this._changed(); + } + } + + get shadowBlur() { + return this._shadowBlur; + } + + set shadowBlur(v) { + if (this._shadowBlur !== v) { + this._shadowBlur = v; + this._changed(); + } + } + + get highlight() { + return this._highlight; + } + + set highlight(v) { + if (this._highlight !== v) { + this._highlight = v; + this._changed(); + } + } + + get highlightHeight() { + return this._highlightHeight; + } + + set highlightHeight(v) { + if (this._highlightHeight !== v) { + this._highlightHeight = v; + this._changed(); + } + } + + get highlightColor() { + return this._highlightColor; + } + + set highlightColor(v) { + if (this._highlightColor !== v) { + this._highlightColor = v; + this._changed(); + } + } + + get highlightOffset() { + return this._highlightOffset; + } + + set highlightOffset(v) { + if (this._highlightOffset !== v) { + this._highlightOffset = v; + this._changed(); + } + } + + get highlightPaddingLeft() { + return this._highlightPaddingLeft; + } + + set highlightPaddingLeft(v) { + if (this._highlightPaddingLeft !== v) { + this._highlightPaddingLeft = v; + this._changed(); + } + } + + get highlightPaddingRight() { + return this._highlightPaddingRight; + } + + set highlightPaddingRight(v) { + if (this._highlightPaddingRight !== v) { + this._highlightPaddingRight = v; + this._changed(); + } + } + + get cutSx() { + return this._cutSx; + } + + set cutSx(v) { + if (this._cutSx !== v) { + this._cutSx = v; + this._changed(); + } + } + + get cutEx() { + return this._cutEx; + } + + set cutEx(v) { + if (this._cutEx !== v) { + this._cutEx = v; + this._changed(); + } + } + + get cutSy() { + return this._cutSy; + } + + set cutSy(v) { + if (this._cutSy !== v) { + this._cutSy = v; + this._changed(); + } + } + + get cutEy() { + return this._cutEy; + } + + set cutEy(v) { + if (this._cutEy !== v) { + this._cutEy = v; + this._changed(); + } + } + + get advancedRenderer() { + return this._advancedRenderer; + } + + set advancedRenderer(v) { + if (this._advancedRenderer !== v) { + this._advancedRenderer = v; + this._changed(); + } + } + + set letterSpacing(v) { + if (this._letterSpacing !== v) { + this._letterSpacing = v; + this._changed(); + } + } + + get letterSpacing() { + return this._letterSpacing; + } + + set textIndent(v) { + if (this._textIndent !== v) { + this._textIndent = v; + this._changed(); + } + } + + get textIndent() { + return this._textIndent; + } + + set rtl(v) { + if (this._rtl !== v) { + this._rtl = v; + this._changed(); + } + } + + get rtl() { + return this._rtl; + } + + get precision() { + return super.precision; + } + + set precision(v) { + // We actually draw differently when the precision changes. + if (this.precision !== v) { + super.precision = v; + this._changed(); + } + } + + _getIsValid() { + return !!this.text; + } + + _getLookupId() { + let parts = []; + + if (this.w !== 0) parts.push("w " + this.w); + if (this.h !== 0) parts.push("h " + this.h); + if (this.fontStyle !== "normal") parts.push("fS" + this.fontStyle); + if (this.fontSize !== 40) parts.push("fs" + this.fontSize); + if (this.fontBaselineRatio !== 0) parts.push('fb' + this.fontBaselineRatio); + if (this.fontFace !== null) parts.push("ff" + (Array.isArray(this.fontFace) ? this.fontFace.join(",") : this.fontFace)); + if (this.wordWrap !== true) parts.push("wr" + (this.wordWrap ? 1 : 0)); + if (this.wordWrapWidth !== 0) parts.push("ww" + this.wordWrapWidth); + if (this.wordBreak !== false) parts.push( true ? 1 : undefined); + if (this.textOverflow != "") parts.push("to" + this.textOverflow); + if (this.lineHeight !== null) parts.push("lh" + this.lineHeight); + if (this.textBaseline !== "alphabetic") parts.push("tb" + this.textBaseline); + if (this.textAlign !== "left") parts.push("ta" + this.textAlign); + if (this.verticalAlign !== "top") parts.push("va" + this.verticalAlign); + if (this.offsetY !== null) parts.push("oy" + this.offsetY); + if (this.maxLines !== 0) parts.push("ml" + this.maxLines); + if (this.maxLinesSuffix !== "..") parts.push("ms" + this.maxLinesSuffix); + parts.push("pc" + this.precision); + if (this.textColor !== 0xffffffff) parts.push("co" + this.textColor.toString(16)); + if (this.paddingLeft !== 0) parts.push("pl" + this.paddingLeft); + if (this.paddingRight !== 0) parts.push("pr" + this.paddingRight); + if (this.shadow !== false) parts.push("sh" + (this.shadow ? 1 : 0)); + if (this.shadowColor !== 0xff000000) parts.push("sc" + this.shadowColor.toString(16)); + if (this.shadowOffsetX !== 0) parts.push("sx" + this.shadowOffsetX); + if (this.shadowOffsetY !== 0) parts.push("sy" + this.shadowOffsetY); + if (this.shadowBlur !== 5) parts.push("sb" + this.shadowBlur); + if (this.highlight !== false) parts.push("hL" + (this.highlight ? 1 : 0)); + if (this.highlightHeight !== 0) parts.push("hh" + this.highlightHeight); + if (this.highlightColor !== 0xff000000) parts.push("hc" + this.highlightColor.toString(16)); + if (this.highlightOffset !== null) parts.push("ho" + this.highlightOffset); + if (this.highlightPaddingLeft !== null) parts.push("hl" + this.highlightPaddingLeft); + if (this.highlightPaddingRight !== null) parts.push("hr" + this.highlightPaddingRight); + if (this.letterSpacing !== null) parts.push("ls" + this.letterSpacing); + if (this.textIndent !== null) parts.push("ti" + this.textIndent); + + if (this.cutSx) parts.push("csx" + this.cutSx); + if (this.cutEx) parts.push("cex" + this.cutEx); + if (this.cutSy) parts.push("csy" + this.cutSy); + if (this.cutEy) parts.push("cey" + this.cutEy); + + if (this.advancedRenderer) parts.push( true ? 1 : undefined); + + let id = "TX$" + parts.join("|") + ":" + this.text; + return id; + } + + _getSourceLoader() { + const args = this.cloneArgs(); + + const gl = this.stage.gl; + + return function (cb) { + const canvas = this.stage.platform.getDrawingCanvas(); + const renderer = (args.advancedRenderer) + ? new _TextTextureRendererAdvanced_mjs__WEBPACK_IMPORTED_MODULE_3__["default"](this.stage, canvas, args) + : new _TextTextureRenderer_mjs__WEBPACK_IMPORTED_MODULE_2__["default"](this.stage, canvas, args); + + const p = renderer.draw(); + + const texParams = {}; + + const sharpCfg = this.stage.getOption('fontSharp'); + let sharpen = false; + + // Prevent text blur when text texture is downscaled + if (_tree_Utils_mjs__WEBPACK_IMPORTED_MODULE_1__["default"].isBoolean(sharpCfg)) { + sharpen = sharpCfg; + } else if (_tree_Utils_mjs__WEBPACK_IMPORTED_MODULE_1__["default"].isObject(sharpCfg)) { + const precision = this.stage.getRenderPrecision(); + sharpen = precision <= sharpCfg.precision && args.fontSize <= sharpCfg.fontSize; + } + + if (gl && sharpen) { + texParams[gl.TEXTURE_MAG_FILTER] = gl.NEAREST; + } + + if (p) { + p.then(() => { + /* FIXME: on some platforms (e.g. RPI), throttling text textures cause artifacts */ + cb(null, Object.assign({ + renderInfo: renderer.renderInfo, + throttle: false, + texParams: texParams, + }, this.stage.platform.getTextureOptionsForDrawingCanvas(canvas))); + }).catch((err) => { + cb(err); + }); + } else { + cb(null, Object.assign({ + renderInfo: renderer.renderInfo, + throttle: false, + texParams: texParams, + }, this.stage.platform.getTextureOptionsForDrawingCanvas(canvas))); + } + }; + } + + + getNonDefaults() { + const nonDefaults = super.getNonDefaults(); + if (this.text !== "") nonDefaults['text'] = this.text; + if (this.w !== 0) nonDefaults['w'] = this.w; + if (this.h !== 0) nonDefaults['h'] = this.h; + if (this.fontStyle !== "normal") nonDefaults['fontStyle'] = this.fontStyle; + if (this.fontSize !== 40) nonDefaults["fontSize"] = this.fontSize; + if (this.fontBaselineRatio !== 0) nonDefaults['fontBaselineRatio'] = this.fontBaselineRatio; + if (this.fontFace !== null) nonDefaults["fontFace"] = this.fontFace; + if (this.wordWrap !== true) nonDefaults["wordWrap"] = this.wordWrap; + if (this.wordWrapWidth !== 0) nonDefaults["wordWrapWidth"] = this.wordWrapWidth; + if (this.wordBreak !== false) nonDefaults["wordBreak"] = this.wordBreak; + if (this.textOverflow != "") nonDefaults["textOverflow"] = this.textOverflow; + if (this.lineHeight !== null) nonDefaults["lineHeight"] = this.lineHeight; + if (this.textBaseline !== "alphabetic") nonDefaults["textBaseline"] = this.textBaseline; + if (this.textAlign !== "left") nonDefaults["textAlign"] = this.textAlign; + if (this.verticalAlign !== "top") nonDefaults["verticalAlign"] = this.verticalAlign; + if (this.offsetY !== null) nonDefaults["offsetY"] = this.offsetY; + if (this.maxLines !== 0) nonDefaults["maxLines"] = this.maxLines; + if (this.maxLinesSuffix !== "..") nonDefaults["maxLinesSuffix"] = this.maxLinesSuffix; + if (this.precision !== this.stage.getOption('precision')) nonDefaults["precision"] = this.precision; + if (this.textColor !== 0xffffffff) nonDefaults["textColor"] = this.textColor; + if (this.paddingLeft !== 0) nonDefaults["paddingLeft"] = this.paddingLeft; + if (this.paddingRight !== 0) nonDefaults["paddingRight"] = this.paddingRight; + if (this.shadow !== false) nonDefaults["shadow"] = this.shadow; + if (this.shadowColor !== 0xff000000) nonDefaults["shadowColor"] = this.shadowColor; + if (this.shadowOffsetX !== 0) nonDefaults["shadowOffsetX"] = this.shadowOffsetX; + if (this.shadowOffsetY !== 0) nonDefaults["shadowOffsetY"] = this.shadowOffsetY; + if (this.shadowBlur !== 5) nonDefaults["shadowBlur"] = this.shadowBlur; + if (this.highlight !== false) nonDefaults["highlight"] = this.highlight; + if (this.highlightHeight !== 0) nonDefaults["highlightHeight"] = this.highlightHeight; + if (this.highlightColor !== 0xff000000) nonDefaults["highlightColor"] = this.highlightColor; + if (this.highlightOffset !== 0) nonDefaults["highlightOffset"] = this.highlightOffset; + if (this.highlightPaddingLeft !== 0) nonDefaults["highlightPaddingLeft"] = this.highlightPaddingLeft; + if (this.highlightPaddingRight !== 0) nonDefaults["highlightPaddingRight"] = this.highlightPaddingRight; + if (this.letterSpacing !== 0) nonDefaults["letterSpacing"] = this.letterSpacing; + if (this.textIndent !== 0) nonDefaults["textIndent"] = this.textIndent; + if (this.rtl !== 0) nonDefaults["rtl"] = this.rtl; + + if (this.cutSx) nonDefaults["cutSx"] = this.cutSx; + if (this.cutEx) nonDefaults["cutEx"] = this.cutEx; + if (this.cutSy) nonDefaults["cutSy"] = this.cutSy; + if (this.cutEy) nonDefaults["cutEy"] = this.cutEy; + + if (this.advancedRenderer) nonDefaults["renderer"] = this.advancedRenderer; + return nonDefaults; + } + + cloneArgs() { + let obj = {}; + obj.text = this._text; + obj.w = this._w; + obj.h = this._h; + obj.fontStyle = this._fontStyle; + obj.fontSize = this._fontSize; + obj.fontBaselineRatio = this._fontBaselineRatio; + obj.fontFace = this._fontFace; + obj.wordWrap = this._wordWrap; + obj.wordWrapWidth = this._wordWrapWidth; + obj.wordBreak = this._wordBreak; + obj.textOverflow = this._textOverflow; + obj.lineHeight = this._lineHeight; + obj.textBaseline = this._textBaseline; + obj.textAlign = this._textAlign; + obj.verticalAlign = this._verticalAlign; + obj.offsetY = this._offsetY; + obj.maxLines = this._maxLines; + obj.maxLinesSuffix = this._maxLinesSuffix; + obj.precision = this._precision; + obj.textColor = this._textColor; + obj.paddingLeft = this._paddingLeft; + obj.paddingRight = this._paddingRight; + obj.shadow = this._shadow; + obj.shadowColor = this._shadowColor; + obj.shadowOffsetX = this._shadowOffsetX; + obj.shadowOffsetY = this._shadowOffsetY; + obj.shadowBlur = this._shadowBlur; + obj.highlight = this._highlight; + obj.highlightHeight = this._highlightHeight; + obj.highlightColor = this._highlightColor; + obj.highlightOffset = this._highlightOffset; + obj.highlightPaddingLeft = this._highlightPaddingLeft; + obj.highlightPaddingRight = this._highlightPaddingRight; + obj.letterSpacing = this._letterSpacing; + obj.textIndent = this._textIndent; + obj.rtl = this._rtl; + obj.cutSx = this._cutSx; + obj.cutEx = this._cutEx; + obj.cutSy = this._cutSy; + obj.cutEy = this._cutEy; + obj.advancedRenderer = this._advancedRenderer; + return obj; + } + + +} + +// Because there are so many properties, we prefer to use the prototype for default values. +// This causes a decrease in performance, but also a decrease in memory usage. +let proto = TextTexture.prototype; +proto._text = ""; +proto._w = 0; +proto._h = 0; +proto._fontStyle = "normal"; +proto._fontSize = 40; +proto._fontFace = null; +proto._wordWrap = true; +proto._wordWrapWidth = 0; +proto._wordBreak = false; +proto._textOverflow = ""; +proto._lineHeight = null; +proto._textBaseline = "alphabetic"; +proto._textAlign = "left"; +proto._verticalAlign = "top"; +proto._offsetY = null; +proto._maxLines = 0; +proto._maxLinesSuffix = ".."; +proto._textColor = 0xFFFFFFFF; +proto._paddingLeft = 0; +proto._paddingRight = 0; +proto._shadow = false; +proto._shadowColor = 0xFF000000; +proto._shadowOffsetX = 0; +proto._shadowOffsetY = 0; +proto._shadowBlur = 5; +proto._highlight = false; +proto._highlightHeight = 0; +proto._highlightColor = 0xFF000000; +proto._highlightOffset = 0; +proto._highlightPaddingLeft = 0; +proto._highlightPaddingRight = 0; +proto._letterSpacing = 0; +proto._textIndent = 0; +proto._rtl = 0; +proto._cutSx = 0; +proto._cutEx = 0; +proto._cutSy = 0; +proto._cutEy = 0; +proto._advancedRenderer = false; +proto._fontBaselineRatio = 0; + + + + + + +/***/ }), + +/***/ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/textures/TextTextureRenderer.mjs": +/*!****************************************************************************************************************!*\ + !*** ./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/textures/TextTextureRenderer.mjs ***! + \****************************************************************************************************************/ +/*! exports provided: default */ +/***/ (function(__webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return TextTextureRenderer; }); +/* harmony import */ var _tree_StageUtils_mjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../tree/StageUtils.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/tree/StageUtils.mjs"); +/* harmony import */ var _tree_Utils_mjs__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../tree/Utils.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/tree/Utils.mjs"); +/* harmony import */ var _TextTextureRendererUtils_mjs__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./TextTextureRendererUtils.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/textures/TextTextureRendererUtils.mjs"); +/* + * If not stated otherwise in this file or this component's LICENSE file the + * following copyright and licenses apply: + * + * Copyright 2020 Metrological + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + + + +class TextTextureRenderer { + + constructor(stage, canvas, settings) { + this._stage = stage; + this._canvas = canvas; + this._context = this._canvas.getContext('2d'); + this._settings = settings; + } + + getPrecision() { + return this._settings.precision; + }; + + setFontProperties() { + this._context.font = Object(_TextTextureRendererUtils_mjs__WEBPACK_IMPORTED_MODULE_2__["getFontSetting"])( + this._settings.fontFace, + this._settings.fontStyle, + this._settings.fontSize, + this.getPrecision(), + this._stage.getOption('defaultFontFace'), + ); + this._context.textBaseline = this._settings.textBaseline; + this._context.direction = this._settings.rtl ? "rtl" : "ltr"; + }; + + _load() { + if (_tree_Utils_mjs__WEBPACK_IMPORTED_MODULE_1__["default"].isWeb && document.fonts) { + const fontSetting = Object(_TextTextureRendererUtils_mjs__WEBPACK_IMPORTED_MODULE_2__["getFontSetting"])( + this._settings.fontFace, + this._settings.fontStyle, + this._settings.fontSize, + this.getPrecision(), + this._stage.getOption('defaultFontFace') + ); + try { + if (!document.fonts.check(fontSetting, this._settings.text)) { + // Use a promise that waits for loading. + return document.fonts.load(fontSetting, this._settings.text).catch(err => { + // Just load the fallback font. + console.warn('[Lightning] Font load error', err, fontSetting); + }).then(() => { + if (!document.fonts.check(fontSetting, this._settings.text)) { + console.warn('[Lightning] Font not found', fontSetting); + } + }); + } + } catch(e) { + console.warn("[Lightning] Can't check font loading for " + fontSetting); + } + } + } + + draw() { + // We do not use a promise so that loading is performed syncronous when possible. + const loadPromise = this._load(); + if (!loadPromise) { + return _tree_Utils_mjs__WEBPACK_IMPORTED_MODULE_1__["default"].isSpark ? this._stage.platform.drawText(this) : this._draw(); + } else { + return loadPromise.then(() => { + return _tree_Utils_mjs__WEBPACK_IMPORTED_MODULE_1__["default"].isSpark ? this._stage.platform.drawText(this) : this._draw(); + }); + } + } + + _calculateRenderInfo() { + let renderInfo = {}; + + const precision = this.getPrecision(); + + const paddingLeft = this._settings.paddingLeft * precision; + const paddingRight = this._settings.paddingRight * precision; + const fontSize = this._settings.fontSize * precision; + let offsetY = this._settings.offsetY === null ? null : (this._settings.offsetY * precision); + let lineHeight = this._settings.lineHeight * precision; + const w = this._settings.w * precision; + const h = this._settings.h * precision; + let wordWrapWidth = this._settings.wordWrapWidth * precision; + const cutSx = this._settings.cutSx * precision; + const cutEx = this._settings.cutEx * precision; + const cutSy = this._settings.cutSy * precision; + const cutEy = this._settings.cutEy * precision; + const letterSpacing = (this._settings.letterSpacing || 0) * precision; + const textIndent = this._settings.textIndent * precision; + + // Set font properties. + this.setFontProperties(); + + // Total width. + let width = w || this._stage.getOption('w'); + + // Inner width. + let innerWidth = width - (paddingLeft); + if (innerWidth < 10) { + width += (10 - innerWidth); + innerWidth = 10; + } + + if (!wordWrapWidth) { + wordWrapWidth = innerWidth + } + + // Text overflow + if (this._settings.textOverflow && !this._settings.wordWrap) { + let suffix; + switch (this._settings.textOverflow) { + case 'clip': + suffix = ''; + break; + case 'ellipsis': + suffix = this._settings.maxLinesSuffix; + break; + default: + suffix = this._settings.textOverflow; + } + this._settings.text = this.wrapWord(this._settings.text, wordWrapWidth - textIndent, suffix) + } + + // word wrap + // preserve original text + let linesInfo; + if (this._settings.wordWrap) { + linesInfo = this.wrapText(this._settings.text, wordWrapWidth, letterSpacing, textIndent); + } else { + linesInfo = {l: this._settings.text.split(/(?:\r\n|\r|\n)/), n: []}; + let i, n = linesInfo.l.length; + for (let i = 0; i < n - 1; i++) { + linesInfo.n.push(i); + } + } + let lines = linesInfo.l; + + if (this._settings.maxLines && lines.length > this._settings.maxLines) { + let usedLines = lines.slice(0, this._settings.maxLines); + + let otherLines = null; + if (this._settings.maxLinesSuffix) { + // Wrap again with max lines suffix enabled. + let w = this._settings.maxLinesSuffix ? this.measureText(this._settings.maxLinesSuffix) : 0; + let al = this.wrapText(usedLines[usedLines.length - 1], wordWrapWidth - w, letterSpacing, textIndent); + usedLines[usedLines.length - 1] = al.l[0] + this._settings.maxLinesSuffix; + otherLines = [al.l.length > 1 ? al.l[1] : '']; + } else { + otherLines = ['']; + } + + // Re-assemble the remaining text. + let i, n = lines.length; + let j = 0; + let m = linesInfo.n.length; + for (i = this._settings.maxLines; i < n; i++) { + otherLines[j] += (otherLines[j] ? " " : "") + lines[i]; + if (i + 1 < m && linesInfo.n[i + 1]) { + j++; + } + } + + renderInfo.remainingText = otherLines.join("\n"); + + renderInfo.moreTextLines = true; + + lines = usedLines; + } else { + renderInfo.moreTextLines = false; + renderInfo.remainingText = ""; + } + + // calculate text width + let maxLineWidth = 0; + let lineWidths = []; + for (let i = 0; i < lines.length; i++) { + let lineWidth = this.measureText(lines[i], letterSpacing) + (i === 0 ? textIndent : 0); + lineWidths.push(lineWidth); + maxLineWidth = Math.max(maxLineWidth, lineWidth); + } + + renderInfo.lineWidths = lineWidths; + + if (!w) { + // Auto-set width to max text length. + width = maxLineWidth + paddingLeft + paddingRight; + innerWidth = maxLineWidth; + } + + // calculate text height + lineHeight = lineHeight || fontSize; + + let height; + if (h) { + height = h; + } else { + const baselineOffset = (this._settings.textBaseline != 'bottom') ? 0.5 * fontSize : 0; + height = lineHeight * (lines.length - 1) + baselineOffset + Math.max(lineHeight, fontSize) + offsetY; + } + + if (offsetY === null) { + offsetY = fontSize; + } + + renderInfo.w = width; + renderInfo.h = height; + renderInfo.lines = lines; + renderInfo.precision = precision; + + if (!width) { + // To prevent canvas errors. + width = 1; + } + + if (!height) { + // To prevent canvas errors. + height = 1; + } + + if (cutSx || cutEx) { + width = Math.min(width, cutEx - cutSx); + } + + if (cutSy || cutEy) { + height = Math.min(height, cutEy - cutSy); + } + + renderInfo.width = width; + renderInfo.innerWidth = innerWidth; + renderInfo.height = height; + renderInfo.fontSize = fontSize; + renderInfo.cutSx = cutSx; + renderInfo.cutSy = cutSy; + renderInfo.cutEx = cutEx; + renderInfo.cutEy = cutEy; + renderInfo.lineHeight = lineHeight; + renderInfo.lineWidths = lineWidths; + renderInfo.offsetY = offsetY; + renderInfo.paddingLeft = paddingLeft; + renderInfo.paddingRight = paddingRight; + renderInfo.letterSpacing = letterSpacing; + renderInfo.textIndent = textIndent; + + return renderInfo; + } + + _draw() { + const renderInfo = this._calculateRenderInfo(); + const precision = this.getPrecision(); + + // Add extra margin to prevent issue with clipped text when scaling. + this._canvas.width = Math.ceil(renderInfo.width + this._stage.getOption('textRenderIssueMargin')); + this._canvas.height = Math.ceil(renderInfo.height); + + // Canvas context has been reset. + this.setFontProperties(); + + if (renderInfo.fontSize >= 128) { + // WpeWebKit bug: must force compositing because cairo-traps-compositor will not work with text first. + this._context.globalAlpha = 0.01; + this._context.fillRect(0, 0, 0.01, 0.01); + this._context.globalAlpha = 1.0; + } + + if (renderInfo.cutSx || renderInfo.cutSy) { + this._context.translate(-renderInfo.cutSx, -renderInfo.cutSy); + } + + let linePositionX; + let linePositionY; + + let drawLines = []; + + // Draw lines line by line. + for (let i = 0, n = renderInfo.lines.length; i < n; i++) { + linePositionX = i === 0 ? renderInfo.textIndent : 0; + + // By default, text is aligned to top + linePositionY = (i * renderInfo.lineHeight) + renderInfo.offsetY; + + if (this._settings.verticalAlign == 'middle') { + linePositionY += (renderInfo.lineHeight - renderInfo.fontSize) / 2; + } else if (this._settings.verticalAlign == 'bottom') { + linePositionY += renderInfo.lineHeight - renderInfo.fontSize; + } + + if (this._settings.textAlign === 'right') { + linePositionX += (renderInfo.innerWidth - renderInfo.lineWidths[i]); + } else if (this._settings.textAlign === 'center') { + linePositionX += ((renderInfo.innerWidth - renderInfo.lineWidths[i]) / 2); + } + linePositionX += renderInfo.paddingLeft; + if (this._settings.rtl) { + linePositionX += renderInfo.lineWidths[i]; + } + + drawLines.push({text: renderInfo.lines[i], x: linePositionX, y: linePositionY, w: renderInfo.lineWidths[i]}); + } + + // Highlight. + if (this._settings.highlight) { + let color = this._settings.highlightColor || 0x00000000; + + let hlHeight = (this._settings.highlightHeight * precision || renderInfo.fontSize * 1.5); + const offset = this._settings.highlightOffset * precision; + const hlPaddingLeft = (this._settings.highlightPaddingLeft !== null ? this._settings.highlightPaddingLeft * precision : renderInfo.paddingLeft); + const hlPaddingRight = (this._settings.highlightPaddingRight !== null ? this._settings.highlightPaddingRight * precision : renderInfo.paddingRight); + + this._context.fillStyle = _tree_StageUtils_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].getRgbaString(color); + for (let i = 0; i < drawLines.length; i++) { + let drawLine = drawLines[i]; + this._context.fillRect((drawLine.x - hlPaddingLeft), (drawLine.y - renderInfo.offsetY + offset), (drawLine.w + hlPaddingRight + hlPaddingLeft), hlHeight); + } + } + + // Text shadow. + let prevShadowSettings = null; + if (this._settings.shadow) { + prevShadowSettings = [this._context.shadowColor, this._context.shadowOffsetX, this._context.shadowOffsetY, this._context.shadowBlur]; + + this._context.shadowColor = _tree_StageUtils_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].getRgbaString(this._settings.shadowColor); + this._context.shadowOffsetX = this._settings.shadowOffsetX * precision; + this._context.shadowOffsetY = this._settings.shadowOffsetY * precision; + this._context.shadowBlur = this._settings.shadowBlur * precision; + } + + this._context.fillStyle = _tree_StageUtils_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].getRgbaString(this._settings.textColor); + for (let i = 0, n = drawLines.length; i < n; i++) { + let drawLine = drawLines[i]; + + if (renderInfo.letterSpacing === 0) { + this._context.fillText(drawLine.text, drawLine.x, drawLine.y); + } else { + const textSplit = drawLine.text.split(''); + let x = drawLine.x; + for (let i = 0, j = textSplit.length; i < j; i++) { + this._context.fillText(textSplit[i], x, drawLine.y); + x += this.measureText(textSplit[i], renderInfo.letterSpacing); + } + } + } + + if (prevShadowSettings) { + this._context.shadowColor = prevShadowSettings[0]; + this._context.shadowOffsetX = prevShadowSettings[1]; + this._context.shadowOffsetY = prevShadowSettings[2]; + this._context.shadowBlur = prevShadowSettings[3]; + } + + if (renderInfo.cutSx || renderInfo.cutSy) { + this._context.translate(renderInfo.cutSx, renderInfo.cutSy); + } + + this.renderInfo = renderInfo; + }; + + wrapWord(word, wordWrapWidth, suffix) { + const suffixWidth = this.measureText(suffix); + const wordLen = word.length + const wordWidth = this.measureText(word); + + /* If word fits wrapWidth, do nothing */ + if (wordWidth <= wordWrapWidth) { + return word; + } + + /* Make initial guess for text cuttoff */ + let cutoffIndex = Math.floor((wordWrapWidth * wordLen) / wordWidth); + let truncWordWidth = this.measureText(word.substring(0, cutoffIndex)) + suffixWidth; + + /* In case guess was overestimated, shrink it letter by letter. */ + if (truncWordWidth > wordWrapWidth) { + while (cutoffIndex > 0) { + truncWordWidth = this.measureText(word.substring(0, cutoffIndex)) + suffixWidth; + if (truncWordWidth > wordWrapWidth) { + cutoffIndex -= 1; + } else { + break; + } + } + + /* In case guess was underestimated, extend it letter by letter. */ + } else { + while (cutoffIndex < wordLen) { + truncWordWidth = this.measureText(word.substring(0, cutoffIndex)) + suffixWidth; + if (truncWordWidth < wordWrapWidth) { + cutoffIndex += 1; + } else { + // Finally, when bound is crossed, retract last letter. + cutoffIndex -=1; + break; + } + } + } + + /* If wrapWidth is too short to even contain suffix alone, return empty string */ + return word.substring(0, cutoffIndex) + (wordWrapWidth >= suffixWidth ? suffix : ''); + } + + /** + * See {@link wrapText} + * + * @param {string} text + * @param {number} wordWrapWidth + * @param {number} letterSpacing + * @param {number} indent + * @returns + */ + wrapText(text, wordWrapWidth, letterSpacing, indent = 0) { + return Object(_TextTextureRendererUtils_mjs__WEBPACK_IMPORTED_MODULE_2__["wrapText"])(this._context, text, wordWrapWidth, letterSpacing, indent); + }; + + /** + * See {@link measureText} + * + * @param {string} word + * @param {number} space + * @returns {number} + */ + measureText(word, space = 0) { + return Object(_TextTextureRendererUtils_mjs__WEBPACK_IMPORTED_MODULE_2__["measureText"])(this._context, word, space); + } + +} + + +/***/ }), + +/***/ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/textures/TextTextureRendererAdvanced.mjs": +/*!************************************************************************************************************************!*\ + !*** ./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/textures/TextTextureRendererAdvanced.mjs ***! + \************************************************************************************************************************/ +/*! exports provided: default */ +/***/ (function(__webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return TextTextureRendererAdvanced; }); +/* harmony import */ var _tree_StageUtils_mjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../tree/StageUtils.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/tree/StageUtils.mjs"); +/* harmony import */ var _tree_Utils_mjs__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../tree/Utils.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/tree/Utils.mjs"); +/* harmony import */ var _TextTextureRendererUtils_mjs__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./TextTextureRendererUtils.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/textures/TextTextureRendererUtils.mjs"); +/* + * If not stated otherwise in this file or this component's LICENSE file the + * following copyright and licenses apply: + * + * Copyright 2020 Metrological + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + + + +class TextTextureRendererAdvanced { + + constructor(stage, canvas, settings) { + this._stage = stage; + this._canvas = canvas; + this._context = this._canvas.getContext('2d'); + this._settings = settings; + } + + getPrecision() { + return this._settings.precision; + }; + + setFontProperties() { + const font = Object(_TextTextureRendererUtils_mjs__WEBPACK_IMPORTED_MODULE_2__["getFontSetting"])( + this._settings.fontFace, + this._settings.fontStyle, + this._settings.fontSize, + this.getPrecision(), + this._stage.getOption('defaultFontFace') + ); + this._context.font = font; + this._context.textBaseline = this._settings.textBaseline; + return font; + }; + + _load() { + if (_tree_Utils_mjs__WEBPACK_IMPORTED_MODULE_1__["default"].isWeb && document.fonts) { + const fontSetting = Object(_TextTextureRendererUtils_mjs__WEBPACK_IMPORTED_MODULE_2__["getFontSetting"])( + this._settings.fontFace, + this._settings.fontStyle, + this._settings.fontSize, + this.getPrecision(), + this._stage.getOption('defaultFontFace') + ); + try { + if (!document.fonts.check(fontSetting, this._settings.text)) { + // Use a promise that waits for loading. + return document.fonts.load(fontSetting, this._settings.text).catch(err => { + // Just load the fallback font. + console.warn('Font load error', err, fontSetting); + }).then(() => { + if (!document.fonts.check(fontSetting, this._settings.text)) { + console.warn('Font not found', fontSetting); + } + }); + } + } catch(e) { + console.warn("Can't check font loading for " + fontSetting); + } + } + } + + draw() { + // We do not use a promise so that loading is performed syncronous when possible. + const loadPromise = this._load(); + if (!loadPromise) { + return _tree_Utils_mjs__WEBPACK_IMPORTED_MODULE_1__["default"].isSpark ? this._stage.platform.drawText(this) : this._draw(); + } else { + return loadPromise.then(() => { + return _tree_Utils_mjs__WEBPACK_IMPORTED_MODULE_1__["default"].isSpark ? this._stage.platform.drawText(this) : this._draw(); + }); + } + } + + _calculateRenderInfo() { + let renderInfo = {}; + + const precision = this.getPrecision(); + + const paddingLeft = this._settings.paddingLeft * precision; + const paddingRight = this._settings.paddingRight * precision; + const fontSize = this._settings.fontSize * precision; + // const offsetY = this._settings.offsetY === null ? null : (this._settings.offsetY * precision); + const lineHeight = this._settings.lineHeight * precision || fontSize; + const w = this._settings.w != 0 ? this._settings.w * precision : this._stage.getOption('w'); + // const h = this._settings.h * precision; + const wordWrapWidth = this._settings.wordWrapWidth * precision; + const cutSx = this._settings.cutSx * precision; + const cutEx = this._settings.cutEx * precision; + const cutSy = this._settings.cutSy * precision; + const cutEy = this._settings.cutEy * precision; + const letterSpacing = this._settings.letterSpacing || 0; + + // Set font properties. + renderInfo.baseFont = this.setFontProperties(); + + renderInfo.w = w; + renderInfo.width = w; + renderInfo.text = this._settings.text; + renderInfo.precision = precision; + renderInfo.fontSize = fontSize; + renderInfo.fontBaselineRatio = this._settings.fontBaselineRatio; + renderInfo.lineHeight = lineHeight; + renderInfo.letterSpacing = letterSpacing; + renderInfo.textAlign = this._settings.textAlign; + renderInfo.textColor = this._settings.textColor; + renderInfo.verticalAlign = this._settings.verticalAlign; + renderInfo.highlight = this._settings.highlight; + renderInfo.highlightColor = this._settings.highlightColor; + renderInfo.highlightHeight = this._settings.highlightHeight; + renderInfo.highlightPaddingLeft = this._settings.highlightPaddingLeft; + renderInfo.highlightPaddingRight = this._settings.highlightPaddingRight; + renderInfo.highlightOffset = this._settings.highlightOffset; + renderInfo.paddingLeft = this._settings.paddingLeft; + renderInfo.paddingRight = this._settings.paddingRight; + renderInfo.maxLines = this._settings.maxLines; + renderInfo.maxLinesSuffix = this._settings.maxLinesSuffix; + renderInfo.textOverflow = this._settings.textOverflow; + renderInfo.wordWrap = this._settings.wordWrap; + renderInfo.wordWrapWidth = wordWrapWidth; + renderInfo.shadow = this._settings.shadow; + renderInfo.shadowColor = this._settings.shadowColor; + renderInfo.shadowOffsetX = this._settings.shadowOffsetX; + renderInfo.shadowOffsetY = this._settings.shadowOffsetY; + renderInfo.shadowBlur = this._settings.shadowBlur; + renderInfo.cutSx = cutSx; + renderInfo.cutEx = cutEx; + renderInfo.cutSy = cutSy; + renderInfo.cutEy = cutEy; + renderInfo.textIndent = this._settings.textIndent * precision; + renderInfo.wordBreak = this._settings.wordBreak; + + let text = renderInfo.text; + let wrapWidth = renderInfo.wordWrap ? (renderInfo.wordWrapWidth || renderInfo.width) : renderInfo.width; + + // Text overflow + if (renderInfo.textOverflow && !renderInfo.wordWrap) { + let suffix; + switch (this._settings.textOverflow) { + case 'clip': + suffix = ''; + break; + case 'ellipsis': + suffix = this._settings.maxLinesSuffix; + break; + default: + suffix = this._settings.textOverflow; + } + text = this.wrapWord(text, wordWrapWidth || renderInfo.w, suffix); + } + + text = this.tokenize(text); + text = this.parse(text); + text = this.measure(text, letterSpacing, renderInfo.baseFont); + + if (renderInfo.textIndent) { + text = this.indent(text, renderInfo.textIndent); + } + + if (renderInfo.wordBreak) { + text = text.reduce((acc, t) => acc.concat(this.wordBreak(t, wrapWidth, renderInfo.baseFont)), []) + this.resetFontStyle() + } + + // Calculate detailed drawing information + let x = paddingLeft; + let lineNo = 0; + + for (const t of text) { + // Wrap text + if (renderInfo.wordWrap && x + t.width > wrapWidth || t.text == '\n') { + x = paddingLeft; + lineNo += 1; + } + t.lineNo = lineNo; + + if (t.text == '\n') { + continue; + } + + t.x = x; + x += t.width; + } + renderInfo.lineNum = lineNo + 1; + + if (this._settings.h) { + renderInfo.h = this._settings.h; + } else if (renderInfo.maxLines && renderInfo.maxLines < renderInfo.lineNum) { + renderInfo.h = renderInfo.maxLines * renderInfo.lineHeight + fontSize / 2; + } else { + renderInfo.h = renderInfo.lineNum * renderInfo.lineHeight + fontSize / 2; + } + + // This calculates the baseline offset in pixels from the font size. + // To retrieve this ratio, you would do this calculation: + // (FontUnitsPerEm − hhea.Ascender − hhea.Descender) / (2 × FontUnitsPerEm) + // + // This give you the ratio for the baseline, which is then used to figure out + // where the baseline is relative to the bottom of the text bounding box. + const baselineOffsetInPx = renderInfo.fontBaselineRatio * renderInfo.fontSize; + + // Vertical align + let vaOffset = 0; + if (renderInfo.verticalAlign == 'top' && this._context.textBaseline == 'alphabetic') { + vaOffset = -baselineOffsetInPx; + } else if (renderInfo.verticalAlign == 'middle') { + vaOffset = (renderInfo.lineHeight - renderInfo.fontSize - baselineOffsetInPx) / 2; + } else if (this._settings.verticalAlign == 'bottom') { + vaOffset = renderInfo.lineHeight - renderInfo.fontSize; + } + + // Calculate lines information + renderInfo.lines = [] + for (let i = 0; i < renderInfo.lineNum; i++) { + renderInfo.lines[i] = { + width: 0, + x: 0, + y: renderInfo.lineHeight * i + vaOffset, + text: [], + } + } + + for (let t of text) { + renderInfo.lines[t.lineNo].text.push(t); + } + + // Filter out white spaces at beginning and end of each line + for (const l of renderInfo.lines) { + if (l.text.length == 0) { + continue; + } + + const firstWord = l.text[0].text; + const lastWord = l.text[l.text.length - 1].text; + + if (firstWord == '\n') { + l.text.shift(); + } + if (Object(_TextTextureRendererUtils_mjs__WEBPACK_IMPORTED_MODULE_2__["isSpace"])(lastWord) || lastWord == '\n') { + l.text.pop(); + } + } + + + // Calculate line width + for (let l of renderInfo.lines) { + l.width = l.text.reduce((acc, t) => acc + t.width, 0); + } + + renderInfo.width = this._settings.w != 0 ? this._settings.w * precision : Math.max(...renderInfo.lines.map((l) => l.width)) + paddingRight; + renderInfo.w = renderInfo.width; + + // Apply maxLinesSuffix + if (renderInfo.maxLines && renderInfo.lineNum > renderInfo.maxLines && renderInfo.maxLinesSuffix) { + const index = renderInfo.maxLines - 1; + let lastLineText = text.filter((t) => t.lineNo == index) + let suffix = renderInfo.maxLinesSuffix; + suffix = this.tokenize(suffix); + suffix = this.parse(suffix); + suffix = this.measure(suffix, renderInfo.letterSpacing, renderInfo.baseFont); + for (const s of suffix) { + s.lineNo = index; + s.x = 0; + lastLineText.push(s) + } + + const spl = suffix.length + 1 + let _w = lastLineText.reduce((acc, t) => acc + t.width, 0); + while (_w > renderInfo.width || Object(_TextTextureRendererUtils_mjs__WEBPACK_IMPORTED_MODULE_2__["isSpace"])(lastLineText[lastLineText.length - spl].text)) { + lastLineText.splice(lastLineText.length - spl, 1); + _w = lastLineText.reduce((acc, t) => acc + t.width, 0); + if (lastLineText.length < spl) { + break; + } + } + this.alignLine(lastLineText, lastLineText[0].x) + + renderInfo.lines[index].text = lastLineText; + renderInfo.lines[index].width = _w; + } + + // Horizontal alignment offset + if (renderInfo.textAlign == 'center') { + for (let l of renderInfo.lines) { + l.x = (renderInfo.width - l.width - paddingLeft) / 2; + } + } else if (renderInfo.textAlign == 'right') { + for (let l of renderInfo.lines) { + l.x = renderInfo.width - l.width - paddingLeft; + } + } + + return renderInfo; + } + + _draw() { + const renderInfo = this._calculateRenderInfo(); + const precision = this.getPrecision(); + const paddingLeft = renderInfo.paddingLeft * precision; + + // Set canvas dimensions + let canvasWidth = renderInfo.w || renderInfo.width; + if (renderInfo.cutSx || renderInfo.cutEx) { + canvasWidth = Math.min(renderInfo.w, renderInfo.cutEx - renderInfo.cutSx); + } + + let canvasHeight = renderInfo.h; + if (renderInfo.cutSy || renderInfo.cutEy) { + canvasHeight = Math.min(renderInfo.h, renderInfo.cutEy - renderInfo.cutSy); + } + + this._canvas.width = Math.ceil(canvasWidth + this._stage.getOption('textRenderIssueMargin')); + this._canvas.height = Math.ceil(canvasHeight); + + // Canvas context has been reset. + this.setFontProperties(); + + if (renderInfo.fontSize >= 128) { + // WpeWebKit bug: must force compositing because cairo-traps-compositor will not work with text first. + this._context.globalAlpha = 0.01; + this._context.fillRect(0, 0, 0.01, 0.01); + this._context.globalAlpha = 1.0; + } + + // Cut + if (renderInfo.cutSx || renderInfo.cutSy) { + this._context.translate(-renderInfo.cutSx, -renderInfo.cutSy); + } + + // Highlight + if (renderInfo.highlight) { + const hlColor = renderInfo.highlightColor || 0x00000000; + const hlHeight = renderInfo.highlightHeight ? renderInfo.highlightHeight * precision : renderInfo.fontSize * 1.5; + const hlOffset = renderInfo.highlightOffset ? renderInfo.highlightOffset * precision : 0; + const hlPaddingLeft = (renderInfo.highlightPaddingLeft !== null ? renderInfo.highlightPaddingLeft * precision : renderInfo.paddingLeft); + const hlPaddingRight = (renderInfo.highlightPaddingRight !== null ? renderInfo.highlightPaddingRight * precision : renderInfo.paddingRight); + + this._context.fillStyle = _tree_StageUtils_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].getRgbaString(hlColor); + const lineNum = renderInfo.maxLines ? Math.min(renderInfo.maxLines, renderInfo.lineNum) : renderInfo.lineNum; + for (let i = 0; i < lineNum; i++) { + const l = renderInfo.lines[i]; + this._context.fillRect(l.x - hlPaddingLeft + paddingLeft, l.y + hlOffset, l.width + hlPaddingLeft + hlPaddingRight, hlHeight); + } + } + + // Text shadow. + let prevShadowSettings = null; + if (this._settings.shadow) { + prevShadowSettings = [this._context.shadowColor, this._context.shadowOffsetX, this._context.shadowOffsetY, this._context.shadowBlur]; + + this._context.shadowColor = _tree_StageUtils_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].getRgbaString(this._settings.shadowColor); + this._context.shadowOffsetX = this._settings.shadowOffsetX * precision; + this._context.shadowOffsetY = this._settings.shadowOffsetY * precision; + this._context.shadowBlur = this._settings.shadowBlur * precision; + } + + // Draw text + const defaultColor = _tree_StageUtils_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].getRgbaString(this._settings.textColor); + let currentColor = defaultColor; + this._context.fillStyle = defaultColor; + for (const line of renderInfo.lines) { + for (const t of line.text) { + let lx = 0; + + if (t.text == '\n') { + continue; + } + + if (renderInfo.maxLines && t.lineNo >= renderInfo.maxLines) { + continue; + } + + if (t.color != currentColor) { + currentColor = t.color; + this._context.fillStyle = currentColor; + } + + this._context.font = t.fontStyle; + + // Draw with letter spacing + if (t.letters) { + for (let l of t.letters) { + const _x = renderInfo.lines[t.lineNo].x + t.x + lx; + this._context.fillText(l.text, _x, renderInfo.lines[t.lineNo].y + renderInfo.fontSize); + lx += l.width; + } + // Standard drawing + } else { + const _x = renderInfo.lines[t.lineNo].x + t.x; + this._context.fillText(t.text, _x, renderInfo.lines[t.lineNo].y + renderInfo.fontSize); + } + } + } + + // Reset text shadow + if (prevShadowSettings) { + this._context.shadowColor = prevShadowSettings[0]; + this._context.shadowOffsetX = prevShadowSettings[1]; + this._context.shadowOffsetY = prevShadowSettings[2]; + this._context.shadowBlur = prevShadowSettings[3]; + } + + // Reset cut translation + if (renderInfo.cutSx || renderInfo.cutSy) { + this._context.translate(renderInfo.cutSx, renderInfo.cutSy); + } + + // Postprocess renderInfo.lines to be compatible with standard version + renderInfo.lines = renderInfo.lines.map((l) => l.text.reduce((acc, v) => acc + v.text, '')); + if (renderInfo.maxLines) { + renderInfo.lines = renderInfo.lines.slice(0, renderInfo.maxLines); + } + + + this.renderInfo = renderInfo; + + }; + + /** + * See {@link measureText} + * + * @param {string} word + * @param {number} space + * @returns {number} + */ + measureText(word, space = 0) { + return Object(_TextTextureRendererUtils_mjs__WEBPACK_IMPORTED_MODULE_2__["measureText"])(this._context, word, space); + } + + tokenize(text) { + return Object(_TextTextureRendererUtils_mjs__WEBPACK_IMPORTED_MODULE_2__["tokenizeString"])(/ |\u200B|\n||<\/i>||<\/b>||<\/color>/g, text); + } + + parse(tokens) { + let italic = 0; + let bold = 0; + let colorStack = [_tree_StageUtils_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].getRgbaString(this._settings.textColor)]; + let color = 0; + + const colorRegexp = //; + + return tokens.map((t) => { + if (t == '') { + italic += 1; + t = ''; + } else if (t == '' && italic > 0) { + italic -= 1; + t = ''; + } else if (t == '') { + bold += 1; + t = ''; + } else if (t == '' && bold > 0) { + bold -= 1; + t = ''; + } else if (t == '') { + if (colorStack.length > 1) { + color -= 1; + colorStack.pop(); + } + t = ''; + } else if (colorRegexp.test(t)) { + const matched = colorRegexp.exec(t); + colorStack.push( + _tree_StageUtils_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].getRgbaString(parseInt(matched[1])) + ); + color += 1; + t = ''; + + } + + return { + text: t, + italic: italic, + bold: bold, + color: colorStack[color], + } + }) + .filter((o) => o.text != ''); + } + + applyFontStyle(word, baseFont) { + let font = baseFont; + if (word.bold) { + font = 'bold ' + font; + } + if (word.italic) { + font = 'italic ' + font; + } + this._context.font = font + word.fontStyle = font; + } + + resetFontStyle(baseFont) { + this._context.font = baseFont; + } + + measure(parsed, letterSpacing = 0, baseFont) { + for (const p of parsed) { + this.applyFontStyle(p, baseFont); + p.width = this.measureText(p.text, letterSpacing); + + // Letter by letter detail for letter spacing + if (letterSpacing > 0) { + p.letters = p.text.split('').map((l) => {return {text: l}}); + for (let l of p.letters) { + l.width = this.measureText(l.text, letterSpacing); + } + } + + } + this.resetFontStyle(baseFont); + return parsed; + } + + indent(parsed, textIndent) { + parsed.splice(0, 0, {text: "", width: textIndent}); + return parsed; + } + + wrapWord(word, wordWrapWidth, suffix) { + const suffixWidth = this.measureText(suffix); + const wordLen = word.length + const wordWidth = this.measureText(word); + + /* If word fits wrapWidth, do nothing */ + if (wordWidth <= wordWrapWidth) { + return word; + } + + /* Make initial guess for text cuttoff */ + let cutoffIndex = Math.floor((wordWrapWidth * wordLen) / wordWidth); + let truncWordWidth = this.measureText(word.substring(0, cutoffIndex)) + suffixWidth; + + /* In case guess was overestimated, shrink it letter by letter. */ + if (truncWordWidth > wordWrapWidth) { + while (cutoffIndex > 0) { + truncWordWidth = this.measureText(word.substring(0, cutoffIndex)) + suffixWidth; + if (truncWordWidth > wordWrapWidth) { + cutoffIndex -= 1; + } else { + break; + } + } + + /* In case guess was underestimated, extend it letter by letter. */ + } else { + while (cutoffIndex < wordLen) { + truncWordWidth = this.measureText(word.substring(0, cutoffIndex)) + suffixWidth; + if (truncWordWidth < wordWrapWidth) { + cutoffIndex += 1; + } else { + // Finally, when bound is crossed, retract last letter. + cutoffIndex -=1; + break; + } + } + } + + /* If wrapWidth is too short to even contain suffix alone, return empty string */ + return word.substring(0, cutoffIndex) + (wordWrapWidth >= suffixWidth ? suffix : '') + } + + _getBreakIndex(word, width) { + const wordLen = word.length; + const wordWidth = this.measureText(word); + + if (wordWidth <= width) { + return {breakIndex: word.length, truncWordWidth: wordWidth}; + } + + let breakIndex = Math.floor((width * wordLen) / wordWidth); + let truncWordWidth = this.measureText(word.substring(0, breakIndex)) + + /* In case guess was overestimated, shrink it letter by letter. */ + if (truncWordWidth > width) { + while (breakIndex > 0) { + truncWordWidth = this.measureText(word.substring(0, breakIndex)); + if (truncWordWidth > width) { + breakIndex -= 1; + } else { + break; + } + } + + /* In case guess was underestimated, extend it letter by letter. */ + } else { + while (breakIndex < wordLen) { + truncWordWidth = this.measureText(word.substring(0, breakIndex)); + if (truncWordWidth < width) { + breakIndex += 1; + } else { + // Finally, when bound is crossed, retract last letter. + breakIndex -=1; + truncWordWidth = this.measureText(word.substring(0, breakIndex)); + break; + } + } + } + return {breakIndex, truncWordWidth}; + + } + + wordBreak(word, width, baseFont) { + if (!word.text) { + return word + } + this.applyFontStyle(word, baseFont) + const parts = []; + let text = word.text; + if (!word.letters) { + while (true) { + const {breakIndex, truncWordWidth} = this._getBreakIndex(text, width); + parts.push({...word}); + parts[parts.length - 1].text = text.slice(0, breakIndex); + parts[parts.length - 1].width = truncWordWidth; + + if (breakIndex === text.length) { + break; + } + + text = text.slice(breakIndex); + } + } else { + let totalWidth = 0; + let letters = []; + let breakIndex = 0; + for (const l of word.letters) { + if (totalWidth + l.width >= width) { + parts.push({...word}); + parts[parts.length - 1].text = text.slice(0, breakIndex); + parts[parts.length - 1].width = totalWidth; + parts[parts.length - 1].letters = letters; + text = text.slice(breakIndex); + totalWidth = 0; + letters = []; + breakIndex = 0; + + } else { + breakIndex += 1; + letters.push(l); + totalWidth += l.width; + } + } + + if (totalWidth > 0) { + parts.push({...word}); + parts[parts.length - 1].text = text.slice(0, breakIndex); + parts[parts.length - 1].width = totalWidth; + parts[parts.length - 1].letters = letters; + } + } + + return parts; + } + + alignLine(parsed, initialX = 0) { + let prevWidth = 0; + let prevX = initialX; + for (const word of parsed) { + if (word.text == '\n') { + continue; + } + word.x = prevX + prevWidth; + prevX = word.x; + prevWidth = word.width; + } + + } +} + +/***/ }), + +/***/ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/textures/TextTextureRendererUtils.mjs": +/*!*********************************************************************************************************************!*\ + !*** ./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/textures/TextTextureRendererUtils.mjs ***! + \*********************************************************************************************************************/ +/*! exports provided: getFontSetting, isZeroWidthSpace, isSpace, tokenizeString, measureText, wrapText */ +/***/ (function(__webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getFontSetting", function() { return getFontSetting; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isZeroWidthSpace", function() { return isZeroWidthSpace; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isSpace", function() { return isSpace; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "tokenizeString", function() { return tokenizeString; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "measureText", function() { return measureText; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "wrapText", function() { return wrapText; }); +/* + * If not stated otherwise in this file or this component's LICENSE file the + * following copyright and licenses apply: + * + * Copyright 2020 Metrological + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Returns CSS font setting string for use in canvas context. + * + * @param fontFace + * @param fontStyle + * @param fontSize + * @param precision + * @param defaultFontFace + * @returns + */ +function getFontSetting(fontFace, fontStyle, fontSize, precision, defaultFontFace) { + let ff = fontFace; + if (!Array.isArray(ff)) { + ff = [ff]; + } + let ffs = []; + for (let i = 0, n = ff.length; i < n; i++) { + let curFf = ff[i]; + // Replace the default font face `null` with the actual default font face set + // on the stage. + if (curFf == null) { + curFf = defaultFontFace; + } + if (curFf.indexOf(' ') < 0) { + ffs.push(curFf); + } + else { + ffs.push(`"${curFf}"`); + } + } + return `${fontStyle} ${fontSize * precision}px ${ffs.join(",")}`; +} +/** + * Returns true if the given character is a zero-width space. + * + * @param space + */ +function isZeroWidthSpace(space) { + return space === '' || space === '\u200B'; +} +/** + * Returns true if the given character is a zero-width space or a regular space. + * + * @param space + */ +function isSpace(space) { + return isZeroWidthSpace(space) || space === ' '; +} +/** + * Converts a string into an array of tokens and the words between them. + * + * @param tokenRegex + * @param text + */ +function tokenizeString(tokenRegex, text) { + const delimeters = text.match(tokenRegex) || []; + const words = text.split(tokenRegex) || []; + let final = []; + for (let i = 0; i < words.length; i++) { + final.push(words[i], delimeters[i]); + } + final.pop(); + return final.filter((word) => word != ''); +} +/** + * Measure the width of a string accounting for letter spacing. + * + * @param context + * @param word + * @param space + */ +function measureText(context, word, space = 0) { + if (!space) { + return context.measureText(word).width; + } + return word.split('').reduce((acc, char) => { + // Zero-width spaces should not include letter spacing. + // And since we know the width of a zero-width space is 0, we can skip + // measuring it. + if (isZeroWidthSpace(char)) { + return acc; + } + return acc + context.measureText(char).width + space; + }, 0); +} +/** + * Applies newlines to a string to have it optimally fit into the horizontal + * bounds set by the Text object's wordWrapWidth property. + * + * @param context + * @param text + * @param wordWrapWidth + * @param letterSpacing + * @param indent + */ +function wrapText(context, text, wordWrapWidth, letterSpacing, indent) { + // Greedy wrapping algorithm that will wrap words as the line grows longer. + // than its horizontal bounds. + const spaceRegex = / |\u200B/g; + let lines = text.split(/\r?\n/g); + let allLines = []; + let realNewlines = []; + for (let i = 0; i < lines.length; i++) { + let resultLines = []; + let result = ''; + let spaceLeft = wordWrapWidth - indent; + let words = lines[i].split(spaceRegex); + let spaces = lines[i].match(spaceRegex) || []; + for (let j = 0; j < words.length; j++) { + const space = spaces[j - 1] || ''; + const word = words[j]; + const wordWidth = measureText(context, word, letterSpacing); + const wordWidthWithSpace = wordWidth + measureText(context, space, letterSpacing); + if (j === 0 || wordWidthWithSpace > spaceLeft) { + // Skip printing the newline if it's the first word of the line that is. + // greater than the word wrap width. + if (j > 0) { + resultLines.push(result); + result = ''; + } + result += word; + spaceLeft = wordWrapWidth - wordWidth - (j === 0 ? indent : 0); + } + else { + spaceLeft -= wordWidthWithSpace; + result += space + word; + } + } + resultLines.push(result); + result = ''; + allLines = allLines.concat(resultLines); + if (i < lines.length - 1) { + realNewlines.push(allLines.length); + } + } + return { l: allLines, n: realNewlines }; +} +//# sourceMappingURL=TextTextureRendererUtils.mjs.map + +/***/ }), + +/***/ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/tools/MultiSpline.mjs": +/*!*****************************************************************************************************!*\ + !*** ./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/tools/MultiSpline.mjs ***! + \*****************************************************************************************************/ +/*! exports provided: default */ +/***/ (function(__webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return MultiSpline; }); +/* harmony import */ var _tree_Utils_mjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../tree/Utils.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/tree/Utils.mjs"); +/* + * If not stated otherwise in this file or this component's LICENSE file the + * following copyright and licenses apply: + * + * Copyright 2020 Metrological + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + +class MultiSpline { + + constructor() { + this._clear(); + } + + _clear() { + this._p = []; + this._pe = []; + this._idp = []; + this._f = []; + this._v = []; + this._lv = []; + this._sm = []; + this._s = []; + this._ve = []; + this._sme = []; + this._se = []; + + this._length = 0; + } + + parse(rgba, def) { + let i, n; + if (!_tree_Utils_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].isObjectLiteral(def)) { + def = {0: def} + } + + let defaultSmoothness = 0.5; + + let items = []; + for (let key in def) { + if (def.hasOwnProperty(key)) { + let obj = def[key]; + if (!_tree_Utils_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].isObjectLiteral(obj)) { + obj = {v: obj} + } + + let p = parseFloat(key); + + if (key === "sm") { + defaultSmoothness = obj.v; + } else if (!isNaN(p) && p >= 0 && p <= 2) { + obj.p = p; + + obj.f = _tree_Utils_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].isFunction(obj.v); + obj.lv = obj.f ? obj.v(0, 0) : obj.v; + + items.push(obj); + } + } + } + + // Sort by progress value. + items = items.sort(function(a, b) {return a.p - b.p}); + + n = items.length; + + for (i = 0; i < n; i++) { + let last = (i === n - 1); + if (!items[i].hasOwnProperty('pe')) { + // Progress. + items[i].pe = last ? (items[i].p <= 1 ? 1 : 2 /* support onetotwo stop */) : items[i + 1].p; + } else { + // Prevent multiple items at the same time. + const max = i < n - 1 ? items[i + 1].p : 1; + if (items[i].pe > max) { + items[i].pe = max; + } + } + if (items[i].pe === items[i].p) { + items[i].idp = 0; + } else { + items[i].idp = 1 / (items[i].pe - items[i].p); + } + } + + // Color merger: we need to split/combine RGBA components. + + // Calculate bezier helper values.; + for (i = 0; i < n; i++) { + if (!items[i].hasOwnProperty('sm')) { + // Smoothness.; + items[i].sm = defaultSmoothness; + } + if (!items[i].hasOwnProperty('s')) { + // Slope.; + if (i === 0 || i === n - 1 || (items[i].p === 1 /* for onetotwo */)) { + // Horizontal slope at start and end.; + items[i].s = rgba ? [0, 0, 0, 0] : 0; + } else { + const pi = items[i - 1]; + const ni = items[i + 1]; + if (pi.p === ni.p) { + items[i].s = rgba ? [0, 0, 0, 0] : 0; + } else { + if (rgba) { + const nc = MultiSpline.getRgbaComponents(ni.lv); + const pc = MultiSpline.getRgbaComponents(pi.lv); + const d = 1 / (ni.p - pi.p); + items[i].s = [ + d * (nc[0] - pc[0]), + d * (nc[1] - pc[1]), + d * (nc[2] - pc[2]), + d * (nc[3] - pc[3]) + ]; + } else { + items[i].s = (ni.lv - pi.lv) / (ni.p - pi.p); + } + } + } + } + } + + for (i = 0; i < n - 1; i++) { + // Calculate value function.; + if (!items[i].f) { + + let last = (i === n - 1); + if (!items[i].hasOwnProperty('ve')) { + items[i].ve = last ? items[i].lv : items[i + 1].lv; + } + + // We can only interpolate on numeric values. Non-numeric values are set literally when reached time. + if (_tree_Utils_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].isNumber(items[i].v) && _tree_Utils_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].isNumber(items[i].lv)) { + if (!items[i].hasOwnProperty('sme')) { + items[i].sme = last ? defaultSmoothness : items[i + 1].sm; + } + if (!items[i].hasOwnProperty('se')) { + items[i].se = last ? (rgba ? [0, 0, 0, 0] : 0) : items[i + 1].s; + } + + // Generate spline.; + if (rgba) { + items[i].v = MultiSpline.getSplineRgbaValueFunction(items[i].v, items[i].ve, items[i].p, items[i].pe, items[i].sm, items[i].sme, items[i].s, items[i].se); + } else { + items[i].v = MultiSpline.getSplineValueFunction(items[i].v, items[i].ve, items[i].p, items[i].pe, items[i].sm, items[i].sme, items[i].s, items[i].se); + } + + items[i].f = true; + } + } + } + + if (this.length) { + this._clear(); + } + + for (i = 0, n = items.length; i < n; i++) { + this._add(items[i]); + } + } + + _add(item) { + this._p.push(item.p || 0); + this._pe.push(item.pe || 0); + this._idp.push(item.idp || 0); + this._f.push(item.f || false); + this._v.push(item.hasOwnProperty('v') ? item.v : 0 /* v might be false or null */ ); + this._lv.push(item.lv || 0); + this._sm.push(item.sm || 0); + this._s.push(item.s || 0); + this._ve.push(item.ve || 0); + this._sme.push(item.sme || 0); + this._se.push(item.se || 0); + this._length++; + } + + _getItem(p) { + const n = this._length; + if (!n) { + return -1; + } + + if (p < this._p[0]) { + return 0; + } + + for (let i = 0; i < n; i++) { + if (this._p[i] <= p && p < this._pe[i]) { + return i; + } + } + + return n - 1; + } + + getValue(p) { + const i = this._getItem(p); + if (i === -1) { + return undefined; + } else { + if (this._f[i]) { + const o = Math.min(1, Math.max(0, (p - this._p[i]) * this._idp[i])); + return this._v[i](o); + } else { + return this._v[i]; + } + } + } + + get length() { + return this._length; + } + + static getRgbaComponents(argb) { + let r = ((argb / 65536) | 0) % 256; + let g = ((argb / 256) | 0) % 256; + let b = argb % 256; + let a = ((argb / 16777216) | 0); + return [r, g, b, a]; + }; + + static getSplineValueFunction(v1, v2, p1, p2, o1, i2, s1, s2) { + // Normalize slopes because we use a spline that goes from 0 to 1. + let dp = p2 - p1; + s1 *= dp; + s2 *= dp; + + let helpers = MultiSpline.getSplineHelpers(v1, v2, o1, i2, s1, s2); + if (!helpers) { + return function (p) { + if (p === 0) return v1; + if (p === 1) return v2; + + return v2 * p + v1 * (1 - p); + }; + } else { + return function (p) { + if (p === 0) return v1; + if (p === 1) return v2; + return MultiSpline.calculateSpline(helpers, p); + }; + } + }; + + static getSplineRgbaValueFunction(v1, v2, p1, p2, o1, i2, s1, s2) { + // Normalize slopes because we use a spline that goes from 0 to 1. + let dp = p2 - p1; + s1[0] *= dp; + s1[1] *= dp; + s1[2] *= dp; + s1[3] *= dp; + s2[0] *= dp; + s2[1] *= dp; + s2[2] *= dp; + s2[3] *= dp; + + let cv1 = MultiSpline.getRgbaComponents(v1); + let cv2 = MultiSpline.getRgbaComponents(v2); + + let helpers = [ + MultiSpline.getSplineHelpers(cv1[0], cv2[0], o1, i2, s1[0], s2[0]), + MultiSpline.getSplineHelpers(cv1[1], cv2[1], o1, i2, s1[1], s2[1]), + MultiSpline.getSplineHelpers(cv1[2], cv2[2], o1, i2, s1[2], s2[2]), + MultiSpline.getSplineHelpers(cv1[3], cv2[3], o1, i2, s1[3], s2[3]) + ]; + + if (!helpers[0]) { + return function (p) { + // Linear. + if (p === 0) return v1; + if (p === 1) return v2; + + return MultiSpline.mergeColors(v2, v1, p); + }; + } else { + return function (p) { + if (p === 0) return v1; + if (p === 1) return v2; + + return MultiSpline.getArgbNumber([ + Math.min(255, MultiSpline.calculateSpline(helpers[0], p)), + Math.min(255, MultiSpline.calculateSpline(helpers[1], p)), + Math.min(255, MultiSpline.calculateSpline(helpers[2], p)), + Math.min(255, MultiSpline.calculateSpline(helpers[3], p)) + ]); + }; + } + + }; + + /** + * Creates helpers to be used in the spline function. + * @param {number} v1 + * From value. + * @param {number} v2 + * To value. + * @param {number} o1 + * From smoothness (0 = linear, 1 = smooth). + * @param {number} s1 + * From slope (0 = horizontal, infinite = vertical). + * @param {number} i2 + * To smoothness. + * @param {number} s2 + * To slope. + * @returns {Number[]} + * The helper values to be supplied to the spline function. + * If the configuration is actually linear, null is returned. + */ + static getSplineHelpers(v1, v2, o1, i2, s1, s2) { + if (!o1 && !i2) { + // Linear. + return null; + } + + // Cubic bezier points. + // http://cubic-bezier.com/ + let csx = o1; + let csy = v1 + s1 * o1; + let cex = 1 - i2; + let cey = v2 - s2 * i2; + + let xa = 3 * csx - 3 * cex + 1; + let xb = -6 * csx + 3 * cex; + let xc = 3 * csx; + + let ya = 3 * csy - 3 * cey + v2 - v1; + let yb = 3 * (cey + v1) - 6 * csy; + let yc = 3 * (csy - v1); + let yd = v1; + + return [xa, xb, xc, ya, yb, yc, yd]; + }; + + /** + * Calculates the intermediate spline value based on the specified helpers. + * @param {number[]} helpers + * Obtained from getSplineHelpers. + * @param {number} p + * @return {number} + */ + static calculateSpline(helpers, p) { + let xa = helpers[0]; + let xb = helpers[1]; + let xc = helpers[2]; + let ya = helpers[3]; + let yb = helpers[4]; + let yc = helpers[5]; + let yd = helpers[6]; + + if (xa === -2 && ya === -2 && xc === 0 && yc === 0) { + // Linear. + return p; + } + + // Find t for p. + let t = 0.5, cbx, dx; + + for (let it = 0; it < 20; it++) { + // Cubic bezier function: f(t)=t*(t*(t*a+b)+c). + cbx = t * (t * (t * xa + xb) + xc); + + dx = p - cbx; + if (dx > -1e-8 && dx < 1e-8) { + // Solution found! + return t * (t * (t * ya + yb) + yc) + yd; + } + + // Cubic bezier derivative function: f'(t)=t*(t*(3*a)+2*b)+c + let cbxd = t * (t * (3 * xa) + 2 * xb) + xc; + + if (cbxd > 1e-10 && cbxd < 1e-10) { + // Problematic. Fall back to binary search method. + break; + } + + t += dx / cbxd; + } + + // Fallback: binary search method. This is more reliable when there are near-0 slopes. + let minT = 0; + let maxT = 1; + for (let it = 0; it < 20; it++) { + t = 0.5 * (minT + maxT); + + // Cubic bezier function: f(t)=t*(t*(t*a+b)+c)+d. + cbx = t * (t * (t * xa + xb) + xc); + + dx = p - cbx; + if (dx > -1e-8 && dx < 1e-8) { + // Solution found! + return t * (t * (t * ya + yb) + yc) + yd; + } + + if (dx < 0) { + maxT = t; + } else { + minT = t; + } + } + + return t; + }; + + static mergeColors(c1, c2, p) { + let r1 = ((c1 / 65536) | 0) % 256; + let g1 = ((c1 / 256) | 0) % 256; + let b1 = c1 % 256; + let a1 = ((c1 / 16777216) | 0); + + let r2 = ((c2 / 65536) | 0) % 256; + let g2 = ((c2 / 256) | 0) % 256; + let b2 = c2 % 256; + let a2 = ((c2 / 16777216) | 0); + + let r = r1 * p + r2 * (1 - p); + let g = g1 * p + g2 * (1 - p); + let b = b1 * p + b2 * (1 - p); + let a = a1 * p + a2 * (1 - p); + + return Math.round(a) * 16777216 + Math.round(r) * 65536 + Math.round(g) * 256 + Math.round(b); + }; + + static getArgbNumber(rgba) { + rgba[0] = Math.max(0, Math.min(255, rgba[0])); + rgba[1] = Math.max(0, Math.min(255, rgba[1])); + rgba[2] = Math.max(0, Math.min(255, rgba[2])); + rgba[3] = Math.max(0, Math.min(255, rgba[3])); + let v = ((rgba[3] | 0) << 24) + ((rgba[0] | 0) << 16) + ((rgba[1] | 0) << 8) + (rgba[2] | 0); + if (v < 0) { + v = 0xFFFFFFFF + v + 1; + } + return v; + }; +} + + +/***/ }), + +/***/ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/tools/ObjMerger.mjs": +/*!***************************************************************************************************!*\ + !*** ./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/tools/ObjMerger.mjs ***! + \***************************************************************************************************/ +/*! exports provided: default */ +/***/ (function(__webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return ObjMerger; }); +/* harmony import */ var _tree_Utils_mjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../tree/Utils.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/tree/Utils.mjs"); +/* + * If not stated otherwise in this file or this component's LICENSE file the + * following copyright and licenses apply: + * + * Copyright 2020 Metrological + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + +class ObjMerger { + + static isMf(f) { + return _tree_Utils_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].isFunction(f) && f.__mf; + } + + static mf(f) { + // Set as merge function. + f.__mf = true; + return f; + } + + static merge(a, b) { + const aks = Object.keys(a); + const bks = Object.keys(b); + + if (!bks.length) { + return a; + } + + // Create index array for all elements. + const ai = {}; + const bi = {}; + for (let i = 0, n = bks.length; i < n; i++) { + const key = bks[i]; + ai[key] = -1; + bi[key] = i; + } + for (let i = 0, n = aks.length; i < n; i++) { + const key = aks[i]; + ai[key] = i; + if (bi[key] === undefined) { + bi[key] = -1; + } + } + + const aksl = aks.length; + + const result = {}; + for (let i = 0, n = bks.length; i < n; i++) { + const key = bks[i]; + + // Prepend all items in a that are not in b - before the now added b attribute. + const aIndex = ai[key]; + let curIndex = aIndex; + while(--curIndex >= 0) { + const akey = aks[curIndex]; + if (bi[akey] !== -1) { + // Already found? Stop processing. + // Not yet found but exists in b? Also stop processing: wait until we find it in b. + break; + } + } + while(++curIndex < aIndex) { + const akey = aks[curIndex]; + result[akey] = a[akey]; + } + + const bv = b[key]; + const av = a[key]; + let r; + if (this.isMf(bv)) { + r = bv(av); + } else { + if (!_tree_Utils_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].isObjectLiteral(av) || !_tree_Utils_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].isObjectLiteral(bv)) { + r = bv; + } else { + r = ObjMerger.merge(av, bv); + } + } + + // When marked as undefined, property is deleted. + if (r !== undefined) { + result[key] = r; + } + } + + // Append remaining final items in a. + let curIndex = aksl; + while(--curIndex >= 0) { + const akey = aks[curIndex]; + if (bi[akey] !== -1) { + break; + } + } + while(++curIndex < aksl) { + const akey = aks[curIndex]; + result[akey] = a[akey]; + } + + return result; + } + +} + + +/***/ }), + +/***/ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/tools/ObjectListProxy.mjs": +/*!*********************************************************************************************************!*\ + !*** ./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/tools/ObjectListProxy.mjs ***! + \*********************************************************************************************************/ +/*! exports provided: default */ +/***/ (function(__webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return ObjectListProxy; }); +/* harmony import */ var _tree_ObjectList_mjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../tree/ObjectList.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/tree/ObjectList.mjs"); +/* + * If not stated otherwise in this file or this component's LICENSE file the + * following copyright and licenses apply: + * + * Copyright 2020 Metrological + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * Manages the list of children for an element. + */ + + + +class ObjectListProxy extends _tree_ObjectList_mjs__WEBPACK_IMPORTED_MODULE_0__["default"] { + + constructor(target) { + super(); + this._target = target; + } + + onAdd(item, index) { + this._target.addAt(item, index); + } + + onRemove(item, index) { + this._target.removeAt(index); + } + + onSync(removed, added, order) { + this._target._setByArray(order); + } + + onSet(item, index) { + this._target.setAt(item, index); + } + + onMove(item, fromIndex, toIndex) { + this._target.setAt(item, toIndex); + } + + createItem(object) { + return this._target.createItem(object); + } + + isItem(object) { + return this._target.isItem(object); + } + +} + + + + +/***/ }), + +/***/ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/tools/ObjectListWrapper.mjs": +/*!***********************************************************************************************************!*\ + !*** ./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/tools/ObjectListWrapper.mjs ***! + \***********************************************************************************************************/ +/*! exports provided: default */ +/***/ (function(__webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return ObjectListWrapper; }); +/* harmony import */ var _ObjectListProxy_mjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./ObjectListProxy.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/tools/ObjectListProxy.mjs"); +/* + * If not stated otherwise in this file or this component's LICENSE file the + * following copyright and licenses apply: + * + * Copyright 2020 Metrological + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * Manages the list of children for an element. + */ + + + +class ObjectListWrapper extends _ObjectListProxy_mjs__WEBPACK_IMPORTED_MODULE_0__["default"] { + + constructor(target, wrap) { + super(target); + this._wrap = wrap; + } + + wrap(item) { + let wrapper = this._wrap(item); + item._wrapper = wrapper; + return wrapper; + } + + onAdd(item, index) { + item = this.wrap(item); + super.onAdd(item, index); + } + + onRemove(item, index) { + super.onRemove(item, index); + } + + onSync(removed, added, order) { + added.forEach(a => this.wrap(a)); + order = order.map(a => a._wrapper); + super.onSync(removed, added, order); + } + + onSet(item, index) { + item = this.wrap(item); + super.onSet(item, index); + } + + onMove(item, fromIndex, toIndex) { + super.onMove(item, fromIndex, toIndex); + } + +} + + +/***/ }), + +/***/ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/tools/Tools.mjs": +/*!***********************************************************************************************!*\ + !*** ./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/tools/Tools.mjs ***! + \***********************************************************************************************/ +/*! exports provided: default */ +/***/ (function(__webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return Tools; }); +/* harmony import */ var _tree_Utils_mjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../tree/Utils.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/tree/Utils.mjs"); +/* harmony import */ var _tree_StageUtils_mjs__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../tree/StageUtils.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/tree/StageUtils.mjs"); +/* harmony import */ var _textures_StaticCanvasTexture_mjs__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../textures/StaticCanvasTexture.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/textures/StaticCanvasTexture.mjs"); +/* + * If not stated otherwise in this file or this component's LICENSE file the + * following copyright and licenses apply: + * + * Copyright 2020 Metrological + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + + + +class Tools { + + static getCanvasTexture(canvasFactory, lookupId) { + return {type: _textures_StaticCanvasTexture_mjs__WEBPACK_IMPORTED_MODULE_2__["default"], content: {factory: canvasFactory, lookupId: lookupId}} + } + + static getRoundRect(w, h, radius, strokeWidth, strokeColor, fill, fillColor) { + if (!Array.isArray(radius)){ + // upper-left, upper-right, bottom-right, bottom-left. + radius = [radius, radius, radius, radius]; + } + + let factory = (cb, stage) => { + if (_tree_Utils_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].isSpark) { + stage.platform.createRoundRect(cb, stage, w, h, radius, strokeWidth, strokeColor, fill, fillColor); + } else { + cb(null, this.createRoundRect(stage, w, h, radius, strokeWidth, strokeColor, fill, fillColor)); + } + }; + let id = 'rect' + [w, h, strokeWidth, strokeColor, fill ? 1 : 0, fillColor].concat(radius).join(","); + return Tools.getCanvasTexture(factory, id); + } + + static createRoundRect(stage, w, h, radius, strokeWidth, strokeColor, fill, fillColor) { + if (fill === undefined) fill = true; + if (strokeWidth === undefined) strokeWidth = 0; + + let canvas = stage.platform.getDrawingCanvas(); + let ctx = canvas.getContext('2d'); + ctx.imageSmoothingEnabled = true; + + canvas.width = w + strokeWidth + 2; + canvas.height = h + strokeWidth + 2; + + ctx.beginPath(); + let x = 0.5 * strokeWidth + 1, y = 0.5 * strokeWidth + 1; + + ctx.moveTo(x + radius[0], y); + ctx.lineTo(x + w - radius[1], y); + ctx.arcTo(x + w, y, x + w, y + radius[1], radius[1]); + ctx.lineTo(x + w, y + h - radius[2]); + ctx.arcTo(x + w, y + h, x + w - radius[2], y + h, radius[2]); + ctx.lineTo(x + radius[3], y + h); + ctx.arcTo(x, y + h, x, y + h - radius[3], radius[3]); + ctx.lineTo(x, y + radius[0]); + ctx.arcTo(x, y, x + radius[0], y, radius[0]); + ctx.closePath(); + + if (fill) { + if (_tree_Utils_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].isNumber(fillColor)) { + ctx.fillStyle = _tree_StageUtils_mjs__WEBPACK_IMPORTED_MODULE_1__["default"].getRgbaString(fillColor); + } else { + ctx.fillStyle = "white"; + } + ctx.fill(); + } + + if (strokeWidth) { + if (_tree_Utils_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].isNumber(strokeColor)) { + ctx.strokeStyle = _tree_StageUtils_mjs__WEBPACK_IMPORTED_MODULE_1__["default"].getRgbaString(strokeColor); + } else { + ctx.strokeStyle = "white"; + } + ctx.lineWidth = strokeWidth; + ctx.stroke(); + } + + return canvas; + } + + static getShadowRect(w, h, radius = 0, blur = 5, margin = blur * 2) { + if (!Array.isArray(radius)){ + // upper-left, upper-right, bottom-right, bottom-left. + radius = [radius, radius, radius, radius]; + } + + let factory = (cb, stage) => { + if (_tree_Utils_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].isSpark) { + stage.platform.createShadowRect(cb, stage, w, h, radius, blur, margin); + } else { + cb(null, this.createShadowRect(stage, w, h, radius, blur, margin)); + } + }; + let id = 'shadow' + [w, h, blur, margin].concat(radius).join(","); + return Tools.getCanvasTexture(factory, id); + } + + static createShadowRect(stage, w, h, radius, blur, margin) { + let canvas = stage.platform.getDrawingCanvas(); + let ctx = canvas.getContext('2d'); + ctx.imageSmoothingEnabled = true; + + canvas.width = w + margin * 2; + canvas.height = h + margin * 2; + + // WpeWebKit bug: we experienced problems without this with shadows in noncompositedwebgl mode. + ctx.globalAlpha = 0.01; + ctx.fillRect(0, 0, 0.01, 0.01); + ctx.globalAlpha = 1.0; + + ctx.shadowColor = _tree_StageUtils_mjs__WEBPACK_IMPORTED_MODULE_1__["default"].getRgbaString(0xFFFFFFFF); + ctx.fillStyle = _tree_StageUtils_mjs__WEBPACK_IMPORTED_MODULE_1__["default"].getRgbaString(0xFFFFFFFF); + ctx.shadowBlur = blur; + ctx.shadowOffsetX = (w + 10) + margin; + ctx.shadowOffsetY = margin; + + ctx.beginPath(); + const x = -(w + 10); + const y = 0; + + ctx.moveTo(x + radius[0], y); + ctx.lineTo(x + w - radius[1], y); + ctx.arcTo(x + w, y, x + w, y + radius[1], radius[1]); + ctx.lineTo(x + w, y + h - radius[2]); + ctx.arcTo(x + w, y + h, x + w - radius[2], y + h, radius[2]); + ctx.lineTo(x + radius[3], y + h); + ctx.arcTo(x, y + h, x, y + h - radius[3], radius[3]); + ctx.lineTo(x, y + radius[0]); + ctx.arcTo(x, y, x + radius[0], y, radius[0]); + ctx.closePath(); + ctx.fill(); + + return canvas; + } + + static getSvgTexture(url, w, h) { + let factory = (cb, stage) => { + if (_tree_Utils_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].isSpark) { + stage.platform.createSvg(cb, stage, url, w, h); + } else { + this.createSvg(cb, stage, url, w, h); + } + }; + let id = 'svg' + [w, h, url].join(","); + return Tools.getCanvasTexture(factory, id); + } + + static createSvg(cb, stage, url, w, h) { + let canvas = stage.platform.getDrawingCanvas(); + let ctx = canvas.getContext('2d'); + ctx.imageSmoothingEnabled = true; + + let img = new Image(); + img.onload = () => { + canvas.width = w; + canvas.height = h; + ctx.drawImage(img, 0, 0, canvas.width, canvas.height); + cb(null, canvas); + } + img.onerror = (err) => { + cb(err); + } + + // On the PS4 platform setting the `crossOrigin` attribute on images + // can cause CORS failures. + if (!_tree_Utils_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].isPS4) { + img.crossOrigin = "Anonymous"; + } + + img.src = url; + } + +} + + +/***/ }), + +/***/ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/tools/WebGLStateManager.mjs": +/*!***********************************************************************************************************!*\ + !*** ./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/tools/WebGLStateManager.mjs ***! + \***********************************************************************************************************/ +/*! exports provided: default */ +/***/ (function(__webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* + * If not stated otherwise in this file or this component's LICENSE file the + * following copyright and licenses apply: + * + * Copyright 2020 Metrological + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +class Utils { + + static isFunction(value) { + return typeof value === 'function'; + } + + static isNumber(value) { + return typeof value === 'number'; + } + + static isInteger(value) { + return (typeof value === 'number' && (value % 1) === 0); + } + + static isBoolean(value) { + return value === true || value === false; + } + + static isString(value) { + return typeof value == 'string'; + } + + static isObject(value) { + let type = typeof value; + return !!value && (type == 'object' || type == 'function'); + } + + static isPlainObject(value) { + let type = typeof value; + return !!value && (type == 'object'); + } + + static isObjectLiteral(value){ + return typeof value === 'object' && value && value.constructor === Object + } + + static getArrayIndex(index, arr) { + return Utils.getModuloIndex(index, arr.length); + } + + static equalValues(v1, v2) { + if ((typeof v1) !== (typeof v2)) return false + if (Utils.isObjectLiteral(v1)) { + return Utils.isObjectLiteral(v2) && Utils.equalObjectLiterals(v1, v2) + } else if (Array.isArray(v1)) { + return Array.isArray(v2) && Utils.equalArrays(v1, v2) + } else { + return v1 === v2 + } + } + + static equalObjectLiterals(obj1, obj2) { + let keys1 = Object.keys(obj1); + let keys2 = Object.keys(obj2); + if (keys1.length !== keys2.length) { + return false + } + + for (let i = 0, n = keys1.length; i < n; i++) { + const k1 = keys1[i]; + const k2 = keys2[i]; + if (k1 !== k2) { + return false + } + + const v1 = obj1[k1]; + const v2 = obj2[k2]; + + if (!Utils.equalValues(v1, v2)) { + return false + } + } + + return true; + } + + static equalArrays(v1, v2) { + if (v1.length !== v2.length) { + return false + } + for (let i = 0, n = v1.length; i < n; i++) { + if (!this.equalValues(v1[i], v2[i])) { + return false + } + } + + return true + } + +} + +/** + * Maintains the state of a WebGLRenderingContext. + */ +class WebGLState { + + constructor(id, gl) { + this._id = id; + this._gl = gl; + this._program = undefined; + this._buffers = new Map(); + this._framebuffers = new Map(); + this._renderbuffers = new Map(); + + // Contains vertex attribute definition arrays (enabled, size, type, normalized, stride, offset). + this._vertexAttribs = new Array(16); + this._nonDefaultFlags = new Set(); + this._settings = new Map(); + this._textures = new Array(8); + this._maxTexture = 0; + this._activeTexture = gl.TEXTURE0; + this._pixelStorei = new Array(5); + } + + _getDefaultFlag(cap) { + return (cap === this._gl.DITHER); + } + + setFlag(cap, v) { + const def = this._getDefaultFlag(cap); + if (v === def) { + return this._nonDefaultFlags.delete(cap); + } else { + if (!this._nonDefaultFlags.has(cap)) { + this._nonDefaultFlags.add(cap); + return true; + } else { + return false; + } + } + } + + setBuffer(target, buffer) { + const change = this._buffers.get(target) !== buffer; + this._buffers.set(target, buffer); + + if (change && (target === this._gl.ARRAY_BUFFER)) { + // When the array buffer is changed all attributes are cleared. + this._vertexAttribs = []; + } + + return change; + } + + setFramebuffer(target, buffer) { + const change = this._framebuffers.get(target) !== buffer; + this._framebuffers.set(target, buffer); + return change; + } + + setRenderbuffer(target, buffer) { + const change = this._renderbuffers.get(target) !== buffer; + this._renderbuffers.set(target, buffer); + return change; + } + + setProgram(program) { + const change = this._program !== program; + this._program = program; + return change + } + + setSetting(func, v) { + const s = this._settings.get(func); + const change = !s || !Utils.equalValues(s, v); + this._settings.set(func, v); + return change + } + + disableVertexAttribArray(index) { + const va = this._vertexAttribs[index]; + if (va && va[5]) { + va[5] = false; + return true; + } + return false; + } + + enableVertexAttribArray(index) { + const va = this._vertexAttribs[index]; + if (va) { + if (!va[0]) { + va[0] = true; + return true; + } + } else { + this._vertexAttribs[index] = [0, 0, 0, 0, 0, true]; + return true; + } + return false; + } + + vertexAttribPointer(index, props) { + let va = this._vertexAttribs[index]; + let equal = false; + if (va) { + equal = va[0] === props[0] && + va[1] === props[1] && + va[2] === props[2] && + va[3] === props[3] && + va[4] === props[4]; + } + + if (equal) { + return false; + } else { + props[5] = va ? va[5] : false; + return true; + } + } + + setActiveTexture(texture) { + const changed = this._activeTexture !== texture; + this._activeTexture = texture; + return changed; + } + + bindTexture(target, texture) { + const activeIndex = WebGLState._getTextureIndex(this._activeTexture); + this._maxTexture = Math.max(this._maxTexture, activeIndex + 1); + const current = this._textures[activeIndex]; + const targetIndex = WebGLState._getTextureTargetIndex(target); + if (current) { + if (current[targetIndex] === texture) { + return false; + } + current[targetIndex] = texture; + return true; + } else { + if (texture) { + this._textures[activeIndex] = []; + this._textures[activeIndex][targetIndex] = texture; + return true + } else { + return false + } + } + } + + setPixelStorei(pname, param) { + const i = WebGLState._getPixelStoreiIndex(pname); + const change = !Utils.equalValues(this._pixelStorei[i], param); + this._pixelStorei[i] = param; + return change; + } + + migrate(s) { + const t = this; + + // Warning: migrate should call the original prototype methods directly. + + this._migrateFlags(t, s); + + // useProgram + if (s._program !== t._program) { + this._gl._useProgram(s._program); + } + + this._migrateFramebuffers(t, s); + this._migrateRenderbuffers(t, s); + + const buffersChanged = this._migrateBuffers(t, s); + this._migrateAttributes(t, s, buffersChanged); + + this._migrateFlags(t, s); + + this._migrateSettings(t, s); + + this._migratePixelStorei(t, s); + + this._migrateTextures(t, s); + + } + + _migratePixelStorei(t, s) { + for (let i = 0, n = t._pixelStorei.length; i < n; i++) { + if (t._pixelStorei[i] !== s._pixelStorei[i]) { + const value = s._pixelStorei[i] !== undefined ? s._pixelStorei[i] : WebGLState._getDefaultPixelStoreiByIndex(i); + this._gl._pixelStorei(WebGLState._getPixelStoreiByIndex(i), value); + } + } + } + + _migrateTextures(t, s) { + const max = Math.max(t._maxTexture, s._maxTexture); + + let activeTexture = t._activeTexture; + + for (let i = 0; i < max; i++) { + const sTargets = s._textures[i]; + const tTargets = t._textures[i]; + const textureNumb = WebGLState._getTextureByIndex(i); + + const targetMax = Math.max(tTargets ? tTargets.length : 0, sTargets ? sTargets.length : 0); + for (let j = 0, n = targetMax; j < n; j++) { + const target = WebGLState._getTextureTargetByIndex(j); + if (activeTexture !== textureNumb) { + this._gl._activeTexture(textureNumb); + activeTexture = textureNumb; + } + + const texture = (sTargets && sTargets[j]) || null; + this._gl._bindTexture(target, texture); + } + } + + if (s._activeTexture !== activeTexture) { + this._gl._activeTexture(s._activeTexture); + } + } + + _migrateBuffers(t, s) { + s._buffers.forEach((framebuffer, target) => { + if (t._buffers.get(target) !== framebuffer) { + this._gl._bindBuffer(target, framebuffer); + } + }); + + t._buffers.forEach((buffer, target) => { + const b = s._buffers.get(target); + if (b === undefined) { + this._gl._bindBuffer(target, null); + } + }); + return (s._buffers.get(this._gl.ARRAY_BUFFER) !== t._buffers.get(this._gl.ARRAY_BUFFER)) + } + + _migrateFramebuffers(t, s) { + s._framebuffers.forEach((framebuffer, target) => { + if (t._framebuffers.get(target) !== framebuffer) { + this._gl._bindFramebuffer(target, framebuffer); + } + }); + + t._framebuffers.forEach((framebuffer, target) => { + const fb = s._framebuffers.get(target); + if (fb === undefined) { + this._gl._bindFramebuffer(target, null); + } + }); + } + + _migrateRenderbuffers(t, s) { + s._renderbuffers.forEach((renderbuffer, target) => { + if (t._renderbuffers.get(target) !== renderbuffer) { + this._gl._bindRenderbuffer(target, renderbuffer); + } + }); + + t._renderbuffers.forEach((renderbuffer, target) => { + const fb = s._renderbuffers.get(target); + if (fb === undefined) { + this._gl._bindRenderbuffer(target, null); + } + }); + } + + _migrateAttributes(t, s, buffersChanged) { + + if (!buffersChanged) { + t._vertexAttribs.forEach((attrib, index) => { + if (!s._vertexAttribs[index]) { + // We can't 'delete' a vertex attrib so we'll disable it. + this._gl._disableVertexAttribArray(index); + } + }); + + s._vertexAttribs.forEach((attrib, index) => { + this._gl._vertexAttribPointer(index, attrib[0], attrib[1], attrib[2], attrib[4]); + if (attrib[5]) { + this._gl._enableVertexAttribArray(index); + } else { + this._gl._disableVertexAttribArray(index); + } + }); + } else { + // When buffers are changed, previous attributes were reset automatically. + s._vertexAttribs.forEach((attrib, index) => { + if (attrib[0]) { + // Do not set vertex attrib pointer when it was just the default value. + this._gl._vertexAttribPointer(index, attrib[0], attrib[1], attrib[2], attrib[3], attrib[4]); + } + if (attrib[5]) { + this._gl._enableVertexAttribArray(index); + } + }); + } + } + + _migrateSettings(t, s) { + const defaults = this.constructor.getDefaultSettings(); + t._settings.forEach((value, func) => { + const name = func.name || func.xname; + if (!s._settings.has(func)) { + let args = defaults.get(name); + if (Utils.isFunction(args)) { + args = args(this._gl); + } + // We are actually setting the setting for optimization purposes. + s._settings.set(func, args); + func.apply(this._gl, args); + } + }); + s._settings.forEach((value, func) => { + const tValue = t._settings.get(func); + if (!tValue || !Utils.equalValues(tValue, value)) { + func.apply(this._gl, value); + } + }); + } + + _migrateFlags(t, s) { + t._nonDefaultFlags.forEach(setting => { + if (!s._nonDefaultFlags.has(setting)) { + if (this._getDefaultFlag(setting)) { + this._gl._enable(setting); + } else { + this._gl._disable(setting); + } + } + }); + s._nonDefaultFlags.forEach(setting => { + if (!t._nonDefaultFlags.has(setting)) { + if (this._getDefaultFlag(setting)) { + this._gl._disable(setting); + } else { + this._gl._enable(setting); + } + } + }); + } + + static getDefaultSettings() { + if (!this._defaultSettings) { + this._defaultSettings = new Map(); + const d = this._defaultSettings; + const g = WebGLRenderingContext.prototype; + d.set("viewport", function(gl) {return [0,0,gl.canvas.width, gl.canvas.height]}); + d.set("scissor", function(gl) {return [0,0,gl.canvas.width, gl.canvas.height]}); + d.set("blendColor", [0, 0, 0, 0]); + d.set("blendEquation", [g.FUNC_ADD]); + d.set("blendEquationSeparate", [g.FUNC_ADD, g.FUNC_ADD]); + d.set("blendFunc", [g.ONE, g.ZERO]); + d.set("blendFuncSeparate", [g.ONE, g.ZERO, g.ONE, g.ZERO]); + d.set("clearColor", [0, 0, 0, 0]); + d.set("clearDepth", [1]); + d.set("clearStencil", [0]); + d.set("colorMask", [true, true, true, true]); + d.set("cullFace", [g.BACK]); + d.set("depthFunc", [g.LESS]); + d.set("depthMask", [true]); + d.set("depthRange", [0, 1]); + d.set("frontFace", [g.CCW]); + d.set("lineWidth", [1]); + d.set("polygonOffset", [0, 0]); + d.set("sampleCoverage", [1, false]); + d.set("stencilFunc", [g.ALWAYS, 0, 1]); + d.set("_stencilFuncSeparateFront", [g.ALWAYS, 0, 1]); + d.set("_stencilFuncSeparateBack", [g.ALWAYS, 0, 1]); + d.set("_stencilFuncSeparateFrontAndBack", [g.ALWAYS, 0, 1]); + d.set("stencilMask", [1]); + d.set("_stencilMaskSeparateFront", [1]); + d.set("_stencilMaskSeparateBack", [1]); + d.set("_stencilMaskSeparateFrontAndBack", [1]); + d.set("stencilOp", [g.KEEP, g.KEEP, g.KEEP]); + d.set("_stencilOpSeparateFront", [g.KEEP, g.KEEP, g.KEEP]); + d.set("_stencilOpSeparateBack", [g.KEEP, g.KEEP, g.KEEP]); + d.set("_stencilOpSeparateFrontAndBack", [g.KEEP, g.KEEP, g.KEEP]); + d.set("vertexAttrib1f", []); + d.set("vertexAttrib1fv", []); + d.set("vertexAttrib2f", []); + d.set("vertexAttrib2fv", []); + d.set("vertexAttrib3f", []); + d.set("vertexAttrib3fv", []); + d.set("vertexAttrib4f", []); + d.set("vertexAttrib4fv", []); + } + return this._defaultSettings + } + + static _getTextureTargetIndex(target) { + switch(target) { + case 0x0DE1: + /* TEXTURE_2D */ + return 0; + case 0x8513: + /* TEXTURE_CUBE_MAP */ + return 1; + default: + // Shouldn't happen. + throw new Error('Unknown texture target: ' + target); + } + } + + static _getTextureTargetByIndex(index) { + if (!this._textureTargetIndices) { + this._textureTargetIndices = [0x0DE1, 0x8513]; + } + return this._textureTargetIndices[index] + } + + static _getTextureIndex(index) { + return index - 0x84C0 /* GL_TEXTURE0 */; + } + + static _getTextureByIndex(index) { + return index + 0x84C0; + } + + static _getPixelStoreiIndex(pname) { + switch(pname) { + case 0x0D05: + /* PACK_ALIGNMENT */ + return 0; + case 0x0CF5: + /* UNPACK_ALIGNMENT */ + return 1; + case 0x9240: + /* UNPACK_FLIP_Y_WEBGL */ + return 2; + case 0x9241: + /* UNPACK_PREMULTIPLY_ALPHA_WEBGL */ + return 3; + case 0x9243: + /* UNPACK_COLORSPACE_CONVERSION_WEBGL */ + return 4; + //@todo: support WebGL2 properties, see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/pixelStorei + case 0x9245: + /* UNPACK_FLIP_BLUE_RED */ + return 5; + default: + // Shouldn't happen. + throw new Error('Unknown pixelstorei: ' + pname); + } + } + + static _getPixelStoreiByIndex(index) { + if (!this._pixelStoreiIndices) { + this._pixelStoreiIndices = [0x0D05, 0x0CF5, 0x9240, 0x9241, 0x9243]; + } + return this._pixelStoreiIndices[index] + } + + static _getDefaultPixelStoreiByIndex(index) { + if (!this._pixelStoreiDefaults) { + this._pixelStoreiDefaults = [4, 4, false, false, WebGLRenderingContext.prototype.BROWSER_DEFAULT_WEBGL]; + } + return this._pixelStoreiDefaults[index] + } +} + +class WebGLStateManager { + + _initStateManager(id = "default") { + this._states = {}; + this._state = this._getState(id); + } + + _getState(id) { + if (!this._states[id]) { + this._states[id] = new WebGLState(id, this); + } + return this._states[id]; + } + + switchState(id = "default") { + if (this._state._id !== id) { + const newState = this._getState(id); + this._state.migrate(newState); + this._state = newState; + } + } + + $useProgram(program) { + if (this._state.setProgram(program)) + this._useProgram(program); + } + + $bindBuffer(target, fb) { + if (this._state.setBuffer(target, fb)) + this._bindBuffer(target, fb); + } + + $bindFramebuffer(target, fb) { + if (this._state.setFramebuffer(target, fb)) + this._bindFramebuffer(target, fb); + } + + $bindRenderbuffer(target, fb) { + if (this._state.setRenderbuffer(target, fb)) + this._bindRenderbuffer(target, fb); + } + + $enable(cap) { + if (this._state.setFlag(cap, true)) + this._enable(cap); + } + + $disable(cap) { + if (this._state.setFlag(cap, false)) + this._disable(cap); + } + + $viewport(x, y, w, h) { + if (this._state.setSetting(this._viewport, [x, y, w, h])) + this._viewport(x, y, w, h); + } + + $scissor(x, y, w, h) { + if (this._state.setSetting(this._scissor, [x, y, w, h])) + this._scissor(x, y, w, h); + } + + $disableVertexAttribArray(index) { + if (this._state.disableVertexAttribArray(index)) + this._disableVertexAttribArray(index); + } + + $enableVertexAttribArray(index) { + if (this._state.enableVertexAttribArray(index)) + this._enableVertexAttribArray(index); + } + + $vertexAttribPointer(index, size, type, normalized, stride, offset) { + if (this._state.vertexAttribPointer(index, [size, type, normalized, stride, offset])) + this._vertexAttribPointer(index, size, type, normalized, stride, offset); + } + + $activeTexture(texture) { + if (this._state.setActiveTexture(texture)) + this._activeTexture(texture); + } + + $bindTexture(target, texture) { + if (this._state.bindTexture(target, texture)) + this._bindTexture(target, texture); + } + + $pixelStorei(pname, param) { + if (this._state.setPixelStorei(pname, param)) { + this._pixelStorei(pname, param); + } + } + + $stencilFuncSeparate(face, func, ref, mask) { + let f; + switch(face) { + case this.FRONT: + f = this._stencilFuncSeparateFront; + break; + case this.BACK: + f = this._stencilFuncSeparateBack; + break; + case this.FRONT_AND_BACK: + f = this._stencilFuncSeparateFrontAndBack; + break; + } + + if (this._state.setSetting(f, [func, ref, mask])) + f.apply(this, [func, ref, mask]); + } + + _stencilFuncSeparateFront(func, ref, mask) { + this._stencilFuncSeparate(this.FRONT, func, ref, mask); + } + + _stencilFuncSeparateBack(func, ref, mask) { + this._stencilFuncSeparate(this.BACK, func, ref, mask); + } + + _stencilFuncSeparateFrontAndBack(func, ref, mask) { + this._stencilFuncSeparate(this.FRONT_AND_BACK, func, ref, mask); + } + + $stencilMaskSeparate(face, mask) { + let f; + switch(face) { + case this.FRONT: + f = this._stencilMaskSeparateFront; + break; + case this.BACK: + f = this._stencilMaskSeparateBack; + break; + case this.FRONT_AND_BACK: + f = this._stencilMaskSeparateFrontAndBack; + break; + } + + if (this._state.setSetting(f, [mask])) + f.apply(this, [mask]); + } + + _stencilMaskSeparateFront(mask) { + this._stencilMaskSeparate(this.FRONT, mask); + } + + _stencilMaskSeparateBack(mask) { + this._stencilMaskSeparate(this.BACK, mask); + } + + _stencilMaskSeparateFrontAndBack(mask) { + this._stencilMaskSeparate(this.FRONT_AND_BACK, mask); + } + + $stencilOpSeparate(face, fail, zfail, zpass) { + let f; + switch(face) { + case this.FRONT: + f = this._stencilOpSeparateFront; + break; + case this.BACK: + f = this._stencilOpSeparateBack; + break; + case this.FRONT_AND_BACK: + f = this._stencilOpSeparateFrontAndBack; + break; + } + + if (this._state.setSetting(f, [fail, zfail, zpass])) + f.apply(this, [fail, zfail, zpass]); + } + + _stencilOpSeparateFront(fail, zfail, zpass) { + this._stencilOpSeparate(this.FRONT, fail, zfail, zpass); + } + + _stencilOpSeparateBack(fail, zfail, zpass) { + this._stencilOpSeparate(this.BACK, fail, zfail, zpass); + } + + _stencilOpSeparateFrontAndBack(fail, zfail, zpass) { + this._stencilOpSeparate(this.FRONT_AND_BACK, fail, zfail, zpass); + } + + $blendColor(red, green, blue, alpha) { + if (this._state.setSetting(this._blendColor, [red, green, blue, alpha])) + this._blendColor(red, green, blue, alpha); + } + + $blendEquation(mode) { + if (this._state.setSetting(this._blendEquation, [mode])) + this._blendEquation(mode); + } + + $blendEquationSeparate(modeRGB, modeAlpha) { + if (this._state.setSetting(this._blendEquationSeparate, [modeRGB, modeAlpha])) + this._blendEquationSeparate(modeRGB, modeAlpha); + } + + $blendFunc(sfactor, dfactor) { + if (this._state.setSetting(this._blendFunc, [sfactor, dfactor])) + this._blendFunc(sfactor, dfactor); + } + + $blendFuncSeparate(srcRGB, dstRGB, srcAlpha, dstAlpha) { + if (this._state.setSetting(this._blendFuncSeparate, [srcRGB, dstRGB, srcAlpha, dstAlpha])) + this._blendFuncSeparate(srcRGB, dstRGB, srcAlpha, dstAlpha); + } + + $clearColor(red, green, blue, alpha) { + if (this._state.setSetting(this._clearColor, [red, green, blue, alpha])) + this._clearColor(red, green, blue, alpha); + } + + $clearDepth(depth) { + if (this._state.setSetting(this._clearDepth, [depth])) + this._clearDepth(depth); + } + + $clearStencil(s) { + if (this._state.setSetting(this._clearStencil, [s])) + this._clearStencil(s); + } + + $colorMask(red, green, blue, alpha) { + if (this._state.setSetting(this._colorMask, [red, green, blue, alpha])) + this._colorMask(red, green, blue, alpha); + } + + $cullFace(mode) { + if (this._state.setSetting(this._cullFace, [mode])) + this._cullFace(mode); + } + + $depthFunc(func) { + if (this._state.setSetting(this._depthFunc, [func])) + this._depthFunc(func); + } + + $depthMask(flag) { + if (this._state.setSetting(this._depthMask, [flag])) + this._depthMask(flag); + } + + $depthRange(zNear, zFar) { + if (this._state.setSetting(this._depthRange, [zNear, zFar])) + this._depthRange(zNear, zFar); + } + + $frontFace(mode) { + if (this._state.setSetting(this._frontFace, [mode])) + this._frontFace(mode); + } + + $lineWidth(width) { + if (this._state.setSetting(this._lineWidth, [width])) + this._lineWidth(width); + } + + $polygonOffset(factor, units) { + if (this._state.setSetting(this._polygonOffset, [factor, units])) + this._polygonOffset(factor, units); + } + + $sampleCoverage(value, invert) { + if (this._state.setSetting(this._sampleCoverage, [value, invert])) + this._sampleCoverage(value, invert); + } + + $stencilFunc(func, ref, mask) { + if (this._state.setSetting(this._stencilFunc, [func, ref, mask])) + this._stencilFunc(func, ref, mask); + } + + $stencilMask(mask) { + if (this._state.setSetting(this._stencilMask, [mask])) + this._stencilMask(mask); + } + + $stencilOp(fail, zfail, zpass) { + if (this._state.setSetting(this._stencilOp, [fail, zfail, zpass])) + this._stencilOp(fail, zfail, zpass); + } + + $vertexAttrib1f(indx, x) { + if (this._state.setSetting(this._vertexAttrib1f, [indx, x])) + this._vertexAttrib1f(indx, x); + } + + $vertexAttrib1fv(indx, values) { + if (this._state.setSetting(this._vertexAttrib1fv, [indx, values])) + this._vertexAttrib1fv(indx, values); + } + + $vertexAttrib2f(indx, x, y) { + if (this._state.setSetting(this._vertexAttrib2f, [indx, x, y])) + this._vertexAttrib2f(indx, x, y); + } + + $vertexAttrib2fv(indx, values) { + if (this._state.setSetting(this._vertexAttrib2fv, [indx, values])) + this._vertexAttrib2fv(indx, values); + } + + $vertexAttrib3f(indx, x, y, z) { + if (this._state.setSetting(this._vertexAttrib3f, [indx, x, y, z])) + this._vertexAttrib3f(indx, x, y, z); + } + + $vertexAttrib3fv(indx, values) { + if (this._state.setSetting(this._vertexAttrib3fv, [indx, values])) + this._vertexAttrib3fv(indx, values); + } + + $vertexAttrib4f(indx, x, y, z, w) { + if (this._state.setSetting(this._vertexAttrib4f, [indx, x, y, z, w])) + this._vertexAttrib4f(indx, x, y, z, w); + } + + $vertexAttrib4fv(indx, values) { + if (this._state.setSetting(this._vertexAttrib4fv, [indx, values])) + this._vertexAttrib4fv(indx, values); + } + + /** + * Sets up the rendering context for context sharing. + * @param {WebGLRenderingContext} gl + * @param {string} id + */ + static enable(gl, id = "default") { + const names = Object.getOwnPropertyNames(WebGLStateManager.prototype); + const WebGLRenderingContextProto = gl.__proto__; + names.forEach(name => { + if (name !== "constructor") { + const method = WebGLStateManager.prototype[name]; + if (name.charAt(0) === "$") { + name = name.substr(1); + } + if (gl[name] !== method) { + if (gl[name]) { + if (!gl[name].name) { + // We do this for compatibility with the Chrome WebGL Inspector plugin. + gl[name].xname = name; + } + gl['_' + name] = gl[name]; + } + gl[name] = method; + } + } + }); + + WebGLStateManager.prototype._initStateManager.call(gl, id); + + return gl; + } + +} + +/* harmony default export */ __webpack_exports__["default"] = (WebGLStateManager); + + +/***/ }), + +/***/ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/tree/Base.mjs": +/*!*********************************************************************************************!*\ + !*** ./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/tree/Base.mjs ***! + \*********************************************************************************************/ +/*! exports provided: default */ +/***/ (function(__webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return Base; }); +/* harmony import */ var _Utils_mjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./Utils.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/tree/Utils.mjs"); +/* + * If not stated otherwise in this file or this component's LICENSE file the + * following copyright and licenses apply: + * + * Copyright 2020 Metrological + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +class Base { + + static defaultSetter(obj, name, value) { + obj[name] = value; + } + + static patchObject(obj, settings) { + if (!_Utils_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].isObjectLiteral(settings)) { + console.error("[Lightning] Settings must be object literal"); + } else { + let names = Object.keys(settings); + for (let i = 0, n = names.length; i < n; i++) { + let name = names[i]; + + this.patchObjectProperty(obj, name, settings[name]); + } + } + } + + static patchObjectProperty(obj, name, value) { + let setter = obj.setSetting || Base.defaultSetter; + + if (name.charAt(0) === "_") { + // Disallow patching private variables. + if (name !== "__create") { + console.error("[Lightning] Patch of private property '" + name + "' is not allowed"); + } + } else if (name !== "type") { + // Type is a reserved keyword to specify the class type on creation. + if (_Utils_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].isFunction(value) && value.__local) { + // Local function (Base.local(s => s.something)) + value = value.__local(obj); + } + + setter(obj, name, value); + } + } + + static local(func) { + // This function can be used as an object setting, which is called with the target object. + func.__local = true; + } + + +} + + + + + +/***/ }), + +/***/ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/tree/Element.mjs": +/*!************************************************************************************************!*\ + !*** ./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/tree/Element.mjs ***! + \************************************************************************************************/ +/*! exports provided: default */ +/***/ (function(__webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return Element; }); +/* harmony import */ var _StageUtils_mjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./StageUtils.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/tree/StageUtils.mjs"); +/* harmony import */ var _core_ElementCore_mjs__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./core/ElementCore.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/tree/core/ElementCore.mjs"); +/* harmony import */ var _Base_mjs__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./Base.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/tree/Base.mjs"); +/* harmony import */ var _Utils_mjs__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./Utils.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/tree/Utils.mjs"); +/* harmony import */ var _EventEmitter_mjs__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../EventEmitter.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/EventEmitter.mjs"); +/* harmony import */ var _Shader_mjs__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./Shader.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/tree/Shader.mjs"); +/* harmony import */ var _Texture_mjs__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./Texture.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/tree/Texture.mjs"); +/* harmony import */ var _textures_ImageTexture_mjs__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../textures/ImageTexture.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/textures/ImageTexture.mjs"); +/* harmony import */ var _textures_TextTexture_mjs__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../textures/TextTexture.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/textures/TextTexture.mjs"); +/* harmony import */ var _textures_SourceTexture_mjs__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ../textures/SourceTexture.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/textures/SourceTexture.mjs"); +/* harmony import */ var _animation_Transition_mjs__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ../animation/Transition.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/animation/Transition.mjs"); +/* harmony import */ var _ElementChildList_mjs__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ./ElementChildList.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/tree/ElementChildList.mjs"); +/* + * If not stated otherwise in this file or this component's LICENSE file the + * following copyright and licenses apply: + * + * Copyright 2020 Metrological + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * Render tree node. + */ + + + + + + + + + +class Element { + + constructor(stage) { + this.stage = stage; + + this.__id = Element.id++; + + this.__start(); + + // EventEmitter constructor. + this._hasEventListeners = false; + + this.__core = new _core_ElementCore_mjs__WEBPACK_IMPORTED_MODULE_1__["default"](this); + + /** + * A reference that can be used while merging trees. + * @type {string} + */ + this.__ref = null; + + /** + * An element is attached if it is a descendant of the stage root. + * @type {boolean} + */ + this.__attached = false; + + /** + * An element is enabled when it is attached and it is visible (worldAlpha > 0). + * @type {boolean} + */ + this.__enabled = false; + + /** + * An element is active when it is enabled and it is within bounds. + * @type {boolean} + */ + this.__active = false; + + /** + * @type {Element} + */ + this.__parent = null; + + /** + * The texture that is currently set. + * @type {Texture} + */ + this.__texture = null; + + /** + * The currently displayed texture. While this.texture is loading, this one may be different. + * @type {Texture} + */ + this.__displayedTexture = null; + + /** + * Tags that can be used to identify/search for a specific element. + * @type {String[]} + */ + this.__tags = null; + + /** + * The tree's tags mapping. + * This contains all elements for all known tags, at all times. + * @type {Map} + */ + this.__treeTags = null; + + /** + * Creates a tag context: tagged elements in this branch will not be reachable from ancestors of this elements. + * @type {boolean} + */ + this.__tagRoot = false; + + /** + * (Lazy-initialised) list of children owned by this elements. + * @type {ElementChildList} + */ + this.__childList = null; + + this._w = 0; + + this._h = 0; + } + + __start() { + } + + get id() { + return this.__id; + } + + set ref(ref) { + if (this.__ref !== ref) { + const charcode = ref.charCodeAt(0); + if (!_Utils_mjs__WEBPACK_IMPORTED_MODULE_3__["default"].isUcChar(charcode)) { + this._throwError("Ref must start with an upper case character: " + ref); + } + if (this.__ref !== null) { + this.removeTag(this.__ref); + if (this.__parent) { + this.__parent.__childList.clearRef(this.__ref); + } + } + + this.__ref = ref; + + if (this.__ref) { + this._addTag(this.__ref); + if (this.__parent) { + this.__parent.__childList.setRef(this.__ref, this); + } + } + } + } + + get ref() { + return this.__ref; + } + + get core() { + return this.__core; + } + + setAsRoot() { + this.__core.setAsRoot(); + this._updateAttachedFlag(); + this._updateEnabledFlag(); + } + + get isRoot() { + return this.__core.isRoot; + } + + _setParent(parent) { + if (this.__parent === parent) return; + + if (this.__parent) { + this._unsetTagsParent(); + } + + this.__parent = parent; + + if (parent) { + this._setTagsParent(); + } + + this._updateAttachedFlag(); + this._updateEnabledFlag(); + this._updateCollision(); + + if (this.isRoot && parent) { + this._throwError("Root should not be added as a child! Results are unspecified!"); + } + }; + + getDepth() { + let depth = 0; + + let p = this.__parent; + while(p) { + depth++; + p = p.__parent; + } + + return depth; + }; + + getAncestor(l) { + let p = this; + while (l > 0 && p.__parent) { + p = p.__parent; + l--; + } + return p; + }; + + getAncestors() { + const a = []; + let p = this; + while (p) { + a.push(p); + p = p.__parent; + } + return a; + } + + getAncestorAtDepth(depth) { + let levels = this.getDepth() - depth; + if (levels < 0) { + return null; + } + return this.getAncestor(levels); + }; + + isAncestorOf(c) { + let p = c; + while(p = p.parent) { + if (this === p) { + return true; + } + } + return false; + }; + + getSharedAncestor(c) { + let o1 = this; + let o2 = c; + let l1 = o1.getDepth(); + let l2 = o2.getDepth(); + if (l1 > l2) { + o1 = o1.getAncestor(l1 - l2); + } else if (l2 > l1) { + o2 = o2.getAncestor(l2 - l1); + } + + do { + if (o1 === o2) { + return o1; + } + + o1 = o1.__parent; + o2 = o2.__parent; + } while (o1 && o2); + + return null; + }; + + get attached() { + return this.__attached; + } + + get enabled() { + return this.__enabled; + } + + get active() { + return this.__active; + } + + _isAttached() { + return (this.__parent ? this.__parent.__attached : (this.stage.root === this)); + }; + + _isEnabled() { + return this.__core.visible && (this.__core.alpha > 0) && (this.__parent ? this.__parent.__enabled : (this.stage.root === this)); + }; + + _isActive() { + return this._isEnabled() && this.withinBoundsMargin; + }; + + /** + * Updates the 'attached' flag for this branch. + */ + _updateAttachedFlag() { + let newAttached = this._isAttached(); + if (this.__attached !== newAttached) { + this.__attached = newAttached; + + if (newAttached) { + this._onSetup(); + } + + let children = this._children.get(); + if (children) { + let m = children.length; + if (m > 0) { + for (let i = 0; i < m; i++) { + children[i]._updateAttachedFlag(); + } + } + } + + if (newAttached) { + this._onAttach(); + } else { + this._onDetach(); + } + } + }; + + /** + * Updates the 'enabled' flag for this branch. + */ + _updateEnabledFlag() { + let newEnabled = this._isEnabled(); + if (this.__enabled !== newEnabled) { + if (newEnabled) { + this._onEnabled(); + this._setEnabledFlag(); + } else { + this._onDisabled(); + this._unsetEnabledFlag(); + } + + let children = this._children.get(); + if (children) { + let m = children.length; + if (m > 0) { + for (let i = 0; i < m; i++) { + children[i]._updateEnabledFlag(); + } + } + } + } + }; + + _setEnabledFlag() { + this.__enabled = true; + + // Force re-check of texture because dimensions might have changed (cutting). + this._updateDimensions(); + this._updateTextureCoords(); + + if (this.__texture) { + this.__texture.addElement(this); + } + + if (this.withinBoundsMargin) { + this._setActiveFlag(); + } + + if (this.__core.shader) { + this.__core.shader.addElement(this.__core); + } + + } + + _unsetEnabledFlag() { + if (this.__active) { + this._unsetActiveFlag(); + } + + if (this.__texture) { + this.__texture.removeElement(this); + } + + if (this.__core.shader) { + this.__core.shader.removeElement(this.__core); + } + + if (this._texturizer) { + this.texturizer.filters.forEach(filter => filter.removeElement(this.__core)); + } + + this.__enabled = false; + } + + _setActiveFlag() { + this.__active = true; + + // This must happen before enabling the texture, because it may already be loaded or load directly. + if (this.__texture) { + this.__texture.incActiveCount(); + } + + if (this.__texture) { + this._enableTexture(); + } + this._onActive(); + } + + _unsetActiveFlag() { + if (this.__texture) { + this.__texture.decActiveCount(); + } + + this.__active = false; + if (this.__texture) { + this._disableTexture(); + } + + if (this._hasTexturizer()) { + this.texturizer.deactivate(); + } + + this._onInactive(); + } + + _onSetup() { + } + + _onAttach() { + } + + _onDetach() { + } + + _onEnabled() { + } + + _onDisabled() { + } + + _onActive() { + } + + _onInactive() { + } + + _onResize() { + } + + _getRenderWidth() { + if (this._w) { + return this._w; + } else if (this.__displayedTexture) { + return this.__displayedTexture.getRenderWidth(); + } else if (this.__texture) { + // Texture already loaded, but not yet updated (probably because this element is not active). + return this.__texture.getRenderWidth(); + } else { + return 0; + } + }; + + _getRenderHeight() { + if (this._h) { + return this._h; + } else if (this.__displayedTexture) { + return this.__displayedTexture.getRenderHeight(); + } else if (this.__texture) { + // Texture already loaded, but not yet updated (probably because this element is not active). + return this.__texture.getRenderHeight(); + } else { + return 0; + } + }; + + get renderWidth() { + if (this.__enabled) { + // Render width is only maintained if this element is enabled. + return this.__core.getRenderWidth(); + } else { + return this._getRenderWidth(); + } + } + + get renderHeight() { + if (this.__enabled) { + return this.__core.getRenderHeight(); + } else { + return this._getRenderHeight(); + } + } + + get finalX() { + return this.__core.x; + } + + get finalY() { + return this.__core.y; + } + + get finalW() { + return this.__core.w; + } + + get finalH() { + return this.__core.h; + } + + textureIsLoaded() { + return this.__texture && this.__texture.isLoaded(); + } + + loadTexture() { + if (this.__texture) { + this.__texture.load(); + + if (!this.__texture.isUsed() || !this._isEnabled()) { + // Loading the texture will have no effect on the dimensions of this element. + // Manually update them, so that calcs can be performed immediately in userland. + this._updateDimensions(); + } + } + } + + _enableTextureError() { + // txError event should automatically be re-triggered when a element becomes active. + const loadError = this.__texture.loadError; + if (loadError) { + this.emit('txError', loadError, this.__texture._source); + } + } + + _enableTexture() { + if (this.__texture.isLoaded()) { + this._setDisplayedTexture(this.__texture); + } else { + // We don't want to retain the old 'ghost' image as it wasn't visible anyway. + this._setDisplayedTexture(null); + + this._enableTextureError(); + } + } + + _disableTexture() { + // We disable the displayed texture because, when the texture changes while invisible, we should use that w, h, + // mw, mh for checking within bounds. + this._setDisplayedTexture(null); + } + + get texture() { + return this.__texture; + } + + set texture(v) { + let texture; + if (_Utils_mjs__WEBPACK_IMPORTED_MODULE_3__["default"].isObjectLiteral(v)) { + if (v.type) { + texture = new v.type(this.stage); + } else { + texture = this.texture; + } + + if (texture) { + _Base_mjs__WEBPACK_IMPORTED_MODULE_2__["default"].patchObject(texture, v); + } + } else if (!v) { + texture = null; + } else { + if (v.isTexture) { + texture = v; + } else if (v.isTextureSource) { + texture = new _textures_SourceTexture_mjs__WEBPACK_IMPORTED_MODULE_9__["default"](this.stage); + texture.textureSource = v; + } else { + console.error("[Lightning] Please specify a texture type."); + return; + } + } + + const prevTexture = this.__texture; + if (texture !== prevTexture) { + this.__texture = texture; + + if (this.__texture) { + if (this.__enabled) { + this.__texture.addElement(this); + + if (this.withinBoundsMargin) { + if (this.__texture.isLoaded()) { + this._setDisplayedTexture(this.__texture); + } else { + this._enableTextureError(); + } + } + } + } else { + // Make sure that current texture is cleared when the texture is explicitly set to null. + this._setDisplayedTexture(null); + } + + if (prevTexture && prevTexture !== this.__displayedTexture) { + prevTexture.removeElement(this); + } + + this._updateDimensions(); + } + } + + get displayedTexture() { + return this.__displayedTexture; + } + + _setDisplayedTexture(v) { + let prevTexture = this.__displayedTexture; + + if (prevTexture && (v !== prevTexture)) { + if (this.__texture !== prevTexture) { + // The old displayed texture is deprecated. + prevTexture.removeElement(this); + } + } + + const prevSource = this.__core.displayedTextureSource; + const sourceChanged = (v ? v._source : null) !== prevSource; + + this.__displayedTexture = v; + this._updateDimensions(); + + if (this.__displayedTexture) { + if (sourceChanged) { + // We don't need to reference the displayed texture because it was already referenced (this.texture === this.displayedTexture). + this._updateTextureCoords(); + this.__core.setDisplayedTextureSource(this.__displayedTexture._source); + } + } else { + this.__core.setDisplayedTextureSource(null); + } + + if (sourceChanged) { + if (this.__displayedTexture) { + this.stage.removeUpdateSourceTexture(this.__displayedTexture) + this.emit('txLoaded', this.__displayedTexture); + } else { + this.emit('txUnloaded', this.__displayedTexture); + } + } + } + + onTextureSourceLoaded() { + // This function is called when element is enabled, but we only want to set displayed texture for active elements. + if (this.active) { + // We may be dealing with a texture reloading, so we must force update. + this._setDisplayedTexture(this.__texture); + } + }; + + onTextureSourceLoadError(e) { + this.emit('txError', e, this.__texture._source); + }; + + forceRenderUpdate() { + this.__core.setHasRenderUpdates(3); + } + + onDisplayedTextureClippingChanged() { + this._updateDimensions(); + this._updateTextureCoords(); + }; + + onPrecisionChanged() { + this._updateDimensions(); + }; + + onDimensionsChanged(w, h) { + if (this.texture instanceof _textures_TextTexture_mjs__WEBPACK_IMPORTED_MODULE_8__["default"]) { + this.texture.w = w; + this.texture.h = h; + this.w = w; + this.h = h; + } + } + + _updateDimensions() { + let w = this._getRenderWidth(); + let h = this._getRenderHeight(); + + let unknownSize = false; + if (!w || !h) { + if (!this.__displayedTexture && this.__texture) { + // We use a 'max width' replacement instead in the ElementCore calcs. + // This makes sure that it is able to determine withinBounds. + w = w || this.__texture.mw; + h = h || this.__texture.mh; + + if ((!w || !h) && this.__texture.isAutosizeTexture()) { + unknownSize = true; + } + } + } + + if (this.__core.setDimensions(w, h, unknownSize)) { + this._onResize(); + } + } + + _updateTextureCoords() { + if (this.displayedTexture && this.displayedTexture._source) { + let displayedTexture = this.displayedTexture; + let displayedTextureSource = this.displayedTexture._source; + + let tx1 = 0, ty1 = 0, tx2 = 1.0, ty2 = 1.0; + if (displayedTexture.clipping) { + // Apply texture clipping. + let w = displayedTextureSource.getRenderWidth(); + let h = displayedTextureSource.getRenderHeight(); + let iw, ih, rw, rh; + iw = 1 / w; + ih = 1 / h; + + if (displayedTexture.pw) { + rw = (displayedTexture.pw) * iw; + } else { + rw = (w - displayedTexture.px) * iw; + } + + if (displayedTexture.ph) { + rh = displayedTexture.ph * ih; + } else { + rh = (h - displayedTexture.py) * ih; + } + + iw *= (displayedTexture.px); + ih *= (displayedTexture.py); + + tx1 = iw; + ty1 = ih; + tx2 = tx2 * rw + iw; + ty2 = ty2 * rh + ih; + + tx1 = Math.max(0, tx1); + ty1 = Math.max(0, ty1); + tx2 = Math.min(1, tx2); + ty2 = Math.min(1, ty2); + } + + if (displayedTextureSource._flipTextureY) { + let tempty = ty2; + ty2 = ty1; + ty1 = tempty; + } + this.__core.setTextureCoords(tx1, ty1, tx2, ty2); + } + } + + getCornerPoints() { + return this.__core.getCornerPoints(); + } + + _unsetTagsParent() { + if (this.__tags) { + this.__tags.forEach((tag) => { + // Remove from treeTags. + let p = this; + while (p = p.__parent) { + let parentTreeTags = p.__treeTags.get(tag); + parentTreeTags.delete(this); + + if (p.__tagRoot) { + break; + } + } + }); + } + + let tags = null; + let n = 0; + if (this.__treeTags) { + if (!this.__tagRoot) { + tags = _Utils_mjs__WEBPACK_IMPORTED_MODULE_3__["default"].iteratorToArray(this.__treeTags.keys()); + n = tags.length; + + if (n > 0) { + for (let i = 0; i < n; i++) { + let tagSet = this.__treeTags.get(tags[i]); + + // Remove from treeTags. + let p = this; + while ((p = p.__parent)) { + let parentTreeTags = p.__treeTags.get(tags[i]); + + tagSet.forEach(function (comp) { + parentTreeTags.delete(comp); + }); + + if (p.__tagRoot) { + break; + } + } + } + } + } + } + }; + + _setTagsParent() { + // Just copy over the 'local' tags. + if (this.__tags) { + this.__tags.forEach((tag) => { + let p = this; + while (p = p.__parent) { + if (!p.__treeTags) { + p.__treeTags = new Map(); + } + + let s = p.__treeTags.get(tag); + if (!s) { + s = new Set(); + p.__treeTags.set(tag, s); + } + + s.add(this); + + if (p.__tagRoot) { + break; + } + } + }); + } + + if (this.__treeTags && this.__treeTags.size) { + if (!this.__tagRoot) { + this.__treeTags.forEach((tagSet, tag) => { + let p = this; + while (!p.__tagRoot && (p = p.__parent)) { + if (p.__tagRoot) { + // Do not copy all subs. + } + if (!p.__treeTags) { + p.__treeTags = new Map(); + } + + let s = p.__treeTags.get(tag); + if (!s) { + s = new Set(); + p.__treeTags.set(tag, s); + } + + tagSet.forEach(function (comp) { + s.add(comp); + }); + } + }); + } + } + }; + + + _getByTag(tag) { + if (!this.__treeTags) { + return []; + } + let t = this.__treeTags.get(tag); + return t ? _Utils_mjs__WEBPACK_IMPORTED_MODULE_3__["default"].setToArray(t) : []; + }; + + getTags() { + return this.__tags ? this.__tags : []; + }; + + setTags(tags) { + tags = tags.reduce((acc, tag) => { + return acc.concat(tag.split(' ')); + }, []); + + if (this.__ref) { + tags.push(this.__ref); + } + + let i, n = tags.length; + let removes = []; + let adds = []; + for (i = 0; i < n; i++) { + if (!this.hasTag(tags[i])) { + adds.push(tags[i]); + } + } + + let currentTags = this.tags || []; + n = currentTags.length; + for (i = 0; i < n; i++) { + if (tags.indexOf(currentTags[i]) == -1) { + removes.push(currentTags[i]); + } + } + + for (i = 0; i < removes.length; i++) { + this.removeTag(removes[i]); + } + + for (i = 0; i < adds.length; i++) { + this.addTag(adds[i]); + } + } + + addTag(tag) { + if (tag.indexOf(' ') === -1) { + if (_Utils_mjs__WEBPACK_IMPORTED_MODULE_3__["default"].isUcChar(tag.charCodeAt(0))) { + this._throwError("Tag may not start with an upper case character."); + } + + this._addTag(tag); + } else { + const tags = tag.split(' '); + for (let i = 0, m = tags.length; i < m; i++) { + const tag = tags[i]; + + if (_Utils_mjs__WEBPACK_IMPORTED_MODULE_3__["default"].isUcChar(tag.charCodeAt(0))) { + this._throwError("Tag may not start with an upper case character."); + } + + this._addTag(tag); + } + } + } + + _addTag(tag) { + if (!this.__tags) { + this.__tags = []; + } + if (this.__tags.indexOf(tag) === -1) { + this.__tags.push(tag); + + // Add to treeTags hierarchy. + let p = this.__parent; + if (p) { + do { + if (!p.__treeTags) { + p.__treeTags = new Map(); + } + + let s = p.__treeTags.get(tag); + if (!s) { + s = new Set(); + p.__treeTags.set(tag, s); + } + + s.add(this); + + } while (!p.__tagRoot && (p = p.__parent)); + } + } + } + + removeTag(tag) { + let i = this.__tags.indexOf(tag); + if (i !== -1) { + this.__tags.splice(i, 1); + + // Remove from treeTags hierarchy. + let p = this.__parent; + if (p) { + do { + let list = p.__treeTags.get(tag); + if (list) { + list.delete(this); + } + } while (!p.__tagRoot && (p = p.__parent)); + } + } + } + + hasTag(tag) { + return (this.__tags && (this.__tags.indexOf(tag) !== -1)); + } + + /** + * Returns one of the elements from the subtree that have this tag. + * @param {string} tag + * @returns {Element} + */ + _tag(tag) { + if (tag.indexOf(".") !== -1) { + return this.mtag(tag)[0]; + } else { + if (this.__treeTags) { + let t = this.__treeTags.get(tag); + if (t) { + const item = t.values().next(); + return item ? item.value : undefined; + } + } + } + }; + + get tag() { + return this._tag; + } + + set tag(t) { + this.tags = t; + } + + /** + * Returns all elements from the subtree that have this tag. + * @param {string} tag + * @returns {Element[]} + */ + mtag(tag) { + let idx = tag.indexOf("."); + if (idx >= 0) { + let parts = tag.split('.'); + let res = this._getByTag(parts[0]); + let level = 1; + let c = parts.length; + while (res.length && level < c) { + let resn = []; + for (let j = 0, n = res.length; j < n; j++) { + resn = resn.concat(res[j]._getByTag(parts[level])); + } + + res = resn; + level++; + } + return res; + } else { + return this._getByTag(tag); + } + }; + + stag(tag, settings) { + let t = this.mtag(tag); + let n = t.length; + for (let i = 0; i < n; i++) { + _Base_mjs__WEBPACK_IMPORTED_MODULE_2__["default"].patchObject(t[i], settings); + } + } + + get tagRoot() { + return this.__tagRoot; + } + + set tagRoot(v) { + if (this.__tagRoot !== v) { + if (!v) { + this._setTagsParent(); + } else { + this._unsetTagsParent(); + } + + this.__tagRoot = v; + } + } + + sel(path) { + const results = this.select(path); + if (results.length) { + return results[0]; + } else { + return undefined; + } + } + + select(path) { + if (path.indexOf(",") !== -1) { + let selectors = path.split(','); + let res = []; + for (let i = 0; i < selectors.length; i++) { + res = res.concat(this._select(selectors[i])); + } + return res; + } else { + return this._select(path); + } + } + + _select(path) { + if (path === "") return [this]; + + + let pointIdx = path.indexOf("."); + let arrowIdx = path.indexOf(">"); + if (pointIdx === -1 && arrowIdx === -1) { + // Quick case. + return this.mtag(path); + } + + // Detect by first char. + let isRef; + if (arrowIdx === 0) { + isRef = true; + path = path.substr(1); + } else if (pointIdx === 0) { + isRef = false; + path = path.substr(1); + } else { + isRef = false; + } + + return this._selectChilds(path, isRef); + } + + _selectChilds(path, isRef) { + const pointIdx = path.indexOf("."); + const arrowIdx = path.indexOf(">"); + + if (pointIdx === -1 && arrowIdx === -1) { + if (isRef) { + const ref = this.getByRef(path); + return ref ? [ref] : []; + } else { + return this.mtag(path); + } + } + + if ((arrowIdx === -1) || (pointIdx !== -1 && pointIdx < arrowIdx)) { + let next; + const str = path.substr(0, pointIdx); + if (isRef) { + const ref = this.getByRef(str); + next = ref ? [ref] : []; + } else { + next = this.mtag(str); + } + let total = []; + const subPath = path.substr(pointIdx + 1); + for (let i = 0, n = next.length; i < n; i++) { + total = total.concat(next[i]._selectChilds(subPath, false)); + } + return total; + } else { + let next; + const str = path.substr(0, arrowIdx); + if (isRef) { + const ref = this.getByRef(str); + next = ref ? [ref] : []; + } else { + next = this.mtag(str); + } + let total = []; + const subPath = path.substr(arrowIdx + 1); + for (let i = 0, n = next.length; i < n; i++) { + total = total.concat(next[i]._selectChilds(subPath, true)); + } + return total; + } + } + + getByRef(ref) { + return this.childList.getByRef(ref); + } + + getLocationString() { + let i; + i = this.__parent ? this.__parent._children.getIndex(this) : "R"; + let localTags = this.getTags(); + let str = this.__parent ? this.__parent.getLocationString(): ""; + if (this.ref) { + str += ":[" + i + "]" + this.ref; + } else if (localTags.length) { + str += ":[" + i + "]" + localTags.join(","); + } else { + str += ":[" + i + "]#" + this.id; + } + return str; + } + + toString() { + let obj = this.getSettings(); + return Element.getPrettyString(obj, ""); + }; + + static getPrettyString(obj, indent) { + let children = obj.children; + delete obj.children; + + + // Convert singular json settings object. + let colorKeys = ["color", "colorUl", "colorUr", "colorBl", "colorBr"]; + let str = JSON.stringify(obj, function (k, v) { + if (colorKeys.indexOf(k) !== -1) { + return "COLOR[" + v.toString(16) + "]"; + } + return v; + }); + str = str.replace(/"COLOR\[([a-f0-9]{1,8})\]"/g, "0x$1"); + + if (children) { + let childStr = ""; + if (_Utils_mjs__WEBPACK_IMPORTED_MODULE_3__["default"].isObjectLiteral(children)) { + let refs = Object.keys(children); + childStr = ""; + for (let i = 0, n = refs.length; i < n; i++) { + childStr += `\n${indent} "${refs[i]}":` + delete children[refs[i]].ref; + childStr += Element.getPrettyString(children[refs[i]], indent + " ") + (i < n - 1 ? "," : ""); + } + let isEmpty = (str === "{}"); + str = str.substr(0, str.length - 1) + (isEmpty ? "" : ",") + childStr + "\n" + indent + "}"; + } else { + let n = children.length; + childStr = "["; + for (let i = 0; i < n; i++) { + childStr += Element.getPrettyString(children[i], indent + " ") + (i < n - 1 ? "," : "") + "\n"; + } + childStr += indent + "]}"; + let isEmpty = (str === "{}"); + str = str.substr(0, str.length - 1) + (isEmpty ? "" : ",") + "\"children\":\n" + indent + childStr + "}"; + } + + } + + return str; + } + + getSettings() { + let settings = this.getNonDefaults(); + + let children = this._children.get(); + if (children) { + let n = children.length; + if (n) { + const childArray = []; + let missing = false; + for (let i = 0; i < n; i++) { + childArray.push(children[i].getSettings()); + missing = missing || !children[i].ref; + } + + if (!missing) { + settings.children = {} + childArray.forEach(child => { + settings.children[child.ref] = child; + }); + } else { + settings.children = childArray; + } + } + } + + settings.id = this.id; + + return settings; + } + + getNonDefaults() { + let settings = {}; + + if (this.constructor !== Element) { + settings.type = this.constructor.name; + } + + if (this.__ref) { + settings.ref = this.__ref; + } + + if (this.__tags && this.__tags.length) { + settings.tags = this.__tags; + } + + if (this.x !== 0) settings.x = this.x; + if (this.y !== 0) settings.y = this.y; + if (this.w !== 0) settings.w = this.w; + if (this.h !== 0) settings.h = this.h; + + if (this.scaleX === this.scaleY) { + if (this.scaleX !== 1) settings.scale = this.scaleX; + } else { + if (this.scaleX !== 1) settings.scaleX = this.scaleX; + if (this.scaleY !== 1) settings.scaleY = this.scaleY; + } + + if (this.pivotX === this.pivotY) { + if (this.pivotX !== 0.5) settings.pivot = this.pivotX; + } else { + if (this.pivotX !== 0.5) settings.pivotX = this.pivotX; + if (this.pivotY !== 0.5) settings.pivotY = this.pivotY; + } + + if (this.mountX === this.mountY) { + if (this.mountX !== 0) settings.mount = this.mountX; + } else { + if (this.mountX !== 0) settings.mountX = this.mountX; + if (this.mountY !== 0) settings.mountY = this.mountY; + } + + if (this.alpha !== 1) settings.alpha = this.alpha; + + if (!this.visible) settings.visible = false; + + if (this.rotation !== 0) settings.rotation = this.rotation; + + if (this.colorUl === this.colorUr && this.colorBl === this.colorBr && this.colorUl === this.colorBl) { + if (this.colorUl !== 0xFFFFFFFF) settings.color = this.colorUl.toString(16); + } else { + if (this.colorUl !== 0xFFFFFFFF) settings.colorUl = this.colorUl.toString(16); + if (this.colorUr !== 0xFFFFFFFF) settings.colorUr = this.colorUr.toString(16); + if (this.colorBl !== 0xFFFFFFFF) settings.colorBl = this.colorBl.toString(16); + if (this.colorBr !== 0xFFFFFFFF) settings.colorBr = this.colorBr.toString(16); + } + + if (this.zIndex) settings.zIndex = this.zIndex; + + if (this.forceZIndexContext) settings.forceZIndexContext = true; + + if (this.clipping) settings.clipping = this.clipping; + + if (!this.clipbox) settings.clipbox = this.clipbox; + + if (this.__texture) { + let tnd = this.__texture.getNonDefaults(); + if (Object.keys(tnd).length) { + settings.texture = tnd; + } + } + + if (this.shader && _Utils_mjs__WEBPACK_IMPORTED_MODULE_3__["default"].isFunction(this.shader.getNonDefaults)) { + let tnd = this.shader.getNonDefaults(); + if (Object.keys(tnd).length) { + settings.shader = tnd; + } + } + + if (this._hasTexturizer()) { + if (this.texturizer.enabled) { + settings.renderToTexture = this.texturizer.enabled; + } + if (this.texturizer.lazy) { + settings.renderToTextureLazy = this.texturizer.lazy; + } + if (this.texturizer.colorize) { + settings.colorizeResultTexture = this.texturizer.colorize; + } + if (this.texturizer.renderOffscreen) { + settings.renderOffscreen = this.texturizer.renderOffscreen; + } + } + + return settings; + }; + + static getGetter(propertyPath) { + let getter = Element.PROP_GETTERS.get(propertyPath); + if (!getter) { + getter = new Function('obj', 'return obj.' + propertyPath); + Element.PROP_GETTERS.set(propertyPath, getter); + } + return getter; + } + + static getSetter(propertyPath) { + let setter = Element.PROP_SETTERS.get(propertyPath); + if (!setter) { + setter = new Function('obj', 'v', 'obj.' + propertyPath + ' = v'); + Element.PROP_SETTERS.set(propertyPath, setter); + } + return setter; + } + + get withinBoundsMargin() { + return this.__core._withinBoundsMargin; + } + + _enableWithinBoundsMargin() { + // Iff enabled, this toggles the active flag. + if (this.__enabled) { + this._setActiveFlag(); + } + } + + _disableWithinBoundsMargin() { + // Iff active, this toggles the active flag. + if (this.__active) { + this._unsetActiveFlag(); + } + } + + set boundsMargin(v) { + if (!Array.isArray(v) && v !== null) { + throw new Error("boundsMargin should be an array of left-top-right-bottom values or null (inherit margin)"); + } + this.__core.boundsMargin = v; + } + + get boundsMargin() { + return this.__core.boundsMargin; + } + + get x() { + return this.__core.offsetX; + } + + set x(v) { + this.__core.offsetX = v; + } + + get y() { + return this.__core.offsetY; + } + + set y(v) { + this.__core.offsetY = v; + } + + get w() { + return this._w; + } + + set w(v) { + if (_Utils_mjs__WEBPACK_IMPORTED_MODULE_3__["default"].isFunction(v)) { + this._w = 0; + this.__core.funcW = v; + } else { + v = Math.max(v, 0); + if (this._w !== v) { + this.__core.disableFuncW(); + this._w = v; + this._updateDimensions(); + } + } + } + + get h() { + return this._h; + } + + set h(v) { + if (_Utils_mjs__WEBPACK_IMPORTED_MODULE_3__["default"].isFunction(v)) { + this._h = 0; + this.__core.funcH = v; + } else { + v = Math.max(v, 0); + if (this._h !== v) { + this.__core.disableFuncH(); + this._h = v; + this._updateDimensions(); + } + } + } + + get collision() { + return this._collision; + } + + set collision(v) { + this._collision = v; + } + + _updateCollision() { + if (this.collision && this.__parent && this.__parent.collision === undefined) { + /** + * Mark collision as 2 to indicate atleast one descendant has collision enabled. + * This narrows down the search for elements with active collision. + */ + this.__parent.collision = 2; + } + } + + get scaleX() { + return this.__core.scaleX; + } + + set scaleX(v) { + this.__core.scaleX = v; + } + + get scaleY() { + return this.__core.scaleY; + } + + set scaleY(v) { + this.__core.scaleY = v; + } + + get scale() { + return this.__core.scale; + } + + set scale(v) { + this.__core.scale = v; + } + + get pivotX() { + return this.__core.pivotX; + } + + set pivotX(v) { + this.__core.pivotX = v; + } + + get pivotY() { + return this.__core.pivotY; + } + + set pivotY(v) { + this.__core.pivotY = v; + } + + get pivot() { + return this.__core.pivot; + } + + set pivot(v) { + this.__core.pivot = v; + } + + get mountX() { + return this.__core.mountX; + } + + set mountX(v) { + this.__core.mountX = v; + } + + get mountY() { + return this.__core.mountY; + } + + set mountY(v) { + this.__core.mountY = v; + } + + get mount() { + return this.__core.mount; + } + + set mount(v) { + this.__core.mount = v; + } + + get rotation() { + return this.__core.rotation; + } + + set rotation(v) { + this.__core.rotation = v; + } + + get alpha() { + return this.__core.alpha; + } + + set alpha(v) { + this.__core.alpha = v; + } + + get visible() { + return this.__core.visible; + } + + set visible(v) { + this.__core.visible = v; + } + + get colorUl() { + return this.__core.colorUl; + } + + set colorUl(v) { + this.__core.colorUl = v; + } + + get colorUr() { + return this.__core.colorUr; + } + + set colorUr(v) { + this.__core.colorUr = v; + } + + get colorBl() { + return this.__core.colorBl; + } + + set colorBl(v) { + this.__core.colorBl = v; + } + + get colorBr() { + return this.__core.colorBr; + } + + set colorBr(v) { + this.__core.colorBr = v; + } + + get color() { + return this.__core.colorUl; + } + + set color(v) { + if (this.colorUl !== v || this.colorUr !== v || this.colorBl !== v || this.colorBr !== v) { + this.colorUl = v; + this.colorUr = v; + this.colorBl = v; + this.colorBr = v; + } + } + + get colorTop() { + return this.colorUl; + } + + set colorTop(v) { + if (this.colorUl !== v || this.colorUr !== v) { + this.colorUl = v; + this.colorUr = v; + } + } + + get colorBottom() { + return this.colorBl; + } + + set colorBottom(v) { + if (this.colorBl !== v || this.colorBr !== v) { + this.colorBl = v; + this.colorBr = v; + } + } + + get colorLeft() { + return this.colorUl; + } + + set colorLeft(v) { + if (this.colorUl !== v || this.colorBl !== v) { + this.colorUl = v; + this.colorBl = v; + } + } + + get colorRight() { + return this.colorUr; + } + + set colorRight(v) { + if (this.colorUr !== v || this.colorBr !== v) { + this.colorUr = v; + this.colorBr = v; + } + } + + get zIndex() {return this.__core.zIndex} + set zIndex(v) { + this.__core.zIndex = v; + } + + get forceZIndexContext() {return this.__core.forceZIndexContext} + set forceZIndexContext(v) { + this.__core.forceZIndexContext = v; + } + + get clipping() {return this.__core.clipping} + set clipping(v) { + this.__core.clipping = v; + } + + get clipbox() {return this.__core.clipbox} + set clipbox(v) { + this.__core.clipbox = v; + } + + get tags() { + return this.getTags(); + } + + set tags(v) { + if (!Array.isArray(v)) v = [v]; + this.setTags(v); + } + + set t(v) { + this.tags = v; + } + + get _children() { + if (!this.__childList) { + this.__childList = new _ElementChildList_mjs__WEBPACK_IMPORTED_MODULE_11__["default"](this, false); + } + return this.__childList; + } + + get childList() { + if (!this._allowChildrenAccess()) { + this._throwError("Direct access to children is not allowed in " + this.getLocationString()); + } + return this._children; + } + + hasChildren() { + return this._allowChildrenAccess() && this.__childList && (this.__childList.length > 0); + } + + _allowChildrenAccess() { + return true; + } + + get children() { + return this.childList.get(); + } + + set children(children) { + this.childList.patch(children); + } + + add(o) { + return this.childList.a(o); + } + + get p() { + return this.__parent; + } + + get parent() { + return this.__parent; + } + + get src() { + if (this.texture && this.texture instanceof _textures_ImageTexture_mjs__WEBPACK_IMPORTED_MODULE_7__["default"]) { + return this.texture._src; + } else { + return undefined; + } + } + + set src(v) { + const texture = new _textures_ImageTexture_mjs__WEBPACK_IMPORTED_MODULE_7__["default"](this.stage); + texture.src = v; + this.texture = texture; + } + + set mw(v) { + if (this.texture) { + this.texture.mw = v; + this._updateDimensions(); + } else { + this._throwError('Please set mw after setting a texture.'); + } + } + + set mh(v) { + if (this.texture) { + this.texture.mh = v; + this._updateDimensions(); + } else { + this._throwError('Please set mh after setting a texture.'); + } + } + + get rect() { + return (this.texture === this.stage.rectangleTexture); + } + + set rect(v) { + if (v) { + this.texture = this.stage.rectangleTexture; + } else { + this.texture = null; + } + } + + enableTextTexture() { + if (!this.texture || !(this.texture instanceof _textures_TextTexture_mjs__WEBPACK_IMPORTED_MODULE_8__["default"])) { + this.texture = new _textures_TextTexture_mjs__WEBPACK_IMPORTED_MODULE_8__["default"](this.stage); + + if (!this.texture.w && !this.texture.h) { + // Inherit dimensions from element. + // This allows userland to set dimensions of the Element and then later specify the text. + this.texture.w = this.w; + this.texture.h = this.h; + } + } + return this.texture; + } + + get text() { + if (this.texture && (this.texture instanceof _textures_TextTexture_mjs__WEBPACK_IMPORTED_MODULE_8__["default"])) { + return this.texture; + } else { + return null; + } + } + + set text(v) { + if (!this.texture || !(this.texture instanceof _textures_TextTexture_mjs__WEBPACK_IMPORTED_MODULE_8__["default"])) { + this.enableTextTexture(); + } + if (_Utils_mjs__WEBPACK_IMPORTED_MODULE_3__["default"].isString(v)) { + this.texture.text = v; + } else { + this.texture.patch(v); + } + } + + set onUpdate(f) { + this.__core.onUpdate = f; + } + + set onAfterCalcs(f) { + this.__core.onAfterCalcs = f; + } + + set onAfterUpdate(f) { + this.__core.onAfterUpdate = f; + } + + forceUpdate() { + // Make sure that the update loop is run. + this.__core._setHasUpdates(); + } + + get shader() { + return this.__core.shader; + } + + set shader(v) { + if (_Utils_mjs__WEBPACK_IMPORTED_MODULE_3__["default"].isObjectLiteral(v) && !v.type) { + // Setting properties on an existing shader. + if (this.shader) { + this.shader.patch(v); + } + } else { + const shader = _Shader_mjs__WEBPACK_IMPORTED_MODULE_5__["default"].create(this.stage, v); + + if (this.__enabled && this.__core.shader) { + this.__core.shader.removeElement(this.__core); + } + + this.__core.shader = shader; + + if (this.__enabled && this.__core.shader) { + this.__core.shader.addElement(this.__core); + } + } + } + + _hasTexturizer() { + return !!this.__core._texturizer; + } + + get renderToTexture() { + return this.rtt + } + + set renderToTexture(v) { + this.rtt = v + } + + get rtt() { + return this._hasTexturizer() && this.texturizer.enabled; + } + + set rtt(v) { + this.texturizer.enabled = v; + } + + get rttLazy() { + return this._hasTexturizer() && this.texturizer.lazy; + } + + set rttLazy(v) { + this.texturizer.lazy = v; + } + + get renderOffscreen() { + return this._hasTexturizer() && this.texturizer.renderOffscreen; + } + + set renderOffscreen(v) { + this.texturizer.renderOffscreen = v; + } + + get colorizeResultTexture() { + return this._hasTexturizer() && this.texturizer.colorize; + } + + set colorizeResultTexture(v) { + this.texturizer.colorize = v; + } + + getTexture() { + return this.texturizer._getTextureSource(); + } + + get texturizer() { + return this.__core.texturizer; + } + + patch(settings) { + let paths = Object.keys(settings); + + for (let i = 0, n = paths.length; i < n; i++) { + let path = paths[i]; + const v = settings[path]; + + const firstCharCode = path.charCodeAt(0); + if (_Utils_mjs__WEBPACK_IMPORTED_MODULE_3__["default"].isUcChar(firstCharCode)) { + // Ref. + const child = this.getByRef(path); + if (!child) { + if (v !== undefined) { + // Add to list immediately. + let c; + if (_Utils_mjs__WEBPACK_IMPORTED_MODULE_3__["default"].isObjectLiteral(v)) { + // Catch this case to capture createMode flag. + c = this.childList.createItem(v); + c.patch(v); + } else if (_Utils_mjs__WEBPACK_IMPORTED_MODULE_3__["default"].isObject(v)) { + c = v; + } + if (c.isElement) { + c.ref = path; + } + + this.childList.a(c); + } + } else { + if (v === undefined) { + if (child.parent) { + child.parent.childList.remove(child); + } + } else if (_Utils_mjs__WEBPACK_IMPORTED_MODULE_3__["default"].isObjectLiteral(v)) { + child.patch(v); + } else if (v.isElement) { + // Replace element by new element. + v.ref = path; + this.childList.replace(v, child); + } else { + this._throwError("Unexpected value for path: " + path); + } + } + } else { + // Property. + _Base_mjs__WEBPACK_IMPORTED_MODULE_2__["default"].patchObjectProperty(this, path, v); + } + } + } + + _throwError(message) { + throw new Error(this.constructor.name + " (" + this.getLocationString() + "): " + message); + } + + animation(settings) { + return this.stage.animations.createAnimation(this, settings); + } + + transition(property, settings = null) { + if (settings === null) { + return this._getTransition(property); + } else { + this._setTransition(property, settings); + // We do not create/return the transition, because it would undo the 'lazy transition creation' optimization. + return null; + } + } + + set transitions(object) { + let keys = Object.keys(object); + keys.forEach(property => { + this.transition(property, object[property]); + }); + } + + set smooth(object) { + let keys = Object.keys(object); + keys.forEach(property => { + let value = object[property]; + if (Array.isArray(value)) { + this.setSmooth(property, value[0], value[1]); + } else { + this.setSmooth(property, value); + } + }); + } + + fastForward(property) { + if (this._transitions) { + let t = this._transitions[property]; + if (t && t.isTransition) { + t.finish(); + } + } + } + + _getTransition(property) { + if (!this._transitions) { + this._transitions = {}; + } + let t = this._transitions[property]; + if (!t) { + // Create default transition. + t = new _animation_Transition_mjs__WEBPACK_IMPORTED_MODULE_10__["default"](this.stage.transitions, this.stage.transitions.defaultTransitionSettings, this, property); + } else if (t.isTransitionSettings) { + // Upgrade to 'real' transition. + t = new _animation_Transition_mjs__WEBPACK_IMPORTED_MODULE_10__["default"]( + this.stage.transitions, + t, + this, + property + ); + } + this._transitions[property] = t; + return t; + } + + _setTransition(property, settings) { + if (!settings) { + this._removeTransition(property); + } else { + if (_Utils_mjs__WEBPACK_IMPORTED_MODULE_3__["default"].isObjectLiteral(settings)) { + // Convert plain object to proper settings object. + settings = this.stage.transitions.createSettings(settings); + } + + if (!this._transitions) { + this._transitions = {}; + } + + let current = this._transitions[property]; + if (current && current.isTransition) { + // Runtime settings change. + current.settings = settings; + return current; + } else { + // Initially, only set the settings and upgrade to a 'real' transition when it is used. + this._transitions[property] = settings; + } + } + } + + _removeTransition(property) { + if (this._transitions) { + delete this._transitions[property]; + } + } + + getSmooth(property, v) { + let t = this._getTransition(property); + if (t && t.isAttached()) { + return t.targetValue; + } else { + return v; + } + } + + setSmooth(property, v, settings) { + if (settings) { + this._setTransition(property, settings); + } + let t = this._getTransition(property); + t.start(v); + return t; + } + + get flex() { + return this.__core.flex; + } + + set flex(v) { + this.__core.flex = v; + } + + get flexItem() { + return this.__core.flexItem; + } + + set flexItem(v) { + this.__core.flexItem = v; + } + + static isColorProperty(property) { + return property.toLowerCase().indexOf("color") >= 0; + } + + static getMerger(property) { + if (Element.isColorProperty(property)) { + return _StageUtils_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].mergeColors; + } else { + return _StageUtils_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].mergeNumbers; + } + } + + toJSON() { + const ref = [`${this.constructor.name}`]; + const tree = {}; + tree[ref] = {}; + + if (this.hasChildren()) { + Element.collectChildren(tree[ref], this.__childList); + } else { + tree[ref] = {...Element.getProperties(this)}; + } + return tree; + } + + static collectChildren(tree, children) { + const childList = children; + for (let i = 0, j = childList.length; i < j; i++) { + const element = childList.getAt(i); + const ref = `${element.__ref || `Element-${element.id}`}`; + const properties = this.getProperties(element); + + tree[ref] = {...properties}; + + if (element.hasChildren()) { + tree[ref].children = {}; + this.collectChildren( + tree[ref].children, element.__childList + ); + } + } + } + + static getProperties(element) { + const props = {}; + const list = [ + "alpha", "active", "attached", "boundsMargin", "color", "clipping", "enabled", "h", "id", "isComponent", + "mount", "mountY", "mountX", "pivot", "pivotX", "pivotY", "ref", "renderOffscreen", "renderToTexture", "scale", + "scaleX", "scaleY", "state", "tag", "visible", "w", "x", "y", "zIndex", + "!!flex", "!!flexItem", "hasFocus()", "hasFinalFocus()" + ]; + let n = list.length; + + while (n--) { + let key = list[n]; + const getBoolean = /^!{2}/; + const isFunction = /\(\)$/; + + if (getBoolean.test(key)) { + key = key.substring(2, key.length); + props[key] = !!element[key]; + } else if (isFunction.test(key)) { + key = key.substring(0, key.length - 2); + if (typeof element[key] === "function") { + props[key] = element[key](); + } + } else { + props[key] = element[key]; + } + } + return {...props, ...element.getNonDefaults()}; + } +} + +// This gives a slight performance benefit compared to extending EventEmitter. +_EventEmitter_mjs__WEBPACK_IMPORTED_MODULE_4__["default"].addAsMixin(Element); + +Element.prototype.isElement = 1; + +Element.id = 1; + +// Getters reused when referencing element (subobject) properties by a property path, as used in a transition or animation ('x', 'texture.x', etc). +Element.PROP_GETTERS = new Map(); + +// Setters reused when referencing element (subobject) properties by a property path, as used in a transition or animation ('x', 'texture.x', etc). +Element.PROP_SETTERS = new Map(); + + + + + + + + + +/***/ }), + +/***/ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/tree/ElementChildList.mjs": +/*!*********************************************************************************************************!*\ + !*** ./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/tree/ElementChildList.mjs ***! + \*********************************************************************************************************/ +/*! exports provided: default */ +/***/ (function(__webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return ElementChildList; }); +/* harmony import */ var _ObjectList_mjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./ObjectList.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/tree/ObjectList.mjs"); +/* + * If not stated otherwise in this file or this component's LICENSE file the + * following copyright and licenses apply: + * + * Copyright 2020 Metrological + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * Manages the list of children for an element. + */ + + + +class ElementChildList extends _ObjectList_mjs__WEBPACK_IMPORTED_MODULE_0__["default"] { + + constructor(element) { + super(); + this._element = element; + } + + _connectParent(item) { + const prevParent = item.parent; + if (prevParent && prevParent !== this._element) { + // Cleanup in previous child list, without + const prevChildList = item.parent.childList; + const index = prevChildList.getIndex(item); + + if (item.ref) { + prevChildList._refs[item.ref] = undefined; + } + prevChildList._items.splice(index, 1); + + // Also clean up element core. + prevParent.core.removeChildAt(index); + + } + + item._setParent(this._element); + + // We are expecting the caller to sync it to the core. + } + + onAdd(item, index) { + this._connectParent(item); + this._element.core.addChildAt(index, item.core); + } + + onRemove(item, index) { + item._setParent(null); + this._element.core.removeChildAt(index); + } + + onSync(removed, added, order) { + for (let i = 0, n = removed.length; i < n; i++) { + removed[i]._setParent(null); + } + for (let i = 0, n = added.length; i < n; i++) { + this._connectParent(added[i]); + } + let gc = i => i.core; + this._element.core.syncChildren(removed.map(gc), added.map(gc), order.map(gc)); + } + + onSet(item, index, prevItem) { + prevItem._setParent(null); + + this._connectParent(item); + this._element.core.setChildAt(index, item.core); + } + + onMove(item, fromIndex, toIndex) { + this._element.core.moveChild(fromIndex, toIndex); + } + + createItem(object) { + if (object.type) { + return new object.type(this._element.stage); + } else { + return this._element.stage.createElement(); + } + } + + isItem(object) { + return object.isElement; + } + +} + + + + +/***/ }), + +/***/ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/tree/ObjectList.mjs": +/*!***************************************************************************************************!*\ + !*** ./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/tree/ObjectList.mjs ***! + \***************************************************************************************************/ +/*! exports provided: default */ +/***/ (function(__webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return ObjectList; }); +/* harmony import */ var _Utils_mjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./Utils.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/tree/Utils.mjs"); +/* + * If not stated otherwise in this file or this component's LICENSE file the + * following copyright and licenses apply: + * + * Copyright 2020 Metrological + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * Manages a list of objects. + * Objects may be patched. Then, they can be referenced using the 'ref' (string) property. + */ +class ObjectList { + + constructor() { + this._items = []; + this._refs = {} + } + + get() { + return this._items; + } + + get first() { + return this._items[0]; + } + + get last() { + return this._items.length ? this._items[this._items.length - 1] : undefined; + } + + add(item) { + this.addAt(item, this._items.length); + } + + addAt(item, index) { + if (index >= 0 && index <= this._items.length) { + let currentIndex = this._items.indexOf(item); + if (currentIndex === index) { + return item; + } + + if (_Utils_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].isObjectLiteral(item)) { + const o = item; + item = this.createItem(o); + item.patch(o); + } + + if (currentIndex != -1) { + this.setAt(item, index); + } else { + if (item.ref) { + this._refs[item.ref] = item; + } + this._items.splice(index, 0, item); + this.onAdd(item, index); + } + } else { + throw new Error('addAt: The index ' + index + ' is out of bounds ' + this._items.length); + } + } + + replaceByRef(item) { + if (item.ref) { + const existingItem = this.getByRef(item.ref); + if (!existingItem) { + throw new Error('replaceByRef: no item found with reference: ' + item.ref); + } + this.replace(item, existingItem); + } else { + throw new Error('replaceByRef: no ref specified in item'); + } + this.addAt(item, this._items.length); + + } + + replace(item, prevItem) { + const index = this.getIndex(prevItem); + if (index === -1) { + throw new Error('replace: The previous item does not exist'); + } + this.setAt(item, index); + } + + setAt(item, index) { + if (index >= 0 && index <= this._items.length) { + + if (_Utils_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].isObjectLiteral(item)) { + const o = item; + item = this.createItem(o); + item.patch(o); + } + + let currentIndex = this._items.indexOf(item); + if (currentIndex != -1) { + if (currentIndex !== index) { + const fromIndex = currentIndex; + if (fromIndex !== index) { + this._items.splice(fromIndex, 1); + this._items.splice(index, 0, item); + this.onMove(item, fromIndex, index); + } + } + } else { + if( index < this._items.length){ + + if (this._items[index].ref) { + this._refs[this._items[index].ref] = undefined; + } + + const prevItem = this._items[index]; + + // Doesn't exist yet: overwrite current. + this._items[index] = item; + + if (item.ref) { + this._refs[item.ref] = item; + } + + this.onSet(item, index, prevItem); + } else { + throw new Error('setAt: The index ' + index + ' is out of bounds ' + this._items.length); + } + } + } else { + throw new Error('setAt: The index ' + index + ' is out of bounds ' + this._items.length); + } + } + + getAt(index) { + return this._items[index]; + } + + getIndex(item) { + return this._items.indexOf(item); + } + + remove(item) { + let index = this._items.indexOf(item); + + if (index !== -1) { + this.removeAt(index); + } + }; + + removeAt(index) { + if (index >= 0 && index < this._items.length) { + const item = this._items[index]; + + if (item.ref) { + this._refs[item.ref] = undefined; + } + + this._items.splice(index, 1); + + this.onRemove(item, index); + + return item; + } else { + throw new Error(`removeAt: The index ${index} is out of bounds ${this._items.length - 1}`); + } + }; + + clear() { + let n = this._items.length; + if (n) { + let prev = this._items; + this._items = []; + this._refs = {} + this.onSync(prev, [], []); + } + }; + + a(o) { + if (_Utils_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].isObjectLiteral(o)) { + let c = this.createItem(o); + c.patch(o); + this.add(c); + return c; + } else if (Array.isArray(o)) { + for (let i = 0, n = o.length; i < n; i++) { + this.a(o[i]); + } + return null; + } else if (this.isItem(o)) { + this.add(o); + return o; + } + }; + + get length() { + return this._items.length; + } + + _getRefs() { + return this._refs; + } + + getByRef(ref) { + return this._refs[ref]; + } + + clearRef(ref) { + delete this._refs[ref]; + } + + setRef(ref, child) { + this._refs[ref] = child; + } + + patch(settings) { + if (_Utils_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].isObjectLiteral(settings)) { + this._setByObject(settings); + } else if (Array.isArray(settings)) { + this._setByArray(settings); + } + } + + _setByObject(settings) { + // Overrule settings of known referenced items. + let refs = this._getRefs(); + let crefs = Object.keys(settings); + for (let i = 0, n = crefs.length; i < n; i++) { + let cref = crefs[i]; + let s = settings[cref]; + + let c = refs[cref]; + if (!c) { + if (this.isItem(s)) { + // Replace previous item; + s.ref = cref; + this.add(s); + } else { + // Create new item. + c = this.createItem(s); + c.ref = cref; + c.patch(s); + this.add(c); + } + } else { + if (this.isItem(s)) { + if (c !== s) { + // Replace previous item; + let idx = this.getIndex(c); + s.ref = cref; + this.setAt(s, idx); + } + } else { + c.patch(s); + } + } + } + } + + _equalsArray(array) { + let same = true; + if (array.length === this._items.length) { + for (let i = 0, n = this._items.length; (i < n) && same; i++) { + same = same && (this._items[i] === array[i]); + } + } else { + same = false; + } + return same; + } + + _setByArray(array) { + // For performance reasons, first check if the arrays match exactly and bail out if they do. + if (this._equalsArray(array)) { + return; + } + + for (let i = 0, n = this._items.length; i < n; i++) { + this._items[i].marker = true; + } + + let refs; + let newItems = []; + for (let i = 0, n = array.length; i < n; i++) { + let s = array[i]; + if (this.isItem(s)) { + s.marker = false; + newItems.push(s); + } else { + let cref = s.ref; + let c; + if (cref) { + if (!refs) refs = this._getRefs(); + c = refs[cref]; + } + + if (!c) { + // Create new item. + c = this.createItem(s); + } else { + c.marker = false; + } + + if (_Utils_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].isObjectLiteral(s)) { + c.patch(s); + } + + newItems.push(c); + } + } + + this._setItems(newItems); + } + + _setItems(newItems) { + let prevItems = this._items; + this._items = newItems; + + // Remove the items. + let removed = prevItems.filter(item => {let m = item.marker; delete item.marker; return m}); + let added = newItems.filter(item => (prevItems.indexOf(item) === -1)); + + if (removed.length || added.length) { + // Recalculate refs. + this._refs = {} + for (let i = 0, n = this._items.length; i < n; i++) { + let ref = this._items[i].ref; + if (ref) { + this._refs[ref] = this._items[i]; + } + } + } + + this.onSync(removed, added, newItems); + } + + sort(f) { + const items = this._items.slice(); + items.sort(f); + this._setByArray(items); + } + + onAdd(item, index) { + } + + onRemove(item, index) { + } + + onSync(removed, added, order) { + } + + onSet(item, index, prevItem) { + } + + onMove(item, fromIndex, toIndex) { + } + + createItem(object) { + throw new Error("ObjectList.createItem must create and return a new object"); + } + + isItem(object) { + return false; + } + + forEach(f) { + this.get().forEach(f); + } + +} + + + + + + +/***/ }), + +/***/ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/tree/Shader.mjs": +/*!***********************************************************************************************!*\ + !*** ./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/tree/Shader.mjs ***! + \***********************************************************************************************/ +/*! exports provided: default */ +/***/ (function(__webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return Shader; }); +/* harmony import */ var _Utils_mjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./Utils.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/tree/Utils.mjs"); +/* harmony import */ var _Base_mjs__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./Base.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/tree/Base.mjs"); +/* + * If not stated otherwise in this file or this component's LICENSE file the + * following copyright and licenses apply: + * + * Copyright 2020 Metrological + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + + +class Shader { + + constructor(coreContext) { + this._initialized = false; + + this.ctx = coreContext; + + /** + * The (enabled) elements that use this shader. + * @type {Set} + */ + this._elements = new Set(); + } + + static create(stage, v) { + let shader; + if (_Utils_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].isObjectLiteral(v)) { + if (v.type) { + shader = stage.renderer.createShader(stage.ctx, v); + } else { + shader = this.shader; + } + + if (shader) { + _Base_mjs__WEBPACK_IMPORTED_MODULE_1__["default"].patchObject(shader, v); + } + } else if (v === null) { + shader = stage.ctx.renderState.defaultShader; + } else if (v === undefined) { + shader = null; + } else { + if (v.isShader) { + if (!stage.renderer.isValidShaderType(v.constructor)) { + console.error("[Lightning] Invalid shader type"); + v = null; + } + shader = v; + } else { + console.error("[Lightning] Please specify a shader type."); + return; + } + } + + return shader; + } + + static getWebGL() { + return undefined; + } + + static getC2d() { + return undefined; + } + + addElement(elementCore) { + this._elements.add(elementCore); + } + + removeElement(elementCore) { + this._elements.delete(elementCore); + if (!this._elements) { + this.cleanup(); + } + } + + redraw() { + this._elements.forEach(elementCore => { + elementCore.setHasRenderUpdates(2); + }); + } + + patch(settings) { + _Base_mjs__WEBPACK_IMPORTED_MODULE_1__["default"].patchObject(this, settings); + } + + useDefault() { + // Should return true if this shader is configured (using it's properties) to not have any effect. + // This may allow the render engine to avoid unnecessary shader program switches or even texture copies. + return false; + } + + addEmpty() { + // Draws this shader even if there are no quads to be added. + // This is handy for custom shaders. + return false; + } + + cleanup() { + // Called when no more enabled elements have this shader. + } + + get isShader() { + return true; + } +} + + + +/***/ }), + +/***/ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/tree/Stage.mjs": +/*!**********************************************************************************************!*\ + !*** ./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/tree/Stage.mjs ***! + \**********************************************************************************************/ +/*! exports provided: default */ +/***/ (function(__webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return Stage; }); +/* harmony import */ var _EventEmitter_mjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../EventEmitter.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/EventEmitter.mjs"); +/* harmony import */ var _Utils_mjs__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./Utils.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/tree/Utils.mjs"); +/* harmony import */ var _renderer_webgl_WebGLRenderer_mjs__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../renderer/webgl/WebGLRenderer.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/renderer/webgl/WebGLRenderer.mjs"); +/* harmony import */ var _renderer_c2d_C2dRenderer_mjs__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../renderer/c2d/C2dRenderer.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/renderer/c2d/C2dRenderer.mjs"); +/* harmony import */ var _renderer_spark_SparkRenderer_mjs__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../renderer/spark/SparkRenderer.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/renderer/spark/SparkRenderer.mjs"); +/* harmony import */ var _platforms_PlatformLoader_mjs__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../platforms/PlatformLoader.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/platforms/PlatformLoader.mjs"); +/* harmony import */ var _tools_WebGLStateManager_mjs__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../tools/WebGLStateManager.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/tools/WebGLStateManager.mjs"); +/* harmony import */ var _Shader_mjs__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./Shader.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/tree/Shader.mjs"); +/* harmony import */ var _Element_mjs__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./Element.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/tree/Element.mjs"); +/* harmony import */ var _StageUtils_mjs__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./StageUtils.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/tree/StageUtils.mjs"); +/* harmony import */ var _TextureManager_mjs__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./TextureManager.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/tree/TextureManager.mjs"); +/* harmony import */ var _TextureThrottler_mjs__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ./TextureThrottler.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/tree/TextureThrottler.mjs"); +/* harmony import */ var _core_CoreContext_mjs__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ./core/CoreContext.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/tree/core/CoreContext.mjs"); +/* harmony import */ var _animation_TransitionManager_mjs__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ../animation/TransitionManager.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/animation/TransitionManager.mjs"); +/* harmony import */ var _animation_AnimationManager_mjs__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ../animation/AnimationManager.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/animation/AnimationManager.mjs"); +/* harmony import */ var _textures_RectangleTexture_mjs__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ../textures/RectangleTexture.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/textures/RectangleTexture.mjs"); +/* + * If not stated otherwise in this file or this component's LICENSE file the + * following copyright and licenses apply: + * + * Copyright 2020 Metrological + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * Application render tree. + */ + + + + + + + + + + +class Stage extends _EventEmitter_mjs__WEBPACK_IMPORTED_MODULE_0__["default"] { + + constructor(options = {}) { + super(); + this._setOptions(options); + + this._usedMemory = 0; + this._lastGcFrame = 0; + + // attempt to track VRAM usage more accurately by accounting for different color channels + this._usedVramAlpha = 0; + this._usedVramNonAlpha = 0; + + const platformType = Stage.platform ? Stage.platform : _platforms_PlatformLoader_mjs__WEBPACK_IMPORTED_MODULE_5__["default"].load(options); + this.platform = new platformType(); + + if (this.platform.init) { + this.platform.init(this); + } + + this.gl = null; + this.c2d = null; + + const context = this.getOption('context'); + if (context) { + if (context.useProgram) { + this.gl = context; + } else { + this.c2d = context; + } + } else { + if (_Utils_mjs__WEBPACK_IMPORTED_MODULE_1__["default"].isWeb && (!Stage.isWebglSupported() || this.getOption('canvas2d'))) { + this.c2d = this.platform.createCanvasContext(this.getOption('w'), this.getOption('h')); + } else { + this.gl = this.platform.createWebGLContext(this.getOption('w'), this.getOption('h')); + } + } + + if (this.gl) { + // Wrap in WebGLStateManager. + // This prevents unnecessary double WebGL commands from being executed, and allows context switching. + // Context switching is necessary when reusing the same context for Three.js. + // Note that the user must make sure that the WebGL context is untouched before creating the application, + // when manually passing over a canvas or context in the options. + _tools_WebGLStateManager_mjs__WEBPACK_IMPORTED_MODULE_6__["default"].enable(this.gl, "lightning") + } + + this._mode = this.gl ? 0 : 1; + + // Override width and height. + if (this.getCanvas()) { + if (this.getOption('devicePixelRatio') !== 1) { + const ratio = this.getOption('devicePixelRatio'); + // set correct display sie + this.getCanvas().style.width = this._options['w'] / ratio + 'px'; + this.getCanvas().style.height = this._options['h'] / ratio + 'px'; + } + + // set display buffer size + this._options.w = this.getCanvas().width; + this._options.h = this.getCanvas().height; + } + + if (this._mode === 0) { + if (_Utils_mjs__WEBPACK_IMPORTED_MODULE_1__["default"].isSpark) { + this._renderer = new _renderer_spark_SparkRenderer_mjs__WEBPACK_IMPORTED_MODULE_4__["default"](this); + } else { + this._renderer = new _renderer_webgl_WebGLRenderer_mjs__WEBPACK_IMPORTED_MODULE_2__["default"](this); + } + } else { + this._renderer = new _renderer_c2d_C2dRenderer_mjs__WEBPACK_IMPORTED_MODULE_3__["default"](this); + } + + this.setClearColor(this.getOption('clearColor')); + + this.frameCounter = 0; + + this.transitions = new _animation_TransitionManager_mjs__WEBPACK_IMPORTED_MODULE_13__["default"](this); + this.animations = new _animation_AnimationManager_mjs__WEBPACK_IMPORTED_MODULE_14__["default"](this); + + this.textureManager = new _TextureManager_mjs__WEBPACK_IMPORTED_MODULE_10__["default"](this); + this.textureThrottler = new _TextureThrottler_mjs__WEBPACK_IMPORTED_MODULE_11__["default"](this); + + this.startTime = 0; + this.currentTime = 0; + this.dt = 0; + + // Preload rectangle texture, so that we can skip some border checks for loading textures. + this.rectangleTexture = new _textures_RectangleTexture_mjs__WEBPACK_IMPORTED_MODULE_15__["default"](this); + this.rectangleTexture.load(); + + // Never clean up because we use it all the time. + this.rectangleTexture.source.permanent = true; + + this.ctx = new _core_CoreContext_mjs__WEBPACK_IMPORTED_MODULE_12__["default"](this); + + this._updateSourceTextures = new Set(); + } + + get renderer() { + return this._renderer; + } + + static isWebglSupported() { + if (_Utils_mjs__WEBPACK_IMPORTED_MODULE_1__["default"].isNode) { + return true; + } + + try { + return !!window.WebGLRenderingContext; + } catch (e) { + return false; + } + } + + /** + * Returns the rendering mode. + * @returns {number} + * 0: WebGL + * 1: Canvas2d + */ + get mode() { + return this._mode; + } + + isWebgl() { + return this.mode === 0; + } + + isC2d() { + return this.mode === 1; + } + + getOption(name) { + return this._options[name]; + } + + _setOptions(o) { + this._options = {}; + + let opt = (name, def) => { + let value = o[name]; + + if (value === undefined) { + this._options[name] = def; + } else { + this._options[name] = value; + } + } + + opt('canvas', null); + opt('context', null); + opt('w', 1920); + opt('h', 1080); + opt('srcBasePath', null); + opt('memoryPressure', 24e6); + opt('bufferMemory', 2e6); + opt('textRenderIssueMargin', 0); + opt('fontSharp', { precision: 0.6666666667, fontSize: 24 }) + opt('clearColor', [0, 0, 0, 0]); + opt('defaultFontFace', 'sans-serif'); + opt('fixedDt', 0); + opt('useImageWorker', true); + opt('autostart', true); + opt('precision', 1); + opt('canvas2d', false); + opt('platform', null); + opt('readPixelsBeforeDraw', false); + opt('devicePixelRatio', 1) + opt('readPixelsAfterDraw', false); + opt('readPixelsAfterDrawThreshold', 0); + opt('debugFrame', false); + opt('forceTxCanvasSource', false); + opt('pauseRafLoopOnIdle', false); + + if (o['devicePixelRatio'] != null && o['devicePixelRatio'] !== 1) { + this._options['precision'] *= o['devicePixelRatio'] + this._options['w'] *= o['devicePixelRatio'] + this._options['h'] *= o['devicePixelRatio'] + } + } + + setApplication(app) { + this.application = app; + } + + init() { + + if (this.application.getOption('debug') && this.platform._imageWorker) { + console.log('[Lightning] Using image worker!'); + } + + if (this.application.getOption('debug') && this.c2d) { + console.log('[Lightning] Using canvas2d renderer'); + } + + this.application.setAsRoot(); + if (this.getOption('autostart')) { + this.platform.startLoop(); + } + } + + destroy() { + this.platform.stopLoop(); + this.platform.destroy(); + this.ctx.destroy(); + this.textureManager.destroy(); + this._renderer.destroy(); + + // clear last rendered frame + if (this.gl) { + this.gl.clearColor(0.0, 0.0, 0.0, 0.0); + this.gl.clear(this.gl.COLOR_BUFFER_BIT); + } else if (this.c2d) { + this.c2d.clearRect( + 0, 0, this.c2d.canvas.width, this.c2d.canvas.height + ); + } + + this.gl = null; + this.c2d = null; + this.ctx = null; + this._options = null; + this.platform = null; + this.textureManager = null; + this._renderer = null; + + delete this.gl; + delete this.c2d; + delete this.ctx; + delete this._options; + delete this.platform; + delete this.textureManager; + delete this._renderer; + } + + stop() { + this.platform.stopLoop(); + } + + resume() { + this.platform.startLoop(); + } + + get root() { + return this.application; + } + + getCanvas() { + return this._mode ? this.c2d.canvas : this.gl.canvas; + } + + getRenderPrecision() { + return this._options.precision; + } + + /** + * Marks a texture for updating it's source upon the next drawFrame. + * @param texture + */ + addUpdateSourceTexture(texture) { + if (this._updatingFrame) { + // When called from the upload loop, we must immediately load the texture in order to avoid a 'flash'. + texture._performUpdateSource(); + } else { + this._updateSourceTextures.add(texture); + } + } + + removeUpdateSourceTexture(texture) { + if (this._updateSourceTextures) { + this._updateSourceTextures.delete(texture); + } + } + + hasUpdateSourceTexture(texture) { + return (this._updateSourceTextures && this._updateSourceTextures.has(texture)); + } + + + _performUpdateSource() { + if (this._updateSourceTextures.size) { + this._updateSourceTextures.forEach(texture => { + texture._performUpdateSource(); + }); + this._updateSourceTextures = new Set(); + } + } + + _calculateDt() { + this.startTime = this.currentTime; + this.currentTime = this.platform.getHrTime(); + + if (this._options.fixedDt) { + this.dt = this._options.fixedDt; + } else { + this.dt = (!this.startTime) ? .02 : .001 * (this.currentTime - this.startTime); + } + } + + updateFrame() { + this._calculateDt(); + this.emit('frameStart'); + this._performUpdateSource(); + this.emit('update'); + } + + idleFrame() { + this.textureThrottler.processSome(); + this.emit('frameEnd'); + this.frameCounter++; + } + + onIdle() { + this.emit('idle'); + } + + renderFrame() { + const changes = this.ctx.hasRenderUpdates(); + + // Update may cause textures to be loaded in sync, so by processing them here we may be able to show them + // during the current frame already. + this.textureThrottler.processSome(); + + if (changes) { + this._updatingFrame = true; + this.ctx.update(); + this.ctx.render(); + this._updatingFrame = false; + } + + this.platform.nextFrame(changes); + + this.emit('frameEnd'); + + this.frameCounter++; + } + + isUpdatingFrame() { + return this._updatingFrame; + } + + drawFrame() { + // Maintain original functionality of `drawFrame()` while retaining the + // RAF mitigration feature from: https://github.com/rdkcentral/Lightning/pull/402 + // The full functionality of this method is relied directly by our own unit tests and + // the unit tests of third party users + this.updateFrame(); + this.renderFrame(); + } + + forceRenderUpdate() { + // Enforce re-rendering. + if (this.root) { + this.root.core._parent.setHasRenderUpdates(1); + } + } + + setClearColor(clearColor) { + this.forceRenderUpdate(); + if (clearColor === null) { + // Do not clear. + this._clearColor = null; + } else if (Array.isArray(clearColor)) { + this._clearColor = clearColor; + } else { + this._clearColor = _StageUtils_mjs__WEBPACK_IMPORTED_MODULE_9__["default"].getRgbaComponentsNormalized(clearColor); + } + } + + getClearColor() { + return this._clearColor; + } + + createElement(settings) { + if (settings) { + return this.element(settings); + } else { + return new _Element_mjs__WEBPACK_IMPORTED_MODULE_8__["default"](this); + } + } + + createShader(settings) { + return _Shader_mjs__WEBPACK_IMPORTED_MODULE_7__["default"].create(this, settings); + } + + element(settings) { + if (settings.isElement) return settings; + + let element; + if (settings.type) { + element = new settings.type(this); + } else { + element = new _Element_mjs__WEBPACK_IMPORTED_MODULE_8__["default"](this); + } + + element.patch(settings); + + return element; + } + + c(settings) { + return this.element(settings); + } + + get w() { + return this._options.w; + } + + get h() { + return this._options.h; + } + + get coordsWidth() { + return this.w / this._options.precision; + } + + get coordsHeight() { + return this.h / this._options.precision; + } + + addMemoryUsage(delta) { + this._usedMemory += delta; + if (delta > 0 && this._lastGcFrame !== this.frameCounter) { + if (this._usedMemory > this.getOption('memoryPressure')) { + this.gc(false); + if (this._usedMemory > this.getOption('memoryPressure') - 2e6) { + // Too few released. Aggressive cleanup. + this.gc(true); + } + } + } + } + + get usedMemory() { + return this._usedMemory; + } + + addVramUsage(delta, alpha) { + if (alpha) { + this._usedVramAlpha += delta; + } + else { + this._usedVramNonAlpha += delta; + } + } + + get usedVramAlpha() { + return this._usedVramAlpha; + } + + get usedVramNonAlpha() { + return this._usedVramNonAlpha; + } + + get usedVram() { + return this._usedVramAlpha + this._usedVramNonAlpha; + } + + gc(aggressive) { + if (this._lastGcFrame !== this.frameCounter) { + this._lastGcFrame = this.frameCounter; + const memoryUsageBefore = this._usedMemory; + this.gcTextureMemory(aggressive); + this.gcRenderTextureMemory(aggressive); + this.renderer.gc(aggressive); + + if (this.application.getOption('debug')) { + console.log(`[Lightning] GC${aggressive ? "[aggressive]" : ""}! Frame ${this._lastGcFrame} Freed ${((memoryUsageBefore - this._usedMemory) / 1e6).toFixed(2)}MP from GPU memory. Remaining: ${(this._usedMemory / 1e6).toFixed(2)}MP`); + const other = this._usedMemory - this.textureManager.usedMemory - this.ctx.usedMemory; + console.log(`[Lightning] Textures: ${(this.textureManager.usedMemory / 1e6).toFixed(2)}MP, Render Textures: ${(this.ctx.usedMemory / 1e6).toFixed(2)}MP, Renderer caches: ${(other / 1e6).toFixed(2)}MP`); + } + } + } + + gcTextureMemory(aggressive = false) { + if (aggressive && this.ctx.root.visible) { + // Make sure that ALL textures are cleaned; + this.ctx.root.visible = false; + this.textureManager.gc(); + this.ctx.root.visible = true; + } else { + this.textureManager.gc(); + } + } + + gcRenderTextureMemory(aggressive = false) { + if (aggressive && this.root.visible) { + // Make sure that ALL render textures are cleaned; + this.root.visible = false; + this.ctx.freeUnusedRenderTextures(0); + this.root.visible = true; + } else { + this.ctx.freeUnusedRenderTextures(0); + } + } + + getDrawingCanvas() { + return this.platform.getDrawingCanvas(); + } + + update() { + this.ctx.update() + } + + addServiceProvider(serviceprovider) { + if (_Utils_mjs__WEBPACK_IMPORTED_MODULE_1__["default"].isSpark) { + this.platform.addServiceProvider(serviceprovider); + } + } + + getChildrenByPosition(x, y) { + const children = []; + this.root.core.update(); + this.root.core.collectAtCoord(x, y, children); + + return children; + } +} + + + + + + + + + + + +/***/ }), + +/***/ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/tree/StageUtils.mjs": +/*!***************************************************************************************************!*\ + !*** ./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/tree/StageUtils.mjs ***! + \***************************************************************************************************/ +/*! exports provided: default */ +/***/ (function(__webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return StageUtils; }); +/* + * If not stated otherwise in this file or this component's LICENSE file the + * following copyright and licenses apply: + * + * Copyright 2020 Metrological + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +class StageUtils { + + static mergeNumbers(v1, v2, p) { + return v1 * p + v2 * (1 - p); + }; + + static rgb(r, g, b) { + return (r << 16) + (g << 8) + b + (255 * 16777216); + }; + + static rgba(r, g, b, a) { + return (r << 16) + (g << 8) + b + (((a * 255) | 0) * 16777216); + }; + + static getRgbString(color) { + let r = ((color / 65536) | 0) % 256; + let g = ((color / 256) | 0) % 256; + let b = color % 256; + return 'rgb(' + r + ',' + g + ',' + b + ')'; + }; + + static getRgbaString(color) { + let r = ((color / 65536) | 0) % 256; + let g = ((color / 256) | 0) % 256; + let b = color % 256; + let a = ((color / 16777216) | 0) / 255; + return 'rgba(' + r + ',' + g + ',' + b + ',' + a.toFixed(4) + ')'; + }; + + static getRgbaStringFromArray(color) { + let r = Math.floor(color[0] * 255); + let g = Math.floor(color[1] * 255); + let b = Math.floor(color[2] * 255); + let a = Math.floor(color[3] * 255) / 255; + return 'rgba(' + r + ',' + g + ',' + b + ',' + a.toFixed(4) + ')'; + }; + + static getRgbaComponentsNormalized(argb) { + let r = ((argb / 65536) | 0) % 256; + let g = ((argb / 256) | 0) % 256; + let b = argb % 256; + let a = ((argb / 16777216) | 0); + return [r / 255, g / 255, b / 255, a / 255]; + }; + + static getRgbComponentsNormalized(argb) { + let r = ((argb / 65536) | 0) % 256; + let g = ((argb / 256) | 0) % 256; + let b = argb % 256; + return [r / 255, g / 255, b / 255]; + }; + + static getRgbaComponents(argb) { + let r = ((argb / 65536) | 0) % 256; + let g = ((argb / 256) | 0) % 256; + let b = argb % 256; + let a = ((argb / 16777216) | 0); + return [r, g, b, a]; + }; + + static getArgbNumber(rgba) { + rgba[0] = Math.max(0, Math.min(255, rgba[0])); + rgba[1] = Math.max(0, Math.min(255, rgba[1])); + rgba[2] = Math.max(0, Math.min(255, rgba[2])); + rgba[3] = Math.max(0, Math.min(255, rgba[3])); + let v = ((rgba[3] | 0) << 24) + ((rgba[0] | 0) << 16) + ((rgba[1] | 0) << 8) + (rgba[2] | 0); + if (v < 0) { + v = 0xFFFFFFFF + v + 1; + } + return v; + }; + + static mergeColors(c1, c2, p) { + let r1 = ((c1 / 65536) | 0) % 256; + let g1 = ((c1 / 256) | 0) % 256; + let b1 = c1 % 256; + let a1 = ((c1 / 16777216) | 0); + + let r2 = ((c2 / 65536) | 0) % 256; + let g2 = ((c2 / 256) | 0) % 256; + let b2 = c2 % 256; + let a2 = ((c2 / 16777216) | 0); + + let r = r1 * p + r2 * (1 - p); + let g = g1 * p + g2 * (1 - p); + let b = b1 * p + b2 * (1 - p); + let a = a1 * p + a2 * (1 - p); + + return Math.round(a) * 16777216 + Math.round(r) * 65536 + Math.round(g) * 256 + Math.round(b); + }; + + static mergeMultiColors(c, p) { + let r = 0, g = 0, b = 0, a = 0, t = 0; + let n = c.length; + for (let i = 0; i < n; i++) { + let r1 = ((c[i] / 65536) | 0) % 256; + let g1 = ((c[i] / 256) | 0) % 256; + let b1 = c[i] % 256; + let a1 = ((c[i] / 16777216) | 0); + r += r1 * p[i]; + g += g1 * p[i]; + b += b1 * p[i]; + a += a1 * p[i]; + t += p[i]; + } + + t = 1 / t; + return Math.round(a * t) * 16777216 + Math.round(r * t) * 65536 + Math.round(g * t) * 256 + Math.round(b * t); + }; + + static mergeMultiColorsEqual(c) { + let r = 0, g = 0, b = 0, a = 0, t = 0; + let n = c.length; + for (let i = 0; i < n; i++) { + let r1 = ((c[i] / 65536) | 0) % 256; + let g1 = ((c[i] / 256) | 0) % 256; + let b1 = c[i] % 256; + let a1 = ((c[i] / 16777216) | 0); + r += r1; + g += g1; + b += b1; + a += a1; + t += 1.0; + } + + t = 1 / t; + return Math.round(a * t) * 16777216 + Math.round(r * t) * 65536 + Math.round(g * t) * 256 + Math.round(b * t); + }; + + static mergeColorAlpha(c, alpha) { + let a = ((c / 16777216 | 0) * alpha) | 0; + return (((((c >> 16) & 0xff) * a) / 255) & 0xff) + + ((((c & 0xff00) * a) / 255) & 0xff00) + + (((((c & 0xff) << 16) * a) / 255) & 0xff0000) + + (a << 24); + }; + + static rad(deg) { + return deg * (Math.PI / 180); + }; + + static getTimingBezier(a, b, c, d) { + let xc = 3.0 * a; + let xb = 3.0 * (c - a) - xc; + let xa = 1.0 - xc - xb; + let yc = 3.0 * b; + let yb = 3.0 * (d - b) - yc; + let ya = 1.0 - yc - yb; + + return function (time) { + if (time >= 1.0) { + return 1; + } + if (time <= 0) { + return 0; + } + + let t = 0.5, cbx, cbxd, dx; + + for (let it = 0; it < 20; it++) { + cbx = t * (t * (t * xa + xb) + xc); + dx = time - cbx; + if (dx > -1e-8 && dx < 1e-8) { + return t * (t * (t * ya + yb) + yc); + } + + // Cubic bezier derivative. + cbxd = t * (t * (3 * xa) + 2 * xb) + xc; + + if (cbxd > 1e-10 && cbxd < 1e-10) { + // Problematic. Fall back to binary search method. + break; + } + + t += dx / cbxd; + } + + // Fallback: binary search method. This is more reliable when there are near-0 slopes. + let minT = 0; + let maxT = 1; + for (let it = 0; it < 20; it++) { + t = 0.5 * (minT + maxT); + + cbx = t * (t * (t * xa + xb) + xc); + + dx = time - cbx; + if (dx > -1e-8 && dx < 1e-8) { + // Solution found! + return t * (t * (t * ya + yb) + yc); + } + + if (dx < 0) { + maxT = t; + } else { + minT = t; + } + } + + }; + }; + + static getTimingFunction(str) { + switch (str) { + case "linear": + return function (time) { + return time + }; + case "ease": + return StageUtils.getTimingBezier(0.25, 0.1, 0.25, 1.0); + case "ease-in": + return StageUtils.getTimingBezier(0.42, 0, 1.0, 1.0); + case "ease-out": + return StageUtils.getTimingBezier(0, 0, 0.58, 1.0); + case "ease-in-out": + return StageUtils.getTimingBezier(0.42, 0, 0.58, 1.0); + case "step-start": + return function () { + return 1 + }; + case "step-end": + return function (time) { + return time === 1 ? 1 : 0; + }; + default: + let s = "cubic-bezier("; + if (str && str.indexOf(s) === 0) { + let parts = str.substr(s.length, str.length - s.length - 1).split(","); + if (parts.length !== 4) { + console.warn("[Lightning] Unknown timing function: " + str); + + // Fallback: use linear. + return function (time) { + return time + }; + } + let a = parseFloat(parts[0]); + let b = parseFloat(parts[1]); + let c = parseFloat(parts[2]); + let d = parseFloat(parts[3]); + if (isNaN(a) || isNaN(b) || isNaN(c) || isNaN(d)) { + console.warn("[Lightning] Unknown timing function: " + str); + // Fallback: use linear. + return function (time) { + return time + }; + } + + return StageUtils.getTimingBezier(a, b, c, d); + } else { + console.warn("[Lightning] Unknown timing function: " + str); + // Fallback: use linear. + return function (time) { + return time + }; + } + } + }; + +} + + +/***/ }), + +/***/ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/tree/Texture.mjs": +/*!************************************************************************************************!*\ + !*** ./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/tree/Texture.mjs ***! + \************************************************************************************************/ +/*! exports provided: default */ +/***/ (function(__webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return Texture; }); +/* harmony import */ var _Base_mjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./Base.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/tree/Base.mjs"); +/* + * If not stated otherwise in this file or this component's LICENSE file the + * following copyright and licenses apply: + * + * Copyright 2020 Metrological + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +class Texture { + + /** + * @param {Stage} stage + */ + constructor(stage) { + this.stage = stage; + + this.manager = this.stage.textureManager; + + this.id = Texture.id++; + + /** + * All enabled elements that use this texture object (either as texture or displayedTexture). + * @type {Set} + */ + this.elements = new Set(); + + /** + * The number of enabled elements that are active. + * @type {number} + */ + this._activeCount = 0; + + /** + * The associated texture source. + * Should not be changed. + * @type {TextureSource} + */ + this._source = null; + + /** + * A resize mode can be set to cover or contain a certain area. + * It will reset the texture clipping settings. + * When manual texture clipping is performed, the resizeMode is reset. + * @type {{type: string, width: number, height: number}} + * @private + */ + this._resizeMode = null; + + /** + * The texture clipping x-offset. + * @type {number} + */ + this._x = 0; + + /** + * The texture clipping y-offset. + * @type {number} + */ + this._y = 0; + + /** + * The texture clipping width. If 0 then full width. + * @type {number} + */ + this._w = 0; + + /** + * The texture clipping height. If 0 then full height. + * @type {number} + */ + this._h = 0; + + /** + * Render precision (0.5 = fuzzy, 1 = normal, 2 = sharp even when scaled twice, etc.). + * @type {number} + * @private + */ + this._precision = 1; + + /** + * The (maximum) expected texture source width. Used for within bounds determination while texture is not yet loaded. + * If not set, 2048 is used by ElementCore.update. + * @type {number} + */ + this.mw = 0; + + /** + * The (maximum) expected texture source height. Used for within bounds determination while texture is not yet loaded. + * If not set, 2048 is used by ElementCore.update. + * @type {number} + */ + this.mh = 0; + + /** + * Indicates if Texture.prototype.texture uses clipping. + * @type {boolean} + */ + this.clipping = false; + + /** + * Indicates whether this texture must update (when it becomes used again). + * @type {boolean} + * @private + */ + this._mustUpdate = true; + + } + + get source() { + if (this._mustUpdate || this.stage.hasUpdateSourceTexture(this)) { + this._performUpdateSource(true); + this.stage.removeUpdateSourceTexture(this); + } + return this._source; + } + + addElement(v) { + if (!this.elements.has(v)) { + this.elements.add(v); + + if (this.elements.size === 1) { + if (this._source) { + this._source.addTexture(this); + } + } + + if (v.active) { + this.incActiveCount(); + } + } + } + + removeElement(v) { + if (this.elements.delete(v)) { + if (this.elements.size === 0) { + if (this._source) { + this._source.removeTexture(this); + } + } + + if (v.active) { + this.decActiveCount(); + } + } + } + + incActiveCount() { + // Ensure that texture source's activeCount has transferred ownership. + const source = this.source; + + if (source) { + this._checkForNewerReusableTextureSource(); + } + + this._activeCount++; + if (this._activeCount === 1) { + this.becomesUsed(); + } + } + + decActiveCount() { + const source = this.source; // Force updating the source. + this._activeCount--; + if (!this._activeCount) { + this.becomesUnused(); + } + } + + becomesUsed() { + if (this.source) { + this.source.incActiveTextureCount(); + } + } + + onLoad() { + if (this._resizeMode) { + this._applyResizeMode(); + } + + this.elements.forEach(element => { + if (element.active) { + element.onTextureSourceLoaded(); + } + }); + } + + _checkForNewerReusableTextureSource() { + // When this source became unused and cleaned up, it may have disappeared from the reusable texture map. + // In the meantime another texture may have been generated loaded with the same lookup id. + // If this is the case, use that one instead to make sure only one active texture source per lookup id exists. + const source = this.source; + if (!source.isLoaded()) { + const reusable = this._getReusableTextureSource(); + if (reusable && reusable.isLoaded() && (reusable !== source)) { + this._replaceTextureSource(reusable); + } + } else { + if (this._resizeMode) { + this._applyResizeMode(); + } + } + } + + becomesUnused() { + if (this.source) { + this.source.decActiveTextureCount(); + } + } + + isUsed() { + return this._activeCount > 0; + } + + /** + * Returns the lookup id for the current texture settings, to be able to reuse it. + * @returns {string|null} + */ + _getLookupId() { + // Default: do not reuse texture. + return null; + } + + /** + * Generates a loader function that is able to generate the texture for the current settings of this texture. + * It should return a function that receives a single callback argument. + * That callback should be called with the following arguments: + * - err + * - options: object + * - source: ArrayBuffer|WebGlTexture|ImageData|HTMLImageElement|HTMLCanvasElement|HTMLVideoElement|ImageBitmap + * - w: Number + * - h: Number + * - permanent: Boolean + * - hasAlpha: boolean + * - permultiplyAlpha: boolean + * - flipBlueRed: boolean + * - renderInfo: object + * The loader itself may return a Function that is called when loading of the texture is cancelled. This can be used + * to stop fetching an image when it is no longer in element, for example. + */ + _getSourceLoader() { + throw new Error("Texture.generate must be implemented."); + } + + get isValid() { + return this._getIsValid(); + } + + /** + * If texture is not 'valid', no source can be created for it. + * @returns {boolean} + */ + _getIsValid() { + return true; + } + + /** + * This must be called when the texture source must be re-generated. + */ + _changed() { + // If no element is actively using this texture, ignore it altogether. + if (this.isUsed()) { + this._updateSource(); + } else { + this._mustUpdate = true; + } + } + + _updateSource() { + // We delay all updateSource calls to the next drawFrame, so that we can bundle them. + // Otherwise we may reload a texture more often than necessary, when, for example, patching multiple text + // properties. + this.stage.addUpdateSourceTexture(this); + } + + _performUpdateSource(force = false) { + // If, in the meantime, the texture was no longer used, just remember that it must update until it becomes used + // again. + if (force || this.isUsed()) { + this._mustUpdate = false; + let source = this._getTextureSource(); + this._replaceTextureSource(source); + } + } + + _getTextureSource() { + let source = null; + if (this._getIsValid()) { + const lookupId = this._getLookupId(); + source = this._getReusableTextureSource(lookupId); + if (!source) { + source = this.manager.getTextureSource(this._getSourceLoader(), lookupId); + } + } + return source; + } + + _getReusableTextureSource(lookupId = this._getLookupId()) { + if (this._getIsValid()) { + if (lookupId) { + return this.manager.getReusableTextureSource(lookupId); + } + } + return null; + } + + _replaceTextureSource(newSource = null) { + let oldSource = this._source; + + this._source = newSource; + + if (this.elements.size) { + if (oldSource) { + if (this._activeCount) { + oldSource.decActiveTextureCount(); + } + + oldSource.removeTexture(this); + + // free up unused TextTextures immediately as they are not reused anyway + if(this['text'] && !oldSource.isUsed()) { + this.manager.freeTextureSource(oldSource); + } + } + + if (newSource) { + // Must happen before setDisplayedTexture to ensure sprite map texcoords are used. + newSource.addTexture(this); + if (this._activeCount) { + newSource.incActiveTextureCount(); + } + } + } + + if (this.isUsed()) { + if (newSource) { + if (newSource.isLoaded()) { + + // Apply resizeMode + if (this._resizeMode) { + this._applyResizeMode(); + } + + this.elements.forEach(element => { + if (element.active) { + element._setDisplayedTexture(this); + } + }); + } else { + const loadError = newSource.loadError; + if (loadError) { + this.elements.forEach(element => { + if (element.active) { + element.onTextureSourceLoadError(loadError); + } + }); + } + } + } else { + this.elements.forEach(element => { + if (element.active) { + element._setDisplayedTexture(null); + } + }); + } + } + } + + load() { + // Make sure that source is up to date. + if (this.source) { + if (!this.isLoaded()) { + this.source.load(true); + } + } + } + + isLoaded() { + return this._source && this._source.isLoaded(); + } + + get loadError() { + return this._source && this._source.loadError; + } + + free() { + if (this._source) { + this._source.free(); + } + } + + set resizeMode({type = "cover", w = 0, h = 0, clipX = 0.5, clipY = 0.5}) { + this._resizeMode = {type, w, h, clipX, clipY}; + if (this.isLoaded()) { + this._applyResizeMode(); + } + } + + get resizeMode() { + return this._resizeMode; + } + + _clearResizeMode() { + this._resizeMode = null; + } + + _applyResizeMode() { + if (this._resizeMode.type === "cover") { + this._applyResizeCover(); + } else if (this._resizeMode.type === "contain") { + this._applyResizeContain(); + } + this._updatePrecision(); + this._updateClipping(); + } + + _applyResizeCover() { + const scaleX = this._resizeMode.w / this._source.w; + const scaleY = this._resizeMode.h / this._source.h; + let scale = Math.max(scaleX, scaleY); + if (!scale) return; + this._precision = 1/scale; + if (scaleX && scaleX < scale) { + const desiredSize = this._precision * this._resizeMode.w; + const choppedOffPixels = this._source.w - desiredSize; + this._x = choppedOffPixels * this._resizeMode.clipX; + this._w = this._source.w - choppedOffPixels; + } + if (scaleY && scaleY < scale) { + const desiredSize = this._precision * this._resizeMode.h; + const choppedOffPixels = this._source.h - desiredSize; + this._y = choppedOffPixels * this._resizeMode.clipY; + this._h = this._source.h - choppedOffPixels; + } + } + + _applyResizeContain() { + const scaleX = this._resizeMode.w / this._source.w; + const scaleY = this._resizeMode.h / this._source.h; + let scale = scaleX; + if (!scale || scaleY < scale) { + scale = scaleY; + } + if (!scale) return; + this._precision = 1/scale; + } + + enableClipping(x, y, w, h) { + this._clearResizeMode(); + + x *= this._precision; + y *= this._precision; + w *= this._precision; + h *= this._precision; + if (this._x !== x || this._y !== y || this._w !== w || this._h !== h) { + this._x = x; + this._y = y; + this._w = w; + this._h = h; + + this._updateClipping(true); + } + } + + disableClipping() { + this._clearResizeMode(); + + if (this._x || this._y || this._w || this._h) { + this._x = 0; + this._y = 0; + this._w = 0; + this._h = 0; + + this._updateClipping(); + } + } + + _updateClipping() { + this.clipping = !!(this._x || this._y || this._w || this._h); + + let self = this; + this.elements.forEach(function(element) { + // Ignore if not the currently displayed texture. + if (element.displayedTexture === self) { + element.onDisplayedTextureClippingChanged(); + } + }); + } + + _updatePrecision() { + let self = this; + this.elements.forEach(function(element) { + // Ignore if not the currently displayed texture. + if (element.displayedTexture === self) { + element.onPrecisionChanged(); + } + }); + } + + getNonDefaults() { + let nonDefaults = {}; + nonDefaults['type'] = this.constructor.name; + if (this.x !== 0) nonDefaults['x'] = this.x; + if (this.y !== 0) nonDefaults['y'] = this.y; + if (this.w !== 0) nonDefaults['w'] = this.w; + if (this.h !== 0) nonDefaults['h'] = this.h; + if (this.precision !== 1) nonDefaults['precision'] = this.precision; + return nonDefaults; + } + + get px() { + return this._x; + } + + get py() { + return this._y; + } + + get pw() { + return this._w; + } + + get ph() { + return this._h; + } + + get x() { + return this._x / this._precision; + } + set x(v) { + this._clearResizeMode(); + v = v * this._precision; + if (this._x !== v) { + this._x = v; + this._updateClipping(); + } + } + + get y() { + return this._y / this._precision; + } + set y(v) { + this._clearResizeMode(); + v = v * this._precision; + if (this._y !== v) { + this._y = v; + this._updateClipping(); + } + } + + get w() { + return this._w / this._precision; + } + + set w(v) { + this._clearResizeMode(); + v = v * this._precision; + if (this._w !== v) { + this._w = v; + this._updateClipping(); + } + } + + get h() { + return this._h / this._precision; + } + + set h(v) { + this._clearResizeMode(); + v = v * this._precision; + if (this._h !== v) { + this._h = v; + this._updateClipping(); + } + } + + get precision() { + return this._precision; + } + + set precision(v) { + this._clearResizeMode(); + if (this._precision !== v) { + this._precision = v; + this._updatePrecision(); + } + } + + isAutosizeTexture() { + return true; + } + + getRenderWidth() { + if (!this.isAutosizeTexture()) { + // In case of the rectangle texture, we'd prefer to not cause a 1x1 w,h as it would interfere with flex layout fit-to-contents. + return 0; + } + + // If dimensions are unknown (texture not yet loaded), use maximum width as a fallback as render width to allow proper bounds checking. + return (this._w || (this._source ? this._source.getRenderWidth() - this._x : 0)) / this._precision; + } + + getRenderHeight() { + if (!this.isAutosizeTexture()) { + // In case of the rectangle texture, we'd prefer to not cause a 1x1 w,h as it would interfere with flex layout fit-to-contents. + return 0; + } + + return (this._h || (this._source ? this._source.getRenderHeight() - this._y : 0)) / this._precision; + } + + patch(settings) { + _Base_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].patchObject(this, settings); + } + +} + +Texture.prototype.isTexture = true; + +Texture.id = 0; + + + + +/***/ }), + +/***/ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/tree/TextureManager.mjs": +/*!*******************************************************************************************************!*\ + !*** ./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/tree/TextureManager.mjs ***! + \*******************************************************************************************************/ +/*! exports provided: default */ +/***/ (function(__webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return TextureManager; }); +/* harmony import */ var _TextureSource_mjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./TextureSource.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/tree/TextureSource.mjs"); +/* harmony import */ var _Stage_mjs__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./Stage.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/tree/Stage.mjs"); +/* + * If not stated otherwise in this file or this component's LICENSE file the + * following copyright and licenses apply: + * + * Copyright 2020 Metrological + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + + +class TextureManager { + + constructor(stage) { + this.stage = stage; + + /** + * The currently used amount of texture memory. + * @type {number} + */ + this._usedMemory = 0; + + /** + * All uploaded texture sources. + * @type {TextureSource[]} + */ + this._uploadedTextureSources = []; + + /** + * The texture source lookup id to texture source hashmap. + * @type {Map} + */ + this.textureSourceHashmap = new Map(); + + } + + get usedMemory() { + return this._usedMemory; + } + + destroy() { + for (let i = 0, n = this._uploadedTextureSources.length; i < n; i++) { + this._nativeFreeTextureSource(this._uploadedTextureSources[i]); + } + + this.textureSourceHashmap.clear(); + this._usedMemory = 0; + } + + getReusableTextureSource(id) { + return this.textureSourceHashmap.get(id); + } + + getTextureSource(func, id) { + // Check if texture source is already known. + let textureSource = id ? this.textureSourceHashmap.get(id) : null; + if (!textureSource) { + // Create new texture source. + textureSource = new _TextureSource_mjs__WEBPACK_IMPORTED_MODULE_0__["default"](this, func); + + if (id) { + textureSource.lookupId = id; + this.textureSourceHashmap.set(id, textureSource); + } + } + + return textureSource; + } + + uploadTextureSource(textureSource, options) { + if (textureSource.isLoaded()) return; + + this._addMemoryUsage(textureSource.w * textureSource.h); + + // Load texture. + const nativeTexture = this._nativeUploadTextureSource(textureSource, options); + + textureSource._nativeTexture = nativeTexture; + + // We attach w and h to native texture (we need it in CoreRenderState._isRenderTextureReusable). + nativeTexture.w = textureSource.w; + nativeTexture.h = textureSource.h; + + nativeTexture.update = this.stage.frameCounter; + + this._uploadedTextureSources.push(textureSource); + + this.addToLookupMap(textureSource); + + // add VRAM tracking if using the webgl renderer + this._updateVramUsage(textureSource, 1); + } + + _addMemoryUsage(delta) { + this._usedMemory += delta; + this.stage.addMemoryUsage(delta); + } + + _updateVramUsage(textureSource, sign) { + const nativeTexture = textureSource.nativeTexture; + var usage; + + // do nothing if webgl isn't even supported + if (!_Stage_mjs__WEBPACK_IMPORTED_MODULE_1__["default"].isWebglSupported()) + return; + + // or if there is no native texture + if (!textureSource.isLoaded()) + return; + + // or, finally, if there is no bytes per pixel specified + if (!nativeTexture.hasOwnProperty('bytesPerPixel') || isNaN(nativeTexture.bytesPerPixel)) + return; + + usage = sign * (textureSource.w * textureSource.h * nativeTexture.bytesPerPixel); + + this.stage.addVramUsage(usage, textureSource.hasAlpha); + } + + addToLookupMap(textureSource) { + const lookupId = textureSource.lookupId; + if (lookupId) { + if (!this.textureSourceHashmap.has(lookupId)) { + this.textureSourceHashmap.set(lookupId, textureSource); + } + } + } + + gc() { + this.freeUnusedTextureSources(); + } + + freeUnusedTextureSources() { + let remainingTextureSources = []; + for (let i = 0, n = this._uploadedTextureSources.length; i < n; i++) { + let ts = this._uploadedTextureSources[i]; + if (ts.allowCleanup()) { + this._freeManagedTextureSource(ts); + } else { + remainingTextureSources.push(ts); + } + } + + this._uploadedTextureSources = remainingTextureSources; + + this._cleanupLookupMap(); + } + + _freeManagedTextureSource(textureSource) { + if (textureSource.isLoaded()) { + this._nativeFreeTextureSource(textureSource); + this._addMemoryUsage(-textureSource.w * textureSource.h); + + // add VRAM tracking if using the webgl renderer + this._updateVramUsage(textureSource, -1); + } + + // Should be reloaded. + textureSource.loadingSince = null; + } + + _cleanupLookupMap() { + // We keep those that still have value (are being loaded or already loaded, or are likely to be reused). + this.textureSourceHashmap.forEach((textureSource, lookupId) => { + if (!(textureSource.isLoaded() || textureSource.isLoading()) && !textureSource.isUsed()) { + this.textureSourceHashmap.delete(lookupId); + } + }); + } + + /** + * Externally free texture source. + * @param textureSource + */ + freeTextureSource(textureSource) { + const index = this._uploadedTextureSources.indexOf(textureSource); + const managed = (index !== -1); + + if (textureSource.isLoaded()) { + if (managed) { + this._addMemoryUsage(-textureSource.w * textureSource.h); + this._uploadedTextureSources.splice(index, 1); + } + this._nativeFreeTextureSource(textureSource); + } + + // Should be reloaded. + textureSource.loadingSince = null; + } + + _nativeUploadTextureSource(textureSource, options) { + return this.stage.renderer.uploadTextureSource(textureSource, options); + } + + _nativeFreeTextureSource(textureSource) { + this.stage.renderer.freeTextureSource(textureSource); + textureSource.clearNativeTexture(); + } + +} + + +/***/ }), + +/***/ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/tree/TextureSource.mjs": +/*!******************************************************************************************************!*\ + !*** ./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/tree/TextureSource.mjs ***! + \******************************************************************************************************/ +/*! exports provided: default */ +/***/ (function(__webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return TextureSource; }); +/* harmony import */ var _Utils_mjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./Utils.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/tree/Utils.mjs"); +/* + * If not stated otherwise in this file or this component's LICENSE file the + * following copyright and licenses apply: + * + * Copyright 2020 Metrological + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +class TextureSource { + + constructor(manager, loader = null) { + this.id = TextureSource.id++; + + this.manager = manager; + + this.stage = manager.stage; + + /** + * All enabled textures (textures that are used by visible elements). + * @type {Set} + */ + this.textures = new Set(); + + /** + * The number of active textures (textures that have at least one active element). + * @type {number} + * @private + */ + this._activeTextureCount = 0; + + /** + * The factory for the source of this texture. + * @type {Function} + */ + this.loader = loader; + + /** + * Identifier for reuse. + * @type {String} + */ + this.lookupId = null; + + /** + * If set, this.is called when the texture source is no longer displayed (this.components.size becomes 0). + * @type {Function} + */ + this._cancelCb = null; + + /** + * Loading since timestamp in millis. + * @type {number} + */ + this.loadingSince = 0; + + this.w = 0; + this.h = 0; + + this._nativeTexture = null; + + /** + * If true, then this.texture source is never freed from memory during garbage collection. + * @type {boolean} + */ + this.permanent = false; + + /** + * Sub-object with texture-specific rendering information. + * For images, contains the src property, for texts, contains handy rendering information. + * @type {Object} + */ + this.renderInfo = null; + + /** + * Generated for 'renderToTexture'. + * @type {boolean} + * @private + */ + this._isResultTexture = !this.loader; + + /** + * Contains the load error, if the texture source could previously not be loaded. + * @type {object} + * @private + */ + this._loadError = null; + + /** + * Hold a reference to the javascript variable which contains the texture, this is not required for WebGL in WebBrowsers but is required for Spark runtime. + * @type {object} + * @private + */ + this._imageRef = null; + + + /** + * Track whether or not there is an alpha channel in this source + * @type {boolean} + * @private + */ + this._hasAlpha = false; + } + + get hasAlpha() { + return this._hasAlpha; + } + + get loadError() { + return this._loadError; + } + + addTexture(v) { + if (!this.textures.has(v)) { + this.textures.add(v); + } + } + + removeTexture(v) { + this.textures.delete(v); + } + + incActiveTextureCount() { + this._activeTextureCount++; + if (this._activeTextureCount === 1) { + this.becomesUsed(); + } + } + + decActiveTextureCount() { + this._activeTextureCount--; + if (this._activeTextureCount === 0) { + this.becomesUnused(); + } + } + + get isResultTexture() { + return this._isResultTexture; + } + + set isResultTexture(v) { + this._isResultTexture = v; + } + + forEachEnabledElement(cb) { + this.textures.forEach(texture => { + texture.elements.forEach(cb); + }); + } + + hasEnabledElements() { + return this.textures.size > 0; + } + + forEachActiveElement(cb) { + this.textures.forEach(texture => { + texture.elements.forEach(element => { + if (element.active) { + cb(element); + } + }); + }); + } + + getRenderWidth() { + return this.w; + } + + getRenderHeight() { + return this.h; + } + + allowCleanup() { + return !this.permanent && !this.isUsed(); + } + + becomesUsed() { + // Even while the texture is being loaded, make sure it is on the lookup map so that others can reuse it. + this.load(); + } + + becomesUnused() { + this.cancel(); + } + + cancel() { + if (this.isLoading()) { + if (this._cancelCb) { + this._cancelCb(this); + + // Clear callback to avoid memory leaks. + this._cancelCb = null; + } + this.loadingSince = 0; + } + } + + isLoaded() { + return !!this._nativeTexture; + } + + isLoading() { + return (this.loadingSince > 0); + } + + isError() { + return !!this._loadError; + } + + reload() { + this.free(); + if (this.isUsed()) { + this.load(); + } + } + + load(forceSync = false) { + // From the moment of loading (when a texture source becomes used by active elements) + if (this.isResultTexture) { + // Element result texture source, for which the loading is managed by the core. + return; + } + + if (!this._nativeTexture && !this.isLoading()) { + this.loadingSince = (new Date()).getTime(); + this._cancelCb = this.loader((err, options) => { + // Ignore loads that come in after a cancel. + if (this.isLoading()) { + // Clear callback to avoid memory leaks. + this._cancelCb = null; + + if (this.manager.stage.destroyed) { + // Ignore async load when stage is destroyed. + return; + } + if (err) { + // Emit txError. + this.onError(err); + } else if (options && options.source) { + if (!this.stage.isUpdatingFrame() && !forceSync && (options.throttle !== false)) { + const textureThrottler = this.stage.textureThrottler; + this._cancelCb = textureThrottler.genericCancelCb; + textureThrottler.add(this, options); + } else { + this.processLoadedSource(options); + } + } + } + }, this); + } + } + + processLoadedSource(options) { + this.loadingSince = 0; + this.setSource(options); + } + + setSource(options) { + const source = options.source; + + this._hasAlpha = (options ? (options.hasAlpha || false) : false); + this.w = source.width || (options && options.w) || 0; + this.h = source.height || (options && options.h) || 0; + + if (options && options.renderInfo) { + // Assign to id in cache so that it can be reused. + this.renderInfo = options.renderInfo; + } + + this.permanent = !!options.permanent; + + if (options && options.imageRef) + this._imageRef = options.imageRef; + if (options && options.flipTextureY) { + this._flipTextureY = options.flipTextureY; + } else { + this._flipTextureY = false; + } + + if (this._isNativeTexture(source)) { + // Texture managed by caller. + this._nativeTexture = source; + + this.w = this.w || source.w; + this.h = this.h || source.h; + + // WebGLTexture objects are by default; + this.permanent = options.hasOwnProperty('permanent') ? options.permanent : true; + } else { + this.manager.uploadTextureSource(this, options); + } + + // Must be cleared when reload is succesful. + this._loadError = null; + + this.onLoad(); + } + + isUsed() { + return this._activeTextureCount > 0; + } + + onLoad() { + if (this.isUsed()) { + this.textures.forEach(texture => { + texture.onLoad(); + }); + } + } + + forceRenderUpdate() { + // Userland should call this method after changing the nativeTexture manually outside of the framework + // (using tex[Sub]Image2d for example). + + if (this._nativeTexture) { + // Change 'update' flag. This is currently not used by the framework but is handy in userland. + this._nativeTexture.update = this.stage.frameCounter; + } + + this.forEachActiveElement(function (element) { + element.forceRenderUpdate(); + }); + + } + + forceUpdateRenderCoords() { + this.forEachActiveElement(function (element) { + element._updateTextureCoords(); + }); + } + + get nativeTexture() { + return this._nativeTexture; + } + + clearNativeTexture() { + this._nativeTexture = null; + //also clear the reference to the texture variable. + this._imageRef = null; + } + + /** + * Used for result textures. + */ + replaceNativeTexture(newNativeTexture, w, h) { + let prevNativeTexture = this._nativeTexture; + // Loaded by core. + this._nativeTexture = newNativeTexture; + this.w = w; + this.h = h; + + if (!prevNativeTexture && this._nativeTexture) { + this.forEachActiveElement(element => element.onTextureSourceLoaded()); + } + + if (!this._nativeTexture) { + this.forEachActiveElement(element => element._setDisplayedTexture(null)); + } + + // Dimensions must be updated also on enabled elements, as it may force it to go within bounds. + this.forEachEnabledElement(element => element._updateDimensions()); + + // Notice that the sprite map must never contain render textures. + } + + onError(e) { + this._loadError = e; + this.loadingSince = 0; + console.error('[Lightning] texture load error', e, this.lookupId); + this.forEachActiveElement(element => element.onTextureSourceLoadError(e)); + } + + free() { + if (this.isLoaded()) { + this.manager.freeTextureSource(this); + } + } + + _isNativeTexture(source) { + if (_Utils_mjs__WEBPACK_IMPORTED_MODULE_0__["default"].isNode) { + return source.constructor.name === "WebGLTexture"; + } + + if ('WebGLTexture' in window) { + return source instanceof WebGLTexture; + } + + return false; + } + +} + +TextureSource.prototype.isTextureSource = true; + +TextureSource.id = 1; + + + + +/***/ }), + +/***/ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/tree/TextureThrottler.mjs": +/*!*********************************************************************************************************!*\ + !*** ./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/tree/TextureThrottler.mjs ***! + \*********************************************************************************************************/ +/*! exports provided: default */ +/***/ (function(__webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return TextureThrottler; }); +/* + * If not stated otherwise in this file or this component's LICENSE file the + * following copyright and licenses apply: + * + * Copyright 2020 Metrological + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * Allows throttling of loading texture sources, keeping the app responsive. + */ +class TextureThrottler { + + constructor(stage) { + this.stage = stage; + + this.genericCancelCb = (textureSource) => { + this._remove(textureSource); + }; + + this._sources = []; + this._data = []; + } + + destroy() { + this._sources = []; + this._data = []; + this.stage = null; + + delete this._sources; + delete this._data; + delete this.stage; + } + + processSome() { + if (this._sources.length) { + const start = Date.now(); + do { + this._processItem(); + } while(this._sources.length && (Date.now() - start < TextureThrottler.MAX_UPLOAD_TIME_PER_FRAME)); + } + } + + _processItem() { + const source = this._sources.pop(); + const data = this._data.pop(); + if (source.isLoading()) { + source.processLoadedSource(data); + } + } + + add(textureSource, data) { + this._sources.push(textureSource); + this._data.push(data); + } + + _remove(textureSource) { + const index = this._sources.indexOf(textureSource); + if (index >= 0) { + this._sources.splice(index, 1); + this._data.splice(index, 1); + } + } + +} + +TextureThrottler.MAX_UPLOAD_TIME_PER_FRAME = 10; + + +/***/ }), + +/***/ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/tree/Utils.mjs": +/*!**********************************************************************************************!*\ + !*** ./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/tree/Utils.mjs ***! + \**********************************************************************************************/ +/*! exports provided: default */ +/***/ (function(__webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return Utils; }); +/* + * If not stated otherwise in this file or this component's LICENSE file the + * following copyright and licenses apply: + * + * Copyright 2020 Metrological + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +class Utils { + + static isFunction(value) { + return typeof value === 'function'; + } + + static isNumber(value) { + return typeof value === 'number'; + } + + static isInteger(value) { + return (typeof value === 'number' && (value % 1) === 0); + } + + static isBoolean(value) { + return value === true || value === false; + } + + static isString(value) { + return typeof value === 'string'; + } + + static clone(v) { + if (Utils.isObjectLiteral(v) || Array.isArray(v)) { + return Utils.getDeepClone(v); + } else { + // Copy by value. + return v; + } + } + + static cloneObjShallow(obj) { + let keys = Object.keys(obj); + let clone = {} + for (let i = 0; i < keys.length; i++) { + clone[keys[i]] = obj[keys[i]]; + } + return clone; + } + + static merge(obj1, obj2) { + let keys = Object.keys(obj2); + for (let i = 0; i < keys.length; i++) { + obj1[keys[i]] = obj2[keys[i]]; + } + return obj1; + } + + static isObject(value) { + let type = typeof value; + return !!value && (type === 'object' || type === 'function'); + } + + static isPlainObject(value) { + let type = typeof value; + return !!value && (type === 'object'); + } + + static isObjectLiteral(value){ + return typeof value === 'object' && value && value.constructor === Object; + } + + static getArrayIndex(index, arr) { + return Utils.getModuloIndex(index, arr.length); + } + + static getModuloIndex(index, len) { + if (len === 0) return index; + while (index < 0) { + index += Math.ceil(-index / len) * len; + } + index = index % len; + return index; + } + + static getDeepClone(obj) { + let i, c; + if (Utils.isFunction(obj)) { + // Copy functions by reference. + return obj; + } + if (Array.isArray(obj)) { + c = []; + let keys = Object.keys(obj); + for (i = 0; i < keys.length; i++) { + c[keys[i]] = Utils.getDeepClone(obj[keys[i]]); + } + return c; + } else if (Utils.isObject(obj)) { + c = {} + let keys = Object.keys(obj); + for (i = 0; i < keys.length; i++) { + c[keys[i]] = Utils.getDeepClone(obj[keys[i]]); + } + return c; + } else { + return obj; + } + } + + static equalValues(v1, v2) { + if ((typeof v1) !== (typeof v2)) return false; + if (Utils.isObjectLiteral(v1)) { + return Utils.isObjectLiteral(v2) && Utils.equalObjectLiterals(v1, v2); + } else if (Array.isArray(v1)) { + return Array.isArray(v2) && Utils.equalArrays(v1, v2); + } else { + return v1 === v2; + } + } + + static equalObjectLiterals(obj1, obj2) { + let keys1 = Object.keys(obj1); + let keys2 = Object.keys(obj2); + if (keys1.length !== keys2.length) { + return false; + } + + for (let i = 0, n = keys1.length; i < n; i++) { + const k1 = keys1[i]; + const k2 = keys2[i]; + if (k1 !== k2) { + return false; + } + + const v1 = obj1[k1]; + const v2 = obj2[k2]; + + if (!Utils.equalValues(v1, v2)) { + return false; + } + } + + return true; + } + + static equalArrays(v1, v2) { + if (v1.length !== v2.length) { + return false; + } + for (let i = 0, n = v1.length; i < n; i++) { + if (!this.equalValues(v1[i], v2[i])) { + return false; + } + } + + return true; + } + + static setToArray(s) { + let result = []; + s.forEach(function (value) { + result.push(value); + }); + return result; + } + + static iteratorToArray(iterator) { + let result = []; + let iteratorResult = iterator.next(); + while (!iteratorResult.done) { + result.push(iteratorResult.value); + iteratorResult = iterator.next(); + } + return result; + } + + static isUcChar(charcode) { + return charcode >= 65 && charcode <= 90; + } + +} + +Utils.isWeb = (typeof window !== "undefined") && (typeof sparkscene === "undefined"); +Utils.isWPE = Utils.isWeb && (navigator.userAgent.indexOf("WPE") !== -1); +Utils.isSpark = (typeof sparkscene !== "undefined"); +Utils.isNode = (typeof window === "undefined") || Utils.isSpark; +Utils.isPS4 = Utils.isWeb && (navigator.userAgent.indexOf("PlayStation 4") !== -1); +Utils.isZiggo = Utils.isWeb && (navigator.userAgent.indexOf("EOSSTB") !== -1 || navigator.userAgent.indexOf("HZNSTB") !== -1); + + +/***/ }), + +/***/ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/tree/core/CoreContext.mjs": +/*!*********************************************************************************************************!*\ + !*** ./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/tree/core/CoreContext.mjs ***! + \*********************************************************************************************************/ +/*! exports provided: default */ +/***/ (function(__webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return CoreContext; }); +/* + * If not stated otherwise in this file or this component's LICENSE file the + * following copyright and licenses apply: + * + * Copyright 2020 Metrological + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +class CoreContext { + + constructor(stage) { + this.stage = stage; + + this.root = null; + + this.updateTreeOrder = 0; + + this.renderState = this.stage.renderer.createCoreRenderState(this); + + this.renderExec = this.stage.renderer.createCoreRenderExecutor(this); + this.renderExec.init(); + + this._usedMemory = 0; + this._renderTexturePool = []; + + this._renderTextureId = 1; + + this._zSorts = []; + + this.renderToTextureCount = 0; + } + + get usedMemory() { + return this._usedMemory; + } + + destroy() { + this._renderTexturePool.forEach(texture => this._freeRenderTexture(texture)); + this._usedMemory = 0; + + this.stage = null; + this.root = null; + + this.renderState = null; + this.renderExec = null; + this._renderTexturePool = null; + this._zSorts = null; + + delete this.stage; + delete this.root; + delete this.renderState; + delete this.renderExec; + delete this._renderTexturePool; + delete this._zSorts; + } + + hasRenderUpdates() { + return !!this.root._parent._hasRenderUpdates; + } + + render() { + // Clear flag to identify if anything changes before the next frame. + this.root._parent._hasRenderUpdates = 0; + + this._render(); + } + + update() { + this._update(); + + // Due to the boundsVisibility flag feature (and onAfterUpdate hook), it is possible that other elements were + // changed during the update loop (for example due to the txLoaded event). We process these changes immediately + // (but not recursively to prevent infinite loops). + if (this.root._hasUpdates) { + this._update(); + } + + this._performForcedZSorts(); + } + + /** + * Certain ElementCore items may be forced to zSort to strip out references to prevent memleaks.. + */ + _performForcedZSorts() { + const n = this._zSorts.length; + if (n) { + // Forced z-sorts (ElementCore may force a z-sort in order to free memory/prevent memory leaks). + for (let i = 0, n = this._zSorts.length; i < n; i++) { + if (this._zSorts[i].zSort) { + this._zSorts[i].sortZIndexedChildren(); + } + } + this._zSorts = []; + } + } + + _update() { + this.updateTreeOrder = 0; + + this.root.update(); + } + + _render() { + const debugFrame = this.stage.getOption('debugFrame'); + // Obtain a sequence of the quad operations. + this._fillRenderState(); + + if (this.stage.getOption('readPixelsBeforeDraw')) { + this._readPixels(); + } + + // Now run them with the render executor. + this._performRender(); + + if (debugFrame) { + console.log(`[Lightning] RTT Renders in frame: ${this.renderToTextureCount}`) + } + + // Block OpenGL pipeline to prevent framebuffer flickering + // on certain devices + if (this.stage.getOption('readPixelsAfterDraw') && + this.renderToTextureCount >= this.stage.getOption('readPixelsAfterDrawThreshold') + ) { + if (debugFrame) { + console.log(`[Lightning] readPixelsAfterDraw behavior triggered`) + } + this._readPixels(); + } + + this.renderToTextureCount = 0; + } + + _readPixels() { + const pixels = new Uint8Array(4); + const gl = this.stage.gl; + gl.readPixels(0, 0, 1, 1, gl.RGBA, gl.UNSIGNED_BYTE, pixels); + } + + _fillRenderState() { + this.renderState.reset(); + this.root.render(); + this.renderState.finish(); + } + + _performRender() { + this.renderExec.execute(); + } + + _addMemoryUsage(delta) { + this._usedMemory += delta; + this.stage.addMemoryUsage(delta); + } + + allocateRenderTexture(w, h) { + let prec = this.stage.getRenderPrecision(); + let pw = Math.max(1, Math.round(w * prec)); + let ph = Math.max(1, Math.round(h * prec)); + + // Search last item first, so that last released render texture is preferred (may cause memory cache benefits). + const n = this._renderTexturePool.length; + for (let i = n - 1; i >= 0; i--) { + const texture = this._renderTexturePool[i]; + // We don't want to reuse the same render textures within the same frame because that will create gpu stalls. + if (texture.w === pw && texture.h === ph && (texture.update !== this.stage.frameCounter)) { + texture.f = this.stage.frameCounter; + this._renderTexturePool.splice(i, 1); + return texture; + } + } + + const texture = this._createRenderTexture(w, h, pw, ph); + texture.precision = prec; + return texture; + } + + releaseRenderTexture(texture) { + this._renderTexturePool.push(texture); + } + + freeUnusedRenderTextures(maxAge = 60) { + // Clean up all textures that are no longer used. + // This cache is short-lived because it is really just meant to supply running shaders that are + // updated during a number of frames. + let limit = this.stage.frameCounter - maxAge; + + this._renderTexturePool = this._renderTexturePool.filter(texture => { + if (texture.f <= limit) { + this._freeRenderTexture(texture); + return false; + } + return true; + }); + } + + _createRenderTexture(w, h, pw, ph) { + this._addMemoryUsage(pw * ph); + + const texture = this.stage.renderer.createRenderTexture(w, h, pw, ph); + texture.id = this._renderTextureId++; + texture.f = this.stage.frameCounter; + texture.ow = w; + texture.oh = h; + texture.w = pw; + texture.h = ph; + + return texture; + } + + _freeRenderTexture(nativeTexture) { + this.stage.renderer.freeRenderTexture(nativeTexture); + this._addMemoryUsage(-nativeTexture.w * nativeTexture.h); + } + + copyRenderTexture(renderTexture, nativeTexture, options) { + this.stage.renderer.copyRenderTexture(renderTexture, nativeTexture, options); + } + + forceZSort(elementCore) { + this._zSorts.push(elementCore); + } + +} + + +/***/ }), + +/***/ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/tree/core/CoreQuadList.mjs": +/*!**********************************************************************************************************!*\ + !*** ./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/tree/core/CoreQuadList.mjs ***! + \**********************************************************************************************************/ +/*! exports provided: default */ +/***/ (function(__webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return CoreQuadList; }); +/* + * If not stated otherwise in this file or this component's LICENSE file the + * following copyright and licenses apply: + * + * Copyright 2020 Metrological + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +class CoreQuadList { + + constructor(ctx) { + + this.ctx = ctx; + + this.quadTextures = []; + + this.quadElements = []; + } + + get length() { + return this.quadTextures.length; + } + + reset() { + this.quadTextures = []; + this.quadElements = []; + this.dataLength = 0; + } + + getElement(index) { + return this.quadElements[index]._element; + } + + getElementCore(index) { + return this.quadElements[index]; + } + + getTexture(index) { + return this.quadTextures[index]; + } + + getTextureWidth(index) { + let nativeTexture = this.quadTextures[index]; + if (nativeTexture.w) { + // Render texture; + return nativeTexture.w; + } else { + return this.quadElements[index]._displayedTextureSource.w; + } + } + + getTextureHeight(index) { + let nativeTexture = this.quadTextures[index]; + if (nativeTexture.h) { + // Render texture; + return nativeTexture.h; + } else { + return this.quadElements[index]._displayedTextureSource.h; + } + } + +} + + +/***/ }), + +/***/ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/tree/core/CoreQuadOperation.mjs": +/*!***************************************************************************************************************!*\ + !*** ./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/tree/core/CoreQuadOperation.mjs ***! + \***************************************************************************************************************/ +/*! exports provided: default */ +/***/ (function(__webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return CoreQuadOperation; }); +/* + * If not stated otherwise in this file or this component's LICENSE file the + * following copyright and licenses apply: + * + * Copyright 2020 Metrological + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +class CoreQuadOperation { + + constructor(ctx, shader, shaderOwner, renderTextureInfo, scissor, index) { + + this.ctx = ctx; + this.shader = shader; + this.shaderOwner = shaderOwner; + this.renderTextureInfo = renderTextureInfo; + this.scissor = scissor; + this.index = index; + this.length = 0; + + } + + get quads() { + return this.ctx.renderState.quads; + } + + getTexture(index) { + return this.quads.getTexture(this.index + index); + } + + getElementCore(index) { + return this.quads.getElementCore(this.index + index); + } + + getElement(index) { + return this.quads.getElement(this.index + index); + } + + getElementWidth(index) { + return this.getElement(index).renderWidth; + } + + getElementHeight(index) { + return this.getElement(index).renderHeight; + } + + getTextureWidth(index) { + return this.quads.getTextureWidth(this.index + index); + } + + getTextureHeight(index) { + return this.quads.getTextureHeight(this.index + index); + } + + getRenderWidth() { + if (this.renderTextureInfo) { + return this.renderTextureInfo.w; + } else { + return this.ctx.stage.w; + } + } + + getRenderHeight() { + if (this.renderTextureInfo) { + return this.renderTextureInfo.h; + } else { + return this.ctx.stage.h; + } + } + +} + + +/***/ }), + +/***/ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/tree/core/CoreRenderExecutor.mjs": +/*!****************************************************************************************************************!*\ + !*** ./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/tree/core/CoreRenderExecutor.mjs ***! + \****************************************************************************************************************/ +/*! exports provided: default */ +/***/ (function(__webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return CoreRenderExecutor; }); +/* + * If not stated otherwise in this file or this component's LICENSE file the + * following copyright and licenses apply: + * + * Copyright 2020 Metrological + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +class CoreRenderExecutor { + + constructor(ctx) { + this.ctx = ctx; + + this.renderState = ctx.renderState; + + this.gl = this.ctx.stage.gl; + } + + destroy() { + this.ctx = null; + this.renderState = null; + this.gl = null; + + delete this.ctx; + delete this.renderState; + delete this.gl; + } + + _reset() { + this._bindRenderTexture(null); + this._setScissor(null); + this._clearRenderTexture(); + } + + execute() { + this._reset(); + + let qops = this.renderState.quadOperations; + + let i = 0, j = 0, n = qops.length; + while (i < n) { + this._processQuadOperation(qops[i]); + i++; + } + } + + _processQuadOperation(quadOperation) { + if (quadOperation.renderTextureInfo && quadOperation.renderTextureInfo.ignore) { + // Ignore quad operations when we are 're-using' another texture as the render texture result. + return; + } + + this._setupQuadOperation(quadOperation); + this._execQuadOperation(quadOperation); + + } + + _setupQuadOperation(quadOperation) { + } + + _execQuadOperation(op) { + // Set render texture. + let nativeTexture = op.renderTextureInfo ? op.renderTextureInfo.nativeTexture : null; + + if (this._renderTexture !== nativeTexture) { + this._bindRenderTexture(nativeTexture); + } + + if (op.renderTextureInfo && !op.renderTextureInfo.cleared) { + this._setScissor(null); + this._clearRenderTexture(); + op.renderTextureInfo.cleared = true; + this._setScissor(op.scissor); + } else { + this._setScissor(op.scissor); + } + + this._renderQuadOperation(op); + } + + _renderQuadOperation(op) { + } + + _bindRenderTexture(renderTexture) { + this._renderTexture = renderTexture; + } + + _clearRenderTexture(renderTexture) { + } + + _setScissor(area) { + } + +} + + + +/***/ }), + +/***/ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/tree/core/CoreRenderState.mjs": +/*!*************************************************************************************************************!*\ + !*** ./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/tree/core/CoreRenderState.mjs ***! + \*************************************************************************************************************/ +/*! exports provided: default */ +/***/ (function(__webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return CoreRenderState; }); +/* + * If not stated otherwise in this file or this component's LICENSE file the + * following copyright and licenses apply: + * + * Copyright 2020 Metrological + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +class CoreRenderState { + + constructor(ctx) { + this.ctx = ctx; + + this.stage = ctx.stage; + + this.defaultShader = this.stage.renderer.getDefaultShader(ctx); + + this.renderer = ctx.stage.renderer; + + this.quads = this.renderer.createCoreQuadList(ctx); + + } + + reset() { + this._renderTextureInfo = null; + + this._scissor = null; + + this._shader = null; + + this._shaderOwner = null; + + this._realShader = null; + + this._check = false; + + this.quadOperations = []; + + this._texturizer = null; + + this._texturizerTemporary = false; + + this._quadOperation = null; + + this.quads.reset(); + + this._temporaryTexturizers = []; + + this._isCachingTexturizer = false; + + } + + get length() { + return this.quads.quadTextures.length; + } + + setShader(shader, owner) { + if (this._shaderOwner !== owner || this._realShader !== shader) { + // Same shader owner: active shader is also the same. + // Prevent any shader usage to save performance. + + this._realShader = shader; + + if (shader.useDefault()) { + // Use the default shader when possible to prevent unnecessary program changes. + shader = this.defaultShader; + } + if (this._shader !== shader || this._shaderOwner !== owner) { + this._shader = shader; + this._shaderOwner = owner; + this._check = true; + } + } + } + + get renderTextureInfo() { + return this._renderTextureInfo; + } + + setScissor(area) { + if (this._scissor !== area) { + if (area) { + this._scissor = area; + } else { + this._scissor = null; + } + this._check = true; + } + } + + getScissor() { + return this._scissor; + } + + setRenderTextureInfo(renderTextureInfo) { + if (this._renderTextureInfo !== renderTextureInfo) { + this._renderTextureInfo = renderTextureInfo; + this._scissor = null; + this._check = true; + } + } + + /** + * Sets the texturizer to be drawn during subsequent addQuads. + * @param {ElementTexturizer} texturizer + */ + setTexturizer(texturizer, cache = false) { + this._texturizer = texturizer; + this._cacheTexturizer = cache; + } + + set isCachingTexturizer(v) { + this._isCachingTexturizer = v; + } + + get isCachingTexturizer() { + return this._isCachingTexturizer; + } + + addQuad(elementCore) { + if (!this._quadOperation) { + this._createQuadOperation(); + } else if (this._check && this._hasChanges()) { + this._finishQuadOperation(); + this._check = false; + } + + let nativeTexture = null; + if (this._texturizer) { + nativeTexture = this._texturizer.getResultTexture(); + + if (!this._cacheTexturizer) { + // We can release the temporary texture immediately after finalizing this quad operation. + this._temporaryTexturizers.push(this._texturizer); + } + } + + if (!nativeTexture) { + nativeTexture = elementCore._displayedTextureSource.nativeTexture; + } + + if (this._renderTextureInfo) { + if (this._shader === this.defaultShader && this._renderTextureInfo.empty) { + // The texture might be reusable under some conditions. We will check them in ElementCore.renderer. + this._renderTextureInfo.nativeTexture = nativeTexture; + this._renderTextureInfo.offset = this.length; + } else { + // It is not possible to reuse another texture when there is more than one quad. + this._renderTextureInfo.nativeTexture = null; + } + this._renderTextureInfo.empty = false; + } + + this.quads.quadTextures.push(nativeTexture); + this.quads.quadElements.push(elementCore); + + this._quadOperation.length++; + + this.renderer.addQuad(this, this.quads, this.length - 1) + } + + finishedRenderTexture() { + if (this._renderTextureInfo.nativeTexture) { + // There was only one texture drawn in this render texture. + // Check if we can reuse it so that we can optimize out an unnecessary render texture operation. + // (it should exactly span this render texture). + if (!this._isRenderTextureReusable()) { + this._renderTextureInfo.nativeTexture = null; + } + } + } + + _isRenderTextureReusable() { + const offset = this._renderTextureInfo.offset; + return (this.quads.quadTextures[offset].w === this._renderTextureInfo.w) && + (this.quads.quadTextures[offset].h === this._renderTextureInfo.h) && + this.renderer.isRenderTextureReusable(this, this._renderTextureInfo) + } + + _hasChanges() { + let q = this._quadOperation; + if (this._shader !== q.shader) return true; + if (this._shaderOwner !== q.shaderOwner) return true; + if (this._renderTextureInfo !== q.renderTextureInfo) return true; + if (this._scissor !== q.scissor) { + if ((this._scissor[0] !== q.scissor[0]) || (this._scissor[1] !== q.scissor[1]) || (this._scissor[2] !== q.scissor[2]) || (this._scissor[3] !== q.scissor[3])) { + return true; + } + } + + return false; + } + + _finishQuadOperation(create = true) { + if (this._quadOperation) { + if (this._quadOperation.length || this._shader.addEmpty()) { + if (!this._quadOperation.scissor || ((this._quadOperation.scissor[2] > 0) && (this._quadOperation.scissor[3] > 0))) { + // Ignore empty clipping regions. + this.quadOperations.push(this._quadOperation); + } + } + + if (this._temporaryTexturizers.length) { + for (let i = 0, n = this._temporaryTexturizers.length; i < n; i++) { + // We can now reuse these render-to-textures in subsequent stages. + // Huge performance benefit when filtering (fast blur). + this._temporaryTexturizers[i].releaseRenderTexture(); + } + this._temporaryTexturizers = []; + } + + this._quadOperation = null; + } + + if (create) { + this._createQuadOperation(); + } + } + + _createQuadOperation() { + this._quadOperation = this.renderer.createCoreQuadOperation( + this.ctx, + this._shader, + this._shaderOwner, + this._renderTextureInfo, + this._scissor, + this.length + ); + this._check = false; + } + + finish() { + if (this._quadOperation) { + // Add remaining. + this._finishQuadOperation(false); + } + + this.renderer.finishRenderState(this); + } + +} + + + +/***/ }), + +/***/ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/tree/core/ElementCore.mjs": +/*!*********************************************************************************************************!*\ + !*** ./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/tree/core/ElementCore.mjs ***! + \*********************************************************************************************************/ +/*! exports provided: default */ +/***/ (function(__webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return ElementCore; }); +/* harmony import */ var _flex_FlexTarget_mjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../flex/FlexTarget.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/flex/FlexTarget.mjs"); +/* harmony import */ var _ElementTexturizer_mjs__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./ElementTexturizer.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/tree/core/ElementTexturizer.mjs"); +/* harmony import */ var _Utils_mjs__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Utils.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/tree/Utils.mjs"); +/* + * If not stated otherwise in this file or this component's LICENSE file the + * following copyright and licenses apply: + * + * Copyright 2020 Metrological + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + +class ElementCore { + + constructor(element) { + this._element = element; + + this.ctx = element.stage.ctx; + + // The memory layout of the internal variables is affected by their position in the constructor. + // It boosts performance to order them by usage of cpu-heavy functions (renderSimple and update). + + this._recalc = 0; + + this._parent = null; + + this._onUpdate = null; + + this._pRecalc = 0; + + this._worldContext = new ElementCoreContext(); + + this._hasUpdates = false; + + this._localAlpha = 1; + + this._onAfterCalcs = null; + + this._onAfterUpdate = null; + + // All local translation/transform updates: directly propagated from x/y/w/h/scale/whatever. + this._localPx = 0; + this._localPy = 0; + + this._localTa = 1; + this._localTb = 0; + this._localTc = 0; + this._localTd = 1; + + this._isComplex = false; + + this._dimsUnknown = false; + + this._clipping = false; + + // Used by both update and render. + this._zSort = false; + + this._outOfBounds = 0; + + /** + * The texture source to be displayed. + * @type {TextureSource} + */ + this._displayedTextureSource = null; + + this._zContextUsage = 0; + + this._children = null; + + this._hasRenderUpdates = 0; + + this._zIndexedChildren = null; + + this._renderContext = this._worldContext; + + this.renderState = this.ctx.renderState; + + this._scissor = null; + + // The ancestor ElementCore that owns the inherited shader. Null if none is active (default shader). + this._shaderOwner = null; + + + this._updateTreeOrder = 0; + + this._colorUl = this._colorUr = this._colorBl = this._colorBr = 0xFFFFFFFF; + + this._x = 0; + this._y = 0; + this._w = 0; + this._h = 0; + + this._optFlags = 0; + this._funcX = null; + this._funcY = null; + this._funcW = null; + this._funcH = null; + + this._scaleX = 1; + this._scaleY = 1; + this._pivotX = 0.5; + this._pivotY = 0.5; + this._mountX = 0; + this._mountY = 0; + this._rotation = 0; + + this._alpha = 1; + this._visible = true; + + this._ulx = 0; + this._uly = 0; + this._brx = 1; + this._bry = 1; + + this._zIndex = 0; + this._forceZIndexContext = false; + this._zParent = null; + + this._isRoot = false; + + /** + * Iff true, during zSort, this element should be 're-sorted' because either: + * - zIndex did chang + * - zParent did change + * - element was moved in the render tree + * @type {boolean} + */ + this._zIndexResort = false; + + this._shader = null; + + // Element is rendered on another texture. + this._renderToTextureEnabled = false; + + this._texturizer = null; + + this._useRenderToTexture = false; + + this._boundsMargin = null; + + this._recBoundsMargin = null; + + this._withinBoundsMargin = false; + + this._viewport = null; + + this._clipbox = true; + + this.render = this._renderSimple; + + this._layout = null; + } + + get offsetX() { + if (this._funcX) { + return this._funcX; + } else { + if (this.hasFlexLayout()) { + return this._layout.originalX; + } else { + return this._x; + } + } + } + + set offsetX(v) { + if (_Utils_mjs__WEBPACK_IMPORTED_MODULE_2__["default"].isFunction(v)) { + this.funcX = v; + } else { + this._disableFuncX(); + if (this.hasFlexLayout()) { + this.x += (v - this._layout.originalX); + this._layout.setOriginalXWithoutUpdatingLayout(v); + } else { + this.x = v; + } + } + } + + get x() { + return this._x; + } + + set x(v) { + if (v !== this._x) { + this._updateLocalTranslateDelta(v - this._x, 0); + this._x = v; + } + } + + get funcX() { + return (this._optFlags & 1 ? this._funcX : null); + } + + set funcX(v) { + if (this._funcX !== v) { + this._optFlags |= 1; + this._funcX = v; + if (this.hasFlexLayout()) { + this._layout.setOriginalXWithoutUpdatingLayout(0); + this.layout.forceLayout(); + } else { + this._x = 0; + this._triggerRecalcTranslate(); + } + } + } + + _disableFuncX() { + this._optFlags = this._optFlags & (0xFFFF - 1); + this._funcX = null; + } + + get offsetY() { + if (this._funcY) { + return this._funcY; + } else { + if (this.hasFlexLayout()) { + return this._layout.originalY; + } else { + return this._y; + } + } + } + + set offsetY(v) { + if (_Utils_mjs__WEBPACK_IMPORTED_MODULE_2__["default"].isFunction(v)) { + this.funcY = v; + } else { + this._disableFuncY(); + if (this.hasFlexLayout()) { + this.y += (v - this._layout.originalY); + this._layout.setOriginalYWithoutUpdatingLayout(v); + } else { + this.y = v; + } + } + } + + get y() { + return this._y; + } + + set y(v) { + if (v !== this._y) { + this._updateLocalTranslateDelta(0, v - this._y); + this._y = v; + } + } + + get funcY() { + return (this._optFlags & 2 ? this._funcY : null); + } + + set funcY(v) { + if (this._funcY !== v) { + this._optFlags |= 2; + this._funcY = v; + if (this.hasFlexLayout()) { + this._layout.setOriginalYWithoutUpdatingLayout(0); + this.layout.forceLayout(); + } else { + this._y = 0; + this._triggerRecalcTranslate(); + } + } + } + + _disableFuncY() { + this._optFlags = this._optFlags & (0xFFFF - 2); + this._funcY = null; + } + + get funcW() { + return (this._optFlags & 4 ? this._funcW : null); + } + + set funcW(v) { + if (this._funcW !== v) { + this._optFlags |= 4; + this._funcW = v; + if (this.hasFlexLayout()) { + this._layout._originalWidth = 0; + this.layout.changedDimensions(true, false); + } else { + this._w = 0; + this._triggerRecalcTranslate(); + } + } + } + + disableFuncW() { + this._optFlags = this._optFlags & (0xFFFF - 4); + this._funcW = null; + } + + get funcH() { + return (this._optFlags & 8 ? this._funcH : null); + } + + set funcH(v) { + if (this._funcH !== v) { + this._optFlags |= 8; + this._funcH = v; + if (this.hasFlexLayout()) { + this._layout._originalHeight = 0; + this.layout.changedDimensions(false, true); + } else { + this._h = 0; + this._triggerRecalcTranslate(); + } + } + } + + disableFuncH() { + this._optFlags = this._optFlags & (0xFFFF - 8); + this._funcH = null; + } + + get w() { + return this._w; + } + + getRenderWidth() { + if (this.hasFlexLayout()) { + return this._layout.originalWidth; + } else { + return this._w; + } + } + + get h() { + return this._h; + } + + getRenderHeight() { + if (this.hasFlexLayout()) { + return this._layout.originalHeight; + } else { + return this._h; + } + } + + get scaleX() { + return this._scaleX; + } + + set scaleX(v) { + if (this._scaleX !== v) { + this._scaleX = v; + this._updateLocalTransform(); + } + } + + get scaleY() { + return this._scaleY; + } + + set scaleY(v) { + if (this._scaleY !== v) { + this._scaleY = v; + this._updateLocalTransform(); + } + } + + get scale() { + return this.scaleX; + } + + set scale(v) { + if (this._scaleX !== v || this._scaleY !== v) { + this._scaleX = v; + this._scaleY = v; + this._updateLocalTransform(); + } + } + + get pivotX() { + return this._pivotX; + } + + set pivotX(v) { + if (this._pivotX !== v) { + this._pivotX = v; + this._updateLocalTranslate(); + } + } + + get pivotY() { + return this._pivotY; + } + + set pivotY(v) { + if (this._pivotY !== v) { + this._pivotY = v; + this._updateLocalTranslate(); + } + } + + get pivot() { + return this._pivotX; + } + + set pivot(v) { + if (this._pivotX !== v || this._pivotY !== v) { + this._pivotX = v; + this._pivotY = v; + this._updateLocalTranslate(); + } + } + + get mountX() { + return this._mountX; + } + + set mountX(v) { + if (this._mountX !== v) { + this._mountX = v; + this._updateLocalTranslate(); + } + } + + get mountY() { + return this._mountY; + } + + set mountY(v) { + if (this._mountY !== v) { + this._mountY = v; + this._updateLocalTranslate(); + } + } + + get mount() { + return this._mountX; + } + + set mount(v) { + if (this._mountX !== v || this._mountY !== v) { + this._mountX = v; + this._mountY = v; + this._updateLocalTranslate(); + } + } + + get rotation() { + return this._rotation; + } + + set rotation(v) { + if (this._rotation !== v) { + this._rotation = v; + this._updateLocalTransform(); + } + } + + get alpha() { + return this._alpha; + } + + set alpha(v) { + // Account for rounding errors. + v = (v > 1 ? 1 : (v < 1e-14 ? 0 : v)); + if (this._alpha !== v) { + let prev = this._alpha; + this._alpha = v; + this._updateLocalAlpha(); + if ((prev === 0) !== (v === 0)) { + this._element._updateEnabledFlag(); + } + } + } + + get visible() { + return this._visible; + } + + set visible(v) { + if (this._visible !== v) { + this._visible = v; + this._updateLocalAlpha(); + this._element._updateEnabledFlag(); + + if (this.hasFlexLayout()) { + this.layout.setVisible(v); + } + } + } + + _updateLocalTransform() { + if (this._rotation !== 0 && this._rotation % (2 * Math.PI)) { + // check to see if the rotation is the same as the previous render. This means we only need to use sin and cos when rotation actually changes + let _sr = Math.sin(this._rotation); + let _cr = Math.cos(this._rotation); + + this._setLocalTransform( + _cr * this._scaleX, + -_sr * this._scaleY, + _sr * this._scaleX, + _cr * this._scaleY + ); + } else { + this._setLocalTransform( + this._scaleX, + 0, + 0, + this._scaleY + ); + } + this._updateLocalTranslate(); + }; + + _updateLocalTranslate() { + this._recalcLocalTranslate(); + this._triggerRecalcTranslate(); + }; + + _recalcLocalTranslate() { + let pivotXMul = this._pivotX * this._w; + let pivotYMul = this._pivotY * this._h; + let px = this._x - (pivotXMul * this._localTa + pivotYMul * this._localTb) + pivotXMul; + let py = this._y - (pivotXMul * this._localTc + pivotYMul * this._localTd) + pivotYMul; + px -= this._mountX * this._w; + py -= this._mountY * this._h; + this._localPx = px; + this._localPy = py; + } + + _updateLocalTranslateDelta(dx, dy) { + this._addLocalTranslate(dx, dy); + }; + + _updateLocalAlpha() { + this._setLocalAlpha(this._visible ? this._alpha : 0); + }; + + /** + * @param {number} type + * 0: no updates + * 1: re-invoke shader + * 3: re-create render texture and re-invoke shader + */ + setHasRenderUpdates(type) { + if (this._worldContext.alpha) { + // Ignore if 'world invisible'. Render updates will be reset to 3 for every element that becomes visible. + let p = this; + p._hasRenderUpdates = Math.max(type, p._hasRenderUpdates); + while ((p = p._parent) && (p._hasRenderUpdates !== 3)) { + p._hasRenderUpdates = 3; + } + } + } + + /** + * @param {Number} type + * 1: alpha + * 2: translate + * 4: transform + * 128: becomes visible + * 256: flex layout updated + */ + _setRecalc(type) { + this._recalc |= type; + + this._setHasUpdates(); + + // Any changes in descendants should trigger texture updates. + if (this._parent) { + this._parent.setHasRenderUpdates(3); + } + } + + _setHasUpdates() { + let p = this; + while (p && !p._hasUpdates) { + p._hasUpdates = true; + p = p._parent; + } + } + + getParent() { + return this._parent; + } + + setParent(parent) { + if (parent !== this._parent) { + let prevIsZContext = this.isZContext(); + let prevParent = this._parent; + this._parent = parent; + + // Notify flex layout engine. + if (this._layout || (parent && parent.isFlexContainer())) { + this.layout.setParent(prevParent, parent); + } + + if (prevParent) { + // When elements are deleted, the render texture must be re-rendered. + prevParent.setHasRenderUpdates(3); + } + + this._setRecalc(1 + 2 + 4); + + if (this._parent) { + // Force parent to propagate hasUpdates flag. + this._parent._setHasUpdates(); + } + + if (this._zIndex === 0) { + this.setZParent(parent); + } else { + this.setZParent(parent ? parent.findZContext() : null); + } + + if (prevIsZContext !== this.isZContext()) { + if (!this.isZContext()) { + this.disableZContext(); + } else { + this.enableZContext(prevParent.findZContext()); + } + } + + // Tree order did change: even if zParent stays the same, we must resort. + this._zIndexResort = true; + if (this._zParent) { + this._zParent.enableZSort(); + } + + if (!this._shader) { + let newShaderOwner = parent && !parent._renderToTextureEnabled ? parent._shaderOwner : null; + if (newShaderOwner !== this._shaderOwner) { + this.setHasRenderUpdates(1); + this._setShaderOwnerRecursive(newShaderOwner); + } + } + } + }; + + enableZSort(force = false) { + if (!this._zSort && this._zContextUsage > 0) { + this._zSort = true; + if (force) { + // ZSort must be done, even if this element is invisible. + // This is done to prevent memory leaks when removing element from inactive render branches. + this.ctx.forceZSort(this); + } + } + } + + addChildAt(index, child) { + if (!this._children) this._children = []; + this._children.splice(index, 0, child); + child.setParent(this); + }; + + setChildAt(index, child) { + if (!this._children) this._children = []; + this._children[index].setParent(null); + this._children[index] = child; + child.setParent(this); + } + + removeChildAt(index) { + let child = this._children[index]; + this._children.splice(index, 1); + child.setParent(null); + }; + + removeChildren() { + if (this._children) { + for (let i = 0, n = this._children.length; i < n; i++) { + this._children[i].setParent(null); + } + + this._children.splice(0); + + if (this._zIndexedChildren) { + this._zIndexedChildren.splice(0); + } + } + }; + + syncChildren(removed, added, order) { + this._children = order; + for (let i = 0, n = removed.length; i < n; i++) { + removed[i].setParent(null); + } + for (let i = 0, n = added.length; i < n; i++) { + added[i].setParent(this); + } + } + + moveChild(fromIndex, toIndex) { + let c = this._children[fromIndex]; + this._children.splice(fromIndex, 1); + this._children.splice(toIndex, 0, c); + + // Tree order changed: must resort!; + this._zIndexResort = true; + if (this._zParent) { + this._zParent.enableZSort(); + } + } + + _setLocalTransform(a, b, c, d) { + this._setRecalc(4); + this._localTa = a; + this._localTb = b; + this._localTc = c; + this._localTd = d; + + // We also regard negative scaling as a complex case, so that we can optimize the non-complex case better. + this._isComplex = (b !== 0) || (c !== 0) || (a < 0) || (d < 0); + }; + + _addLocalTranslate(dx, dy) { + this._localPx += dx; + this._localPy += dy; + this._triggerRecalcTranslate(); + } + + _setLocalAlpha(a) { + if (!this._worldContext.alpha && ((this._parent && this._parent._worldContext.alpha) && a)) { + // Element is becoming visible. We need to force update. + this._setRecalc(1 + 128); + } else { + this._setRecalc(1); + } + + if (a < 1e-14) { + // Tiny rounding errors may cause failing visibility tests. + a = 0; + } + + this._localAlpha = a; + }; + + setDimensions(w, h, isEstimate = this._dimsUnknown) { + // In case of an estimation, the update loop should perform different bound checks. + this._dimsUnknown = isEstimate; + + if (this.hasFlexLayout()) { + this._layout.originalWidth = w; + this._layout.originalHeight = h; + } else { + if (this._w !== w || this._h !== h) { + this._updateDimensions(w, h); + return true; + } + } + return false; + }; + + _updateDimensions(w, h) { + if (this._w !== w || this._h !== h) { + this._w = w; + this._h = h; + + this._triggerRecalcTranslate(); + + if (this._texturizer) { + this._texturizer.releaseRenderTexture(); + this._texturizer.updateResultTexture(); + } + // Due to width/height change: update the translation vector. + this._updateLocalTranslate(); + } + } + + setTextureCoords(ulx, uly, brx, bry) { + this.setHasRenderUpdates(3); + + this._ulx = ulx; + this._uly = uly; + this._brx = brx; + this._bry = bry; + }; + + get displayedTextureSource() { + return this._displayedTextureSource; + } + + setDisplayedTextureSource(textureSource) { + this.setHasRenderUpdates(3); + this._displayedTextureSource = textureSource; + }; + + get isRoot() { + return this._isRoot; + } + + setAsRoot() { + // Use parent dummy. + this._parent = new ElementCore(this._element); + + // After setting root, make sure it's updated. + this._parent._hasRenderUpdates = 3; + this._parent._hasUpdates = true; + + // Root is, and will always be, the primary zContext. + this._isRoot = true; + + this.ctx.root = this; + + // Set scissor area of 'fake parent' to stage's viewport. + this._parent._viewport = [0, 0, this.ctx.stage.coordsWidth, this.ctx.stage.coordsHeight]; + this._parent._scissor = this._parent._viewport; + + // When recBoundsMargin is null, the defaults are used (100 for all sides). + this._parent._recBoundsMargin = null; + + this._setRecalc(1 + 2 + 4); + }; + + isAncestorOf(c) { + let p = c; + while (p = p._parent) { + if (this === p) { + return true; + } + } + return false; + }; + + isZContext() { + return (this._forceZIndexContext || this._renderToTextureEnabled || this._zIndex !== 0 || this._isRoot || !this._parent); + }; + + findZContext() { + if (this.isZContext()) { + return this; + } else { + return this._parent.findZContext(); + } + }; + + setZParent(newZParent) { + if (this._zParent !== newZParent) { + if (this._zParent !== null) { + if (this._zIndex !== 0) { + this._zParent.decZContextUsage(); + } + + // We must filter out this item upon the next resort. + this._zParent.enableZSort(); + } + + if (newZParent !== null) { + let hadZContextUsage = (newZParent._zContextUsage > 0); + + // @pre: new parent's children array has already been modified. + if (this._zIndex !== 0) { + newZParent.incZContextUsage(); + } + + if (newZParent._zContextUsage > 0) { + if (!hadZContextUsage && (this._parent === newZParent)) { + // This child was already in the children list. + // Do not add double. + } else { + // Add new child to array. + newZParent._zIndexedChildren.push(this); + } + + // Order should be checked. + newZParent.enableZSort(); + } + } + + this._zParent = newZParent; + + // Newly added element must be marked for resort. + this._zIndexResort = true; + } + }; + + incZContextUsage() { + this._zContextUsage++; + if (this._zContextUsage === 1) { + if (!this._zIndexedChildren) { + this._zIndexedChildren = []; + } + if (this._children) { + // Copy. + for (let i = 0, n = this._children.length; i < n; i++) { + this._zIndexedChildren.push(this._children[i]); + } + // Initially, children are already sorted properly (tree order). + this._zSort = false; + } + } + }; + + decZContextUsage() { + this._zContextUsage--; + if (this._zContextUsage === 0) { + this._zSort = false; + this._zIndexedChildren.splice(0); + } + }; + + get zIndex() { + return this._zIndex; + } + + set zIndex(zIndex) { + if (this._zIndex !== zIndex) { + this.setHasRenderUpdates(1); + + let newZParent = this._zParent; + + let prevIsZContext = this.isZContext(); + if (zIndex === 0 && this._zIndex !== 0) { + if (this._parent === this._zParent) { + if (this._zParent) { + this._zParent.decZContextUsage(); + } + } else { + newZParent = this._parent; + } + } else if (zIndex !== 0 && this._zIndex === 0) { + newZParent = this._parent ? this._parent.findZContext() : null; + if (newZParent === this._zParent) { + if (this._zParent) { + this._zParent.incZContextUsage(); + this._zParent.enableZSort(); + } + } + } else if (zIndex !== this._zIndex) { + if (this._zParent && this._zParent._zContextUsage) { + this._zParent.enableZSort(); + } + } + + if (newZParent !== this._zParent) { + this.setZParent(null); + } + + this._zIndex = zIndex; + + if (newZParent !== this._zParent) { + this.setZParent(newZParent); + } + + if (prevIsZContext !== this.isZContext()) { + if (!this.isZContext()) { + this.disableZContext(); + } else { + this.enableZContext(this._parent.findZContext()); + } + } + + // Make sure that resort is done. + this._zIndexResort = true; + if (this._zParent) { + this._zParent.enableZSort(); + } + } + }; + + get forceZIndexContext() { + return this._forceZIndexContext; + } + + set forceZIndexContext(v) { + this.setHasRenderUpdates(1); + + let prevIsZContext = this.isZContext(); + this._forceZIndexContext = v; + + if (prevIsZContext !== this.isZContext()) { + if (!this.isZContext()) { + this.disableZContext(); + } else { + this.enableZContext(this._parent.findZContext()); + } + } + }; + + enableZContext(prevZContext) { + if (prevZContext && prevZContext._zContextUsage > 0) { + // Transfer from upper z context to this z context. + const results = this._getZIndexedDescs(); + results.forEach((c) => { + if (this.isAncestorOf(c) && c._zIndex !== 0) { + c.setZParent(this); + } + }); + } + } + + _getZIndexedDescs() { + const results = []; + if (this._children) { + for (let i = 0, n = this._children.length; i < n; i++) { + this._children[i]._getZIndexedDescsRec(results); + } + } + return results; + } + + _getZIndexedDescsRec(results) { + if (this._zIndex) { + results.push(this); + } else if (this._children && !this.isZContext()) { + for (let i = 0, n = this._children.length; i < n; i++) { + this._children[i]._getZIndexedDescsRec(results); + } + } + } + + disableZContext() { + // Transfer from this z context to upper z context. + if (this._zContextUsage > 0) { + let newZParent = this._parent.findZContext(); + + // Make sure that z-indexed children are up to date (old ones removed). + if (this._zSort) { + this.sortZIndexedChildren(); + } + + this._zIndexedChildren.slice().forEach(function (c) { + if (c._zIndex !== 0) { + c.setZParent(newZParent); + } + }); + } + }; + + get colorUl() { + return this._colorUl; + } + + set colorUl(color) { + if (this._colorUl !== color) { + this.setHasRenderUpdates(this._displayedTextureSource ? 3 : 1); + this._colorUl = color; + } + } + + get colorUr() { + return this._colorUr; + } + + set colorUr(color) { + if (this._colorUr !== color) { + this.setHasRenderUpdates(this._displayedTextureSource ? 3 : 1); + this._colorUr = color; + } + }; + + get colorBl() { + return this._colorBl; + } + + set colorBl(color) { + if (this._colorBl !== color) { + this.setHasRenderUpdates(this._displayedTextureSource ? 3 : 1); + this._colorBl = color; + } + }; + + get colorBr() { + return this._colorBr; + } + + set colorBr(color) { + if (this._colorBr !== color) { + this.setHasRenderUpdates(this._displayedTextureSource ? 3 : 1); + this._colorBr = color; + } + }; + + + set onUpdate(f) { + this._onUpdate = f; + this._setRecalc(7); + } + + set onAfterUpdate(f) { + this._onAfterUpdate = f; + this._setRecalc(7); + } + + set onAfterCalcs(f) { + this._onAfterCalcs = f; + this._setRecalc(7); + } + + get shader() { + return this._shader; + } + + set shader(v) { + this.setHasRenderUpdates(1); + + let prevShader = this._shader; + this._shader = v; + if (!v && prevShader) { + // Disabled shader. + let newShaderOwner = (this._parent && !this._parent._renderToTextureEnabled ? this._parent._shaderOwner : null); + this._setShaderOwnerRecursive(newShaderOwner); + } else if (v) { + // Enabled shader. + this._setShaderOwnerRecursive(this); + } + } + + get activeShader() { + return this._shaderOwner ? this._shaderOwner.shader : this.renderState.defaultShader; + } + + get activeShaderOwner() { + return this._shaderOwner; + } + + get clipping() { + return this._clipping; + } + + set clipping(v) { + if (this._clipping !== v) { + this._clipping = v; + + // Force update of scissor by updating translate. + // Alpha must also be updated because the scissor area may have been empty. + this._setRecalc(1 + 2); + } + } + + get clipbox() { + return this._clipbox; + } + + set clipbox(v) { + // In case of out-of-bounds element, all children will also be ignored. + // It will save us from executing the update/render loops for those. + // The optimization will be used immediately during the next frame. + this._clipbox = v; + } + + _setShaderOwnerRecursive(elementCore) { + this._shaderOwner = elementCore; + + if (this._children && !this._renderToTextureEnabled) { + for (let i = 0, n = this._children.length; i < n; i++) { + let c = this._children[i]; + if (!c._shader) { + c._setShaderOwnerRecursive(elementCore); + c._hasRenderUpdates = 3; + } + } + } + }; + + _setShaderOwnerChildrenRecursive(elementCore) { + if (this._children) { + for (let i = 0, n = this._children.length; i < n; i++) { + let c = this._children[i]; + if (!c._shader) { + c._setShaderOwnerRecursive(elementCore); + c._hasRenderUpdates = 3; + } + } + } + }; + + _hasRenderContext() { + return this._renderContext !== this._worldContext; + } + + get renderContext() { + return this._renderContext; + } + + updateRenderToTextureEnabled() { + // Enforce texturizer initialisation. + let v = this.texturizer._enabled; + + if (v) { + this._enableRenderToTexture(); + } else { + this._disableRenderToTexture(); + this._texturizer.releaseRenderTexture(); + } + } + + _enableRenderToTexture() { + if (!this._renderToTextureEnabled) { + let prevIsZContext = this.isZContext(); + + this._renderToTextureEnabled = true; + + this._renderContext = new ElementCoreContext(); + + // If render to texture is active, a new shader context is started. + this._setShaderOwnerChildrenRecursive(null); + + if (!prevIsZContext) { + // Render context forces z context. + this.enableZContext(this._parent ? this._parent.findZContext() : null); + } + + this.setHasRenderUpdates(3); + + // Make sure that the render coordinates get updated. + this._setRecalc(7); + + this.render = this._renderAdvanced; + } + } + + _disableRenderToTexture() { + if (this._renderToTextureEnabled) { + this._renderToTextureEnabled = false; + + this._setShaderOwnerChildrenRecursive(this._shaderOwner); + + this._renderContext = this._worldContext; + + if (!this.isZContext()) { + this.disableZContext(); + } + + // Make sure that the render coordinates get updated. + this._setRecalc(7); + + this.setHasRenderUpdates(3); + + this.render = this._renderSimple; + } + } + + isWhite() { + return (this._colorUl === 0xFFFFFFFF) && (this._colorUr === 0xFFFFFFFF) && (this._colorBl === 0xFFFFFFFF) && (this._colorBr === 0xFFFFFFFF); + } + + hasSimpleTexCoords() { + return (this._ulx === 0) && (this._uly === 0) && (this._brx === 1) && (this._bry === 1); + } + + _stashTexCoords() { + this._stashedTexCoords = [this._ulx, this._uly, this._brx, this._bry]; + this._ulx = 0; + this._uly = 0; + this._brx = 1; + this._bry = 1; + } + + _unstashTexCoords() { + this._ulx = this._stashedTexCoords[0]; + this._uly = this._stashedTexCoords[1]; + this._brx = this._stashedTexCoords[2]; + this._bry = this._stashedTexCoords[3]; + this._stashedTexCoords = null; + } + + _stashColors() { + this._stashedColors = [this._colorUl, this._colorUr, this._colorBr, this._colorBl]; + this._colorUl = 0xFFFFFFFF; + this._colorUr = 0xFFFFFFFF; + this._colorBr = 0xFFFFFFFF; + this._colorBl = 0xFFFFFFFF; + } + + _unstashColors() { + this._colorUl = this._stashedColors[0]; + this._colorUr = this._stashedColors[1]; + this._colorBr = this._stashedColors[2]; + this._colorBl = this._stashedColors[3]; + this._stashedColors = null; + } + + isVisible() { + return (this._localAlpha > 1e-14); + }; + + get outOfBounds() { + return this._outOfBounds; + } + + set boundsMargin(v) { + + /** + * null: inherit from parent. + * number[4]: specific margins: left, top, right, bottom. + */ + this._boundsMargin = v ? v.slice() : null; + + // We force recalc in order to set all boundsMargin recursively during the next update. + this._triggerRecalcTranslate(); + } + + get boundsMargin() { + return this._boundsMargin; + } + + update() { + this._recalc |= this._parent._pRecalc; + + if (this._layout && this._layout.isEnabled()) { + if (this._recalc & 256) { + this._layout.layoutFlexTree(); + } + } else if ((this._recalc & 2) && this._optFlags) { + this._applyRelativeDimFuncs(); + } + + if (this._onUpdate) { + // Block all 'upwards' updates when changing things in this branch. + this._hasUpdates = true; + this._onUpdate(this.element, this); + } + + const pw = this._parent._worldContext; + let w = this._worldContext; + const visible = (pw.alpha && this._localAlpha); + + /** + * We must update if: + * - branch contains updates (even when invisible because it may contain z-indexed descendants) + * - there are (inherited) updates and this branch is visible + * - this branch becomes invisible (descs may be z-indexed so we must update all alpha values) + */ + if (this._hasUpdates || (this._recalc && visible) || (w.alpha && !visible)) { + let recalc = this._recalc; + + // Update world coords/alpha. + if (recalc & 1) { + if (!w.alpha && visible) { + // Becomes visible. + this._hasRenderUpdates = 3; + } + w.alpha = pw.alpha * this._localAlpha; + + if (w.alpha < 1e-14) { + // Tiny rounding errors may cause failing visibility tests. + w.alpha = 0; + } + } + + if (recalc & 6) { + w.px = pw.px + this._localPx * pw.ta; + w.py = pw.py + this._localPy * pw.td; + if (pw.tb !== 0) w.px += this._localPy * pw.tb; + if (pw.tc !== 0) w.py += this._localPx * pw.tc; + } + + if (recalc & 4) { + w.ta = this._localTa * pw.ta; + w.tb = this._localTd * pw.tb; + w.tc = this._localTa * pw.tc; + w.td = this._localTd * pw.td; + + if (this._isComplex) { + w.ta += this._localTc * pw.tb; + w.tb += this._localTb * pw.ta; + w.tc += this._localTc * pw.td; + w.td += this._localTb * pw.tc; + } + } + + // Update render coords/alpha. + const pr = this._parent._renderContext; + if (this._parent._hasRenderContext()) { + const init = this._renderContext === this._worldContext; + if (init) { + // First render context build: make sure that it is fully initialized correctly. + // Otherwise, if we get into bounds later, the render context would not be initialized correctly. + this._renderContext = new ElementCoreContext(); + } + + const r = this._renderContext; + + // Update world coords/alpha. + if (init || (recalc & 1)) { + r.alpha = pr.alpha * this._localAlpha; + + if (r.alpha < 1e-14) { + r.alpha = 0; + } + } + + if (init || (recalc & 6)) { + r.px = pr.px + this._localPx * pr.ta; + r.py = pr.py + this._localPy * pr.td; + if (pr.tb !== 0) r.px += this._localPy * pr.tb; + if (pr.tc !== 0) r.py += this._localPx * pr.tc; + } + + if (init) { + // We set the recalc toggle, because we must make sure that the scissor is updated. + recalc |= 2; + } + + if (init || (recalc & 4)) { + r.ta = this._localTa * pr.ta; + r.tb = this._localTd * pr.tb; + r.tc = this._localTa * pr.tc; + r.td = this._localTd * pr.td; + + if (this._isComplex) { + r.ta += this._localTc * pr.tb; + r.tb += this._localTb * pr.ta; + r.tc += this._localTc * pr.td; + r.td += this._localTb * pr.tc; + } + } + } else { + this._renderContext = this._worldContext; + } + + if (this.ctx.updateTreeOrder === -1) { + this.ctx.updateTreeOrder = this._updateTreeOrder + 1; + } else { + this._updateTreeOrder = this.ctx.updateTreeOrder++; + } + + // Determine whether we must use a 'renderTexture'. + const useRenderToTexture = this._renderToTextureEnabled && this._texturizer.mustRenderToTexture(); + if (this._useRenderToTexture !== useRenderToTexture) { + // Coords must be changed. + this._recalc |= 2 + 4; + + // Scissor may change: force update. + recalc |= 2; + + if (!this._useRenderToTexture) { + // We must release the texture. + this._texturizer.release(); + } + } + this._useRenderToTexture = useRenderToTexture; + + const r = this._renderContext; + + const bboxW = this._dimsUnknown ? 2048 : this._w; + const bboxH = this._dimsUnknown ? 2048 : this._h; + + // Calculate a bbox for this element. + let sx, sy, ex, ey; + const rComplex = (r.tb !== 0) || (r.tc !== 0) || (r.ta < 0) || (r.td < 0); + if (rComplex) { + sx = Math.min(0, bboxW * r.ta, bboxW * r.ta + bboxH * r.tb, bboxH * r.tb) + r.px; + ex = Math.max(0, bboxW * r.ta, bboxW * r.ta + bboxH * r.tb, bboxH * r.tb) + r.px; + sy = Math.min(0, bboxW * r.tc, bboxW * r.tc + bboxH * r.td, bboxH * r.td) + r.py; + ey = Math.max(0, bboxW * r.tc, bboxW * r.tc + bboxH * r.td, bboxH * r.td) + r.py; + } else { + sx = r.px; + ex = r.px + r.ta * bboxW; + sy = r.py; + ey = r.py + r.td * bboxH; + } + + if (this._dimsUnknown && (rComplex || this._localTa < 1 || this._localTb < 1)) { + // If we are dealing with a non-identity matrix, we must extend the bbox so that withinBounds and + // scissors will include the complete range of (positive) dimensions up to ,lh. + const nx = this._x * pr.ta + this._y * pr.tb + pr.px; + const ny = this._x * pr.tc + this._y * pr.td + pr.py; + if (nx < sx) sx = nx; + if (ny < sy) sy = ny; + if (nx > ex) ex = nx; + if (ny > ey) ey = ny; + } + + if (recalc & 6 || !this._scissor /* initial */) { + // Determine whether we must 'clip'. + if (this._clipping && r.isSquare()) { + // If the parent renders to a texture, it's scissor should be ignored; + const area = this._parent._useRenderToTexture ? this._parent._viewport : this._parent._scissor; + if (area) { + // Merge scissor areas. + const lx = Math.max(area[0], sx); + const ly = Math.max(area[1], sy); + this._scissor = [ + lx, + ly, + Math.min(area[2] + area[0], ex) - lx, + Math.min(area[3] + area[1], ey) - ly + ]; + } else { + this._scissor = [sx, sy, ex - sx, ey - sy]; + } + } else { + // No clipping: reuse parent scissor. + this._scissor = this._parent._useRenderToTexture ? this._parent._viewport : this._parent._scissor; + } + } + + // Calculate the outOfBounds margin. + if (this._boundsMargin) { + this._recBoundsMargin = this._boundsMargin; + } else { + this._recBoundsMargin = this._parent._recBoundsMargin; + } + + if (this._onAfterCalcs) { + // After calcs may change render coords, scissor and/or recBoundsMargin. + if (this._onAfterCalcs(this.element)) { + // Recalculate bbox. + if (rComplex) { + sx = Math.min(0, bboxW * r.ta, bboxW * r.ta + bboxH * r.tb, bboxH * r.tb) + r.px; + ex = Math.max(0, bboxW * r.ta, bboxW * r.ta + bboxH * r.tb, bboxH * r.tb) + r.px; + sy = Math.min(0, bboxW * r.tc, bboxW * r.tc + bboxH * r.td, bboxH * r.td) + r.py; + ey = Math.max(0, bboxW * r.tc, bboxW * r.tc + bboxH * r.td, bboxH * r.td) + r.py; + } else { + sx = r.px; + ex = r.px + r.ta * bboxW; + sy = r.py; + ey = r.py + r.td * bboxH; + } + + if (this._dimsUnknown && (rComplex || this._localTa < 1 || this._localTb < 1)) { + const nx = this._x * pr.ta + this._y * pr.tb + pr.px; + const ny = this._x * pr.tc + this._y * pr.td + pr.py; + if (nx < sx) sx = nx; + if (ny < sy) sy = ny; + if (nx > ex) ex = nx; + if (ny > ey) ey = ny; + } + } + } + + if (this._parent._outOfBounds === 2) { + // Inherit parent out of boundsness. + this._outOfBounds = 2; + + if (this._withinBoundsMargin) { + this._withinBoundsMargin = false; + this.element._disableWithinBoundsMargin(); + } + } else { + if (recalc & 6) { + // Recheck if element is out-of-bounds (all settings that affect this should enable recalc bit 2 or 4). + this._outOfBounds = 0; + let withinMargin = true; + + // Offscreens are always rendered as long as the parent is within bounds. + if (!this._renderToTextureEnabled || !this._texturizer || !this._texturizer.renderOffscreen) { + if (this._scissor && (this._scissor[2] <= 0 || this._scissor[3] <= 0)) { + // Empty scissor area. + this._outOfBounds = 2; + } else { + // Use bbox to check out-of-boundness. + if ((this._scissor[0] > ex) || + (this._scissor[1] > ey) || + (sx > (this._scissor[0] + this._scissor[2])) || + (sy > (this._scissor[1] + this._scissor[3])) + ) { + this._outOfBounds = 1; + } + + if (this._outOfBounds) { + if (this._clipping || this._useRenderToTexture || (this._clipbox && (bboxW && bboxH))) { + this._outOfBounds = 2; + } + } + } + + withinMargin = (this._outOfBounds === 0); + if (!withinMargin) { + // Re-test, now with margins. + if (this._recBoundsMargin) { + withinMargin = !((ex < this._scissor[0] - this._recBoundsMargin[2]) || + (ey < this._scissor[1] - this._recBoundsMargin[3]) || + (sx > this._scissor[0] + this._scissor[2] + this._recBoundsMargin[0]) || + (sy > this._scissor[1] + this._scissor[3] + this._recBoundsMargin[1])); + } else { + withinMargin = !((ex < this._scissor[0] - 100) || + (ey < this._scissor[1] - 100) || + (sx > this._scissor[0] + this._scissor[2] + 100) || + (sy > this._scissor[1] + this._scissor[3] + 100)); + } + if (withinMargin && this._outOfBounds === 2) { + // Children must be visited because they may contain elements that are within margin, so must be visible. + this._outOfBounds = 1; + } + } + } + + if (this._withinBoundsMargin !== withinMargin) { + this._withinBoundsMargin = withinMargin; + + if (this._withinBoundsMargin) { + // This may update things (txLoaded events) in the element itself, but also in descendants and ancestors. + + // Changes in ancestors should be executed during the next call of the stage update. But we must + // take care that the _recalc and _hasUpdates flags are properly registered. That's why we clear + // both before entering the children, and use _pRecalc to transfer inherited updates instead of + // _recalc directly. + + // Changes in descendants are automatically executed within the current update loop, though we must + // take care to not update the hasUpdates flag unnecessarily in ancestors. We achieve this by making + // sure that the hasUpdates flag of this element is turned on, which blocks it for ancestors. + this._hasUpdates = true; + + const recalc = this._recalc; + this._recalc = 0; + this.element._enableWithinBoundsMargin(); + + if (this._recalc) { + // This element needs to be re-updated now, because we want the dimensions (and other changes) to be updated. + return this.update(); + } + + this._recalc = recalc; + } else { + this.element._disableWithinBoundsMargin(); + } + } + } + } + + if (this._useRenderToTexture) { + // Set viewport necessary for children scissor calculation. + if (this._viewport) { + this._viewport[2] = bboxW; + this._viewport[3] = bboxH; + } else { + this._viewport = [0, 0, bboxW, bboxH]; + } + } + + // Filter out bits that should not be copied to the children (currently all are). + this._pRecalc = (this._recalc & 135); + + // Clear flags so that future updates are properly detected. + this._recalc = 0; + this._hasUpdates = false; + + if (this._outOfBounds < 2) { + if (this._useRenderToTexture) { + if (this._worldContext.isIdentity()) { + // Optimization. + // The world context is already identity: use the world context as render context to prevents the + // ancestors from having to update the render context. + this._renderContext = this._worldContext; + } else { + // Temporarily replace the render coord attribs by the identity matrix. + // This allows the children to calculate the render context. + this._renderContext = ElementCoreContext.IDENTITY; + } + } + + if (this._children) { + for (let i = 0, n = this._children.length; i < n; i++) { + this._children[i].update(); + } + } + + if (this._useRenderToTexture) { + this._renderContext = r; + } + } else { + if (this._children) { + for (let i = 0, n = this._children.length; i < n; i++) { + if (this._children[i]._hasUpdates) { + this._children[i].update(); + } else { + // Make sure we don't lose the 'inherited' updates. + this._children[i]._recalc |= this._pRecalc; + this._children[i].updateOutOfBounds(); + } + } + } + } + + if (this._onAfterUpdate) { + this._onAfterUpdate(this.element); + } + } else { + if (this.ctx.updateTreeOrder === -1 || this._updateTreeOrder >= this.ctx.updateTreeOrder) { + // If new tree order does not interfere with the current (gaps allowed) there's no need to traverse the branch. + this.ctx.updateTreeOrder = -1; + } else { + this.updateTreeOrder(); + } + } + } + + _applyRelativeDimFuncs() { + if (this._optFlags & 1) { + const x = this._funcX(this._parent.w); + if (x !== this._x) { + this._localPx += (x - this._x); + this._x = x; + } + } + if (this._optFlags & 2) { + const y = this._funcY(this._parent.h); + if (y !== this._y) { + this._localPy += (y - this._y); + this._y = y; + } + } + + let changedDims = false; + if (this._optFlags & 4) { + const w = this._funcW(this._parent.w); + if (w !== this._w) { + this._w = w; + changedDims = true; + } + } + if (this._optFlags & 8) { + const h = this._funcH(this._parent.h); + if (h !== this._h) { + this._h = h; + changedDims = true; + } + } + + if (changedDims) { + // Recalc mount, scale position. + this._recalcLocalTranslate(); + + this.element.onDimensionsChanged(this._w, this._h); + } + } + + updateOutOfBounds() { + // Propagate outOfBounds flag to descendants (necessary because of z-indexing). + // Invisible elements are not drawn anyway. When alpha is updated, so will _outOfBounds. + if (this._outOfBounds !== 2 && this._renderContext.alpha > 0) { + + // Inherit parent out of boundsness. + this._outOfBounds = 2; + + if (this._withinBoundsMargin) { + this._withinBoundsMargin = false; + this.element._disableWithinBoundsMargin(); + } + + if (this._children) { + for (let i = 0, n = this._children.length; i < n; i++) { + this._children[i].updateOutOfBounds(); + } + } + } + } + + updateTreeOrder() { + if (this._localAlpha && (this._outOfBounds !== 2)) { + this._updateTreeOrder = this.ctx.updateTreeOrder++; + + if (this._children) { + for (let i = 0, n = this._children.length; i < n; i++) { + this._children[i].updateTreeOrder(); + } + } + } + } + + _renderSimple() { + this._hasRenderUpdates = 0; + + if (this._zSort) { + this.sortZIndexedChildren(); + } + + if (this._outOfBounds < 2 && this._renderContext.alpha) { + let renderState = this.renderState; + + if ((this._outOfBounds === 0) && this._displayedTextureSource) { + renderState.setShader(this.activeShader, this._shaderOwner); + renderState.setScissor(this._scissor); + this.renderState.addQuad(this); + } + + // Also add children to the VBO. + if (this._children) { + if (this._zContextUsage) { + for (let i = 0, n = this._zIndexedChildren.length; i < n; i++) { + this._zIndexedChildren[i].render(); + } + } else { + for (let i = 0, n = this._children.length; i < n; i++) { + if (this._children[i]._zIndex === 0) { + // If zIndex is set, this item already belongs to a zIndexedChildren array in one of the ancestors. + this._children[i].render(); + } + + } + } + } + } + } + + _renderAdvanced() { + const hasRenderUpdates = this._hasRenderUpdates; + + // We must clear the hasRenderUpdates flag before rendering, because updating result textures in combination + // with z-indexing may trigger render updates on a render branch that is 'half done'. + // We need to ensure that the full render branch is marked for render updates, not only half (leading to freeze). + this._hasRenderUpdates = 0; + + if (this._zSort) { + this.sortZIndexedChildren(); + } + + if (this._outOfBounds < 2 && this._renderContext.alpha) { + let renderState = this.renderState; + + let mustRenderChildren = true; + let renderTextureInfo; + let prevRenderTextureInfo; + if (this._useRenderToTexture) { + if (this._w === 0 || this._h === 0) { + // Ignore this branch and don't draw anything. + return; + } else if (!this._texturizer.hasRenderTexture() || (hasRenderUpdates >= 3)) { + // Tell the renderer we're rendering a renderToTexture element in this frame + this.ctx.renderToTextureCount++; + // Switch to default shader for building up the render texture. + renderState.setShader(renderState.defaultShader, this); + + prevRenderTextureInfo = renderState.renderTextureInfo; + + renderTextureInfo = { + nativeTexture: null, + offset: 0, // Set by CoreRenderState. + w: this._w, + h: this._h, + empty: true, + cleared: false, + ignore: false, + cache: false + }; + + if (this._texturizer.hasResultTexture() || (!renderState.isCachingTexturizer && (hasRenderUpdates < 3))) { + /** + * We don't always cache render textures. + * + * The rule is, that caching for a specific render texture is only enabled if: + * - There is a result texture to be updated. + * - There were no render updates -within the contents- since last frame (ElementCore.hasRenderUpdates < 3) + * - AND there are no ancestors that are being cached during this frame (CoreRenderState.isCachingTexturizer) + * If an ancestor is cached anyway, it's probably not necessary to keep deeper caches. If the top level is to + * change while a lower one is not, that lower level will be cached instead. + * + * In case of the fast blur element, this prevents having to cache all blur levels and stages, saving a huge amount + * of GPU memory! + * + * Especially when using multiple stacked layers of the same dimensions that are RTT this will have a very + * noticable effect on performance as less render textures need to be allocated. + */ + renderTextureInfo.cache = true; + renderState.isCachingTexturizer = true; + } + + if (!this._texturizer.hasResultTexture()) { + // We can already release the current texture to the pool, as it will be rebuild anyway. + // In case of multiple layers of 'filtering', this may save us from having to create one + // render-to-texture layer. + // Notice that we don't do this when there is a result texture, as any other element may rely on + // that result texture being filled. + this._texturizer.releaseRenderTexture(); + } + + renderState.setRenderTextureInfo(renderTextureInfo); + renderState.setScissor(null); + + if (this._displayedTextureSource) { + let r = this._renderContext; + + // Use an identity context for drawing the displayed texture to the render texture. + this._renderContext = ElementCoreContext.IDENTITY; + + // Add displayed texture source in local coordinates. + this.renderState.addQuad(this); + + this._renderContext = r; + } + } else { + mustRenderChildren = false; + } + } else { + if ((this._outOfBounds === 0) && this._displayedTextureSource) { + renderState.setShader(this.activeShader, this._shaderOwner); + renderState.setScissor(this._scissor); + this.renderState.addQuad(this); + } + } + + // Also add children to the VBO. + if (mustRenderChildren && this._children) { + if (this._zContextUsage) { + for (let i = 0, n = this._zIndexedChildren.length; i < n; i++) { + this._zIndexedChildren[i].render(); + } + } else { + for (let i = 0, n = this._children.length; i < n; i++) { + if (this._children[i]._zIndex === 0) { + // If zIndex is set, this item already belongs to a zIndexedChildren array in one of the ancestors. + this._children[i].render(); + } + } + } + } + + if (this._useRenderToTexture) { + let updateResultTexture = false; + if (mustRenderChildren) { + // Finished refreshing renderTexture. + renderState.finishedRenderTexture(); + + // If nothing was rendered, we store a flag in the texturizer and prevent unnecessary + // render-to-texture and filtering. + this._texturizer.empty = renderTextureInfo.empty; + + if (renderTextureInfo.empty) { + // We ignore empty render textures and do not draw the final quad. + + // The following cleans up memory and enforces that the result texture is also cleared. + this._texturizer.releaseRenderTexture(); + } else if (renderTextureInfo.nativeTexture) { + // If nativeTexture is set, we can reuse that directly instead of creating a new render texture. + this._texturizer.reuseTextureAsRenderTexture(renderTextureInfo.nativeTexture); + + renderTextureInfo.ignore = true; + } else { + if (this._texturizer.renderTextureReused) { + // Quad operations must be written to a render texture actually owned. + this._texturizer.releaseRenderTexture(); + } + // Just create the render texture. + renderTextureInfo.nativeTexture = this._texturizer.getRenderTexture(); + } + + // Restore the parent's render texture. + renderState.setRenderTextureInfo(prevRenderTextureInfo); + + updateResultTexture = true; + } + + if (!this._texturizer.empty) { + let resultTexture = this._texturizer.getResultTexture(); + if (updateResultTexture) { + if (resultTexture) { + // Logging the update frame can be handy for userland. + resultTexture.update = renderState.stage.frameCounter; + } + this._texturizer.updateResultTexture(); + } + + if (!this._texturizer.renderOffscreen) { + // Render result texture to the actual render target. + renderState.setShader(this.activeShader, this._shaderOwner); + renderState.setScissor(this._scissor); + + // If no render texture info is set, the cache can be reused. + const cache = !renderTextureInfo || renderTextureInfo.cache; + + renderState.setTexturizer(this._texturizer, cache); + this._stashTexCoords(); + if (!this._texturizer.colorize) this._stashColors(); + this.renderState.addQuad(this, true); + if (!this._texturizer.colorize) this._unstashColors(); + this._unstashTexCoords(); + renderState.setTexturizer(null); + } + } + } + + if (renderTextureInfo && renderTextureInfo.cache) { + // Allow siblings to cache. + renderState.isCachingTexturizer = false; + } + } + } + + get zSort() { + return this._zSort; + } + + sortZIndexedChildren() { + /** + * We want to avoid resorting everything. Instead, we do a single pass of the full array: + * - filtering out elements with a different zParent than this (were removed) + * - filtering out, but also gathering (in a temporary array) the elements that have zIndexResort flag + * - then, finally, we merge-sort both the new array and the 'old' one + * - element may have been added 'double', so when merge-sorting also check for doubles. + * - if the old one is larger (in size) than it should be, splice off the end of the array. + */ + + const n = this._zIndexedChildren.length; + let ptr = 0; + const a = this._zIndexedChildren; + + // Notice that items may occur multiple times due to z-index changing. + const b = []; + for (let i = 0; i < n; i++) { + if (a[i]._zParent === this) { + if (a[i]._zIndexResort) { + b.push(a[i]); + } else { + if (ptr !== i) { + a[ptr] = a[i]; + } + ptr++; + } + } + } + + const m = b.length; + if (m) { + for (let j = 0; j < m; j++) { + b[j]._zIndexResort = false; + } + + b.sort(ElementCore.sortZIndexedChildren); + const n = ptr; + if (!n) { + ptr = 0; + let j = 0; + do { + a[ptr++] = b[j++]; + } while (j < m); + + if (a.length > ptr) { + // Slice old (unnecessary) part off array. + a.splice(ptr); + } + } else { + a.splice(n); // Remove items that were sorted in b array, so that we can sort a ++ // Beware that the function passed here to Array.sort must be stable ++ a.sort(ElementCore.sortZIndexedChildren); // Needed because items with same _zIndex may not be ordered by _updateTreeOrder + // Merge-sort arrays; + ptr = 0; + let i = 0; + let j = 0; + const mergeResult = []; + do { + const v = (a[i]._zIndex === b[j]._zIndex ? a[i]._updateTreeOrder - b[j]._updateTreeOrder : a[i]._zIndex - b[j]._zIndex); + + const add = v > 0 ? b[j++] : a[i++]; + + if (ptr === 0 || (mergeResult[ptr - 1] !== add)) { + mergeResult[ptr++] = add; + } + + if (i >= n) { + do { + const add = b[j++]; + if (ptr === 0 || (mergeResult[ptr - 1] !== add)) { + mergeResult[ptr++] = add; + } + } while (j < m); + break; + } else if (j >= m) { + do { + const add = a[i++]; + if (ptr === 0 || (mergeResult[ptr - 1] !== add)) { + mergeResult[ptr++] = add; + } + } while (i < n); + break; + } + } while (true); + + this._zIndexedChildren = mergeResult; + } + } else { + if (a.length > ptr) { + // Slice old (unnecessary) part off array. + a.splice(ptr); + } + } + + this._zSort = false; + }; + + get localTa() { + return this._localTa; + }; + + get localTb() { + return this._localTb; + }; + + get localTc() { + return this._localTc; + }; + + get localTd() { + return this._localTd; + }; + + get element() { + return this._element; + } + + get renderUpdates() { + return this._hasRenderUpdates; + } + + get texturizer() { + if (!this._texturizer) { + this._texturizer = new _ElementTexturizer_mjs__WEBPACK_IMPORTED_MODULE_1__["default"](this); + } + return this._texturizer; + } + + getCornerPoints() { + let w = this._worldContext; + + return [ + w.px, + w.py, + w.px + this._w * w.ta, + w.py + this._w * w.tc, + w.px + this._w * w.ta + this._h * w.tb, + w.py + this._w * w.tc + this._h * w.td, + w.px + this._h * w.tb, + w.py + this._h * w.td + ]; + }; + + getRenderTextureCoords(relX, relY) { + let r = this._renderContext; + return [ + r.px + r.ta * relX + r.tb * relY, + r.py + r.tc * relX + r.td * relY + ]; + } + + getAbsoluteCoords(relX, relY) { + let w = this._renderContext; + return [ + w.px + w.ta * relX + w.tb * relY, + w.py + w.tc * relX + w.td * relY + ]; + } + + collectAtCoord(x, y, children) { + // return when branch is hidden + if (this._renderContext.alpha === 0) { + return; + } + + if (this.inBound(x, y)) { + if (this._scissor) { + if (this.inScissor()) { + children.push(this); + } + } else { + children.push(this); + } + } + + if (this._children) { + const j = this._children.length; + for (let i = 0; i < j; i++) { + this._children[i].collectAtCoord(x, y, children); + } + } + + return children.sort(ElementCore.sortZIndexedChildren); + } + + inBound(tx, ty) { + const c = this.getCornerPoints(); + return tx > c[0] && tx < c[2] && ty > c[1] && ty < c[7]; + } + + inScissor() { + const sc = this._scissor; + const c = this.getCornerPoints(); + + return c[2] >= sc[0] && c[0] <= sc[0] + sc[2] && c[7] >= sc[1] && c[1] <= sc[1] + sc[3]; + } + + get layout() { + this._ensureLayout(); + return this._layout; + } + + get flex() { + return this._layout ? this._layout.flex : null; + } + + set flex(v) { + this.layout.flex = v; + } + + get flexItem() { + return this._layout ? this._layout.flexItem : null; + } + + set flexItem(v) { + this.layout.flexItem = v; + } + + isFlexItem() { + return !!this._layout && this._layout.isFlexItemEnabled(); + } + + isFlexContainer() { + return !!this._layout && this._layout.isFlexEnabled(); + } + + enableFlexLayout() { + this._ensureLayout(); + } + + _ensureLayout() { + if (!this._layout) { + this._layout = new _flex_FlexTarget_mjs__WEBPACK_IMPORTED_MODULE_0__["default"](this); + } + } + + disableFlexLayout() { + this._triggerRecalcTranslate(); + } + + hasFlexLayout() { + return (this._layout && this._layout.isEnabled()); + } + + setLayout(x, y, w, h) { + this.x = x; + this.y = y; + this._updateDimensions(w, h); + } + + triggerLayout() { + this._setRecalc(256); + } + + _triggerRecalcTranslate() { + this._setRecalc(2); + } + +} + +class ElementCoreContext { + + constructor() { + this.alpha = 1; + + this.px = 0; + this.py = 0; + + this.ta = 1; + this.tb = 0; + this.tc = 0; + this.td = 1; + } + + isIdentity() { + return this.alpha === 1 && + this.px === 0 && + this.py === 0 && + this.ta === 1 && + this.tb === 0 && + this.tc === 0 && + this.td === 1; + } + + isSquare() { + return this.tb === 0 && this.tc === 0; + } + +} + +ElementCoreContext.IDENTITY = new ElementCoreContext(); +ElementCore.sortZIndexedChildren = function (a, b) { + return (a._zIndex === b._zIndex ? a._updateTreeOrder - b._updateTreeOrder : a._zIndex - b._zIndex); +}; + + + + + +/***/ }), + +/***/ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/tree/core/ElementTexturizer.mjs": +/*!***************************************************************************************************************!*\ + !*** ./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/tree/core/ElementTexturizer.mjs ***! + \***************************************************************************************************************/ +/*! exports provided: default */ +/***/ (function(__webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return ElementTexturizer; }); +/* harmony import */ var _TextureSource_mjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../TextureSource.mjs */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/tree/TextureSource.mjs"); +/* + * If not stated otherwise in this file or this component's LICENSE file the + * following copyright and licenses apply: + * + * Copyright 2020 Metrological + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + +class ElementTexturizer { + + constructor(elementCore) { + + this._element = elementCore.element; + this._core = elementCore; + + this.ctx = this._core.ctx; + + this._enabled = false; + this.lazy = false; + this._colorize = false; + + this._renderTexture = null; + + this._renderTextureReused = false; + + this._resultTextureSource = null; + + this._renderOffscreen = false; + + this.empty = false; + } + + get enabled() { + return this._enabled; + } + + set enabled(v) { + this._enabled = v; + this._core.updateRenderToTextureEnabled(); + } + + get renderOffscreen() { + return this._renderOffscreen; + } + + set renderOffscreen(v) { + this._renderOffscreen = v; + this._core.setHasRenderUpdates(1); + + // This enforces rechecking the 'within bounds'. + this._core._setRecalc(6); + } + + get colorize() { + return this._colorize; + } + + set colorize(v) { + if (this._colorize !== v) { + this._colorize = v; + + // Only affects the finally drawn quad. + this._core.setHasRenderUpdates(1); + } + } + + _getTextureSource() { + if (!this._resultTextureSource) { + this._resultTextureSource = new _TextureSource_mjs__WEBPACK_IMPORTED_MODULE_0__["default"](this._element.stage.textureManager); + this.updateResultTexture(); + } + return this._resultTextureSource; + } + + hasResultTexture() { + return !!this._resultTextureSource; + } + + resultTextureInUse() { + return this._resultTextureSource && this._resultTextureSource.hasEnabledElements(); + } + + updateResultTexture() { + let resultTexture = this.getResultTexture(); + if (this._resultTextureSource) { + if (this._resultTextureSource.nativeTexture !== resultTexture) { + let w = resultTexture ? resultTexture.w : 0; + let h = resultTexture ? resultTexture.h : 0; + this._resultTextureSource.replaceNativeTexture(resultTexture, w, h); + } + + // Texture will be updated: all elements using the source need to be updated as well. + this._resultTextureSource.forEachEnabledElement(element => { + element._updateDimensions(); + element.core.setHasRenderUpdates(3); + }); + } + } + + mustRenderToTexture() { + // Check if we must really render as texture. + if (this._enabled && !this.lazy) { + return true; + } else if (this._enabled && this.lazy && this._core._hasRenderUpdates < 3) { + // Static-only: if renderToTexture did not need to update during last drawn frame, generate it as a cache. + return true; + } + return false; + } + + deactivate() { + this.release(); + } + + get renderTextureReused() { + return this._renderTextureReused; + } + + release() { + this.releaseRenderTexture(); + } + + releaseRenderTexture() { + if (this._renderTexture) { + if (!this._renderTextureReused) { + this.ctx.releaseRenderTexture(this._renderTexture); + } + this._renderTexture = null; + this._renderTextureReused = false; + this.updateResultTexture(); + } + } + + // Reuses the specified texture as the render texture (in ancestor). + reuseTextureAsRenderTexture(nativeTexture) { + if (this._renderTexture !== nativeTexture) { + this.releaseRenderTexture(); + this._renderTexture = nativeTexture; + this._renderTextureReused = true; + } + } + + hasRenderTexture() { + return !!this._renderTexture; + } + + getRenderTexture() { + if (!this._renderTexture) { + this._renderTexture = this.ctx.allocateRenderTexture(this._core._w, this._core._h); + this._renderTextureReused = false; + } + return this._renderTexture; + } + + getResultTexture() { + return this._renderTexture; + } + +} + + + +/***/ }), + +/***/ "./node_modules/@lightningjs/sdk/package.json": +/*!****************************************************!*\ + !*** ./node_modules/@lightningjs/sdk/package.json ***! + \****************************************************/ +/*! exports provided: name, version, license, types, scripts, lint-staged, husky, dependencies, devDependencies, repository, bugs, default */ +/***/ (function(module) { + +module.exports = JSON.parse("{\"name\":\"@lightningjs/sdk\",\"version\":\"5.5.4\",\"license\":\"Apache-2.0\",\"types\":\"index.d.ts\",\"scripts\":{\"postinstall\":\"node ./scripts/postinstall.js\",\"lint\":\"eslint '**/*.js'\",\"release\":\"npm publish --access public\",\"typedoc\":\"typedoc --tsconfig tsconfig.typedoc.json\",\"tsd\":\"tsd\"},\"lint-staged\":{\"*.js\":[\"eslint --fix\"],\"src/startApp.js\":[\"rollup -c ./rollup.config.js\"]},\"husky\":{\"hooks\":{\"pre-commit\":\"lint-staged\"}},\"dependencies\":{\"@babel/polyfill\":\"^7.11.5\",\"@lightningjs/core\":\"^2.13.1\",\"@metrological/sdk\":\"^1.0.2\",\"@michieljs/execute-as-promise\":\"^1.0.0\",\"deepmerge\":\"^4.2.2\",\"is-plain-object\":\"^5.0.0\",\"localcookies\":\"^2.0.0\",\"shelljs\":\"^0.8.5\",\"url-polyfill\":\"^1.1.10\",\"whatwg-fetch\":\"^3.0.0\"},\"devDependencies\":{\"@babel/core\":\"^7.11.6\",\"@babel/plugin-transform-parameters\":\"^7.10.5 \",\"@babel/plugin-transform-spread\":\"^7.11.0\",\"@babel/preset-env\":\"^7.11.5\",\"babel-eslint\":\"^10.1.0\",\"eslint\":\"^7.10.0\",\"eslint-config-prettier\":\"^6.12.0\",\"eslint-plugin-prettier\":\"^3.1.4\",\"husky\":\"^4.3.0\",\"lint-staged\":\"^10.4.0\",\"prettier\":\"^1.19.1\",\"rollup\":\"^1.32.1\",\"rollup-plugin-babel\":\"^4.4.0\",\"tsd\":\"^0.22.0\",\"typedoc\":\"^0.23.9\"},\"repository\":{\"type\":\"git\",\"url\":\"git@github.com:rdkcentral/Lightning-SDK.git\"},\"bugs\":{\"url\":\"https://github.com/rdkcentral/Lightning-SDK/issues\"}}"); + +/***/ }), + +/***/ "./node_modules/@lightningjs/sdk/src/Accessibility/Announcer/Speech.js": +/*!*****************************************************************************!*\ + !*** ./node_modules/@lightningjs/sdk/src/Accessibility/Announcer/Speech.js ***! + \*****************************************************************************/ +/*! exports provided: default */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* + * If not stated otherwise in this file or this component's LICENSE file the + * following copyright and licenses apply: + * + * Copyright 2020 Metrological + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* global SpeechSynthesisErrorEvent */ +function flattenStrings(series = []) { + const flattenedSeries = [] + + for (var i = 0; i < series.length; i++) { + if (typeof series[i] === 'string' && !series[i].includes('PAUSE-')) { + flattenedSeries.push(series[i]) + } else { + break + } + } + // add a "word boundary" to ensure the Announcer doesn't automatically try to + // interpret strings that look like dates but are not actually dates + // for example, if "Rising Sun" and "1993" are meant to be two separate lines, + // when read together, "Sun 1993" is interpretted as "Sunday 1993" + return [flattenedSeries.join(',\b ')].concat(series.slice(i)) +} + +function delay(pause) { + return new Promise(resolve => { + setTimeout(resolve, pause) + }) +} + +/** + * Speak a string + * + * @param {string} phrase Phrase to speak + * @param {SpeechSynthesisUtterance[]} utterances An array which the new SpeechSynthesisUtterance instance representing this utterance will be appended + * @return {Promise} Promise resolved when the utterance has finished speaking, and rejected if there's an error + */ +function speak(phrase, utterances, lang = 'en-US') { + const synth = window.speechSynthesis + return new Promise((resolve, reject) => { + const utterance = new SpeechSynthesisUtterance(phrase) + utterance.lang = lang + utterance.onend = () => { + resolve() + } + utterance.onerror = e => { + reject(e) + } + utterances.push(utterance) + synth.speak(utterance) + }) +} + +function speakSeries(series, lang, root = true) { + const synth = window.speechSynthesis + const remainingPhrases = flattenStrings(Array.isArray(series) ? series : [series]) + const nestedSeriesResults = [] + /* + We hold this array of SpeechSynthesisUtterances in order to prevent them from being + garbage collected prematurely on STB hardware which can cause the 'onend' events of + utterances to not fire consistently. + */ + const utterances = [] + let active = true + + const seriesChain = (async () => { + try { + while (active && remainingPhrases.length) { + const phrase = await Promise.resolve(remainingPhrases.shift()) + if (!active) { + // Exit + // Need to check this after the await in case it was cancelled in between + break + } else if (typeof phrase === 'string' && phrase.includes('PAUSE-')) { + // Pause it + let pause = phrase.split('PAUSE-')[1] * 1000 + if (isNaN(pause)) { + pause = 0 + } + await delay(pause) + } else if (typeof phrase === 'string' && phrase.length) { + // Speak it + const totalRetries = 3 + let retriesLeft = totalRetries + while (active && retriesLeft > 0) { + try { + await speak(phrase, utterances, lang) + retriesLeft = 0 + } catch (e) { + // eslint-disable-next-line no-undef + if (e instanceof SpeechSynthesisErrorEvent) { + if (e.error === 'network') { + retriesLeft-- + console.warn(`Speech synthesis network error. Retries left: ${retriesLeft}`) + await delay(500 * (totalRetries - retriesLeft)) + } else if (e.error === 'canceled' || e.error === 'interrupted') { + // Cancel or interrupt error (ignore) + retriesLeft = 0 + } else { + throw new Error(`SpeechSynthesisErrorEvent: ${e.error}`) + } + } else { + throw e + } + } + } + } else if (typeof phrase === 'function') { + const seriesResult = speakSeries(phrase(), lang, false) + nestedSeriesResults.push(seriesResult) + await seriesResult.series + } else if (Array.isArray(phrase)) { + // Speak it (recursively) + const seriesResult = speakSeries(phrase, lang, false) + nestedSeriesResults.push(seriesResult) + await seriesResult.series + } + } + } finally { + active = false + } + })() + return { + series: seriesChain, + get active() { + return active + }, + append: toSpeak => { + remainingPhrases.push(toSpeak) + }, + cancel: () => { + if (!active) { + return + } + if (root) { + synth.cancel() + } + nestedSeriesResults.forEach(nestedSeriesResults => { + nestedSeriesResults.cancel() + }) + active = false + }, + } +} + +let currentSeries +/* harmony default export */ __webpack_exports__["default"] = (function(toSpeak, lang) { + currentSeries && currentSeries.cancel() + currentSeries = speakSeries(toSpeak, lang) + return currentSeries +}); + + +/***/ }), + +/***/ "./node_modules/@lightningjs/sdk/src/Accessibility/Announcer/index.js": +/*!****************************************************************************!*\ + !*** ./node_modules/@lightningjs/sdk/src/Accessibility/Announcer/index.js ***! + \****************************************************************************/ +/*! exports provided: default */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var _Speech_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./Speech.js */ "./node_modules/@lightningjs/sdk/src/Accessibility/Announcer/Speech.js"); +/* harmony import */ var _utils_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./utils.js */ "./node_modules/@lightningjs/sdk/src/Accessibility/Announcer/utils.js"); +/* + * If not stated otherwise in this file or this component's LICENSE file the + * following copyright and licenses apply: + * + * Copyright 2020 Metrological + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + + +let resetFocusPathTimer +let prevFocusPath = [] +let currentlySpeaking +let voiceOutDisabled = false +const fiveMinutes = 300000 + +function onFocusChangeCore(focusPath = []) { + if (!Announcer.enabled) { + return + } + + const loaded = focusPath.every(elm => !elm.loading) + const focusDiff = focusPath.filter(elm => !prevFocusPath.includes(elm)) + + resetFocusPathTimer() + + if (!loaded) { + Announcer.onFocusChange() + return + } + + prevFocusPath = focusPath.slice(0) + + let toAnnounceText = [] + let toAnnounce = focusDiff.reduce((acc, elm) => { + if (elm.announce) { + acc.push([Object(_utils_js__WEBPACK_IMPORTED_MODULE_1__["getElmName"])(elm), 'Announce', elm.announce]) + toAnnounceText.push(elm.announce) + } else if (elm.title) { + acc.push([Object(_utils_js__WEBPACK_IMPORTED_MODULE_1__["getElmName"])(elm), 'Title', elm.title]) + toAnnounceText.push(elm.title) + } + return acc + }, []) + + focusDiff.reverse().reduce((acc, elm) => { + if (elm.announceContext) { + acc.push([Object(_utils_js__WEBPACK_IMPORTED_MODULE_1__["getElmName"])(elm), 'Context', elm.announceContext]) + toAnnounceText.push(elm.announceContext) + } else { + acc.push([Object(_utils_js__WEBPACK_IMPORTED_MODULE_1__["getElmName"])(elm), 'No Context', '']) + } + return acc + }, toAnnounce) + + if (Announcer.debug) { + console.table(toAnnounce) + } + + if (toAnnounceText.length) { + return Announcer.speak(toAnnounceText.reduce((acc, val) => acc.concat(val), [])) + } +} + +function textToSpeech(toSpeak) { + if (voiceOutDisabled) { + return + } + + return (currentlySpeaking = Object(_Speech_js__WEBPACK_IMPORTED_MODULE_0__["default"])(toSpeak)) +} + +const Announcer = { + enabled: true, + debug: false, + cancel: function() { + currentlySpeaking && currentlySpeaking.cancel() + }, + clearPrevFocus: function(depth = 0) { + prevFocusPath = prevFocusPath.slice(0, depth) + resetFocusPathTimer() + }, + speak: function(text, { append = false, notification = false } = {}) { + if (Announcer.enabled) { + Announcer.onFocusChange.flush() + if (append && currentlySpeaking && currentlySpeaking.active) { + currentlySpeaking.append(text) + } else { + Announcer.cancel() + textToSpeech(text) + } + + if (notification) { + voiceOutDisabled = true + currentlySpeaking.series.finally(() => { + voiceOutDisabled = false + Announcer.refresh() + }) + } + } + + return currentlySpeaking + }, + setupTimers: function({ focusDebounce = 400, focusChangeTimeout = fiveMinutes } = {}) { + Announcer.onFocusChange = Object(_utils_js__WEBPACK_IMPORTED_MODULE_1__["debounce"])(onFocusChangeCore, focusDebounce) + + resetFocusPathTimer = Object(_utils_js__WEBPACK_IMPORTED_MODULE_1__["debounce"])(() => { + // Reset focus path for full announce + prevFocusPath = [] + }, focusChangeTimeout) + }, +} +Announcer.setupTimers() +/* harmony default export */ __webpack_exports__["default"] = (Announcer); + + +/***/ }), + +/***/ "./node_modules/@lightningjs/sdk/src/Accessibility/Announcer/utils.js": +/*!****************************************************************************!*\ + !*** ./node_modules/@lightningjs/sdk/src/Accessibility/Announcer/utils.js ***! + \****************************************************************************/ +/*! exports provided: getElmName, debounce */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getElmName", function() { return getElmName; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "debounce", function() { return debounce; }); +/* + * If not stated otherwise in this file or this component's LICENSE file the + * following copyright and licenses apply: + * + * Copyright 2020 Metrological + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Code from: https://github.com/jashkenas/underscore is + * Copyright (c) 2009-2022 Jeremy Ashkenas, Julian Gonggrijp, and DocumentCloud and Investigative Reporters & Editors + * Licensed under the MIT License based off: + * http://unscriptable.com/2009/03/20/debouncing-javascript-methods/ which is: + * Copyright (c) 2007-2009 unscriptable.com and John M. Hann + * Licensed under the MIT License (with X11 advertising exception) + */ + +function getElmName(elm) { + return elm.ref || elm.constructor.name +} + +/** + * Returns a function, that, as long as it continues to be invoked, will not + * be triggered. The function will be called after it stops being called for + * N milliseconds. If `immediate` is passed, trigger the function on the + * leading edge, instead of the trailing. The function also has a property 'clear' + * that is a function which will clear the timer to prevent previously scheduled executions. + * + * @source underscore.js + * @see http://unscriptable.com/2009/03/20/debouncing-javascript-methods/ + * @param {Function} function to wrap + * @param {Number} timeout in ms (`100`) + * @param {Boolean} whether to execute at the beginning (`false`) + * @api public + */ +function debounce(func, wait, immediate) { + var timeout, args, context, timestamp, result + if (null == wait) wait = 100 + + function later() { + var last = Date.now() - timestamp + + if (last < wait && last >= 0) { + timeout = setTimeout(later, wait - last) + } else { + timeout = null + if (!immediate) { + result = func.apply(context, args) + context = args = null + } + } + } + + var debounced = function() { + context = this + args = arguments + timestamp = Date.now() + var callNow = immediate && !timeout + if (!timeout) timeout = setTimeout(later, wait) + if (callNow) { + result = func.apply(context, args) + context = args = null + } + + return result + } + + debounced.clear = function() { + if (timeout) { + clearTimeout(timeout) + timeout = null + } + } + + debounced.flush = function() { + if (timeout) { + result = func.apply(context, args) + context = args = null + + clearTimeout(timeout) + timeout = null + } + } + + return debounced +} + + +/***/ }), + +/***/ "./node_modules/@lightningjs/sdk/src/Accessibility/index.js": +/*!******************************************************************!*\ + !*** ./node_modules/@lightningjs/sdk/src/Accessibility/index.js ***! + \******************************************************************/ +/*! exports provided: default */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var _Log__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Log */ "./node_modules/@lightningjs/sdk/src/Log/index.js"); +/* harmony import */ var _shaders__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./shaders */ "./node_modules/@lightningjs/sdk/src/Accessibility/shaders/index.js"); +/* harmony import */ var _Announcer__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./Announcer */ "./node_modules/@lightningjs/sdk/src/Accessibility/Announcer/index.js"); +/* + * If not stated otherwise in this file or this component's LICENSE file the + * following copyright and licenses apply: + * + * Copyright 2020 Metrological + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + + + +/* harmony default export */ __webpack_exports__["default"] = ({ + Announcer: _Announcer__WEBPACK_IMPORTED_MODULE_2__["default"], + colorshift(component, type = false, config = { brightness: 50, contrast: 50, gamma: 50 }) { + config = { ...{ brightness: 50, contrast: 50, gamma: 50 }, ...config } + + const shader = type && Object(_shaders__WEBPACK_IMPORTED_MODULE_1__["colorshiftShader"])(type) + if (shader) { + _Log__WEBPACK_IMPORTED_MODULE_0__["default"].info('Accessibility Colorshift', type, config) + component.rtt = true + component.shader = { + type: shader, + ...config, + } + } else { + _Log__WEBPACK_IMPORTED_MODULE_0__["default"].info('Accessibility Colorshift', 'Disabled') + component.rtt = false + component.shader = null + } + }, +}); + + +/***/ }), + +/***/ "./node_modules/@lightningjs/sdk/src/Accessibility/shaders/ColorShift.js": +/*!*******************************************************************************!*\ + !*** ./node_modules/@lightningjs/sdk/src/Accessibility/shaders/ColorShift.js ***! + \*******************************************************************************/ +/*! exports provided: default */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return ColorShift; }); +/* harmony import */ var _Lightning__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../Lightning */ "./node_modules/@lightningjs/sdk/src/Lightning/index.js"); +/* + * If not stated otherwise in this file or this component's LICENSE file the + * following copyright and licenses apply: + * + * Copyright 2020 Metrological + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + +class ColorShift extends _Lightning__WEBPACK_IMPORTED_MODULE_0__["default"].shaders.WebGLDefaultShader { + set brightness(v) { + this._brightness = (v - 50) / 100 + this.redraw() + } + + set contrast(v) { + this._contrast = (v + 50) / 100 + this.redraw() + } + + set gamma(v) { + this._gamma = (v + 50) / 100 + this.redraw() + } + + setupUniforms(operation) { + super.setupUniforms(operation) + const gl = this.gl + this._setUniform( + 'colorAdjust', + [this._brightness || 0.0, this._contrast || 1.0, this._gamma || 1.0], + gl.uniform3fv + ) + } +} + +ColorShift.before = ` + #ifdef GL_ES + # ifdef GL_FRAGMENT_PRECISION_HIGH + precision highp float; + # else + precision lowp float; + # endif + #endif + + varying vec2 vTextureCoord; + varying vec4 vColor; + uniform sampler2D uSampler; + uniform vec3 colorAdjust; + + const mat3 RGBtoOpponentMat = mat3(0.2814, -0.0971, -0.0930, 0.6938, 0.1458,-0.2529, 0.0638, -0.0250, 0.4665); + const mat3 OpponentToRGBMat = mat3(1.1677, 0.9014, 0.7214, -6.4315, 2.5970, 0.1257, -0.5044, 0.0159, 2.0517); +` + +ColorShift.after = ` + vec3 brightnessContrast(vec3 value, float brightness, float contrast) + { + return (value - 0.5) * contrast + 0.5 + brightness; + } + + vec3 updateGamma(vec3 value, float param) + { + return vec3(pow(abs(value.r), param),pow(abs(value.g), param),pow(abs(value.b), param)); + } + + void main(void){ + vec4 fragColor = texture2D(uSampler, vTextureCoord); + vec4 color = filter(fragColor) * vColor; + + vec3 bc = brightnessContrast(color.rgb,colorAdjust[0],colorAdjust[1]); + vec3 ga = updateGamma(bc.rgb, colorAdjust[2]); + + gl_FragColor = vec4(ga.rgb, color.a); + } +` + + +/***/ }), + +/***/ "./node_modules/@lightningjs/sdk/src/Accessibility/shaders/DeuteranopiaShader.js": +/*!***************************************************************************************!*\ + !*** ./node_modules/@lightningjs/sdk/src/Accessibility/shaders/DeuteranopiaShader.js ***! + \***************************************************************************************/ +/*! exports provided: default */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return DeuteranopiaShader; }); +/* harmony import */ var _ColorShift__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./ColorShift */ "./node_modules/@lightningjs/sdk/src/Accessibility/shaders/ColorShift.js"); +/* + * If not stated otherwise in this file or this component's LICENSE file the + * following copyright and licenses apply: + * + * Copyright 2020 Metrological + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + +class DeuteranopiaShader extends _ColorShift__WEBPACK_IMPORTED_MODULE_0__["default"] {} + +DeuteranopiaShader.fragmentShaderSource = ` + ${_ColorShift__WEBPACK_IMPORTED_MODULE_0__["default"].before} + vec4 vision(vec4 color) + { + vec4 r = vec4( 0.43, 0.72, -0.15, 0.0 ); + vec4 g = vec4( 0.34, 0.57, 0.09, 0.0 ); + vec4 b = vec4(-0.02, 0.03, 1.00, 0.0 ); + + return vec4(dot(color, r), dot(color, g), dot(color, b), color.a); + } + + vec4 filter( vec4 color ) + { + vec3 opponentColor = RGBtoOpponentMat * vec3(color.r, color.g, color.b); + opponentColor.x -= opponentColor.y * 1.5; + vec3 rgbColor = OpponentToRGBMat * opponentColor; + return vision(vec4(rgbColor.r, rgbColor.g, rgbColor.b, color.a)); + } + ${_ColorShift__WEBPACK_IMPORTED_MODULE_0__["default"].after} +` + + +/***/ }), + +/***/ "./node_modules/@lightningjs/sdk/src/Accessibility/shaders/MonochromacyShader.js": +/*!***************************************************************************************!*\ + !*** ./node_modules/@lightningjs/sdk/src/Accessibility/shaders/MonochromacyShader.js ***! + \***************************************************************************************/ +/*! exports provided: default */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return MonochromacyShader; }); +/* harmony import */ var _ColorShift__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./ColorShift */ "./node_modules/@lightningjs/sdk/src/Accessibility/shaders/ColorShift.js"); +/* + * If not stated otherwise in this file or this component's LICENSE file the + * following copyright and licenses apply: + * + * Copyright 2020 Metrological + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + +class MonochromacyShader extends _ColorShift__WEBPACK_IMPORTED_MODULE_0__["default"] {} + +MonochromacyShader.fragmentShaderSource = ` + ${_ColorShift__WEBPACK_IMPORTED_MODULE_0__["default"].before} + vec4 filter( vec4 color ) + { + float grey = dot(color.rgb, vec3(0.299, 0.587, 0.114)); + return vec4(vec3(grey, grey, grey), 1.0 ); + } + ${_ColorShift__WEBPACK_IMPORTED_MODULE_0__["default"].after} +` + + +/***/ }), + +/***/ "./node_modules/@lightningjs/sdk/src/Accessibility/shaders/NormalShader.js": +/*!*********************************************************************************!*\ + !*** ./node_modules/@lightningjs/sdk/src/Accessibility/shaders/NormalShader.js ***! + \*********************************************************************************/ +/*! exports provided: default */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return NeutralShader; }); +/* harmony import */ var _ColorShift__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./ColorShift */ "./node_modules/@lightningjs/sdk/src/Accessibility/shaders/ColorShift.js"); +/* + * If not stated otherwise in this file or this component's LICENSE file the + * following copyright and licenses apply: + * + * Copyright 2020 Metrological + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + +class NeutralShader extends _ColorShift__WEBPACK_IMPORTED_MODULE_0__["default"] {} + +NeutralShader.fragmentShaderSource = ` + ${_ColorShift__WEBPACK_IMPORTED_MODULE_0__["default"].before} + vec4 filter( vec4 color ) + { + return color; + } + ${_ColorShift__WEBPACK_IMPORTED_MODULE_0__["default"].after} +` + + +/***/ }), + +/***/ "./node_modules/@lightningjs/sdk/src/Accessibility/shaders/ProtanopiaShader.js": +/*!*************************************************************************************!*\ + !*** ./node_modules/@lightningjs/sdk/src/Accessibility/shaders/ProtanopiaShader.js ***! + \*************************************************************************************/ +/*! exports provided: default */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return ProtanopiaShader; }); +/* harmony import */ var _ColorShift__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./ColorShift */ "./node_modules/@lightningjs/sdk/src/Accessibility/shaders/ColorShift.js"); +/* + * If not stated otherwise in this file or this component's LICENSE file the + * following copyright and licenses apply: + * + * Copyright 2020 Metrological + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + +class ProtanopiaShader extends _ColorShift__WEBPACK_IMPORTED_MODULE_0__["default"] {} + +ProtanopiaShader.fragmentShaderSource = ` + ${_ColorShift__WEBPACK_IMPORTED_MODULE_0__["default"].before} + vec4 vision(vec4 color) + { + vec4 r = vec4( 0.20, 0.99, -0.19, 0.0); + vec4 g = vec4( 0.16, 0.79, 0.04, 0.0); + vec4 b = vec4( 0.01, -0.01, 1.00, 0.0); + + return vec4(dot(color, r), dot(color, g), dot(color, b), color.a); + } + + vec4 filter( vec4 color ) + { + vec3 opponentColor = RGBtoOpponentMat * vec3(color.r, color.g, color.b); + opponentColor.x -= opponentColor.y * 1.5; + vec3 rgbColor = OpponentToRGBMat * opponentColor; + return vision(vec4(rgbColor.r, rgbColor.g, rgbColor.b, color.a)); + } + ${_ColorShift__WEBPACK_IMPORTED_MODULE_0__["default"].after} +` + + +/***/ }), + +/***/ "./node_modules/@lightningjs/sdk/src/Accessibility/shaders/TritanopiaShader.js": +/*!*************************************************************************************!*\ + !*** ./node_modules/@lightningjs/sdk/src/Accessibility/shaders/TritanopiaShader.js ***! + \*************************************************************************************/ +/*! exports provided: default */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return TritanopiaShader; }); +/* harmony import */ var _ColorShift__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./ColorShift */ "./node_modules/@lightningjs/sdk/src/Accessibility/shaders/ColorShift.js"); +/* + * If not stated otherwise in this file or this component's LICENSE file the + * following copyright and licenses apply: + * + * Copyright 2020 Metrological + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + +class TritanopiaShader extends _ColorShift__WEBPACK_IMPORTED_MODULE_0__["default"] {} + +TritanopiaShader.fragmentShaderSource = ` + ${_ColorShift__WEBPACK_IMPORTED_MODULE_0__["default"].before} + vec4 vision(vec4 color) + { + vec4 r = vec4( 0.97, 0.11, -0.08, 0.0 ); + vec4 g = vec4( 0.02, 0.82, 0.16, 0.0 ); + vec4 b = vec4(-0.06, 0.88, 0.18, 0.0 ); + + return vec4(dot(color, r), dot(color, g), dot(color, b), color.a); + } + + vec4 filter( vec4 color ) + { + vec3 opponentColor = RGBtoOpponentMat * vec3(color.r, color.g, color.b); + opponentColor.x -= ((3.0 * opponentColor.z) - opponentColor.y) * 0.25; + vec3 rgbColor = OpponentToRGBMat * opponentColor; + return vision(vec4(rgbColor.r, rgbColor.g, rgbColor.b, color.a)); + } + ${_ColorShift__WEBPACK_IMPORTED_MODULE_0__["default"].after} +` + + +/***/ }), + +/***/ "./node_modules/@lightningjs/sdk/src/Accessibility/shaders/index.js": +/*!**************************************************************************!*\ + !*** ./node_modules/@lightningjs/sdk/src/Accessibility/shaders/index.js ***! + \**************************************************************************/ +/*! exports provided: colorshiftShader */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "colorshiftShader", function() { return colorshiftShader; }); +/* harmony import */ var _ProtanopiaShader__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./ProtanopiaShader */ "./node_modules/@lightningjs/sdk/src/Accessibility/shaders/ProtanopiaShader.js"); +/* harmony import */ var _DeuteranopiaShader__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./DeuteranopiaShader */ "./node_modules/@lightningjs/sdk/src/Accessibility/shaders/DeuteranopiaShader.js"); +/* harmony import */ var _TritanopiaShader__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./TritanopiaShader */ "./node_modules/@lightningjs/sdk/src/Accessibility/shaders/TritanopiaShader.js"); +/* harmony import */ var _NormalShader__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./NormalShader */ "./node_modules/@lightningjs/sdk/src/Accessibility/shaders/NormalShader.js"); +/* harmony import */ var _MonochromacyShader__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./MonochromacyShader */ "./node_modules/@lightningjs/sdk/src/Accessibility/shaders/MonochromacyShader.js"); +/* + * If not stated otherwise in this file or this component's LICENSE file the + * following copyright and licenses apply: + * + * Copyright 2020 Metrological + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + + + + + +const colorshiftShader = type => { + const shadersMap = { + normal: _NormalShader__WEBPACK_IMPORTED_MODULE_3__["default"], + monochromacy: _MonochromacyShader__WEBPACK_IMPORTED_MODULE_4__["default"], + deuteranopia: _DeuteranopiaShader__WEBPACK_IMPORTED_MODULE_1__["default"], + tritanopia: _TritanopiaShader__WEBPACK_IMPORTED_MODULE_2__["default"], + protanopia: _ProtanopiaShader__WEBPACK_IMPORTED_MODULE_0__["default"], + } + + type = (typeof type === 'string' && type.toLowerCase()) || null + + return Object.keys(shadersMap).indexOf(type) > -1 ? shadersMap[type] : false +} + + +/***/ }), + +/***/ "./node_modules/@lightningjs/sdk/src/Ads/index.js": +/*!********************************************************!*\ + !*** ./node_modules/@lightningjs/sdk/src/Ads/index.js ***! + \********************************************************/ +/*! exports provided: initAds, default */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "initAds", function() { return initAds; }); +/* harmony import */ var _Log__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Log */ "./node_modules/@lightningjs/sdk/src/Log/index.js"); +/* harmony import */ var _metrological_sdk__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @metrological/sdk */ "./node_modules/@metrological/sdk/index.js"); +/* + * If not stated otherwise in this file or this component's LICENSE file the + * following copyright and licenses apply: + * + * Copyright 2020 Metrological + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + + +let consumer + +let getAds = () => { + // todo: enable some default ads during development, maybe from the settings.json + return Promise.resolve({ + prerolls: [], + midrolls: [], + postrolls: [], + }) +} + +const initAds = config => { + if (config.getAds) { + getAds = config.getAds + } +} + +const state = { + active: false, +} + +const playSlot = (slot = []) => { + return slot.reduce((promise, ad) => { + return promise.then(() => { + return playAd(ad) + }) + }, Promise.resolve(null)) +} + +const playAd = ad => { + return new Promise(resolve => { + if (state.active === false) { + _Log__WEBPACK_IMPORTED_MODULE_0__["default"].info('Ad', 'Skipping add due to inactive state') + return resolve() + } + // is it safe to rely on videoplayer plugin already created the video tag? + const videoEl = document.getElementsByTagName('video')[0] + videoEl.style.display = 'block' + videoEl.style.visibility = 'visible' + videoEl.src = Object(_metrological_sdk__WEBPACK_IMPORTED_MODULE_1__["mediaUrl"])(ad.url) + videoEl.load() + + let timeEvents = null + let timeout + + const cleanup = () => { + // remove all listeners + Object.keys(handlers).forEach(handler => + videoEl.removeEventListener(handler, handlers[handler]) + ) + resolve() + } + const handlers = { + play() { + _Log__WEBPACK_IMPORTED_MODULE_0__["default"].info('Ad', 'Play ad', ad.url) + fireOnConsumer('Play', ad) + sendBeacon(ad.callbacks, 'defaultImpression') + }, + ended() { + fireOnConsumer('Ended', ad) + sendBeacon(ad.callbacks, 'complete') + cleanup() + }, + timeupdate() { + if (!timeEvents && videoEl.duration) { + // calculate when to fire the time based events (now that duration is known) + timeEvents = { + firstQuartile: videoEl.duration / 4, + midPoint: videoEl.duration / 2, + thirdQuartile: (videoEl.duration / 4) * 3, + } + _Log__WEBPACK_IMPORTED_MODULE_0__["default"].info('Ad', 'Calculated quartiles times', { timeEvents }) + } + if ( + timeEvents && + timeEvents.firstQuartile && + videoEl.currentTime >= timeEvents.firstQuartile + ) { + fireOnConsumer('FirstQuartile', ad) + delete timeEvents.firstQuartile + sendBeacon(ad.callbacks, 'firstQuartile') + } + if (timeEvents && timeEvents.midPoint && videoEl.currentTime >= timeEvents.midPoint) { + fireOnConsumer('MidPoint', ad) + delete timeEvents.midPoint + sendBeacon(ad.callbacks, 'midPoint') + } + if ( + timeEvents && + timeEvents.thirdQuartile && + videoEl.currentTime >= timeEvents.thirdQuartile + ) { + fireOnConsumer('ThirdQuartile', ad) + delete timeEvents.thirdQuartile + sendBeacon(ad.callbacks, 'thirdQuartile') + } + }, + stalled() { + fireOnConsumer('Stalled', ad) + timeout = setTimeout(() => { + cleanup() + }, 5000) // make timeout configurable + }, + canplay() { + timeout && clearTimeout(timeout) + }, + error() { + fireOnConsumer('Error', ad) + cleanup() + }, + // this doesn't work reliably on sky box, moved logic to timeUpdate event + // loadedmetadata() { + // // calculate when to fire the time based events (now that duration is known) + // timeEvents = { + // firstQuartile: videoEl.duration / 4, + // midPoint: videoEl.duration / 2, + // thirdQuartile: (videoEl.duration / 4) * 3, + // } + // }, + abort() { + cleanup() + }, + // todo: pause, resume, mute, unmute beacons + } + // add all listeners + Object.keys(handlers).forEach(handler => videoEl.addEventListener(handler, handlers[handler])) + + videoEl.play() + }) +} + +const sendBeacon = (callbacks, event) => { + if (callbacks && callbacks[event]) { + _Log__WEBPACK_IMPORTED_MODULE_0__["default"].info('Ad', 'Sending beacon', event, callbacks[event]) + return callbacks[event].reduce((promise, url) => { + return promise.then(() => + fetch(url) + // always resolve, also in case of a fetch error (so we don't block firing the rest of the beacons for this event) + // note: for fetch failed http responses don't throw an Error :) + .then(response => { + if (response.status === 200) { + fireOnConsumer('Beacon' + event + 'Sent') + } else { + fireOnConsumer('Beacon' + event + 'Failed' + response.status) + } + Promise.resolve(null) + }) + .catch(() => { + Promise.resolve(null) + }) + ) + }, Promise.resolve(null)) + } else { + _Log__WEBPACK_IMPORTED_MODULE_0__["default"].info('Ad', 'No callback found for ' + event) + } +} + +const fireOnConsumer = (event, args) => { + if (consumer) { + consumer.fire('$ad' + event, args) + consumer.fire('$adEvent', event, args) + } +} + +/* harmony default export */ __webpack_exports__["default"] = ({ + get(config, videoPlayerConsumer) { + if (config.enabled === false) { + return Promise.resolve({ + prerolls() { + return Promise.resolve() + }, + }) + } + consumer = videoPlayerConsumer + + return new Promise(resolve => { + _Log__WEBPACK_IMPORTED_MODULE_0__["default"].info('Ad', 'Starting session') + getAds(config).then(ads => { + _Log__WEBPACK_IMPORTED_MODULE_0__["default"].info('Ad', 'API result', ads) + resolve({ + prerolls() { + if (ads.preroll) { + state.active = true + fireOnConsumer('PrerollSlotImpression', ads) + sendBeacon(ads.preroll.callbacks, 'slotImpression') + return playSlot(ads.preroll.ads).then(() => { + fireOnConsumer('PrerollSlotEnd', ads) + sendBeacon(ads.preroll.callbacks, 'slotEnd') + state.active = false + }) + } + return Promise.resolve() + }, + midrolls() { + return Promise.resolve() + }, + postrolls() { + return Promise.resolve() + }, + }) + }) + }) + }, + cancel() { + _Log__WEBPACK_IMPORTED_MODULE_0__["default"].info('Ad', 'Cancel Ad') + state.active = false + }, + stop() { + _Log__WEBPACK_IMPORTED_MODULE_0__["default"].info('Ad', 'Stop Ad') + state.active = false + // fixme: duplication + const videoEl = document.getElementsByTagName('video')[0] + videoEl.pause() + videoEl.removeAttribute('src') + }, +}); + + +/***/ }), + +/***/ "./node_modules/@lightningjs/sdk/src/Application/index.js": +/*!****************************************************************!*\ + !*** ./node_modules/@lightningjs/sdk/src/Application/index.js ***! + \****************************************************************/ +/*! exports provided: AppInstance, AppData, default */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "AppInstance", function() { return AppInstance; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "AppData", function() { return AppData; }); +/* harmony import */ var _Accessibility__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Accessibility */ "./node_modules/@lightningjs/sdk/src/Accessibility/index.js"); +/* harmony import */ var deepmerge__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! deepmerge */ "./node_modules/deepmerge/dist/cjs.js"); +/* harmony import */ var deepmerge__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(deepmerge__WEBPACK_IMPORTED_MODULE_1__); +/* harmony import */ var is_plain_object__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! is-plain-object */ "./node_modules/is-plain-object/dist/is-plain-object.mjs"); +/* harmony import */ var _Lightning__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../Lightning */ "./node_modules/@lightningjs/sdk/src/Lightning/index.js"); +/* harmony import */ var _Locale__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../Locale */ "./node_modules/@lightningjs/sdk/src/Locale/index.js"); +/* harmony import */ var _Metrics__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../Metrics */ "./node_modules/@lightningjs/sdk/src/Metrics/index.js"); +/* harmony import */ var _VersionLabel__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../VersionLabel */ "./node_modules/@lightningjs/sdk/src/VersionLabel/index.js"); +/* harmony import */ var _FpsCounter__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../FpsCounter */ "./node_modules/@lightningjs/sdk/src/FpsCounter/index.js"); +/* harmony import */ var _Log__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../Log */ "./node_modules/@lightningjs/sdk/src/Log/index.js"); +/* harmony import */ var _Settings__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ../Settings */ "./node_modules/@lightningjs/sdk/src/Settings/index.js"); +/* harmony import */ var _Language__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ../Language */ "./node_modules/@lightningjs/sdk/src/Language/index.js"); +/* harmony import */ var _Utils__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ../Utils */ "./node_modules/@lightningjs/sdk/src/Utils/index.js"); +/* harmony import */ var _Registry__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ../Registry */ "./node_modules/@lightningjs/sdk/src/Registry/index.js"); +/* harmony import */ var _Colors__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ../Colors */ "./node_modules/@lightningjs/sdk/src/Colors/index.js"); +/* harmony import */ var _package_json__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ../../package.json */ "./node_modules/@lightningjs/sdk/package.json"); +var _package_json__WEBPACK_IMPORTED_MODULE_14___namespace = /*#__PURE__*/__webpack_require__.t(/*! ../../package.json */ "./node_modules/@lightningjs/sdk/package.json", 1); +/* + * If not stated otherwise in this file or this component's LICENSE file the + * following copyright and licenses apply: + * + * Copyright 2020 Metrological + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + + + + + + + + + + + + + + + + +let AppInstance +let AppData + +const defaultOptions = { + stage: { w: 1920, h: 1080, precision: 1, clearColor: 0x00000000, canvas2d: false }, + debug: false, + defaultFontFace: 'RobotoRegular', + keys: { + 8: 'Back', + 13: 'Enter', + 27: 'Menu', + 37: 'Left', + 38: 'Up', + 39: 'Right', + 40: 'Down', + 174: 'ChannelDown', + 175: 'ChannelUp', + 178: 'Stop', + 250: 'PlayPause', + 191: 'Search', // Use "/" for keyboard + 409: 'Search', + }, +} + +const customFontFaces = [] + +const fontLoader = (fonts, store) => + new Promise((resolve, reject) => { + fonts + .map(({ family, url, urls, descriptors }) => () => { + const src = urls + ? urls.map(url => { + return 'url(' + url + ')' + }) + : 'url(' + url + ')' + const fontFace = new FontFace(family, src, descriptors || {}) + store.push(fontFace) + _Log__WEBPACK_IMPORTED_MODULE_8__["default"].info('Loading font', family) + document.fonts.add(fontFace) + return fontFace.load() + }) + .reduce((promise, method) => { + return promise.then(() => method()) + }, Promise.resolve(null)) + .then(resolve) + .catch(reject) + }) + +/* harmony default export */ __webpack_exports__["default"] = (function(App, appData, platformSettings) { + const { width, height } = platformSettings + + if (width && height) { + defaultOptions.stage['w'] = width + defaultOptions.stage['h'] = height + defaultOptions.stage['precision'] = width / 1920 + } + + // support for 720p browser + if (!width && !height && window.innerHeight === 720) { + defaultOptions.stage['w'] = 1280 + defaultOptions.stage['h'] = 720 + defaultOptions.stage['precision'] = 1280 / 1920 + } + + return class Application extends _Lightning__WEBPACK_IMPORTED_MODULE_3__["default"].Application { + constructor(options) { + const config = deepmerge__WEBPACK_IMPORTED_MODULE_1___default()(defaultOptions, options, { + isMergeableObject: is_plain_object__WEBPACK_IMPORTED_MODULE_2__["isPlainObject"] + }) + + super(config) + this.config = config + } + + static _template() { + return { + w: 1920, + h: 1080, + } + } + + colorshift(type = false, config = {}) { + _Accessibility__WEBPACK_IMPORTED_MODULE_0__["default"].colorshift(this, type, config) + } + + get keymapping() { + return this.stage.application.config.keys + } + + /** + * This function overrides the default keymap with the latest keymap. + * @param customKeyMap + * @param keepDuplicates + */ + overrideKeyMap(customKeyMap, keepDuplicates = false) { + const baseKeyMap = this.stage.application.config.keys + Object.keys(customKeyMap).reduce((keymapping, key) => { + // prevent duplicate values to exist in final keymapping (i.e. 2 keys triggering 'Back') + if (!keepDuplicates) { + Object.keys(baseKeyMap).forEach(baseKey => { + if (baseKey != key && baseKeyMap[baseKey] == customKeyMap[key]) { + delete keymapping[baseKey] + } + }) + } + keymapping[key] = customKeyMap[key] + return keymapping + }, baseKeyMap) + return baseKeyMap + } + + _setup() { + Promise.all([ + this.loadFonts((App.config && App.config.fonts) || (App.getFonts && App.getFonts()) || []), + // to be deprecated + _Locale__WEBPACK_IMPORTED_MODULE_4__["default"].load((App.config && App.config.locale) || (App.getLocale && App.getLocale())), + App.language && this.loadLanguage(App.language()), + App.colors && this.loadColors(App.colors()), + ]) + .then(() => { + _Metrics__WEBPACK_IMPORTED_MODULE_5__["default"].app.loaded() + + this.w = this.config.stage.w / this.config.stage.precision + this.h = this.config.stage.h / this.config.stage.precision + + AppData = appData + + AppInstance = this.stage.c({ + ref: 'App', + type: App, + zIndex: 1, + forceZIndexContext: !!platformSettings.showVersion || !!platformSettings.showFps, + }) + + this.childList.a(AppInstance) + + this._refocus() + + _Log__WEBPACK_IMPORTED_MODULE_8__["default"].info('App version', this.config.version) + _Log__WEBPACK_IMPORTED_MODULE_8__["default"].info('SDK version', _package_json__WEBPACK_IMPORTED_MODULE_14__.version) + + if (platformSettings.showVersion) { + this.childList.a({ + ref: 'VersionLabel', + type: _VersionLabel__WEBPACK_IMPORTED_MODULE_6__["default"], + version: this.config.version, + sdkVersion: _package_json__WEBPACK_IMPORTED_MODULE_14__.version, + zIndex: 1, + }) + } + + if (platformSettings.showFps) { + this.childList.a({ + ref: 'FpsCounter', + type: _FpsCounter__WEBPACK_IMPORTED_MODULE_7__["default"], + zIndex: 1, + }) + } + + super._setup() + }) + .catch(console.error) + } + + _handleBack() { + this.closeApp() + } + + _handleExit() { + this.closeApp() + } + + closeApp() { + _Log__WEBPACK_IMPORTED_MODULE_8__["default"].info('Signaling App Close') + + if (platformSettings.onClose && typeof platformSettings.onClose === 'function') { + platformSettings.onClose(...arguments) + } else { + this.close() + } + } + + close() { + _Log__WEBPACK_IMPORTED_MODULE_8__["default"].info('Closing App') + + _Settings__WEBPACK_IMPORTED_MODULE_9__["default"].clearSubscribers() + _Registry__WEBPACK_IMPORTED_MODULE_12__["default"].clear() + + this.childList.remove(this.tag('App')) + this.cleanupFonts() + // force texture garbage collect + this.stage.gc() + this.destroy() + } + + loadFonts(fonts) { + return platformSettings.fontLoader && typeof platformSettings.fontLoader === 'function' + ? platformSettings.fontLoader(fonts, customFontFaces) + : fontLoader(fonts, customFontFaces) + } + + cleanupFonts() { + if ('delete' in document.fonts) { + customFontFaces.forEach(fontFace => { + _Log__WEBPACK_IMPORTED_MODULE_8__["default"].info('Removing font', fontFace.family) + document.fonts.delete(fontFace) + }) + } else { + _Log__WEBPACK_IMPORTED_MODULE_8__["default"].info('No support for removing manually-added fonts') + } + } + + loadLanguage(config) { + let file = _Utils__WEBPACK_IMPORTED_MODULE_11__["default"].asset('translations.json') + let language = config + + if (typeof language === 'object') { + language = config.language || null + file = config.file || file + } + + return Object(_Language__WEBPACK_IMPORTED_MODULE_10__["initLanguage"])(file, language) + } + + loadColors(config) { + let file = _Utils__WEBPACK_IMPORTED_MODULE_11__["default"].asset('colors.json') + if (config && (typeof config === 'string' || typeof config === 'object')) { + file = config + } + return Object(_Colors__WEBPACK_IMPORTED_MODULE_13__["initColors"])(file) + } + + set focus(v) { + this._focussed = v + this._refocus() + } + + _getFocused() { + return this._focussed || this.tag('App') + } + } +}); + + +/***/ }), + +/***/ "./node_modules/@lightningjs/sdk/src/AudioPlayer/index.js": +/*!****************************************************************!*\ + !*** ./node_modules/@lightningjs/sdk/src/AudioPlayer/index.js ***! + \****************************************************************/ +/*! exports provided: default */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return AudioPlayer; }); +/* + * If not stated otherwise in this file or this component's LICENSE file the + * following copyright and licenses apply: + * + * Copyright 2020 Metrological + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +class AudioPlayer {} + + +/***/ }), + +/***/ "./node_modules/@lightningjs/sdk/src/Colors/index.js": +/*!***********************************************************!*\ + !*** ./node_modules/@lightningjs/sdk/src/Colors/index.js ***! + \***********************************************************/ +/*! exports provided: initColors, default */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "initColors", function() { return initColors; }); +/* harmony import */ var _helpers_fetchJson__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../helpers/fetchJson */ "./node_modules/@lightningjs/sdk/src/helpers/fetchJson.js"); +/* harmony import */ var _Log__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Log */ "./node_modules/@lightningjs/sdk/src/Log/index.js"); +/* harmony import */ var _utils_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./utils.js */ "./node_modules/@lightningjs/sdk/src/Colors/utils.js"); +/* + * If not stated otherwise in this file or this component's LICENSE file the + * following copyright and licenses apply: + * + * Copyright 2020 Metrological + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + + + +let colors = { + white: '#ffffff', + black: '#000000', + red: '#ff0000', + green: '#00ff00', + blue: '#0000ff', + yellow: '#feff00', + cyan: '#00feff', + magenta: '#ff00ff', +} + +const normalizedColors = { + //store for normalized colors +} + +const addColors = (colorsToAdd, value) => { + if (Object(_utils_js__WEBPACK_IMPORTED_MODULE_2__["isObject"])(colorsToAdd)) { + // clean up normalizedColors if they exist in the to be added colors + Object.keys(colorsToAdd).forEach(color => cleanUpNormalizedColors(color)) + colors = Object.assign({}, colors, colorsToAdd) + } else if (Object(_utils_js__WEBPACK_IMPORTED_MODULE_2__["isString"])(colorsToAdd) && value) { + cleanUpNormalizedColors(colorsToAdd) + colors[colorsToAdd] = value + } +} + +const cleanUpNormalizedColors = color => { + for (let c in normalizedColors) { + if (c.indexOf(color) > -1) { + delete normalizedColors[c] + } + } +} + +const initColors = file => { + return new Promise((resolve, reject) => { + if (typeof file === 'object') { + addColors(file) + return resolve() + } + Object(_helpers_fetchJson__WEBPACK_IMPORTED_MODULE_0__["default"])(file) + .then(json => { + addColors(json) + return resolve() + }) + .catch(() => { + const error = 'Colors file ' + file + ' not found' + _Log__WEBPACK_IMPORTED_MODULE_1__["default"].error(error) + return reject(error) + }) + }) +} + +const normalizeColorToARGB = color => { + let targetColor = normalizedColors[color] || colors[color] || color + if (!targetColor) { + targetColor = color + } + const check = /^#([0-9A-F]{3}|[0-9A-F]{6}|[0-9A-F]{8})$/i + if (Object(_utils_js__WEBPACK_IMPORTED_MODULE_2__["isString"])(targetColor) && check.test(targetColor)) { + let hex = check.exec(targetColor)[1] + if (hex.length === 3) { + hex = hex + .split('') + .map(value => { + return value + value + }) + .join('') + } + targetColor = (hex.length === 8 ? `0x${hex}` : `0xff${hex}`) * 1 + } + if (!normalizedColors[color]) { + normalizedColors[color] = targetColor + } + return targetColor || 0xffffffff +} + +/* harmony default export */ __webpack_exports__["default"] = (color => { + return Color.generate(color) +}); + +const Color = { + color: null, + generate: function(value = this.color) { + if (normalizedColors[value]) { + this.color = normalizedColors[value] + } else { + this.color = normalizeColorToARGB(value) + } + return this + }, + get() { + return this.color + }, + alpha: function(percentage) { + this.color = Object(_utils_js__WEBPACK_IMPORTED_MODULE_2__["calculateAlpha"])(this.color, Math.abs(percentage)) + return this + }, + darker(percentage) { + const hsl = Object(_utils_js__WEBPACK_IMPORTED_MODULE_2__["argbToHSLA"])(this.color) + hsl.l = hsl.l * (1 - percentage) + this.color = Object(_utils_js__WEBPACK_IMPORTED_MODULE_2__["hslaToARGB"])(hsl) + return this + }, + lighter(percentage) { + const hsl = Object(_utils_js__WEBPACK_IMPORTED_MODULE_2__["argbToHSLA"])(this.color) + hsl.l = hsl.l + (1 - hsl.l) * percentage + this.color = Object(_utils_js__WEBPACK_IMPORTED_MODULE_2__["hslaToARGB"])(hsl) + return this + }, + saturation(percentage) { + const hsl = Object(_utils_js__WEBPACK_IMPORTED_MODULE_2__["argbToHSLA"])(this.color) + hsl.s = percentage + this.color = Object(_utils_js__WEBPACK_IMPORTED_MODULE_2__["hslaToARGB"])(hsl) + return this + }, + lightness(percentage) { + const hsl = Object(_utils_js__WEBPACK_IMPORTED_MODULE_2__["argbToHSLA"])(this.color) + hsl.l = percentage + this.color = Object(_utils_js__WEBPACK_IMPORTED_MODULE_2__["hslaToARGB"])(hsl) + return this + }, + hue(degrees) { + const hsl = Object(_utils_js__WEBPACK_IMPORTED_MODULE_2__["argbToHSLA"])(this.color) + hsl.h = degrees + this.color = Object(_utils_js__WEBPACK_IMPORTED_MODULE_2__["hslaToARGB"])(hsl) + return this + }, + mix(argb, p) { + this.color = Object(_utils_js__WEBPACK_IMPORTED_MODULE_2__["mergeColors"])(this.color, argb, p) + return this + }, +} + + +/***/ }), + +/***/ "./node_modules/@lightningjs/sdk/src/Colors/utils.js": +/*!***********************************************************!*\ + !*** ./node_modules/@lightningjs/sdk/src/Colors/utils.js ***! + \***********************************************************/ +/*! exports provided: isObject, isString, getRgbaComponents, limitWithinRange, mergeColors, calculateAlpha, mergeColorAlpha, argbToHsva, hsvaToArgb, argbToHSLA, hslaToARGB */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isObject", function() { return isObject; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isString", function() { return isString; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getRgbaComponents", function() { return getRgbaComponents; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "limitWithinRange", function() { return limitWithinRange; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "mergeColors", function() { return mergeColors; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "calculateAlpha", function() { return calculateAlpha; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "mergeColorAlpha", function() { return mergeColorAlpha; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "argbToHsva", function() { return argbToHsva; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "hsvaToArgb", function() { return hsvaToArgb; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "argbToHSLA", function() { return argbToHSLA; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "hslaToARGB", function() { return hslaToARGB; }); +/* + * If not stated otherwise in this file or this component's LICENSE file the + * following copyright and licenses apply: + * + * Copyright 2020 Metrological + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +const isObject = v => { + return typeof v === 'object' && v !== null +} + +const isString = v => { + return typeof v === 'string' +} + +const getRgbaComponents = argb => { + return { + r: ((argb / 65536) | 0) % 256, + g: ((argb / 256) | 0) % 256, + b: (argb * 1) % 256, + a: (argb / 16777216) | 0, + } +} + +const limitWithinRange = (num, min, max) => { + return Math.min(Math.max(num, min), max) +} + +const mergeColors = (c1, c2, p) => { + let r1 = ((c1 / 65536) | 0) % 256 + let g1 = ((c1 / 256) | 0) % 256 + let b1 = c1 % 256 + let a1 = (c1 / 16777216) | 0 + let r2 = ((c2 / 65536) | 0) % 256 + let g2 = ((c2 / 256) | 0) % 256 + let b2 = c2 % 256 + let a2 = (c2 / 16777216) | 0 + let r = r1 * p + r2 * (1 - p) + let g = g1 * p + g2 * (1 - p) + let b = b1 * p + b2 * (1 - p) + let a = a1 * p + a2 * (1 - p) + return Math.round(a) * 16777216 + Math.round(r) * 65536 + Math.round(g) * 256 + Math.round(b) +} + +const calculateAlpha = (argb, p) => { + if (p > 1) { + p /= 100 + } else if (p < 0) { + p = 0 + } + let r = ((argb / 65536) | 0) % 256 + let g = ((argb / 256) | 0) % 256 + let b = argb % 256 + return (r << 16) + (g << 8) + b + (Math.round(p * 255) | 0) * 16777216 +} + +const mergeColorAlpha = (c, alpha) => { + let a = (((c / 16777216) | 0) * alpha) | 0 + return ( + (((((c >> 16) & 0xff) * a) / 255) & 0xff) + + ((((c & 0xff00) * a) / 255) & 0xff00) + + (((((c & 0xff) << 16) * a) / 255) & 0xff0000) + + (a << 24) + ) +} + +const getArgbNumber = rgba => { + rgba[0] = Math.max(0, Math.min(255, rgba[0])) + rgba[1] = Math.max(0, Math.min(255, rgba[1])) + rgba[2] = Math.max(0, Math.min(255, rgba[2])) + rgba[3] = Math.max(0, Math.min(255, rgba[3])) + let v = ((rgba[3] | 0) << 24) + ((rgba[0] | 0) << 16) + ((rgba[1] | 0) << 8) + (rgba[2] | 0) + if (v < 0) { + v = 0xffffffff + v + 1 + } + return v +} + +const argbToHsva = argb => { + const color = getRgbaComponents(argb) + let r = color.r / 255 + let g = color.g / 255 + let b = color.b / 255 + let h = 0 + let s = 0 + + const cMax = Math.max(r, g, b) + const cMin = Math.min(r, g, b) + const delta = cMax - cMin + + //calculate hue + if (delta < 0.00001) { + h = 0 + } else if (cMax !== 0 || cMin !== 0) { + if (r === cMax) { + h = (60 * ((g - b) / delta) + 360) % 360 + } else if (g === cMax) { + h = (60 * ((b - r) / delta) + 120) % 360 + } else if (b === cMax) { + h = (60 * ((r - g) / delta) + 240) % 360 + } + } + + //calc saturation + if (cMax > 0) { + s = delta / cMax + } + return { + h, + s, + v: cMax, + a: color.a / 255, + } +} + +const hsvaToArgb = color => { + const h = color.h + const c = color.v * color.s + const m = color.v - c + const x = c * (1.0 - Math.abs(((h / 60) % 2) - 1)) + let r = 0 + let g = 0 + let b = 0 + + if (0 <= h && h < 60) { + r = c + g = x + } else if (60 <= h && h < 120) { + r = x + g = c + } else if (120 <= h && h < 180) { + g = c + b = x + } else if (180 <= h && h < 240) { + g = x + b = c + } else if (240 <= h && h < 300) { + r = x + b = c + } else if (300 <= h && h < 360) { + r = c + b = x + } + + r = Math.round((r + m) * 255.0) + g = Math.round((g + m) * 255.0) + b = Math.round((b + m) * 255.0) + return getArgbNumber([r, g, b, color.a * 255]) +} + +const argbToHSLA = argb => { + const col = getRgbaComponents(argb) + const r = col.r / 255 + const g = col.g / 255 + const b = col.b / 255 + + const max = Math.max(r, g, b) + const min = Math.min(r, g, b) + + let h = 0 + let s = 0 + const l = (min + max) * 0.5 + if (l > 0) { + const maxMin = max - min + if (maxMin > 0) { + const r2 = (max - r) / maxMin + const g2 = (max - g) / maxMin + const b2 = (max - b) / maxMin + if (l < 0.5) { + s = max + min + } else { + s = 2 - max - min + } + + if (r === max && g === min) { + h = 5.0 + b2 + } else if (r === max) { + h = 1.0 - g2 + } else if (g === max && b === min) { + h = 1.0 + r2 + } else if (g === max) { + h = 3.0 - b2 + } else if (b === max) { + h = 3.0 + g2 + } else { + h = 5.0 - r2 + } + h = h / 6 + } + } + return { h: h % 1, s, l, a: col.a } +} + +const hslaToARGB = hsla => { + let r = 1 + let g = 1 + let b = 1 + + let h = hsla.h + let s = hsla.s + let l = hsla.l + + if (h < 0) { + h += 1 + } + let max = 0 + if (l <= 0.5) { + max = l * (1.0 + s) + } else { + max = l + s - l * s + } + + if (max > 0) { + h *= 6.0 + const min = l + l - max + const minMax = (max - min) / max + const sextant = Math.floor(h) + const fract = h - sextant + const minMaxFract = max * minMax * fract + const mid1 = min + minMaxFract + const mid2 = max - minMaxFract + + if (sextant === 0) { + r = max + g = mid1 + b = min + } + if (sextant === 1) { + r = mid2 + g = max + b = min + } + if (sextant === 2) { + r = min + g = max + b = mid1 + } + if (sextant === 3) { + r = min + g = mid2 + b = max + } + if (sextant === 4) { + r = mid1 + g = min + b = max + } + if (sextant === 5) { + r = max + g = min + b = mid2 + } + } + return getArgbNumber([Math.floor(r * 255), Math.floor(g * 255), Math.floor(b * 255), hsla.a]) +} + + +/***/ }), + +/***/ "./node_modules/@lightningjs/sdk/src/FpsCounter/index.js": +/*!***************************************************************!*\ + !*** ./node_modules/@lightningjs/sdk/src/FpsCounter/index.js ***! + \***************************************************************/ +/*! exports provided: default */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return FpsIndicator; }); +/* harmony import */ var _Lightning__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Lightning */ "./node_modules/@lightningjs/sdk/src/Lightning/index.js"); +/* harmony import */ var _Settings__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Settings */ "./node_modules/@lightningjs/sdk/src/Settings/index.js"); +/* harmony import */ var _Log__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Log */ "./node_modules/@lightningjs/sdk/src/Log/index.js"); +/* + * If not stated otherwise in this file or this component's LICENSE file the + * following copyright and licenses apply: + * + * Copyright 2020 Metrological + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + + +class FpsIndicator extends _Lightning__WEBPACK_IMPORTED_MODULE_0__["default"].Component { + static _template() { + return { + rect: true, + color: 0xffffffff, + texture: _Lightning__WEBPACK_IMPORTED_MODULE_0__["default"].Tools.getRoundRect(80, 80, 40), + h: 80, + w: 80, + x: 100, + y: 100, + mount: 1, + Background: { + x: 3, + y: 3, + texture: _Lightning__WEBPACK_IMPORTED_MODULE_0__["default"].Tools.getRoundRect(72, 72, 36), + color: 0xff008000, + }, + Counter: { + w: w => w, + h: h => h, + y: 10, + text: { + fontSize: 32, + textAlign: 'center', + }, + }, + Text: { + w: w => w, + h: h => h, + y: 48, + text: { + fontSize: 15, + textAlign: 'center', + text: 'FPS', + }, + }, + } + } + + _setup() { + this.config = { + ...{ + log: false, + interval: 500, + threshold: 1, + }, + ..._Settings__WEBPACK_IMPORTED_MODULE_1__["default"].get('platform', 'showFps'), + } + + this.fps = 0 + this.lastFps = this.fps - this.config.threshold + + const fpsCalculator = () => { + this.fps = ~~(1 / this.stage.dt) + } + this.stage.on('frameStart', fpsCalculator) + this.stage.off('framestart', fpsCalculator) + this.interval = setInterval(this.showFps.bind(this), this.config.interval) + } + + _firstActive() { + this.showFps() + } + + _detach() { + clearInterval(this.interval) + } + + showFps() { + if (Math.abs(this.lastFps - this.fps) <= this.config.threshold) return + this.lastFps = this.fps + // green + let bgColor = 0xff008000 + // orange + if (this.fps <= 40 && this.fps > 20) bgColor = 0xffffa500 + // red + else if (this.fps <= 20) bgColor = 0xffff0000 + + this.tag('Background').setSmooth('color', bgColor) + this.tag('Counter').text = `${this.fps}` + + this.config.log && _Log__WEBPACK_IMPORTED_MODULE_2__["default"].info('FPS', this.fps) + } +} + + +/***/ }), + +/***/ "./node_modules/@lightningjs/sdk/src/Img/ScaledImageTexture.js": +/*!*********************************************************************!*\ + !*** ./node_modules/@lightningjs/sdk/src/Img/ScaledImageTexture.js ***! + \*********************************************************************/ +/*! exports provided: default */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return ScaledImageTexture; }); +/* harmony import */ var _Lightning__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Lightning */ "./node_modules/@lightningjs/sdk/src/Lightning/index.js"); +/* + * If not stated otherwise in this file or this component's LICENSE file the + * following copyright and licenses apply: + * + * Copyright 2020 Metrological + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + +class ScaledImageTexture extends _Lightning__WEBPACK_IMPORTED_MODULE_0__["default"].textures.ImageTexture { + constructor(stage) { + super(stage) + this._scalingOptions = undefined + } + + set options(options) { + this.resizeMode = this._scalingOptions = options + } + + _getLookupId() { + return `${this._src}-${this._scalingOptions.type}-${this._scalingOptions.w}-${this._scalingOptions.h}` + } + + getNonDefaults() { + const obj = super.getNonDefaults() + if (this._src) { + obj.src = this._src + } + return obj + } +} + + +/***/ }), + +/***/ "./node_modules/@lightningjs/sdk/src/Img/index.js": +/*!********************************************************!*\ + !*** ./node_modules/@lightningjs/sdk/src/Img/index.js ***! + \********************************************************/ +/*! exports provided: default */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var _Utils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Utils */ "./node_modules/@lightningjs/sdk/src/Utils/index.js"); +/* harmony import */ var _Settings__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Settings */ "./node_modules/@lightningjs/sdk/src/Settings/index.js"); +/* harmony import */ var _ScaledImageTexture__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./ScaledImageTexture */ "./node_modules/@lightningjs/sdk/src/Img/ScaledImageTexture.js"); +/* + * If not stated otherwise in this file or this component's LICENSE file the + * following copyright and licenses apply: + * + * Copyright 2020 Metrological + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + + + +/* harmony default export */ __webpack_exports__["default"] = ((imageUrl, options) => { + const imageServerUrl = _Settings__WEBPACK_IMPORTED_MODULE_1__["default"].get('platform', 'imageServerUrl') + + // make and return ScaledImageTexture + const make = options => { + // local asset, wrap it in Utils.asset() + if (!/^(?:https?:)?\/\//i.test(imageUrl) && !imageUrl.includes('data:image/png;base64')) { + imageUrl = _Utils__WEBPACK_IMPORTED_MODULE_0__["default"].asset(imageUrl) + } + + // only pass to image server if imageServerUrl is configured + // and if the asset isn't local to the app (i.e. has same origin) + if (imageServerUrl && imageUrl.indexOf(window.location.origin) === -1) { + imageUrl = _Utils__WEBPACK_IMPORTED_MODULE_0__["default"].ensureUrlWithProtocol( + imageServerUrl + '?' + _Utils__WEBPACK_IMPORTED_MODULE_0__["default"].makeQueryString(imageUrl, options) + ) + } else { + // Lightning will handle the resizing and has only 2 flavours (cover and contain) + if (options.type !== 'cover') { + if (options.type === 'crop') options.type = 'cover' + else options.type = 'contain' + } + } + + return { + type: _ScaledImageTexture__WEBPACK_IMPORTED_MODULE_2__["default"], + src: imageUrl, + options: options, + } + } + + // merge options with default + const setOptions = options => { + options = { + ...{ + type: 'contain', + w: 0, + h: 0, + }, + ...options, + } + const imageQuality = Math.max( + 0.1, + Math.min(1, (parseFloat(_Settings__WEBPACK_IMPORTED_MODULE_1__["default"].get('platform', 'image.quality')) || 100) / 100) + ) + + options.w = options.w * imageQuality + options.h = options.h * imageQuality + return options + } + + // if options are passed, return scaled image right away + if (options) { + return make(setOptions(options)) + } + + // otherwise return 'chained' functions + return { + // official api + exact: (w, h) => make(setOptions({ type: 'exact', w, h })), + landscape: w => make(setOptions({ type: 'landscape', w })), + portrait: h => make(setOptions({ type: 'portrait', h })), + cover: (w, h) => make(setOptions({ type: 'cover', w, h })), + contain: (w, h) => make(setOptions({ type: 'contain', w, h })), + original: () => make(setOptions({ type: 'contain' })), + + // todo: add positioning - i.e. top, bottom, center, left etc. + } +}); + + +/***/ }), + +/***/ "./node_modules/@lightningjs/sdk/src/Keyboard/index.js": +/*!*************************************************************!*\ + !*** ./node_modules/@lightningjs/sdk/src/Keyboard/index.js ***! + \*************************************************************/ +/*! exports provided: default */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* + * If not stated otherwise in this file or this component's LICENSE file the + * following copyright and licenses apply: + * + * Copyright 2020 Metrological + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* harmony default export */ __webpack_exports__["default"] = ({}); + + +/***/ }), + +/***/ "./node_modules/@lightningjs/sdk/src/Language/index.js": +/*!*************************************************************!*\ + !*** ./node_modules/@lightningjs/sdk/src/Language/index.js ***! + \*************************************************************/ +/*! exports provided: initLanguage, default */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "initLanguage", function() { return initLanguage; }); +/* harmony import */ var _helpers_fetchJson__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../helpers/fetchJson */ "./node_modules/@lightningjs/sdk/src/helpers/fetchJson.js"); +/* harmony import */ var _Log__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Log */ "./node_modules/@lightningjs/sdk/src/Log/index.js"); +/* harmony import */ var _Utils__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Utils */ "./node_modules/@lightningjs/sdk/src/Utils/index.js"); +/* + * If not stated otherwise in this file or this component's LICENSE file the + * following copyright and licenses apply: + * + * Copyright 2020 Metrological + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + + + +let meta = {} +let translations = {} +let language = null +let dictionary = null + +const initLanguage = (file, language = null) => { + return new Promise((resolve, reject) => { + Object(_helpers_fetchJson__WEBPACK_IMPORTED_MODULE_0__["default"])(file) + .then(json => { + setTranslations(json) + // set language (directly or in a promise) + typeof language === 'object' && 'then' in language && typeof language.then === 'function' + ? language + .then(lang => + setLanguage(lang) + .then(resolve) + .catch(reject) + ) + .catch(e => { + _Log__WEBPACK_IMPORTED_MODULE_1__["default"].error(e) + reject(e) + }) + : setLanguage(language) + .then(resolve) + .catch(reject) + }) + .catch(() => { + const error = 'Language file ' + file + ' not found' + _Log__WEBPACK_IMPORTED_MODULE_1__["default"].error(error) + reject(error) + }) + }) +} + +const setTranslations = obj => { + if ('meta' in obj) { + meta = { ...obj.meta } + delete obj.meta + } + translations = obj +} + +const getLanguage = () => { + return language +} + +const setLanguage = lng => { + language = null + dictionary = null + + return new Promise((resolve, reject) => { + if (lng in translations) { + language = lng + } else { + if ('map' in meta && lng in meta.map && meta.map[lng] in translations) { + language = meta.map[lng] + } else if ('default' in meta && meta.default in translations) { + const error = + 'Translations for Language ' + + language + + ' not found. Using default language ' + + meta.default + _Log__WEBPACK_IMPORTED_MODULE_1__["default"].warn(error) + language = meta.default + } else { + const error = 'Translations for Language ' + language + ' not found.' + _Log__WEBPACK_IMPORTED_MODULE_1__["default"].error(error) + reject(error) + } + } + + if (language) { + _Log__WEBPACK_IMPORTED_MODULE_1__["default"].info('Setting language to', language) + + const translationsObj = translations[language] + if (typeof translationsObj === 'object') { + dictionary = translationsObj + resolve() + } else if (typeof translationsObj === 'string') { + const url = _Utils__WEBPACK_IMPORTED_MODULE_2__["default"].asset(translationsObj) + + Object(_helpers_fetchJson__WEBPACK_IMPORTED_MODULE_0__["default"])(url) + .then(json => { + // save the translations for this language (to prevent loading twice) + translations[language] = json + dictionary = json + resolve() + }) + .catch(e => { + const error = 'Error while fetching ' + url + _Log__WEBPACK_IMPORTED_MODULE_1__["default"].error(error, e) + reject(error) + }) + } + } + }) +} + +/* harmony default export */ __webpack_exports__["default"] = ({ + translate(key) { + let replacements = [...arguments].slice(1) + + // no replacements so just translated string + if (replacements.length === 0) { + return (dictionary && dictionary[key]) || key + } else { + if (replacements.length === 1 && typeof replacements[0] === 'object') { + replacements = replacements.pop() + } + + return Object.keys( + // maps array input to an object {0: 'item1', 1: 'item2'} + Array.isArray(replacements) ? Object.assign({}, replacements) : replacements + ).reduce((text, replacementKey) => { + return text.replace( + new RegExp('{\\s?' + replacementKey + '\\s?}', 'g'), + replacements[replacementKey] + ) + }, (dictionary && dictionary[key]) || key) + } + }, + + translations(obj) { + setTranslations(obj) + }, + + set(language) { + return setLanguage(language) + }, + + get() { + return getLanguage() + }, + + available() { + const languageKeys = Object.keys(translations) + return languageKeys.map(key => ({ code: key, name: (meta.names && meta.names[key]) || key })) + }, +}); + + +/***/ }), + +/***/ "./node_modules/@lightningjs/sdk/src/Launch/index.js": +/*!***********************************************************!*\ + !*** ./node_modules/@lightningjs/sdk/src/Launch/index.js ***! + \***********************************************************/ +/*! exports provided: ApplicationInstance, default */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ApplicationInstance", function() { return ApplicationInstance; }); +/* harmony import */ var _Utils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Utils */ "./node_modules/@lightningjs/sdk/src/Utils/index.js"); +/* harmony import */ var _metrological_sdk__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @metrological/sdk */ "./node_modules/@metrological/sdk/index.js"); +/* harmony import */ var _Settings__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Settings */ "./node_modules/@lightningjs/sdk/src/Settings/index.js"); +/* harmony import */ var _MediaPlayer__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../MediaPlayer */ "./node_modules/@lightningjs/sdk/src/MediaPlayer/index.js"); +/* harmony import */ var _Storage__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../Storage */ "./node_modules/@lightningjs/sdk/src/Storage/index.js"); +/* harmony import */ var _Ads__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../Ads */ "./node_modules/@lightningjs/sdk/src/Ads/index.js"); +/* harmony import */ var _Router__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../Router */ "./node_modules/@lightningjs/sdk/src/Router/index.js"); +/* harmony import */ var _Application__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../Application */ "./node_modules/@lightningjs/sdk/src/Application/index.js"); +/* harmony import */ var _Log__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../Log */ "./node_modules/@lightningjs/sdk/src/Log/index.js"); +/* harmony import */ var _Lightning__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ../Lightning */ "./node_modules/@lightningjs/sdk/src/Lightning/index.js"); +/* + * If not stated otherwise in this file or this component's LICENSE file the + * following copyright and licenses apply: + * + * Copyright 2020 Metrological + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + + + + + + + + + + + + + + + + + + + +let ApplicationInstance + +/* harmony default export */ __webpack_exports__["default"] = ((App, appSettings, platformSettings, appData) => { + Object(_Settings__WEBPACK_IMPORTED_MODULE_2__["initSettings"])(appSettings, platformSettings) + Object(_Utils__WEBPACK_IMPORTED_MODULE_0__["initUtils"])(platformSettings) + Object(_metrological_sdk__WEBPACK_IMPORTED_MODULE_1__["initMetadata"])(appSettings) + Object(_Storage__WEBPACK_IMPORTED_MODULE_4__["initStorage"])() + // Initialize plugins + if (platformSettings.plugins) { + platformSettings.plugins.profile && Object(_metrological_sdk__WEBPACK_IMPORTED_MODULE_1__["initProfile"])(platformSettings.plugins.profile) + platformSettings.plugins.metrics && Object(_metrological_sdk__WEBPACK_IMPORTED_MODULE_1__["initMetrics"])(platformSettings.plugins.metrics) + platformSettings.plugins.mediaPlayer && Object(_MediaPlayer__WEBPACK_IMPORTED_MODULE_3__["initMediaPlayer"])(platformSettings.plugins.mediaPlayer) + platformSettings.plugins.mediaPlayer && Object(_metrological_sdk__WEBPACK_IMPORTED_MODULE_1__["initVideoPlayer"])(platformSettings.plugins.mediaPlayer) + platformSettings.plugins.ads && Object(_Ads__WEBPACK_IMPORTED_MODULE_5__["initAds"])(platformSettings.plugins.ads) + platformSettings.plugins.router && Object(_Router__WEBPACK_IMPORTED_MODULE_6__["initRouter"])(platformSettings.plugins.router) + platformSettings.plugins.tv && Object(_metrological_sdk__WEBPACK_IMPORTED_MODULE_1__["initTV"])(platformSettings.plugins.tv) + platformSettings.plugins.purchase && Object(_metrological_sdk__WEBPACK_IMPORTED_MODULE_1__["initPurchase"])(platformSettings.plugins.purchase) + platformSettings.plugins.pin && Object(_metrological_sdk__WEBPACK_IMPORTED_MODULE_1__["initPin"])(platformSettings.plugins.pin) + } + const app = Object(_Application__WEBPACK_IMPORTED_MODULE_7__["default"])(App, appData, platformSettings) + + _metrological_sdk__WEBPACK_IMPORTED_MODULE_1__["initLightningSdkPlugin"].log = _Log__WEBPACK_IMPORTED_MODULE_8__["default"] + _metrological_sdk__WEBPACK_IMPORTED_MODULE_1__["initLightningSdkPlugin"].settings = _Settings__WEBPACK_IMPORTED_MODULE_2__["default"] + _metrological_sdk__WEBPACK_IMPORTED_MODULE_1__["initLightningSdkPlugin"].ads = _Ads__WEBPACK_IMPORTED_MODULE_5__["default"] + _metrological_sdk__WEBPACK_IMPORTED_MODULE_1__["initLightningSdkPlugin"].lightning = _Lightning__WEBPACK_IMPORTED_MODULE_9__["default"] + + ApplicationInstance = new app(appSettings) + + _metrological_sdk__WEBPACK_IMPORTED_MODULE_1__["initLightningSdkPlugin"].appInstance = ApplicationInstance + + return ApplicationInstance +}); + + +/***/ }), + +/***/ "./node_modules/@lightningjs/sdk/src/Lightning/index.js": +/*!**************************************************************!*\ + !*** ./node_modules/@lightningjs/sdk/src/Lightning/index.js ***! + \**************************************************************/ +/*! exports provided: default */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var _lightningjs_core__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @lightningjs/core */ "./node_modules/@lightningjs/sdk/node_modules/@lightningjs/core/dist/src/index.js"); +/* + * If not stated otherwise in this file or this component's LICENSE file the + * following copyright and licenses apply: + * + * Copyright 2020 Metrological + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +/* harmony default export */ __webpack_exports__["default"] = (_lightningjs_core__WEBPACK_IMPORTED_MODULE_0__["default"]); + + +/***/ }), + +/***/ "./node_modules/@lightningjs/sdk/src/Locale/index.js": +/*!***********************************************************!*\ + !*** ./node_modules/@lightningjs/sdk/src/Locale/index.js ***! + \***********************************************************/ +/*! exports provided: default */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var _Log__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Log */ "./node_modules/@lightningjs/sdk/src/Log/index.js"); +/* + * If not stated otherwise in this file or this component's LICENSE file the + * following copyright and licenses apply: + * + * Copyright 2020 Metrological + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * Simple module for localization of strings. + * + * How to use: + * 1. Create localization file with following JSON format: + * { + * "en" :{ + * "how": "How do you want your egg today?", + * "boiledEgg": "Boiled egg", + * "softBoiledEgg": "Soft-boiled egg", + * "choice": "How to choose the egg", + * "buyQuestion": "I'd like to buy {0} eggs, {1} dollars each." + * }, + * + * "it": { + * "how": "Come vuoi il tuo uovo oggi?", + * "boiledEgg": "Uovo sodo", + * "softBoiledEgg": "Uovo alla coque", + * "choice": "Come scegliere l'uovo", + * "buyQuestion": "Mi piacerebbe comprare {0} uova, {1} dollari ciascuna." + * } + * } + * + * 2. Use Locale's module load method, specifying path to your localization file and set chosen language, e.g.: + * > Locale.load('static/locale/locale.json'); + * > Locale.setLanguage('en'); + * + * 3. Use localization strings: + * > console.log(Locale.tr.how); + * How do you want your egg today? + * > console.log(Locale.tr.boiledEgg); + * Boiled egg + * + * 4. String formatting + * > console.log(Locale.tr.buyQuestion.format(10, 0.5)); + * I'd like to buy 10 eggs, 0.5 dollars each. + */ + + + +let warned = false +const deprecated = (force = false) => { + if (force === true || warned === false) { + console.warn( + [ + "The 'Locale'-plugin in the Lightning-SDK is deprecated and will be removed in future releases.", + "Please consider using the new 'Language'-plugin instead.", + 'https://rdkcentral.github.io/Lightning-SDK/#/plugins/language', + ].join('\n\n') + ) + } + warned = true +} +class Locale { + constructor() { + this.__enabled = false + } + + /** + * Loads translation object from external json file. + * + * @param {String} path Path to resource. + * @return {Promise} + */ + async load(path) { + if (!this.__enabled) { + return + } + + await fetch(path) + .then(resp => resp.json()) + .then(resp => { + this.loadFromObject(resp) + }) + } + + /** + * Sets language used by module. + * + * @param {String} lang + */ + setLanguage(lang) { + deprecated() + this.__enabled = true + this.language = lang + } + + /** + * Returns reference to translation object for current language. + * + * @return {Object} + */ + get tr() { + deprecated(true) + return this.__trObj[this.language] + } + + /** + * Loads translation object from existing object (binds existing object). + * + * @param {Object} trObj + */ + loadFromObject(trObj) { + deprecated() + const fallbackLanguage = 'en' + if (Object.keys(trObj).indexOf(this.language) === -1) { + _Log__WEBPACK_IMPORTED_MODULE_0__["default"].warn('No translations found for: ' + this.language) + if (Object.keys(trObj).indexOf(fallbackLanguage) > -1) { + _Log__WEBPACK_IMPORTED_MODULE_0__["default"].warn('Using fallback language: ' + fallbackLanguage) + this.language = fallbackLanguage + } else { + const error = 'No translations found for fallback language: ' + fallbackLanguage + _Log__WEBPACK_IMPORTED_MODULE_0__["default"].error(error) + throw Error(error) + } + } + + this.__trObj = trObj + for (const lang of Object.values(this.__trObj)) { + for (const str of Object.keys(lang)) { + lang[str] = new LocalizedString(lang[str]) + } + } + } +} + +/** + * Extended string class used for localization. + */ +class LocalizedString extends String { + /** + * Returns formatted LocalizedString. + * Replaces each placeholder value (e.g. {0}, {1}) with corresponding argument. + * + * E.g.: + * > new LocalizedString('{0} and {1} and {0}').format('A', 'B'); + * A and B and A + * + * @param {...any} args List of arguments for placeholders. + */ + format(...args) { + const sub = args.reduce((string, arg, index) => string.split(`{${index}}`).join(arg), this) + return new LocalizedString(sub) + } +} + +/* harmony default export */ __webpack_exports__["default"] = (new Locale()); + + +/***/ }), + +/***/ "./node_modules/@lightningjs/sdk/src/Log/index.js": +/*!********************************************************!*\ + !*** ./node_modules/@lightningjs/sdk/src/Log/index.js ***! + \********************************************************/ +/*! exports provided: default */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var _Settings__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Settings */ "./node_modules/@lightningjs/sdk/src/Settings/index.js"); +/* + * If not stated otherwise in this file or this component's LICENSE file the + * following copyright and licenses apply: + * + * Copyright 2020 Metrological + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + +const prepLog = (type, args) => { + const colors = { + Info: 'green', + Debug: 'gray', + Warn: 'orange', + Error: 'red', + } + + args = Array.from(args) + return [ + '%c' + (args.length > 1 && typeof args[0] === 'string' ? args.shift() : type), + 'background-color: ' + colors[type] + '; color: white; padding: 2px 4px; border-radius: 2px', + args, + ] +} + +/* harmony default export */ __webpack_exports__["default"] = ({ + info() { + _Settings__WEBPACK_IMPORTED_MODULE_0__["default"].get('platform', 'log') && console.log.apply(console, prepLog('Info', arguments)) + }, + debug() { + _Settings__WEBPACK_IMPORTED_MODULE_0__["default"].get('platform', 'log') && console.debug.apply(console, prepLog('Debug', arguments)) + }, + error() { + _Settings__WEBPACK_IMPORTED_MODULE_0__["default"].get('platform', 'log') && console.error.apply(console, prepLog('Error', arguments)) + }, + warn() { + _Settings__WEBPACK_IMPORTED_MODULE_0__["default"].get('platform', 'log') && console.warn.apply(console, prepLog('Warn', arguments)) + }, +}); + + +/***/ }), + +/***/ "./node_modules/@lightningjs/sdk/src/MediaPlayer/index.js": +/*!****************************************************************!*\ + !*** ./node_modules/@lightningjs/sdk/src/MediaPlayer/index.js ***! + \****************************************************************/ +/*! exports provided: initMediaPlayer, default */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "initMediaPlayer", function() { return initMediaPlayer; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return Mediaplayer; }); +/* harmony import */ var _Lightning__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Lightning */ "./node_modules/@lightningjs/sdk/src/Lightning/index.js"); +/* harmony import */ var _Metrics__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Metrics */ "./node_modules/@lightningjs/sdk/src/Metrics/index.js"); +/* harmony import */ var _Settings__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Settings */ "./node_modules/@lightningjs/sdk/src/Settings/index.js"); +/* harmony import */ var _Log__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../Log */ "./node_modules/@lightningjs/sdk/src/Log/index.js"); +/* + * If not stated otherwise in this file or this component's LICENSE file the + * following copyright and licenses apply: + * + * Copyright 2020 Metrological + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + + + + +const events = [ + 'timeupdate', + 'error', + 'ended', + 'loadeddata', + 'canplay', + 'play', + 'playing', + 'pause', + 'loadstart', + 'seeking', + 'seeked', + 'encrypted', +] + +let mediaUrl = url => url + +const initMediaPlayer = config => { + if (config.mediaUrl) { + mediaUrl = config.mediaUrl + } +} + +class Mediaplayer extends _Lightning__WEBPACK_IMPORTED_MODULE_0__["default"].Component { + _construct() { + this._skipRenderToTexture = false + this._metrics = null + this._textureMode = _Settings__WEBPACK_IMPORTED_MODULE_2__["default"].get('platform', 'textureMode') || false + _Log__WEBPACK_IMPORTED_MODULE_3__["default"].info('Texture mode: ' + this._textureMode) + console.warn( + [ + "The 'MediaPlayer'-plugin in the Lightning-SDK is deprecated and will be removed in future releases.", + "Please consider using the new 'VideoPlayer'-plugin instead.", + 'https://rdkcentral.github.io/Lightning-SDK/#/plugins/videoplayer', + ].join('\n\n') + ) + } + + static _template() { + return { + Video: { + VideoWrap: { + VideoTexture: { + visible: false, + pivot: 0.5, + texture: { type: _Lightning__WEBPACK_IMPORTED_MODULE_0__["default"].textures.StaticTexture, options: {} }, + }, + }, + }, + } + } + + set skipRenderToTexture(v) { + this._skipRenderToTexture = v + } + + get textureMode() { + return this._textureMode + } + + get videoView() { + return this.tag('Video') + } + + _init() { + //re-use videotag if already there + const videoEls = document.getElementsByTagName('video') + if (videoEls && videoEls.length > 0) this.videoEl = videoEls[0] + else { + this.videoEl = document.createElement('video') + this.videoEl.setAttribute('id', 'video-player') + this.videoEl.style.position = 'absolute' + this.videoEl.style.zIndex = '1' + this.videoEl.style.display = 'none' + this.videoEl.setAttribute('width', '100%') + this.videoEl.setAttribute('height', '100%') + + this.videoEl.style.visibility = this.textureMode ? 'hidden' : 'visible' + document.body.appendChild(this.videoEl) + } + if (this.textureMode && !this._skipRenderToTexture) { + this._createVideoTexture() + } + + this.eventHandlers = [] + } + + _registerListeners() { + events.forEach(event => { + const handler = e => { + if (this._metrics && this._metrics[event] && typeof this._metrics[event] === 'function') { + this._metrics[event]({ currentTime: this.videoEl.currentTime }) + } + this.fire(event, { videoElement: this.videoEl, event: e }) + } + this.eventHandlers.push(handler) + this.videoEl.addEventListener(event, handler) + }) + } + + _deregisterListeners() { + _Log__WEBPACK_IMPORTED_MODULE_3__["default"].info('Deregistering event listeners MediaPlayer') + events.forEach((event, index) => { + this.videoEl.removeEventListener(event, this.eventHandlers[index]) + }) + this.eventHandlers = [] + } + + _attach() { + this._registerListeners() + } + + _detach() { + this._deregisterListeners() + this.close() + } + + _createVideoTexture() { + const stage = this.stage + + const gl = stage.gl + const glTexture = gl.createTexture() + gl.bindTexture(gl.TEXTURE_2D, glTexture) + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR) + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR) + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE) + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE) + + this.videoTexture.options = { source: glTexture, w: this.videoEl.width, h: this.videoEl.height } + } + + _startUpdatingVideoTexture() { + if (this.textureMode && !this._skipRenderToTexture) { + const stage = this.stage + if (!this._updateVideoTexture) { + this._updateVideoTexture = () => { + if (this.videoTexture.options.source && this.videoEl.videoWidth && this.active) { + const gl = stage.gl + + const currentTime = new Date().getTime() + + // When BR2_PACKAGE_GST1_PLUGINS_BAD_PLUGIN_DEBUGUTILS is not set in WPE, webkitDecodedFrameCount will not be available. + // We'll fallback to fixed 30fps in this case. + const frameCount = this.videoEl.webkitDecodedFrameCount + + const mustUpdate = frameCount + ? this._lastFrame !== frameCount + : this._lastTime < currentTime - 30 + + if (mustUpdate) { + this._lastTime = currentTime + this._lastFrame = frameCount + try { + gl.bindTexture(gl.TEXTURE_2D, this.videoTexture.options.source) + gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false) + gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, this.videoEl) + this._lastFrame = this.videoEl.webkitDecodedFrameCount + this.videoTextureView.visible = true + + this.videoTexture.options.w = this.videoEl.videoWidth + this.videoTexture.options.h = this.videoEl.videoHeight + const expectedAspectRatio = this.videoTextureView.w / this.videoTextureView.h + const realAspectRatio = this.videoEl.videoWidth / this.videoEl.videoHeight + if (expectedAspectRatio > realAspectRatio) { + this.videoTextureView.scaleX = realAspectRatio / expectedAspectRatio + this.videoTextureView.scaleY = 1 + } else { + this.videoTextureView.scaleY = expectedAspectRatio / realAspectRatio + this.videoTextureView.scaleX = 1 + } + } catch (e) { + _Log__WEBPACK_IMPORTED_MODULE_3__["default"].error('texImage2d video', e) + this._stopUpdatingVideoTexture() + this.videoTextureView.visible = false + } + this.videoTexture.source.forceRenderUpdate() + } + } + } + } + if (!this._updatingVideoTexture) { + stage.on('frameStart', this._updateVideoTexture) + this._updatingVideoTexture = true + } + } + } + + _stopUpdatingVideoTexture() { + if (this.textureMode) { + const stage = this.stage + stage.removeListener('frameStart', this._updateVideoTexture) + this._updatingVideoTexture = false + this.videoTextureView.visible = false + + if (this.videoTexture.options.source) { + const gl = stage.gl + gl.bindTexture(gl.TEXTURE_2D, this.videoTexture.options.source) + gl.clearColor(0, 0, 0, 1) + gl.clear(gl.COLOR_BUFFER_BIT) + } + } + } + + updateSettings(settings = {}) { + // The Component that 'consumes' the media player. + this._consumer = settings.consumer + + if (this._consumer && this._consumer.getMediaplayerSettings) { + // Allow consumer to add settings. + settings = Object.assign(settings, this._consumer.getMediaplayerSettings()) + } + + if (!_Lightning__WEBPACK_IMPORTED_MODULE_0__["default"].Utils.equalValues(this._stream, settings.stream)) { + if (settings.stream && settings.stream.keySystem) { + navigator + .requestMediaKeySystemAccess( + settings.stream.keySystem.id, + settings.stream.keySystem.config + ) + .then(keySystemAccess => { + return keySystemAccess.createMediaKeys() + }) + .then(createdMediaKeys => { + return this.videoEl.setMediaKeys(createdMediaKeys) + }) + .then(() => { + if (settings.stream && settings.stream.src) this.open(settings.stream.src) + }) + .catch(() => { + console.error('Failed to set up MediaKeys') + }) + } else if (settings.stream && settings.stream.src) { + // This is here to be backwards compatible, will be removed + // in future sdk release + if (_Settings__WEBPACK_IMPORTED_MODULE_2__["default"].get('app', 'hls')) { + if (!window.Hls) { + window.Hls = class Hls { + static isSupported() { + console.warn('hls-light not included') + return false + } + } + } + if (window.Hls.isSupported()) { + if (!this._hls) this._hls = new window.Hls({ liveDurationInfinity: true }) + this._hls.loadSource(settings.stream.src) + this._hls.attachMedia(this.videoEl) + this.videoEl.style.display = 'block' + } + } else { + this.open(settings.stream.src) + } + } else { + this.close() + } + this._stream = settings.stream + } + + this._setHide(settings.hide) + this._setVideoArea(settings.videoPos) + } + + _setHide(hide) { + if (this.textureMode) { + this.tag('Video').setSmooth('alpha', hide ? 0 : 1) + } else { + this.videoEl.style.visibility = hide ? 'hidden' : 'visible' + } + } + + open(url, settings = { hide: false, videoPosition: null }) { + // prep the media url to play depending on platform (mediaPlayerplugin) + url = mediaUrl(url) + this._metrics = _Metrics__WEBPACK_IMPORTED_MODULE_1__["default"].media(url) + _Log__WEBPACK_IMPORTED_MODULE_3__["default"].info('Playing stream', url) + if (this.application.noVideo) { + _Log__WEBPACK_IMPORTED_MODULE_3__["default"].info('noVideo option set, so ignoring: ' + url) + return + } + // close the video when opening same url as current (effectively reloading) + if (this.videoEl.getAttribute('src') === url) { + this.close() + } + this.videoEl.setAttribute('src', url) + + // force hide, then force show (in next tick!) + // (fixes comcast playback rollover issue) + this.videoEl.style.visibility = 'hidden' + this.videoEl.style.display = 'none' + + setTimeout(() => { + this.videoEl.style.display = 'block' + this.videoEl.style.visibility = 'visible' + }) + + this._setHide(settings.hide) + this._setVideoArea(settings.videoPosition || [0, 0, 1920, 1080]) + } + + close() { + // We need to pause first in order to stop sound. + this.videoEl.pause() + this.videoEl.removeAttribute('src') + + // force load to reset everything without errors + this.videoEl.load() + + this._clearSrc() + + this.videoEl.style.display = 'none' + } + + playPause() { + if (this.isPlaying()) { + this.doPause() + } else { + this.doPlay() + } + } + + get muted() { + return this.videoEl.muted + } + + set muted(v) { + this.videoEl.muted = v + } + + get loop() { + return this.videoEl.loop + } + + set loop(v) { + this.videoEl.loop = v + } + + isPlaying() { + return this._getState() === 'Playing' + } + + doPlay() { + this.videoEl.play() + } + + doPause() { + this.videoEl.pause() + } + + reload() { + var url = this.videoEl.getAttribute('src') + this.close() + this.videoEl.src = url + } + + getPosition() { + return Promise.resolve(this.videoEl.currentTime) + } + + setPosition(pos) { + this.videoEl.currentTime = pos + } + + getDuration() { + return Promise.resolve(this.videoEl.duration) + } + + seek(time, absolute = false) { + if (absolute) { + this.videoEl.currentTime = time + } else { + this.videoEl.currentTime += time + } + } + + get videoTextureView() { + return this.tag('Video').tag('VideoTexture') + } + + get videoTexture() { + return this.videoTextureView.texture + } + + _setVideoArea(videoPos) { + if (_Lightning__WEBPACK_IMPORTED_MODULE_0__["default"].Utils.equalValues(this._videoPos, videoPos)) { + return + } + + this._videoPos = videoPos + + if (this.textureMode) { + this.videoTextureView.patch({ + smooth: { + x: videoPos[0], + y: videoPos[1], + w: videoPos[2] - videoPos[0], + h: videoPos[3] - videoPos[1], + }, + }) + } else { + const precision = this.stage.getRenderPrecision() + this.videoEl.style.left = Math.round(videoPos[0] * precision) + 'px' + this.videoEl.style.top = Math.round(videoPos[1] * precision) + 'px' + this.videoEl.style.width = Math.round((videoPos[2] - videoPos[0]) * precision) + 'px' + this.videoEl.style.height = Math.round((videoPos[3] - videoPos[1]) * precision) + 'px' + } + } + + _fireConsumer(event, args) { + if (this._consumer) { + this._consumer.fire(event, args) + } + } + + _equalInitData(buf1, buf2) { + if (!buf1 || !buf2) return false + if (buf1.byteLength != buf2.byteLength) return false + const dv1 = new Int8Array(buf1) + const dv2 = new Int8Array(buf2) + for (let i = 0; i != buf1.byteLength; i++) if (dv1[i] != dv2[i]) return false + return true + } + + error(args) { + this._fireConsumer('$mediaplayerError', args) + this._setState('') + return '' + } + + loadeddata(args) { + this._fireConsumer('$mediaplayerLoadedData', args) + } + + play(args) { + this._fireConsumer('$mediaplayerPlay', args) + } + + playing(args) { + this._fireConsumer('$mediaplayerPlaying', args) + this._setState('Playing') + } + + canplay(args) { + this.videoEl.play() + this._fireConsumer('$mediaplayerStart', args) + } + + loadstart(args) { + this._fireConsumer('$mediaplayerLoad', args) + } + + seeked() { + this._fireConsumer('$mediaplayerSeeked', { + currentTime: this.videoEl.currentTime, + duration: this.videoEl.duration || 1, + }) + } + + seeking() { + this._fireConsumer('$mediaplayerSeeking', { + currentTime: this.videoEl.currentTime, + duration: this.videoEl.duration || 1, + }) + } + + durationchange(args) { + this._fireConsumer('$mediaplayerDurationChange', args) + } + + encrypted(args) { + const video = args.videoElement + const event = args.event + // FIXME: Double encrypted events need to be properly filtered by Gstreamer + if (video.mediaKeys && !this._equalInitData(this._previousInitData, event.initData)) { + this._previousInitData = event.initData + this._fireConsumer('$mediaplayerEncrypted', args) + } + } + + static _states() { + return [ + class Playing extends this { + $enter() { + this._startUpdatingVideoTexture() + } + $exit() { + this._stopUpdatingVideoTexture() + } + timeupdate() { + this._fireConsumer('$mediaplayerProgress', { + currentTime: this.videoEl.currentTime, + duration: this.videoEl.duration || 1, + }) + } + ended(args) { + this._fireConsumer('$mediaplayerEnded', args) + this._setState('') + } + pause(args) { + this._fireConsumer('$mediaplayerPause', args) + this._setState('Playing.Paused') + } + _clearSrc() { + this._fireConsumer('$mediaplayerStop', {}) + this._setState('') + } + static _states() { + return [class Paused extends this {}] + } + }, + ] + } +} + + +/***/ }), + +/***/ "./node_modules/@lightningjs/sdk/src/Metadata/index.js": +/*!*************************************************************!*\ + !*** ./node_modules/@lightningjs/sdk/src/Metadata/index.js ***! + \*************************************************************/ +/*! exports provided: default */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var _metrological_sdk__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @metrological/sdk */ "./node_modules/@metrological/sdk/index.js"); +/* + * If not stated otherwise in this file or this component's LICENSE file the + * following copyright and licenses apply: + * + * Copyright 2020 Metrological + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + +/* harmony default export */ __webpack_exports__["default"] = (_metrological_sdk__WEBPACK_IMPORTED_MODULE_0__["Metadata"]); + + +/***/ }), + +/***/ "./node_modules/@lightningjs/sdk/src/Metrics/index.js": +/*!************************************************************!*\ + !*** ./node_modules/@lightningjs/sdk/src/Metrics/index.js ***! + \************************************************************/ +/*! exports provided: default */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var _metrological_sdk__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @metrological/sdk */ "./node_modules/@metrological/sdk/index.js"); +/* + * If not stated otherwise in this file or this component's LICENSE file the + * following copyright and licenses apply: + * + * Copyright 2020 Metrological + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + +/* harmony default export */ __webpack_exports__["default"] = (_metrological_sdk__WEBPACK_IMPORTED_MODULE_0__["Metrics"]); + + +/***/ }), + +/***/ "./node_modules/@lightningjs/sdk/src/Pin/index.js": +/*!********************************************************!*\ + !*** ./node_modules/@lightningjs/sdk/src/Pin/index.js ***! + \********************************************************/ +/*! exports provided: default */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var _metrological_sdk__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @metrological/sdk */ "./node_modules/@metrological/sdk/index.js"); +/* + * If not stated otherwise in this file or this component's LICENSE file the + * following copyright and licenses apply: + * + * Copyright 2020 Metrological + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + +/* harmony default export */ __webpack_exports__["default"] = (_metrological_sdk__WEBPACK_IMPORTED_MODULE_0__["Pin"]); + + +/***/ }), + +/***/ "./node_modules/@lightningjs/sdk/src/Profile/index.js": +/*!************************************************************!*\ + !*** ./node_modules/@lightningjs/sdk/src/Profile/index.js ***! + \************************************************************/ +/*! exports provided: default */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var _metrological_sdk__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @metrological/sdk */ "./node_modules/@metrological/sdk/index.js"); +/* + * If not stated otherwise in this file or this component's LICENSE file the + * following copyright and licenses apply: + * + * Copyright 2020 Metrological + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + +/* harmony default export */ __webpack_exports__["default"] = (_metrological_sdk__WEBPACK_IMPORTED_MODULE_0__["Profile"]); + + +/***/ }), + +/***/ "./node_modules/@lightningjs/sdk/src/Purchase/index.js": +/*!*************************************************************!*\ + !*** ./node_modules/@lightningjs/sdk/src/Purchase/index.js ***! + \*************************************************************/ +/*! exports provided: default */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var _metrological_sdk__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @metrological/sdk */ "./node_modules/@metrological/sdk/index.js"); +/* + * If not stated otherwise in this file or this component's LICENSE file the + * following copyright and licenses apply: + * + * Copyright 2020 Metrological + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + +/* harmony default export */ __webpack_exports__["default"] = (_metrological_sdk__WEBPACK_IMPORTED_MODULE_0__["Purchase"]); + + +/***/ }), + +/***/ "./node_modules/@lightningjs/sdk/src/Registry/index.js": +/*!*************************************************************!*\ + !*** ./node_modules/@lightningjs/sdk/src/Registry/index.js ***! + \*************************************************************/ +/*! exports provided: default */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var _Log__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Log */ "./node_modules/@lightningjs/sdk/src/Log/index.js"); +/* + * If not stated otherwise in this file or this component's LICENSE file the + * following copyright and licenses apply: + * + * Copyright 2020 Metrological + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + +const registry = { + eventListeners: [], + timeouts: [], + intervals: [], + targets: [], +} + +/* harmony default export */ __webpack_exports__["default"] = ({ + // Timeouts + setTimeout(cb, timeout, ...params) { + const timeoutId = setTimeout( + () => { + registry.timeouts = registry.timeouts.filter(id => id !== timeoutId) + cb.apply(null, params) + }, + timeout, + params + ) + _Log__WEBPACK_IMPORTED_MODULE_0__["default"].info('Set Timeout', 'ID: ' + timeoutId) + registry.timeouts.push(timeoutId) + return timeoutId + }, + + clearTimeout(timeoutId) { + if (registry.timeouts.indexOf(timeoutId) > -1) { + registry.timeouts = registry.timeouts.filter(id => id !== timeoutId) + _Log__WEBPACK_IMPORTED_MODULE_0__["default"].info('Clear Timeout', 'ID: ' + timeoutId) + clearTimeout(timeoutId) + } else { + _Log__WEBPACK_IMPORTED_MODULE_0__["default"].error('Clear Timeout', 'ID ' + timeoutId + ' not found') + } + }, + + clearTimeouts() { + registry.timeouts.forEach(timeoutId => { + this.clearTimeout(timeoutId) + }) + }, + + // Intervals + setInterval(cb, interval, ...params) { + const intervalId = setInterval( + () => { + registry.intervals.filter(id => id !== intervalId) + cb.apply(null, params) + }, + interval, + params + ) + _Log__WEBPACK_IMPORTED_MODULE_0__["default"].info('Set Interval', 'ID: ' + intervalId) + registry.intervals.push(intervalId) + return intervalId + }, + + clearInterval(intervalId) { + if (registry.intervals.indexOf(intervalId) > -1) { + registry.intervals = registry.intervals.filter(id => id !== intervalId) + _Log__WEBPACK_IMPORTED_MODULE_0__["default"].info('Clear Interval', 'ID: ' + intervalId) + clearInterval(intervalId) + } else { + _Log__WEBPACK_IMPORTED_MODULE_0__["default"].error('Clear Interval', 'ID ' + intervalId + ' not found') + } + }, + + clearIntervals() { + registry.intervals.forEach(intervalId => { + this.clearInterval(intervalId) + }) + }, + + // Event listeners + addEventListener(target, event, handler) { + target.addEventListener(event, handler) + const targetIndex = + registry.targets.indexOf(target) > -1 + ? registry.targets.indexOf(target) + : registry.targets.push(target) - 1 + + registry.eventListeners[targetIndex] = registry.eventListeners[targetIndex] || {} + registry.eventListeners[targetIndex][event] = registry.eventListeners[targetIndex][event] || [] + registry.eventListeners[targetIndex][event].push(handler) + _Log__WEBPACK_IMPORTED_MODULE_0__["default"].info( + 'Add eventListener', + 'Target:', + target, + 'Event: ' + event, + 'Handler:', + handler.toString() + ) + }, + + removeEventListener(target, event, handler) { + const targetIndex = registry.targets.indexOf(target) + if ( + targetIndex > -1 && + registry.eventListeners[targetIndex] && + registry.eventListeners[targetIndex][event] && + registry.eventListeners[targetIndex][event].indexOf(handler) > -1 + ) { + registry.eventListeners[targetIndex][event] = registry.eventListeners[targetIndex][ + event + ].filter(fn => fn !== handler) + _Log__WEBPACK_IMPORTED_MODULE_0__["default"].info( + 'Remove eventListener', + 'Target:', + target, + 'Event: ' + event, + 'Handler:', + handler.toString() + ) + target.removeEventListener(event, handler) + // remove key from event listeners object when no events are registered for that event + Object.keys(registry.eventListeners[targetIndex]).forEach(event => { + if (registry.eventListeners[targetIndex][event].length === 0) { + delete registry.eventListeners[targetIndex][event] + } + }) + // remove reference to the target when target has no event listeners registered + if (Object.keys(registry.eventListeners[targetIndex]).length === 0) { + registry.targets.splice(targetIndex, 1) + registry.eventListeners.splice(targetIndex, 1) + } + } else { + _Log__WEBPACK_IMPORTED_MODULE_0__["default"].error( + 'Remove eventListener', + 'Not found', + 'Target', + target, + 'Event: ' + event, + 'Handler', + handler.toString() + ) + } + }, + + // if `event` is omitted, removes all registered event listeners for target + // if `target` is also omitted, removes all registered event listeners + removeEventListeners(target, event) { + if (target && event) { + const targetIndex = registry.targets.indexOf(target) + if (targetIndex > -1) { + registry.eventListeners[targetIndex][event].forEach(handler => { + this.removeEventListener(target, event, handler) + }) + } + } else if (target) { + const targetIndex = registry.targets.indexOf(target) + if (targetIndex > -1) { + Object.keys(registry.eventListeners[targetIndex]).forEach(_event => { + this.removeEventListeners(target, _event) + }) + } + } else { + Object.keys(registry.eventListeners).forEach(targetIndex => { + this.removeEventListeners(registry.targets[targetIndex]) + }) + } + }, + + // Clear everything (to be called upon app close for proper cleanup) + clear() { + this.clearTimeouts() + this.clearIntervals() + this.removeEventListeners() + registry.eventListeners = [] + registry.timeouts = [] + registry.intervals = [] + registry.targets = [] + }, +}); + + +/***/ }), + +/***/ "./node_modules/@lightningjs/sdk/src/Router/base.js": +/*!**********************************************************!*\ + !*** ./node_modules/@lightningjs/sdk/src/Router/base.js ***! + \**********************************************************/ +/*! exports provided: RoutedApp */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "RoutedApp", function() { return RoutedApp; }); +/* harmony import */ var _Lightning__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Lightning */ "./node_modules/@lightningjs/sdk/src/Lightning/index.js"); +/* harmony import */ var _index__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./index */ "./node_modules/@lightningjs/sdk/src/Router/index.js"); +/* harmony import */ var _utils_router_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./utils/router.js */ "./node_modules/@lightningjs/sdk/src/Router/utils/router.js"); +/* harmony import */ var _utils_helpers__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./utils/helpers */ "./node_modules/@lightningjs/sdk/src/Router/utils/helpers.js"); +/* + * If not stated otherwise in this file or this component's LICENSE file the + * following copyright and licenses apply: + * + * Copyright 2020 Metrological + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + + + + +class RoutedApp extends _Lightning__WEBPACK_IMPORTED_MODULE_0__["default"].Component { + static _template() { + return { + Pages: { + forceZIndexContext: true, + }, + /** + * This is a default Loading page that will be made visible + * during data-provider on() you CAN override in child-class + */ + Loading: { + rect: true, + w: 1920, + h: 1080, + color: 0xff000000, + visible: false, + zIndex: 99, + Label: { + mount: 0.5, + x: 960, + y: 540, + text: { + text: 'Loading..', + }, + }, + }, + } + } + + static _states() { + return [ + class Loading extends this { + $enter() { + this.tag('Loading').visible = true + } + + $exit() { + this.tag('Loading').visible = false + } + }, + class Widgets extends this { + $enter(args, widget) { + // store widget reference + this._widget = widget + + // since it's possible that this behaviour + // is non-remote driven we force a recalculation + // of the focuspath + this._refocus() + } + + _getFocused() { + // we delegate focus to selected widget + // so it can consume remotecontrol presses + return this._widget + } + + // if we want to widget to widget focus delegation + reload(widget) { + this._widget = widget + this._refocus() + } + + _handleKey() { + const restoreFocus = _utils_router_js__WEBPACK_IMPORTED_MODULE_2__["routerConfig"].get('autoRestoreRemote') + /** + * The Router used to delegate focus back to the page instance on + * every unhandled key. This is barely usefull in any situation + * so for now we offer the option to explicity turn that behaviour off + * so we don't don't introduce a breaking change. + */ + if (!Object(_utils_helpers__WEBPACK_IMPORTED_MODULE_3__["isBoolean"])(restoreFocus) || restoreFocus === true) { + _index__WEBPACK_IMPORTED_MODULE_1__["default"].focusPage() + } + } + }, + ] + } + + /** + * Return location where pages need to be stored + */ + get pages() { + return this.tag('Pages') + } + + /** + * Tell router where widgets are stored + */ + get widgets() { + return this.tag('Widgets') + } + + /** + * we MUST register _handleBack method so the Router + * can override it + * @private + */ + _handleBack() {} + + /** + * We MUST return Router.activePage() so the new Page + * can listen to the remote-control. + */ + _getFocused() { + return _index__WEBPACK_IMPORTED_MODULE_1__["default"].getActivePage() + } +} + + +/***/ }), + +/***/ "./node_modules/@lightningjs/sdk/src/Router/index.js": +/*!***********************************************************!*\ + !*** ./node_modules/@lightningjs/sdk/src/Router/index.js ***! + \***********************************************************/ +/*! exports provided: navigateQueue, navigate, step, getResumeHash, initRouter, default */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "navigateQueue", function() { return navigateQueue; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "navigate", function() { return navigate; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "step", function() { return step; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getResumeHash", function() { return getResumeHash; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "initRouter", function() { return initRouter; }); +/* harmony import */ var _utils_helpers__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./utils/helpers */ "./node_modules/@lightningjs/sdk/src/Router/utils/helpers.js"); +/* harmony import */ var _utils_router__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./utils/router */ "./node_modules/@lightningjs/sdk/src/Router/utils/router.js"); +/* harmony import */ var _utils_widgets__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./utils/widgets */ "./node_modules/@lightningjs/sdk/src/Router/utils/widgets.js"); +/* harmony import */ var _utils_history__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./utils/history */ "./node_modules/@lightningjs/sdk/src/Router/utils/history.js"); +/* harmony import */ var _utils_route__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./utils/route */ "./node_modules/@lightningjs/sdk/src/Router/utils/route.js"); +/* harmony import */ var _utils_loader__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./utils/loader */ "./node_modules/@lightningjs/sdk/src/Router/utils/loader.js"); +/* harmony import */ var _utils_regex__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./utils/regex */ "./node_modules/@lightningjs/sdk/src/Router/utils/regex.js"); +/* harmony import */ var _base__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./base */ "./node_modules/@lightningjs/sdk/src/Router/base.js"); +/* harmony import */ var _Registry__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../Registry */ "./node_modules/@lightningjs/sdk/src/Registry/index.js"); +/* + * If not stated otherwise in this file or this component's LICENSE file the + * following copyright and licenses apply: + * + * Copyright 2020 Metrological + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + + + + + + + + + + + +/* +rouThor ==[x] + */ +let navigateQueue = new Map() +let forcedHash = '' +let resumeHash = '' + +/** + * Start routing the app + * @param config - route config object + * @param instance - instance of the app + */ +const startRouter = (config, instance) => { + Object(_utils_router__WEBPACK_IMPORTED_MODULE_1__["bootRouter"])(config, instance) + registerListener() + start() +} + +// start translating url +const start = () => { + let hash = (getHash() || '').replace(/^#/, '') + const bootKey = '$' + const params = Object(_utils_helpers__WEBPACK_IMPORTED_MODULE_0__["getQueryStringParams"])(hash) + const bootRequest = Object(_utils_router__WEBPACK_IMPORTED_MODULE_1__["getBootRequest"])() + const rootHash = Object(_utils_router__WEBPACK_IMPORTED_MODULE_1__["getRootHash"])() + const isDirectLoad = hash.indexOf(bootKey) !== -1 + + // prevent direct reload of wildcard routes + // expect bootComponent + if (_utils_regex__WEBPACK_IMPORTED_MODULE_6__["isWildcard"].test(hash) && hash !== bootKey) { + hash = '' + } + + // store resume point for manual resume + resumeHash = isDirectLoad ? rootHash : hash || rootHash + + const ready = () => { + if (!hash && rootHash) { + if (Object(_utils_helpers__WEBPACK_IMPORTED_MODULE_0__["isString"])(rootHash)) { + navigate(rootHash) + } else if (Object(_utils_helpers__WEBPACK_IMPORTED_MODULE_0__["isFunction"])(rootHash)) { + rootHash().then(res => { + if (Object(_utils_helpers__WEBPACK_IMPORTED_MODULE_0__["isObject"])(res)) { + navigate(res.path, res.params) + } else { + navigate(res) + } + }) + } + } else { + queue(hash) + handleHashChange() + .then(() => { + _utils_router__WEBPACK_IMPORTED_MODULE_1__["app"]._refocus() + }) + .catch(e => { + console.error(e) + }) + } + } + + if (Object(_utils_router__WEBPACK_IMPORTED_MODULE_1__["routeExists"])(bootKey)) { + if (hash && !isDirectLoad) { + if (!Object(_utils_route__WEBPACK_IMPORTED_MODULE_4__["getRouteByHash"])(hash)) { + navigate('*', { failedHash: hash }) + return + } + } + navigate( + bootKey, + { + resume: resumeHash, + reload: bootKey === hash, + }, + false + ) + } else if (Object(_utils_helpers__WEBPACK_IMPORTED_MODULE_0__["isFunction"])(bootRequest)) { + bootRequest(params) + .then(() => { + ready() + }) + .catch(e => { + handleBootError(e) + }) + } else { + ready() + } +} + +const handleBootError = e => { + if (Object(_utils_router__WEBPACK_IMPORTED_MODULE_1__["routeExists"])('!')) { + navigate('!', { request: { error: e } }) + } else { + console.error(e) + } +} + +/** + * start a new request + * @param url + * @param args + * @param store + */ +const navigate = (url, args = {}, store) => { + if (Object(_utils_helpers__WEBPACK_IMPORTED_MODULE_0__["isObject"])(url)) { + url = Object(_utils_route__WEBPACK_IMPORTED_MODULE_4__["getHashByName"])(url) + if (!url) { + return + } + } + + let hash = getHash() + if (!Object(_utils_router__WEBPACK_IMPORTED_MODULE_1__["mustUpdateLocationHash"])() && forcedHash) { + hash = forcedHash + } + if (hash.replace(/^#/, '') !== url) { + // push request in the queue + queue(url, args, store) + + if (Object(_utils_router__WEBPACK_IMPORTED_MODULE_1__["mustUpdateLocationHash"])()) { + setHash(url) + } else { + forcedHash = url + handleHashChange(url) + .then(() => { + _utils_router__WEBPACK_IMPORTED_MODULE_1__["app"]._refocus() + }) + .catch(e => { + console.error(e) + }) + } + } else if (args.reload) { + // push request in the queue + queue(url, args, store) + + handleHashChange(url) + .then(() => { + _utils_router__WEBPACK_IMPORTED_MODULE_1__["app"]._refocus() + }) + .catch(e => { + console.error(e) + }) + } +} + +const queue = (hash, args = {}, store) => { + hash = Object(_utils_helpers__WEBPACK_IMPORTED_MODULE_0__["cleanHash"])(hash) + if (!navigateQueue.has(hash)) { + for (let request of navigateQueue.values()) { + request.cancel() + } + const request = Object(_utils_route__WEBPACK_IMPORTED_MODULE_4__["createRequest"])(hash, args, store) + navigateQueue.set(decodeURIComponent(hash), request) + + return request + } + return false +} + +/** + * Handle change of hash + * @param override + * @returns {Promise} + */ +const handleHashChange = async override => { + const hash = Object(_utils_helpers__WEBPACK_IMPORTED_MODULE_0__["cleanHash"])(override || getHash()) + const queueId = decodeURIComponent(hash) + let request = navigateQueue.get(queueId) + + // handle hash updated manually + if (!request && !navigateQueue.size) { + request = queue(hash) + } + + const route = Object(_utils_route__WEBPACK_IMPORTED_MODULE_4__["getRouteByHash"])(hash) + + if (!route) { + if (Object(_utils_router__WEBPACK_IMPORTED_MODULE_1__["routeExists"])('*')) { + navigate('*', { failedHash: hash }) + } else { + console.error(`Unable to navigate to: ${hash}`) + } + return + } + + // update current processed request + request.hash = hash + request.route = route + + let result = await Object(_utils_router__WEBPACK_IMPORTED_MODULE_1__["beforeEachRoute"])(Object(_utils_router__WEBPACK_IMPORTED_MODULE_1__["getActiveHash"])(), request) + + // test if a local hook is configured for the route + if (result && route.beforeNavigate) { + result = await route.beforeNavigate(Object(_utils_router__WEBPACK_IMPORTED_MODULE_1__["getActiveHash"])(), request) + } + + if (Object(_utils_helpers__WEBPACK_IMPORTED_MODULE_0__["isBoolean"])(result)) { + // only if resolve value is explicitly true + // we continue the current route request + if (result) { + return resolveHashChange(request) + } + } else { + // if navigation guard didn't return true + // we cancel the current request + request.cancel() + navigateQueue.delete(queueId) + + if (Object(_utils_helpers__WEBPACK_IMPORTED_MODULE_0__["isString"])(result)) { + navigate(result) + } else if (Object(_utils_helpers__WEBPACK_IMPORTED_MODULE_0__["isObject"])(result)) { + let store = true + if (Object(_utils_helpers__WEBPACK_IMPORTED_MODULE_0__["isBoolean"])(result.store)) { + store = result.store + } + navigate(result.path, result.params, store) + } + } +} + +/** + * Continue processing the hash change if not blocked + * by global or local hook + * @param request - {} + */ +const resolveHashChange = request => { + const hash = request.hash + const route = request.route + const queueId = decodeURIComponent(hash) + // store last requested hash so we can + // prevent a route that resolved later + // from displaying itself + Object(_utils_router__WEBPACK_IMPORTED_MODULE_1__["setLastHash"])(hash) + + if (route.path) { + const component = Object(_utils_router__WEBPACK_IMPORTED_MODULE_1__["getComponent"])(route.path) + // if a hook is provided for the current route + if (Object(_utils_helpers__WEBPACK_IMPORTED_MODULE_0__["isFunction"])(route.hook)) { + const urlParams = Object(_utils_route__WEBPACK_IMPORTED_MODULE_4__["getValuesFromHash"])(hash, route.path) + const params = {} + for (const key of urlParams.keys()) { + params[key] = urlParams.get(key) + } + route.hook(_utils_router__WEBPACK_IMPORTED_MODULE_1__["app"], { ...params }) + } + // if there is a component attached to the route + if (component) { + // force page to root state to prevent shared state issues + const activePage = Object(_utils_router__WEBPACK_IMPORTED_MODULE_1__["getActivePage"])() + if (activePage) { + const keepAlive = Object(_utils_route__WEBPACK_IMPORTED_MODULE_4__["keepActivePageAlive"])(Object(_utils_router__WEBPACK_IMPORTED_MODULE_1__["getActiveRoute"])(), request) + if (activePage && route.path === Object(_utils_router__WEBPACK_IMPORTED_MODULE_1__["getActiveRoute"])() && !keepAlive) { + activePage._setState('') + } + } + + if (Object(_utils_helpers__WEBPACK_IMPORTED_MODULE_0__["isPage"])(component, _utils_router__WEBPACK_IMPORTED_MODULE_1__["stage"])) { + Object(_utils_loader__WEBPACK_IMPORTED_MODULE_5__["load"])(request).then(() => { + _utils_router__WEBPACK_IMPORTED_MODULE_1__["app"]._refocus() + navigateQueue.delete(queueId) + }) + } else { + // of the component is not a constructor + // or a Component instance we can assume + // that it's a dynamic import + component() + .then(contents => { + return contents.default + }) + .then(module => { + Object(_utils_router__WEBPACK_IMPORTED_MODULE_1__["storeComponent"])(route.path, module) + return Object(_utils_loader__WEBPACK_IMPORTED_MODULE_5__["load"])(request) + }) + .then(() => { + _utils_router__WEBPACK_IMPORTED_MODULE_1__["app"]._refocus() + navigateQueue.delete(queueId) + }) + } + } else { + navigateQueue.delete(queueId) + } + } +} + +/** + * Directional step in history + * @param level + */ +const step = (level = 0) => { + if (!level || isNaN(level)) { + return false + } + const history = Object(_utils_history__WEBPACK_IMPORTED_MODULE_3__["getHistory"])() + // for now we only support negative numbers + level = Math.abs(level) + + //Check whether we have any history avaialble or not + if (history.length) { + // for now we only support history back + const route = history.splice(history.length - level, level)[0] + // store changed history + Object(_utils_history__WEBPACK_IMPORTED_MODULE_3__["setHistory"])(history) + return navigate( + route.hash, + { + [_utils_helpers__WEBPACK_IMPORTED_MODULE_0__["symbols"].backtrack]: true, + [_utils_helpers__WEBPACK_IMPORTED_MODULE_0__["symbols"].historyState]: route.state, + }, + false + ) + } else if (_utils_router__WEBPACK_IMPORTED_MODULE_1__["routerConfig"].get('backtrack')) { + const hashLastPart = /(\/:?[\w%\s-]+)$/ + let hash = Object(_utils_regex__WEBPACK_IMPORTED_MODULE_6__["stripRegex"])(getHash()) + let floor = Object(_utils_route__WEBPACK_IMPORTED_MODULE_4__["getFloor"])(hash) + + // test if we got deep-linked + if (floor > 1) { + while (floor--) { + // strip of last part + hash = hash.replace(hashLastPart, '') + // if we have a configured route + // we navigate to it + if (Object(_utils_route__WEBPACK_IMPORTED_MODULE_4__["getRouteByHash"])(hash)) { + return navigate(hash, { [_utils_helpers__WEBPACK_IMPORTED_MODULE_0__["symbols"].backtrack]: true }, false) + } + } + } + } + + // we can't step back past the amount + // of history entries + if (level > history.length) { + if (Object(_utils_helpers__WEBPACK_IMPORTED_MODULE_0__["isFunction"])(_utils_router__WEBPACK_IMPORTED_MODULE_1__["app"]._handleAppClose)) { + return _utils_router__WEBPACK_IMPORTED_MODULE_1__["app"]._handleAppClose() + } + return _utils_router__WEBPACK_IMPORTED_MODULE_1__["app"].application.closeApp() + } + return false +} + +/** + * Resume Router's page loading process after + * the BootComponent became visible; + */ +const resume = () => { + if (Object(_utils_helpers__WEBPACK_IMPORTED_MODULE_0__["isString"])(resumeHash)) { + navigate(resumeHash, false) + resumeHash = '' + } else if (Object(_utils_helpers__WEBPACK_IMPORTED_MODULE_0__["isFunction"])(resumeHash)) { + resumeHash().then(res => { + resumeHash = '' + if (Object(_utils_helpers__WEBPACK_IMPORTED_MODULE_0__["isObject"])(res)) { + navigate(res.path, res.params) + } else { + navigate(res) + } + }) + } else { + console.warn('[Router]: resume() called but no hash found') + } +} + +/** + * Force reload active hash + */ +const reload = () => { + if (!isNavigating()) { + const hash = Object(_utils_router__WEBPACK_IMPORTED_MODULE_1__["getActiveHash"])() + navigate(hash, { reload: true }, false) + } +} + +/** + * Query if the Router is still processing a Request + * @returns {boolean} + */ +const isNavigating = () => { + if (navigateQueue.size) { + let isProcessing = false + for (let request of navigateQueue.values()) { + if (!request.isCancelled) { + isProcessing = true + } + } + return isProcessing + } + return false +} + +const getResumeHash = () => { + return resumeHash +} + +/** + * By default we return the location hash + * @returns {string} + */ +let getHash = () => { + return document.location.hash +} + +/** + * Update location hash + * @param url + */ +let setHash = url => { + document.location.hash = url +} + +/** + * This can be called from the platform / bootstrapper to override + * the default getting and setting of the hash + * @param config + */ +const initRouter = config => { + if (config.getHash) { + getHash = config.getHash + } + if (config.setHash) { + setHash = config.setHash + } +} + +/** + * On hash change we start processing + */ +const registerListener = () => { + _Registry__WEBPACK_IMPORTED_MODULE_8__["default"].addEventListener(window, 'hashchange', async () => { + if (Object(_utils_router__WEBPACK_IMPORTED_MODULE_1__["mustUpdateLocationHash"])()) { + try { + await handleHashChange() + } catch (e) { + console.error(e) + } + } + }) +} + +/** + * Navigate to root hash + */ +const root = () => { + const rootHash = Object(_utils_router__WEBPACK_IMPORTED_MODULE_1__["getRootHash"])() + if (Object(_utils_helpers__WEBPACK_IMPORTED_MODULE_0__["isString"])(rootHash)) { + navigate(rootHash) + } else if (Object(_utils_helpers__WEBPACK_IMPORTED_MODULE_0__["isFunction"])(rootHash)) { + rootHash().then(res => { + if (Object(_utils_helpers__WEBPACK_IMPORTED_MODULE_0__["isObject"])(res)) { + navigate(res.path, res.params) + } else { + navigate(res) + } + }) + } +} + +const deletePage = (param) => { + Object(_utils_router__WEBPACK_IMPORTED_MODULE_1__["deleteCurrentInstance"])(param) +} + +// export API +/* harmony default export */ __webpack_exports__["default"] = ({ + startRouter, + navigate, + resume, + step, + go: step, + back: step.bind(null, -1), + activePage: _utils_router__WEBPACK_IMPORTED_MODULE_1__["getActivePage"], + getActivePage() { + // warning + return Object(_utils_router__WEBPACK_IMPORTED_MODULE_1__["getActivePage"])() + }, + deletePage, + getActiveRoute: _utils_router__WEBPACK_IMPORTED_MODULE_1__["getActiveRoute"], + getActiveHash: _utils_router__WEBPACK_IMPORTED_MODULE_1__["getActiveHash"], + focusWidget: _utils_widgets__WEBPACK_IMPORTED_MODULE_2__["focusWidget"], + getActiveWidget: _utils_widgets__WEBPACK_IMPORTED_MODULE_2__["getActiveWidget"], + restoreFocus: _utils_widgets__WEBPACK_IMPORTED_MODULE_2__["restoreFocus"], + isNavigating, + getHistory: _utils_history__WEBPACK_IMPORTED_MODULE_3__["getHistory"], + setHistory: _utils_history__WEBPACK_IMPORTED_MODULE_3__["setHistory"], + getHistoryState: _utils_history__WEBPACK_IMPORTED_MODULE_3__["getHistoryState"], + replaceHistoryState: _utils_history__WEBPACK_IMPORTED_MODULE_3__["replaceHistoryState"], + getQueryStringParams: _utils_helpers__WEBPACK_IMPORTED_MODULE_0__["getQueryStringParams"], + reload, + symbols: _utils_helpers__WEBPACK_IMPORTED_MODULE_0__["symbols"], + App: _base__WEBPACK_IMPORTED_MODULE_7__["RoutedApp"], + // keep backwards compatible + focusPage: _utils_widgets__WEBPACK_IMPORTED_MODULE_2__["restoreFocus"], + root: root, + /** + * Deprecated api methods + */ + setupRoutes() { + console.warn('Router: setupRoutes is deprecated, consolidate your configuration') + console.warn('https://rdkcentral.github.io/Lightning-SDK/#/plugins/router/configuration') + }, + on() { + console.warn('Router.on() is deprecated, consolidate your configuration') + console.warn('https://rdkcentral.github.io/Lightning-SDK/#/plugins/router/configuration') + }, + before() { + console.warn('Router.before() is deprecated, consolidate your configuration') + console.warn('https://rdkcentral.github.io/Lightning-SDK/#/plugins/router/configuration') + }, + after() { + console.warn('Router.after() is deprecated, consolidate your configuration') + console.warn('https://rdkcentral.github.io/Lightning-SDK/#/plugins/router/configuration') + }, +}); + + +/***/ }), + +/***/ "./node_modules/@lightningjs/sdk/src/Router/model/Request.js": +/*!*******************************************************************!*\ + !*** ./node_modules/@lightningjs/sdk/src/Router/model/Request.js ***! + \*******************************************************************/ +/*! exports provided: default */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return Request; }); +/* harmony import */ var _utils_helpers__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../utils/helpers */ "./node_modules/@lightningjs/sdk/src/Router/utils/helpers.js"); +/* harmony import */ var _utils_register__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../utils/register */ "./node_modules/@lightningjs/sdk/src/Router/utils/register.js"); +/* harmony import */ var _Log__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Log */ "./node_modules/@lightningjs/sdk/src/Log/index.js"); +/* + * If not stated otherwise in this file or this component's LICENSE file the + * following copyright and licenses apply: + * + * Copyright 2020 Metrological + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + + + +class Request { + constructor(hash = '', navArgs, storeCaller) { + /** + * Hash we navigate to + * @type {string} + * @private + */ + this._hash = hash + + /** + * Do we store previous hash in history + * @type {boolean} + * @private + */ + this._storeCaller = storeCaller + + /** + * Request and navigate data + * @type {Map} + * @private + */ + this._register = new Map() + + /** + * Flag if the instance is created due to + * this request + * @type {boolean} + * @private + */ + this._isCreated = false + + /** + * Flag if the instance is shared between + * previous and current request + * @type {boolean} + * @private + */ + this._isSharedInstance = false + + /** + * Flag if the request has been cancelled + * @type {boolean} + * @private + */ + this._cancelled = false + + /** + * if instance is shared between requests we copy state object + * from instance before the new request overrides state + * @type {null} + * @private + */ + this._copiedHistoryState = null + + // if there are arguments attached to navigate() + // we store them in new request + if (Object(_utils_helpers__WEBPACK_IMPORTED_MODULE_0__["isObject"])(navArgs)) { + this._register = Object(_utils_register__WEBPACK_IMPORTED_MODULE_1__["createRegister"])(navArgs) + } else if (Object(_utils_helpers__WEBPACK_IMPORTED_MODULE_0__["isBoolean"])(navArgs)) { + // if second navigate() argument is explicitly + // set to false we prevent the calling page + // from ending up in history + this._storeCaller = navArgs + } + // @todo: remove because we can simply check + // ._storeCaller property + this._register.set(_utils_helpers__WEBPACK_IMPORTED_MODULE_0__["symbols"].store, this._storeCaller) + } + + cancel() { + _Log__WEBPACK_IMPORTED_MODULE_2__["default"].debug('[router]:', `cancelled ${this._hash}`) + this._cancelled = true + } + + get url() { + return this._hash + } + + get register() { + return this._register + } + + get hash() { + return this._hash + } + + set hash(args) { + this._hash = args + } + + get route() { + return this._route + } + + set route(args) { + this._route = args + } + + get provider() { + return this._provider + } + + set provider(args) { + this._provider = args + } + + get providerType() { + return this._providerType + } + + set providerType(args) { + this._providerType = args + } + + set page(args) { + this._page = args + } + + get page() { + return this._page + } + + set isCreated(args) { + this._isCreated = args + } + + get isCreated() { + return this._isCreated + } + + get isSharedInstance() { + return this._isSharedInstance + } + + set isSharedInstance(args) { + this._isSharedInstance = args + } + + get isCancelled() { + return this._cancelled + } + + set copiedHistoryState(v) { + this._copiedHistoryState = v + } + + get copiedHistoryState() { + return this._copiedHistoryState + } +} + + +/***/ }), + +/***/ "./node_modules/@lightningjs/sdk/src/Router/model/Route.js": +/*!*****************************************************************!*\ + !*** ./node_modules/@lightningjs/sdk/src/Router/model/Route.js ***! + \*****************************************************************/ +/*! exports provided: default */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return Route; }); +/* harmony import */ var _utils_helpers__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../utils/helpers */ "./node_modules/@lightningjs/sdk/src/Router/utils/helpers.js"); +/* + * If not stated otherwise in this file or this component's LICENSE file the + * following copyright and licenses apply: + * + * Copyright 2020 Metrological + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + +class Route { + constructor(config = {}) { + // keep backwards compatible + let type = ['on', 'before', 'after'].reduce((acc, type) => { + return Object(_utils_helpers__WEBPACK_IMPORTED_MODULE_0__["isFunction"])(config[type]) ? type : acc + }, undefined) + + this._cfg = config + if (type) { + this._provider = { + type, + request: config[type], + } + } + } + + get path() { + return this._cfg.path + } + + get name() { + return this._cfg.name + } + + get component() { + return this._cfg.component + } + + get options() { + return this._cfg.options + } + + get widgets() { + return this._cfg.widgets + } + + get cache() { + return this._cfg.cache + } + + get hook() { + return this._cfg.hook + } + + get beforeNavigate() { + return this._cfg.beforeNavigate + } + + get provider() { + return this._provider + } +} + + +/***/ }), + +/***/ "./node_modules/@lightningjs/sdk/src/Router/transitions.js": +/*!*****************************************************************!*\ + !*** ./node_modules/@lightningjs/sdk/src/Router/transitions.js ***! + \*****************************************************************/ +/*! exports provided: default */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* + * If not stated otherwise in this file or this component's LICENSE file the + * following copyright and licenses apply: + * + * Copyright 2020 Metrological + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +const fade = (i, o) => { + return new Promise(resolve => { + i.patch({ + alpha: 0, + visible: true, + smooth: { + alpha: [1, { duration: 0.5, delay: 0.1 }], + }, + }) + // resolve on y finish + i.transition('alpha').on('finish', () => { + if (o) { + o.visible = false + } + resolve() + }) + }) +} + +const crossFade = (i, o) => { + return new Promise(resolve => { + i.patch({ + alpha: 0, + visible: true, + smooth: { + alpha: [1, { duration: 0.5, delay: 0.1 }], + }, + }) + if (o) { + o.patch({ + smooth: { + alpha: [0, { duration: 0.5, delay: 0.3 }], + }, + }) + } + // resolve on y finish + i.transition('alpha').on('finish', () => { + resolve() + }) + }) +} + +const moveOnAxes = (axis, direction, i, o) => { + const bounds = axis === 'x' ? 1920 : 1080 + return new Promise(resolve => { + i.patch({ + [`${axis}`]: direction ? bounds * -1 : bounds, + visible: true, + smooth: { + [`${axis}`]: [0, { duration: 0.4, delay: 0.2 }], + }, + }) + // out is optional + if (o) { + o.patch({ + [`${axis}`]: 0, + smooth: { + [`${axis}`]: [direction ? bounds : bounds * -1, { duration: 0.4, delay: 0.2 }], + }, + }) + } + // resolve on y finish + i.transition(axis).on('finish', () => { + resolve() + }) + }) +} + +const up = (i, o) => { + return moveOnAxes('y', 0, i, o) +} + +const down = (i, o) => { + return moveOnAxes('y', 1, i, o) +} + +const left = (i, o) => { + return moveOnAxes('x', 0, i, o) +} + +const right = (i, o) => { + return moveOnAxes('x', 1, i, o) +} + +/* harmony default export */ __webpack_exports__["default"] = ({ + fade, + crossFade, + up, + down, + left, + right, +}); + + +/***/ }), + +/***/ "./node_modules/@lightningjs/sdk/src/Router/utils/components.js": +/*!**********************************************************************!*\ + !*** ./node_modules/@lightningjs/sdk/src/Router/utils/components.js ***! + \**********************************************************************/ +/*! exports provided: createComponent */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "createComponent", function() { return createComponent; }); +/* harmony import */ var _widgets__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./widgets */ "./node_modules/@lightningjs/sdk/src/Router/utils/widgets.js"); +/* + * If not stated otherwise in this file or this component's LICENSE file the + * following copyright and licenses apply: + * + * Copyright 2020 Metrological + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + +const createComponent = (stage, type) => { + return stage.c({ + type, + visible: false, + widgets: Object(_widgets__WEBPACK_IMPORTED_MODULE_0__["getReferences"])(), + }) +} + + +/***/ }), + +/***/ "./node_modules/@lightningjs/sdk/src/Router/utils/emit.js": +/*!****************************************************************!*\ + !*** ./node_modules/@lightningjs/sdk/src/Router/utils/emit.js ***! + \****************************************************************/ +/*! exports provided: default */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var _helpers__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./helpers */ "./node_modules/@lightningjs/sdk/src/Router/utils/helpers.js"); +/* + * If not stated otherwise in this file or this component's LICENSE file the + * following copyright and licenses apply: + * + * Copyright 2020 Metrological + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + +/* harmony default export */ __webpack_exports__["default"] = ((page, events = [], params = {}) => { + if (!Object(_helpers__WEBPACK_IMPORTED_MODULE_0__["isArray"])(events)) { + events = [events] + } + events.forEach(e => { + const event = `_on${Object(_helpers__WEBPACK_IMPORTED_MODULE_0__["ucfirst"])(e)}` + if (Object(_helpers__WEBPACK_IMPORTED_MODULE_0__["isFunction"])(page[event])) { + page[event](params) + } + }) +}); + + +/***/ }), + +/***/ "./node_modules/@lightningjs/sdk/src/Router/utils/helpers.js": +/*!*******************************************************************!*\ + !*** ./node_modules/@lightningjs/sdk/src/Router/utils/helpers.js ***! + \*******************************************************************/ +/*! exports provided: isFunction, isObject, isBoolean, isPage, isComponentConstructor, isArray, ucfirst, isString, isPromise, cleanHash, getConfigMap, incorrectParams, getQueryStringParams, objectToQueryString, symbols */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isFunction", function() { return isFunction; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isObject", function() { return isObject; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isBoolean", function() { return isBoolean; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isPage", function() { return isPage; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isComponentConstructor", function() { return isComponentConstructor; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isArray", function() { return isArray; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ucfirst", function() { return ucfirst; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isString", function() { return isString; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isPromise", function() { return isPromise; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "cleanHash", function() { return cleanHash; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getConfigMap", function() { return getConfigMap; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "incorrectParams", function() { return incorrectParams; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getQueryStringParams", function() { return getQueryStringParams; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "objectToQueryString", function() { return objectToQueryString; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "symbols", function() { return symbols; }); +/* harmony import */ var _Lightning__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../Lightning */ "./node_modules/@lightningjs/sdk/src/Lightning/index.js"); +/* harmony import */ var _Settings__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Settings */ "./node_modules/@lightningjs/sdk/src/Settings/index.js"); +/* harmony import */ var _router__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./router */ "./node_modules/@lightningjs/sdk/src/Router/utils/router.js"); +/* harmony import */ var _index__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../index */ "./node_modules/@lightningjs/sdk/src/Router/index.js"); +/* + * If not stated otherwise in this file or this component's LICENSE file the + * following copyright and licenses apply: + * + * Copyright 2020 Metrological + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + + + + +const isFunction = v => { + return typeof v === 'function' +} + +const isObject = v => { + return typeof v === 'object' && v !== null +} + +const isBoolean = v => { + return typeof v === 'boolean' +} + +const isPage = v => { + if (v instanceof _Lightning__WEBPACK_IMPORTED_MODULE_0__["default"].Element || isComponentConstructor(v)) { + return true + } + return false +} + +const isComponentConstructor = type => { + return type.prototype && 'isComponent' in type.prototype +} + +const isArray = v => { + return Array.isArray(v) +} + +const ucfirst = v => { + return `${v.charAt(0).toUpperCase()}${v.slice(1)}` +} + +const isString = v => { + return typeof v === 'string' +} + +const isPromise = method => { + let result + if (isFunction(method)) { + try { + result = method.apply(null) + } catch (e) { + result = e + } + } else { + result = method + } + return isObject(result) && isFunction(result.then) +} + +const cleanHash = (hash = '') => { + return hash.replace(/^#/, '').replace(/\/+$/, '') +} + +const getConfigMap = () => { + const routerSettings = _Settings__WEBPACK_IMPORTED_MODULE_1__["default"].get('platform', 'router') + const isObj = isObject(routerSettings) + return [ + 'backtrack', + 'gcOnUnload', + 'destroyOnHistoryBack', + 'lazyCreate', + 'lazyDestroy', + 'reuseInstance', + 'autoRestoreRemote', + 'numberNavigation', + 'updateHash', + 'storeSameHash', + ].reduce((config, key) => { + config.set(key, isObj ? routerSettings[key] : _Settings__WEBPACK_IMPORTED_MODULE_1__["default"].get('platform', key)) + return config + }, new Map()) +} + +const incorrectParams = (cb, route) => { + const isIncorrect = /^\w*?\s?\(\s?\{.*?\}\s?\)/i + if (isIncorrect.test(cb.toString())) { + console.warn( + [ + `DEPRECATION: The data-provider for route: ${route} is not correct.`, + '"page" is no longer a property of the params object but is now the first function parameter: ', + 'https://github.com/rdkcentral/Lightning-SDK/blob/feature/router/docs/plugins/router/dataproviding.md#data-providing', + "It's supported for now but will be removed in a future release.", + ].join('\n') + ) + return true + } + return false +} + +const getQueryStringParams = (hash = Object(_router__WEBPACK_IMPORTED_MODULE_2__["getActiveHash"])()) => { + const resumeHash = Object(_index__WEBPACK_IMPORTED_MODULE_3__["getResumeHash"])() + if ((hash === '$' || !hash) && resumeHash) { + if (isString(resumeHash)) { + hash = resumeHash + } + } + + let parse = '' + const getQuery = /([?&].*)/ + const matches = getQuery.exec(hash) + const params = {} + + if (document.location && document.location.search) { + parse = document.location.search + } + + if (matches && matches.length) { + let hashParams = matches[1] + if (parse) { + // if location.search is not empty we + // remove the leading ? to create a + // valid string + hashParams = hashParams.replace(/^\?/, '') + // we parse hash params last so they we can always + // override search params with hash params + parse = `${parse}&${hashParams}` + } else { + parse = hashParams + } + } + + if (parse) { + const urlParams = new URLSearchParams(parse) + for (const [key, value] of urlParams.entries()) { + params[key] = value + } + return params + } else { + return false + } +} + +const objectToQueryString = obj => { + if (!isObject(obj)) { + return '' + } + return ( + '?' + + Object.keys(obj) + .map(key => { + return `${key}=${obj[key]}` + }) + .join('&') + ) +} + +const symbols = { + route: Symbol('route'), + hash: Symbol('hash'), + store: Symbol('store'), + fromHistory: Symbol('fromHistory'), + expires: Symbol('expires'), + resume: Symbol('resume'), + backtrack: Symbol('backtrack'), + historyState: Symbol('historyState'), + queryParams: Symbol('queryParams'), +} + + +/***/ }), + +/***/ "./node_modules/@lightningjs/sdk/src/Router/utils/history.js": +/*!*******************************************************************!*\ + !*** ./node_modules/@lightningjs/sdk/src/Router/utils/history.js ***! + \*******************************************************************/ +/*! exports provided: updateHistory, getHistoryState, replaceHistoryState, getHistory, setHistory */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "updateHistory", function() { return updateHistory; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getHistoryState", function() { return getHistoryState; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "replaceHistoryState", function() { return replaceHistoryState; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getHistory", function() { return getHistory; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "setHistory", function() { return setHistory; }); +/* harmony import */ var _router__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./router */ "./node_modules/@lightningjs/sdk/src/Router/utils/router.js"); +/* harmony import */ var _route__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./route */ "./node_modules/@lightningjs/sdk/src/Router/utils/route.js"); +/* harmony import */ var _helpers__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./helpers */ "./node_modules/@lightningjs/sdk/src/Router/utils/helpers.js"); +/* + * If not stated otherwise in this file or this component's LICENSE file the + * following copyright and licenses apply: + * + * Copyright 2020 Metrological + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + + + + +/** + * Simple flat array that holds the visited hashes + state Object + * so the router can navigate back to them + * @type {Array} + */ +let history = [] + +const updateHistory = request => { + const hash = Object(_router__WEBPACK_IMPORTED_MODULE_0__["getActiveHash"])() + if (!hash) { + return + } + + // navigate storage flag + const register = request.register + const forceNavigateStore = register.get(_helpers__WEBPACK_IMPORTED_MODULE_2__["symbols"].store) + + // test preventStorage on route configuration + const activeRoute = Object(_route__WEBPACK_IMPORTED_MODULE_1__["getRouteByHash"])(hash) + const preventStorage = Object(_route__WEBPACK_IMPORTED_MODULE_1__["getOption"])(activeRoute.options, 'preventStorage') + + // we give prio to navigate storage flag + let store = Object(_helpers__WEBPACK_IMPORTED_MODULE_2__["isBoolean"])(forceNavigateStore) ? forceNavigateStore : !preventStorage + + if (store) { + const toStore = hash.replace(/^\//, '') + const location = locationInHistory(toStore) + const stateObject = getStateObject(Object(_router__WEBPACK_IMPORTED_MODULE_0__["getActivePage"])(), request) + const routerConfig = Object(_router__WEBPACK_IMPORTED_MODULE_0__["getRouterConfig"])() + + // store hash if it's not a part of history or flag for + // storage of same hash is true + if (location === -1 || routerConfig.get('storeSameHash')) { + history.push({ hash: toStore, state: stateObject }) + } else { + // if we visit the same route we want to sync history + const prev = history.splice(location, 1)[0] + history.push({ hash: prev.hash, state: stateObject }) + } + } +} + +const locationInHistory = hash => { + for (let i = 0; i < history.length; i++) { + if (history[i].hash === hash) { + return i + } + } + return -1 +} + +const getHistoryState = hash => { + let state = null + if (history.length) { + // if no hash is provided we get the last + // pushed history record + if (!hash) { + const record = history[history.length - 1] + // could be null + state = record.state + } else { + if (locationInHistory(hash) !== -1) { + const record = history[locationInHistory(hash)] + state = record.state + } + } + } + return state +} + +const replaceHistoryState = (state = null, hash) => { + if (!history.length) { + return + } + const location = hash ? locationInHistory(hash) : history.length - 1 + if (location !== -1 && Object(_helpers__WEBPACK_IMPORTED_MODULE_2__["isObject"])(state)) { + history[location].state = state + } +} + +const getStateObject = (page, request) => { + // if the new request shared instance with the + // previous request we used the copied state object + if (request.isSharedInstance) { + if (request.copiedHistoryState) { + return request.copiedHistoryState + } + } else if (page && Object(_helpers__WEBPACK_IMPORTED_MODULE_2__["isFunction"])(page.historyState)) { + return page.historyState() + } + return null +} + +const getHistory = () => { + return history.slice(0) +} + +const setHistory = (arr = []) => { + if (Object(_helpers__WEBPACK_IMPORTED_MODULE_2__["isArray"])(arr)) { + history = arr + } +} + + +/***/ }), + +/***/ "./node_modules/@lightningjs/sdk/src/Router/utils/loader.js": +/*!******************************************************************!*\ + !*** ./node_modules/@lightningjs/sdk/src/Router/utils/loader.js ***! + \******************************************************************/ +/*! exports provided: load, mustReuse */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "load", function() { return load; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "mustReuse", function() { return mustReuse; }); +/* harmony import */ var _router__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./router */ "./node_modules/@lightningjs/sdk/src/Router/utils/router.js"); +/* harmony import */ var _Log__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Log */ "./node_modules/@lightningjs/sdk/src/Log/index.js"); +/* harmony import */ var _helpers__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./helpers */ "./node_modules/@lightningjs/sdk/src/Router/utils/helpers.js"); +/* harmony import */ var _provider__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./provider */ "./node_modules/@lightningjs/sdk/src/Router/utils/provider.js"); +/* harmony import */ var _components__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./components */ "./node_modules/@lightningjs/sdk/src/Router/utils/components.js"); +/* harmony import */ var _transition__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./transition */ "./node_modules/@lightningjs/sdk/src/Router/utils/transition.js"); +/* harmony import */ var _widgets__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./widgets */ "./node_modules/@lightningjs/sdk/src/Router/utils/widgets.js"); +/* harmony import */ var _emit__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./emit */ "./node_modules/@lightningjs/sdk/src/Router/utils/emit.js"); +/* harmony import */ var _route__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./route */ "./node_modules/@lightningjs/sdk/src/Router/utils/route.js"); +/* harmony import */ var _index__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ../index */ "./node_modules/@lightningjs/sdk/src/Router/index.js"); +/* harmony import */ var _history__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./history */ "./node_modules/@lightningjs/sdk/src/Router/utils/history.js"); +/* harmony import */ var _regex__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ./regex */ "./node_modules/@lightningjs/sdk/src/Router/utils/regex.js"); +/* + * If not stated otherwise in this file or this component's LICENSE file the + * following copyright and licenses apply: + * + * Copyright 2020 Metrological + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + + + + + + + + + + + + + +/** + * The actual loading of the component + * */ +const load = async request => { + let expired = false + try { + request = await loader(request) + if (request && !request.isCancelled) { + // in case of on() providing we need to reset + // app state; + if (_router__WEBPACK_IMPORTED_MODULE_0__["app"].state === 'Loading') { + if (Object(_router__WEBPACK_IMPORTED_MODULE_0__["getPreviousState"])() === 'Widgets') { + _router__WEBPACK_IMPORTED_MODULE_0__["app"]._setState('Widgets', [Object(_widgets__WEBPACK_IMPORTED_MODULE_6__["getActiveWidget"])()]) + } else { + _router__WEBPACK_IMPORTED_MODULE_0__["app"]._setState('') + } + } + // Do page transition if instance + // is not shared between the routes + if (!request.isSharedInstance && !request.isCancelled) { + await Object(_transition__WEBPACK_IMPORTED_MODULE_5__["executeTransition"])(request.page, Object(_router__WEBPACK_IMPORTED_MODULE_0__["getActivePage"])()) + } + } else { + expired = true + } + // on expired we only cleanup + if (expired || request.isCancelled) { + _Log__WEBPACK_IMPORTED_MODULE_1__["default"].debug('[router]:', `Rejected ${request.hash} because route to ${Object(_router__WEBPACK_IMPORTED_MODULE_0__["getLastHash"])()} started`) + if (request.isCreated && !request.isSharedInstance) { + // remove from render-tree + _router__WEBPACK_IMPORTED_MODULE_0__["pagesHost"].remove(request.page) + } + } else { + Object(_router__WEBPACK_IMPORTED_MODULE_0__["onRequestResolved"])(request) + // resolve promise + return request.page + } + } catch (request) { + if (!request.route) { + console.error(request) + } else if (!expired) { + // @todo: revisit + const { route } = request + // clean up history if modifier is set + if (Object(_route__WEBPACK_IMPORTED_MODULE_8__["getOption"])(route.options, 'clearHistory')) { + Object(_history__WEBPACK_IMPORTED_MODULE_10__["setHistory"])([]) + } else if (!_regex__WEBPACK_IMPORTED_MODULE_11__["isWildcard"].test(route.path)) { + Object(_history__WEBPACK_IMPORTED_MODULE_10__["updateHistory"])(request) + } + + if (request.isCreated && !request.isSharedInstance) { + // remove from render-tree + _router__WEBPACK_IMPORTED_MODULE_0__["pagesHost"].remove(request.page) + } + handleError(request) + } + } +} + +const loader = async request => { + const route = request.route + const hash = request.hash + const register = request.register + + // todo: grab from Route instance + let type = Object(_router__WEBPACK_IMPORTED_MODULE_0__["getComponent"])(route.path) + let isConstruct = Object(_helpers__WEBPACK_IMPORTED_MODULE_2__["isComponentConstructor"])(type) + let provide = false + + // if it's an instance bt we're not coming back from + // history we test if we can re-use this instance + if (!isConstruct && !register.get(_helpers__WEBPACK_IMPORTED_MODULE_2__["symbols"].backtrack)) { + if (!mustReuse(route)) { + type = type.constructor + isConstruct = true + } + } + + // If page is Lightning Component instance + if (!isConstruct) { + request.page = type + // if we have have a data route for current page + if (Object(_provider__WEBPACK_IMPORTED_MODULE_3__["hasProvider"])(route.path)) { + if (Object(_provider__WEBPACK_IMPORTED_MODULE_3__["isPageExpired"])(type) || type[_helpers__WEBPACK_IMPORTED_MODULE_2__["symbols"].hash] !== hash) { + provide = true + } + } + let currentRoute = Object(_router__WEBPACK_IMPORTED_MODULE_0__["getActivePage"])() && Object(_router__WEBPACK_IMPORTED_MODULE_0__["getActivePage"])()[_helpers__WEBPACK_IMPORTED_MODULE_2__["symbols"].route] + // if the new route is equal to the current route it means that both + // route share the Component instance and stack location / since this case + // is conflicting with the way before() and after() loading works we flag it, + // and check platform settings in we want to re-use instance + if (route.path === currentRoute) { + request.isSharedInstance = true + // since we're re-using the instance we must attach + // historyState to the request to prevent it from + // being overridden. + if (Object(_helpers__WEBPACK_IMPORTED_MODULE_2__["isFunction"])(request.page.historyState)) { + request.copiedHistoryState = request.page.historyState() + } + } + } else { + request.page = Object(_components__WEBPACK_IMPORTED_MODULE_4__["createComponent"])(_router__WEBPACK_IMPORTED_MODULE_0__["stage"], type) + _router__WEBPACK_IMPORTED_MODULE_0__["pagesHost"].a(request.page) + // test if need to request data provider + if (Object(_provider__WEBPACK_IMPORTED_MODULE_3__["hasProvider"])(route.path)) { + provide = true + } + request.isCreated = true + } + + // we store hash and route as properties on the page instance + // that way we can easily calculate new behaviour on page reload + request.page[_helpers__WEBPACK_IMPORTED_MODULE_2__["symbols"].hash] = hash + request.page[_helpers__WEBPACK_IMPORTED_MODULE_2__["symbols"].route] = route.path + + try { + if (provide) { + // extract attached data-provider for route + // we're processing + const { type: loadType, provider } = Object(_provider__WEBPACK_IMPORTED_MODULE_3__["getProvider"])(route) + + // update running request + request.provider = provider + request.providerType = loadType + + await _provider__WEBPACK_IMPORTED_MODULE_3__["dataHooks"][loadType](request) + + // we early exit if the current request is expired + if (hash !== Object(_router__WEBPACK_IMPORTED_MODULE_0__["getLastHash"])()) { + return false + } else { + if (request.providerType !== 'after') { + Object(_emit__WEBPACK_IMPORTED_MODULE_7__["default"])(request.page, 'dataProvided') + } + // resolve promise + return request + } + } else { + Object(_provider__WEBPACK_IMPORTED_MODULE_3__["addPersistData"])(request) + return request + } + } catch (e) { + request.error = e + return Promise.reject(request) + } +} + +const handleError = request => { + if (request && request.error) { + console.error(request.error) + } else if (request) { + _Log__WEBPACK_IMPORTED_MODULE_1__["default"].error(request) + } + + if (request.page && Object(_router__WEBPACK_IMPORTED_MODULE_0__["routeExists"])('!')) { + Object(_index__WEBPACK_IMPORTED_MODULE_9__["navigate"])('!', { request }, false) + } +} + +const mustReuse = route => { + const opt = Object(_route__WEBPACK_IMPORTED_MODULE_8__["getOption"])(route.options, 'reuseInstance') + const config = _router__WEBPACK_IMPORTED_MODULE_0__["routerConfig"].get('reuseInstance') + + // route always has final decision + if (Object(_helpers__WEBPACK_IMPORTED_MODULE_2__["isBoolean"])(opt)) { + return opt + } + return !(Object(_helpers__WEBPACK_IMPORTED_MODULE_2__["isBoolean"])(config) && config === false) +} + + +/***/ }), + +/***/ "./node_modules/@lightningjs/sdk/src/Router/utils/provider.js": +/*!********************************************************************!*\ + !*** ./node_modules/@lightningjs/sdk/src/Router/utils/provider.js ***! + \********************************************************************/ +/*! exports provided: dataHooks, addPersistData, isPageExpired, hasProvider, getProvider */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "dataHooks", function() { return dataHooks; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "addPersistData", function() { return addPersistData; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isPageExpired", function() { return isPageExpired; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "hasProvider", function() { return hasProvider; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getProvider", function() { return getProvider; }); +/* harmony import */ var _helpers__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./helpers */ "./node_modules/@lightningjs/sdk/src/Router/utils/helpers.js"); +/* harmony import */ var _router__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./router */ "./node_modules/@lightningjs/sdk/src/Router/utils/router.js"); +/* harmony import */ var _route__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./route */ "./node_modules/@lightningjs/sdk/src/Router/utils/route.js"); +/* harmony import */ var _emit__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./emit */ "./node_modules/@lightningjs/sdk/src/Router/utils/emit.js"); +/* + * If not stated otherwise in this file or this component's LICENSE file the + * following copyright and licenses apply: + * + * Copyright 2020 Metrological + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + + + + +const dataHooks = { + on: request => { + Object(_router__WEBPACK_IMPORTED_MODULE_1__["setPreviousState"])(_router__WEBPACK_IMPORTED_MODULE_1__["app"].state || '') + _router__WEBPACK_IMPORTED_MODULE_1__["app"]._setState('Loading') + return execProvider(request) + }, + before: request => { + return execProvider(request) + }, + after: request => { + try { + execProvider(request, true) + } catch (e) { + // for now we fail silently + } + return Promise.resolve() + }, +} + +const execProvider = (request, emitProvided) => { + const route = request.route + const provider = route.provider + const expires = route.cache ? route.cache * 1000 : 0 + const params = addPersistData(request) + return provider + .request(request.page, { ...params }) + .then(() => { + request.page[_helpers__WEBPACK_IMPORTED_MODULE_0__["symbols"].expires] = Date.now() + expires + if (emitProvided) { + Object(_emit__WEBPACK_IMPORTED_MODULE_3__["default"])(request.page, 'dataProvided') + } + }) + .catch(e => { + request.page[_helpers__WEBPACK_IMPORTED_MODULE_0__["symbols"].expires] = Date.now() + throw e + }) +} + +const addPersistData = ({ page, route, hash, register = new Map() }) => { + const urlValues = Object(_route__WEBPACK_IMPORTED_MODULE_2__["getValuesFromHash"])(hash, route.path) + const queryParams = Object(_helpers__WEBPACK_IMPORTED_MODULE_0__["getQueryStringParams"])(hash) + const pageData = new Map([...urlValues, ...register]) + const params = {} + + // make dynamic url data available to the page + // as instance properties + for (let [name, value] of pageData) { + params[name] = value + } + + if (queryParams) { + params[_helpers__WEBPACK_IMPORTED_MODULE_0__["symbols"].queryParams] = queryParams + } + + // check navigation register for persistent data + if (register.size) { + const obj = {} + for (let [k, v] of register) { + obj[k] = v + } + page.persist = obj + } + + // make url data and persist data available + // via params property + page.params = params + Object(_emit__WEBPACK_IMPORTED_MODULE_3__["default"])(page, ['urlParams'], params) + + return params +} + +/** + * Test if page passed cache-time + * @param page + * @returns {boolean} + */ +const isPageExpired = page => { + if (!page[_helpers__WEBPACK_IMPORTED_MODULE_0__["symbols"].expires]) { + return false + } + + const expires = page[_helpers__WEBPACK_IMPORTED_MODULE_0__["symbols"].expires] + const now = Date.now() + + return now >= expires +} + +const hasProvider = path => { + if (Object(_router__WEBPACK_IMPORTED_MODULE_1__["routeExists"])(path)) { + const record = _router__WEBPACK_IMPORTED_MODULE_1__["routes"].get(path) + return !!record.provider + } + return false +} + +const getProvider = route => { + // @todo: fix, route already is passed in + if (Object(_router__WEBPACK_IMPORTED_MODULE_1__["routeExists"])(route.path)) { + const { provider } = _router__WEBPACK_IMPORTED_MODULE_1__["routes"].get(route.path) + return { + type: provider.type, + provider: provider.request, + } + } +} + + +/***/ }), + +/***/ "./node_modules/@lightningjs/sdk/src/Router/utils/regex.js": +/*!*****************************************************************!*\ + !*** ./node_modules/@lightningjs/sdk/src/Router/utils/regex.js ***! + \*****************************************************************/ +/*! exports provided: hasRegex, isWildcard, hasLookupId, isNamedGroup, stripRegex */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "hasRegex", function() { return hasRegex; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isWildcard", function() { return isWildcard; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "hasLookupId", function() { return hasLookupId; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isNamedGroup", function() { return isNamedGroup; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "stripRegex", function() { return stripRegex; }); +/* + * If not stated otherwise in this file or this component's LICENSE file the + * following copyright and licenses apply: + * + * Copyright 2020 Metrological + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +const hasRegex = /\{\/(.*?)\/([igm]{0,3})\}/g +const isWildcard = /^[!*$]$/ +const hasLookupId = /\/:\w+?@@([0-9]+?)@@/ +const isNamedGroup = /^\/:/ + +/** + * Test if a route is part regular expressed + * and replace it for a simple character + * @param route + * @returns {*} + */ +const stripRegex = (route, char = 'R') => { + // if route is part regular expressed we replace + // the regular expression for a character to + // simplify floor calculation and backtracking + if (hasRegex.test(route)) { + route = route.replace(hasRegex, char) + } + return route +} + + +/***/ }), + +/***/ "./node_modules/@lightningjs/sdk/src/Router/utils/register.js": +/*!********************************************************************!*\ + !*** ./node_modules/@lightningjs/sdk/src/Router/utils/register.js ***! + \********************************************************************/ +/*! exports provided: createRegister */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "createRegister", function() { return createRegister; }); +/* + * If not stated otherwise in this file or this component's LICENSE file the + * following copyright and licenses apply: + * + * Copyright 2020 Metrological + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * Create a local request register + * @param flags + * @returns {Map} + */ +const createRegister = flags => { + const reg = new Map() + // store user defined and router + // defined flags in register + ;[...Object.keys(flags), ...Object.getOwnPropertySymbols(flags)].forEach(key => { + reg.set(key, flags[key]) + }) + return reg +} + + +/***/ }), + +/***/ "./node_modules/@lightningjs/sdk/src/Router/utils/route.js": +/*!*****************************************************************!*\ + !*** ./node_modules/@lightningjs/sdk/src/Router/utils/route.js ***! + \*****************************************************************/ +/*! exports provided: getFloor, getRouteByHash, getValuesFromHash, getOption, createRoute, createRequest, getHashByName, keepActivePageAlive */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getFloor", function() { return getFloor; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getRouteByHash", function() { return getRouteByHash; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getValuesFromHash", function() { return getValuesFromHash; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getOption", function() { return getOption; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "createRoute", function() { return createRoute; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "createRequest", function() { return createRequest; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getHashByName", function() { return getHashByName; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "keepActivePageAlive", function() { return keepActivePageAlive; }); +/* harmony import */ var _regex__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./regex */ "./node_modules/@lightningjs/sdk/src/Router/utils/regex.js"); +/* harmony import */ var _router__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./router */ "./node_modules/@lightningjs/sdk/src/Router/utils/router.js"); +/* harmony import */ var _model_Request__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../model/Request */ "./node_modules/@lightningjs/sdk/src/Router/model/Request.js"); +/* harmony import */ var _model_Route__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../model/Route */ "./node_modules/@lightningjs/sdk/src/Router/model/Route.js"); +/* harmony import */ var _helpers__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./helpers */ "./node_modules/@lightningjs/sdk/src/Router/utils/helpers.js"); +/* + * If not stated otherwise in this file or this component's LICENSE file the + * following copyright and licenses apply: + * + * Copyright 2020 Metrological + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + + + + + +/** + * Simple route length calculation + * @param route {string} + * @returns {number} - floor + */ +const getFloor = route => { + return Object(_regex__WEBPACK_IMPORTED_MODULE_0__["stripRegex"])(route).split('/').length +} + +/** + * return all stored routes that live on the same floor + * @param floor + * @returns {Array} + */ +const getRoutesByFloor = floor => { + const matches = [] + // simple filter of level candidates + for (let [route] of _router__WEBPACK_IMPORTED_MODULE_1__["routes"].entries()) { + if (getFloor(route) === floor) { + matches.push(route) + } + } + return matches +} + +/** + * return a matching route by provided hash + * hash: home/browse/12 will match: + * route: home/browse/:categoryId + * @param hash {string} + * @returns {boolean|{}} - route + */ +const getRouteByHash = hash => { + // @todo: clean up on handleHash + hash = hash.replace(/^#/, '') + + const getUrlParts = /(\/?:?[^/]+)/g + // grab possible candidates from stored routes + const candidates = getRoutesByFloor(getFloor(hash)) + // break hash down in chunks + const hashParts = hash.match(getUrlParts) || [] + + // to simplify the route matching and prevent look around + // in our getUrlParts regex we get the regex part from + // route candidate and store them so that we can reference + // them when we perform the actual regex against hash + let regexStore = [] + + let matches = candidates.filter(route => { + let isMatching = true + // replace regex in route with lookup id => @@{storeId}@@ + if (_regex__WEBPACK_IMPORTED_MODULE_0__["hasRegex"].test(route)) { + const regMatches = route.match(_regex__WEBPACK_IMPORTED_MODULE_0__["hasRegex"]) + if (regMatches && regMatches.length) { + route = regMatches.reduce((fullRoute, regex) => { + const lookupId = regexStore.length + fullRoute = fullRoute.replace(regex, `@@${lookupId}@@`) + regexStore.push(regex.substring(1, regex.length - 1)) + return fullRoute + }, route) + } + } + + const routeParts = route.match(getUrlParts) || [] + + for (let i = 0, j = routeParts.length; i < j; i++) { + const routePart = routeParts[i] + const hashPart = hashParts[i] + + // Since we support catch-all and regex driven name groups + // we first test for regex lookup id and see if the regex + // matches the value from the hash + if (_regex__WEBPACK_IMPORTED_MODULE_0__["hasLookupId"].test(routePart)) { + const routeMatches = _regex__WEBPACK_IMPORTED_MODULE_0__["hasLookupId"].exec(routePart) + const storeId = routeMatches[1] + const routeRegex = regexStore[storeId] + + // split regex and modifiers so we can use both + // to create a new RegExp + // eslint-disable-next-line + const regMatches = /\/([^\/]+)\/([igm]{0,3})/.exec(routeRegex) + + if (regMatches && regMatches.length) { + const expression = regMatches[1] + const modifiers = regMatches[2] + + const regex = new RegExp(`^/${expression}$`, modifiers) + + if (!regex.test(hashPart)) { + isMatching = false + } + } + } else if (_regex__WEBPACK_IMPORTED_MODULE_0__["isNamedGroup"].test(routePart)) { + // we kindly skip namedGroups because this is dynamic + // we only need to the static and regex drive parts + continue + } else if (hashPart && routePart.toLowerCase() !== hashPart.toLowerCase()) { + isMatching = false + } + } + return isMatching + }) + + if (matches.length) { + if (matches.indexOf(hash) !== -1) { + const match = matches[matches.indexOf(hash)] + return _router__WEBPACK_IMPORTED_MODULE_1__["routes"].get(match) + } else { + // we give prio to static routes over dynamic + matches = matches.sort(a => { + return _regex__WEBPACK_IMPORTED_MODULE_0__["isNamedGroup"].test(a) ? -1 : 1 + }) + // would be strange if this fails + // but still we test + if (Object(_router__WEBPACK_IMPORTED_MODULE_1__["routeExists"])(matches[0])) { + return _router__WEBPACK_IMPORTED_MODULE_1__["routes"].get(matches[0]) + } + } + } + return false +} + +const getValuesFromHash = (hash = '', path) => { + // replace the regex definition from the route because + // we already did the matching part + path = Object(_regex__WEBPACK_IMPORTED_MODULE_0__["stripRegex"])(path, '') + + const getUrlParts = /(\/?:?[\w%\s:.-]+)/g + const hashParts = hash.match(getUrlParts) || [] + const routeParts = path.match(getUrlParts) || [] + const getNamedGroup = /^\/:([\w-]+)\/?/ + + return routeParts.reduce((storage, value, index) => { + const match = getNamedGroup.exec(value) + if (match && match.length) { + storage.set(match[1], decodeURIComponent(hashParts[index].replace(/^\//, ''))) + } + return storage + }, new Map()) +} + +const getOption = (stack, prop) => { + // eslint-disable-next-line + if(stack && stack.hasOwnProperty(prop)){ + return stack[prop] + } + // we explicitly return undefined since we're testing + // for explicit test values +} + +/** + * create and return new Route instance + * @param config + */ +const createRoute = config => { + // we need to provide a bit of additional logic + // for the bootComponent + if (config.path === '$') { + let options = { + preventStorage: true, + } + if (Object(_helpers__WEBPACK_IMPORTED_MODULE_4__["isObject"])(config.options)) { + options = { + ...config.options, + ...options, + } + } + config.options = options + // if configured add reference to bootRequest + // as router after provider + if (_router__WEBPACK_IMPORTED_MODULE_1__["bootRequest"]) { + config.after = _router__WEBPACK_IMPORTED_MODULE_1__["bootRequest"] + } + } + return new _model_Route__WEBPACK_IMPORTED_MODULE_3__["default"](config) +} + +/** + * Create a new Router request object + * @param url + * @param args + * @param store + * @returns {*} + */ +const createRequest = (url, args, store) => { + return new _model_Request__WEBPACK_IMPORTED_MODULE_2__["default"](url, args, store) +} + +const getHashByName = obj => { + if (!obj.to && !obj.name) { + return false + } + const route = getRouteByName(obj.to || obj.name) + const hasDynamicGroup = /\/:([\w-]+)\/?/ + let hash = route + + // if route contains dynamic group + // we replace them with the provided params + if (hasDynamicGroup.test(route)) { + if (obj.params) { + const keys = Object.keys(obj.params) + hash = keys.reduce((acc, key) => { + return acc.replace(`:${key}`, obj.params[key]) + }, route) + } + if (obj.query) { + return `${hash}${Object(_helpers__WEBPACK_IMPORTED_MODULE_4__["objectToQueryString"])(obj.query)}` + } + } + return hash +} + +const getRouteByName = name => { + for (let [path, route] of _router__WEBPACK_IMPORTED_MODULE_1__["routes"].entries()) { + if (route.name === name) { + return path + } + } + return false +} + +const keepActivePageAlive = (route, request) => { + if (Object(_helpers__WEBPACK_IMPORTED_MODULE_4__["isString"])(route)) { + const routes = Object(_router__WEBPACK_IMPORTED_MODULE_1__["getRoutes"])() + if (routes.has(route)) { + route = routes.get(route) + } else { + return false + } + } + + const register = request.register + const routeOptions = route.options + + if (register.has('keepAlive')) { + return register.get('keepAlive') + } else if (routeOptions && routeOptions.keepAlive) { + return routeOptions.keepAlive + } + + return false +} + + +/***/ }), + +/***/ "./node_modules/@lightningjs/sdk/src/Router/utils/router.js": +/*!******************************************************************!*\ + !*** ./node_modules/@lightningjs/sdk/src/Router/utils/router.js ***! + \******************************************************************/ +/*! exports provided: application, app, pagesHost, stage, routerConfig, widgetsHost, bootRequest, updateHash, beforeEachRoute, afterEachRoute, routes, components, bootRouter, storeComponent, getComponent, deleteCurrentInstance, mustUpdateLocationHash, onRequestResolved, getActiveHash, setActiveHash, setActivePage, getActivePage, getActiveRoute, getLastHash, setLastHash, setPreviousState, getPreviousState, routeExists, getRootHash, getBootRequest, getRouterConfig, getRoutes */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "application", function() { return application; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "app", function() { return app; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "pagesHost", function() { return pagesHost; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "stage", function() { return stage; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "routerConfig", function() { return routerConfig; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "widgetsHost", function() { return widgetsHost; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "bootRequest", function() { return bootRequest; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "updateHash", function() { return updateHash; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "beforeEachRoute", function() { return beforeEachRoute; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "afterEachRoute", function() { return afterEachRoute; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "routes", function() { return routes; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "components", function() { return components; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "bootRouter", function() { return bootRouter; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "storeComponent", function() { return storeComponent; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getComponent", function() { return getComponent; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "deleteCurrentInstance", function() { return deleteCurrentInstance; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "mustUpdateLocationHash", function() { return mustUpdateLocationHash; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "onRequestResolved", function() { return onRequestResolved; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getActiveHash", function() { return getActiveHash; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "setActiveHash", function() { return setActiveHash; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "setActivePage", function() { return setActivePage; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getActivePage", function() { return getActivePage; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getActiveRoute", function() { return getActiveRoute; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getLastHash", function() { return getLastHash; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "setLastHash", function() { return setLastHash; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "setPreviousState", function() { return setPreviousState; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getPreviousState", function() { return getPreviousState; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "routeExists", function() { return routeExists; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getRootHash", function() { return getRootHash; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getBootRequest", function() { return getBootRequest; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getRouterConfig", function() { return getRouterConfig; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getRoutes", function() { return getRoutes; }); +/* harmony import */ var _helpers__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./helpers */ "./node_modules/@lightningjs/sdk/src/Router/utils/helpers.js"); +/* harmony import */ var _index__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../index */ "./node_modules/@lightningjs/sdk/src/Router/index.js"); +/* harmony import */ var _route__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./route */ "./node_modules/@lightningjs/sdk/src/Router/utils/route.js"); +/* harmony import */ var _components__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./components */ "./node_modules/@lightningjs/sdk/src/Router/utils/components.js"); +/* harmony import */ var _Log__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../Log */ "./node_modules/@lightningjs/sdk/src/Log/index.js"); +/* harmony import */ var _regex__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./regex */ "./node_modules/@lightningjs/sdk/src/Router/utils/regex.js"); +/* harmony import */ var _emit__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./emit */ "./node_modules/@lightningjs/sdk/src/Router/utils/emit.js"); +/* harmony import */ var _widgets__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./widgets */ "./node_modules/@lightningjs/sdk/src/Router/utils/widgets.js"); +/* harmony import */ var _history__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./history */ "./node_modules/@lightningjs/sdk/src/Router/utils/history.js"); +/* harmony import */ var _Application__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ../../Application */ "./node_modules/@lightningjs/sdk/src/Application/index.js"); +/* + * If not stated otherwise in this file or this component's LICENSE file the + * following copyright and licenses apply: + * + * Copyright 2020 Metrological + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + + + + + + + + + + +/** + * @type {Lightning.Application} + */ +let application + +/** + * Actual instance of the app + * @type {Lightning.Component} + */ +let app + +/** + * Component that hosts all routed pages + * @type {Lightning.Component} + */ +let pagesHost + +/** + * @type {Lightning.Stage} + */ +let stage + +/** + * Platform driven Router configuration + * @type {Map} + */ +let routerConfig + +/** + * Component that hosts all attached widgets + * @type {Lightning.Component} + */ +let widgetsHost + +/** + * Hash we point the browser to when we boot the app + * and there is no deep-link provided + * @type {string|Function} + */ +let rootHash + +/** + * Boot request will fire before app start + * can be used to execute some global logic + * and can be configured + */ +let bootRequest + +/** + * Flag if we need to update the browser location hash. + * Router can work without. + * @type {boolean} + */ +let updateHash = true + +/** + * Will be called before a route starts, can be overridden + * via routes config + * @param from - route we came from + * @param to - route we navigate to + * @returns {Promise<*>} + */ +// eslint-disable-next-line +let beforeEachRoute = async (from, to)=>{ + return true +} + +/** + * * Will be called after a navigate successfully resolved, + * can be overridden via routes config + */ +let afterEachRoute = () => {} + +/** + * All configured routes + * @type {Map} + */ +let routes = new Map() + +/** + * Store all page components per route + * @type {Map} + */ +let components = new Map() + +/** + * Flag if router has been initialised + * @type {boolean} + */ +let initialised = false + +/** + * Current page being rendered on screen + * @type {null} + */ +let activePage = null +let activeHash +let activeRoute + +/** + * During the process of a navigation request a new + * request can start, to prevent unwanted behaviour + * the navigate()-method stores the last accepted hash + * so we can invalidate any prior requests + */ +let lastAcceptedHash + +/** + * With on()-data providing behaviour the Router forced the App + * in a Loading state. When the data-provider resolves we want to + * change the state back to where we came from + */ +let previousState + +const mixin = app => { + // by default the Router Baseclass provides the component + // reference in which we store our pages + if (app.pages) { + pagesHost = app.pages.childList + } + // if the app is using widgets we grab refs + // and hide all the widgets + if (app.widgets && app.widgets.children) { + widgetsHost = app.widgets.childList + // hide all widgets on boot + widgetsHost.forEach(w => (w.visible = false)) + } + app._handleBack = e => { + Object(_index__WEBPACK_IMPORTED_MODULE_1__["step"])(-1) + e.preventDefault() + } +} + +const bootRouter = (config, instance) => { + let { appInstance, routes } = config + + // if instance is provided and it's and Lightning Component instance + if (instance && Object(_helpers__WEBPACK_IMPORTED_MODULE_0__["isPage"])(instance)) { + app = instance + } + if (!app) { + app = appInstance || _Application__WEBPACK_IMPORTED_MODULE_9__["AppInstance"] + } + + application = app.application + pagesHost = application.childList + stage = app.stage + routerConfig = Object(_helpers__WEBPACK_IMPORTED_MODULE_0__["getConfigMap"])() + + mixin(app) + + if (Object(_helpers__WEBPACK_IMPORTED_MODULE_0__["isArray"])(routes)) { + setup(config) + } else if (Object(_helpers__WEBPACK_IMPORTED_MODULE_0__["isFunction"])(routes)) { + console.warn('[Router]: Calling Router.route() directly is deprecated.') + console.warn( + 'Use object config: https://rdkcentral.github.io/Lightning-SDK/#/plugins/router/configuration' + ) + } +} + +const setup = config => { + if (!initialised) { + init(config) + } + config.routes.forEach(r => { + const path = Object(_helpers__WEBPACK_IMPORTED_MODULE_0__["cleanHash"])(r.path) + if (!routeExists(path)) { + const route = Object(_route__WEBPACK_IMPORTED_MODULE_2__["createRoute"])(r) + routes.set(path, route) + // if route has a configured component property + // we store it in a different map to simplify + // the creating and destroying per route + if (route.component) { + let type = route.component + if (Object(_helpers__WEBPACK_IMPORTED_MODULE_0__["isComponentConstructor"])(type)) { + if (!routerConfig.get('lazyCreate')) { + type = Object(_components__WEBPACK_IMPORTED_MODULE_3__["createComponent"])(stage, type) + pagesHost.a(type) + } + } + components.set(path, type) + } + } else { + console.error(`${path} already exists in routes configuration`) + } + }) +} + +const init = config => { + rootHash = config.root + if (Object(_helpers__WEBPACK_IMPORTED_MODULE_0__["isFunction"])(config.boot)) { + bootRequest = config.boot + } + if (Object(_helpers__WEBPACK_IMPORTED_MODULE_0__["isBoolean"])(config.updateHash)) { + updateHash = config.updateHash + } + if (Object(_helpers__WEBPACK_IMPORTED_MODULE_0__["isFunction"])(config.beforeEachRoute)) { + beforeEachRoute = config.beforeEachRoute + } + if (Object(_helpers__WEBPACK_IMPORTED_MODULE_0__["isFunction"])(config.afterEachRoute)) { + afterEachRoute = config.afterEachRoute + } + if (config.bootComponent) { + console.warn( + '[Router]: Boot Component is now available as a special router: https://rdkcentral.github.io/Lightning-SDK/#/plugins/router/configuration?id=special-routes' + ) + console.warn( + '[Router]: setting { bootComponent } property will be deprecated in a future release' + ) + if (Object(_helpers__WEBPACK_IMPORTED_MODULE_0__["isPage"])(config.bootComponent)) { + config.routes.push({ + path: '$', + component: config.bootComponent, + // we try to assign the bootRequest as after data-provider + // so it will behave as any other component + after: bootRequest || null, + options: { + preventStorage: true, + }, + }) + } else { + console.error(`[Router]: ${config.bootComponent} is not a valid boot component`) + } + } + config.routes.forEach(item => { + // replacing regexes with 'R' to avoid issues with pattern matching below + const strippedPath = Object(_regex__WEBPACK_IMPORTED_MODULE_5__["stripRegex"])(item.path) + + // Pattern to identify the last path of the route + // It should start with "/:" + any word and ends with "?" + // It should be the last path of the route + // valid => /player/:asset/:assetId? (:assetId is optional) + // invalid => /player/:asset/:assetId?/test (:assetId? is not an optional path) + // invalid => /player/:asset?/:assetId? (second path is not considered as an optional path) + const pattern = /.*\/:.*?\?$/u + + if (pattern.test(strippedPath)) { + const optionalPath = item.path.substring(0, item.path.lastIndexOf('/')) + const originalPath = item.path.substring(0, item.path.lastIndexOf('?')) + item.path = originalPath + //Create another entry with the optional path + let optionalItem = { ...item } + optionalItem.path = optionalPath + config.routes.push(optionalItem) + } + }) + initialised = true +} + +const storeComponent = (route, type) => { + if (components.has(route)) { + components.set(route, type) + } +} + +const getComponent = route => { + if (components.has(route)) { + return components.get(route) + } + return null +} + +// delete existing route instance from memory +const deleteCurrentInstance = route => { + if (components.has(route) && pagesHost.getIndex(components.get(route)) !== -1) { + pagesHost.remove(components.get(route)) + storeComponent(route, components.get(route)._routedType || components.get(route).constructor) + } +} + +/** + * Test if router needs to update browser location hash + * @returns {boolean} + */ +const mustUpdateLocationHash = () => { + if (!routerConfig || !routerConfig.size) { + return false + } + // we need support to either turn change hash off + // per platform or per app + const updateConfig = routerConfig.get('updateHash') + return !((Object(_helpers__WEBPACK_IMPORTED_MODULE_0__["isBoolean"])(updateConfig) && !updateConfig) || (Object(_helpers__WEBPACK_IMPORTED_MODULE_0__["isBoolean"])(updateHash) && !updateHash)) +} + +/** + * Will be called when a new navigate() request has completed + * and has not been expired due to it's async nature + * @param request + */ +const onRequestResolved = request => { + const hash = request.hash + const route = request.route + const register = request.register + const page = request.page + + // clean up history if modifier is set + if (Object(_route__WEBPACK_IMPORTED_MODULE_2__["getOption"])(route.options, 'clearHistory')) { + Object(_history__WEBPACK_IMPORTED_MODULE_8__["setHistory"])([]) + } else if (hash && !_regex__WEBPACK_IMPORTED_MODULE_5__["isWildcard"].test(route.path)) { + Object(_history__WEBPACK_IMPORTED_MODULE_8__["updateHistory"])(request) + } + + // we only update the stackLocation if a route + // is not expired before it resolves + storeComponent(route.path, page) + + if (request.isSharedInstance || !request.isCreated) { + Object(_emit__WEBPACK_IMPORTED_MODULE_6__["default"])(page, 'changed') + } else if (request.isCreated) { + Object(_emit__WEBPACK_IMPORTED_MODULE_6__["default"])(page, 'mounted') + } + + // only update widgets if we have a host + if (widgetsHost) { + Object(_widgets__WEBPACK_IMPORTED_MODULE_7__["updateWidgets"])(route.widgets, page) + } + + // we want to clean up if there is an + // active page that is not being shared + // between current and previous route + if (getActivePage() && !request.isSharedInstance) { + cleanUp(activePage, request) + } + + // provide history object to active page + if (register.get(_helpers__WEBPACK_IMPORTED_MODULE_0__["symbols"].historyState) && Object(_helpers__WEBPACK_IMPORTED_MODULE_0__["isFunction"])(page.historyState)) { + page.historyState(register.get(_helpers__WEBPACK_IMPORTED_MODULE_0__["symbols"].historyState)) + } + + setActivePage(page) + + activeHash = request.hash + activeRoute = route.path + + // cleanup all cancelled requests + for (let request of _index__WEBPACK_IMPORTED_MODULE_1__["navigateQueue"].values()) { + if (request.isCancelled && request.hash) { + _index__WEBPACK_IMPORTED_MODULE_1__["navigateQueue"].delete(request.hash) + } + } + + afterEachRoute(request) + + _Log__WEBPACK_IMPORTED_MODULE_4__["default"].info('[route]:', route.path) + _Log__WEBPACK_IMPORTED_MODULE_4__["default"].info('[hash]:', hash) +} + +const cleanUp = (page, request) => { + const route = activeRoute + const register = request.register + const lazyDestroy = routerConfig.get('lazyDestroy') + const destroyOnBack = routerConfig.get('destroyOnHistoryBack') + const keepAlive = register.get('keepAlive') + const isFromHistory = register.get(_helpers__WEBPACK_IMPORTED_MODULE_0__["symbols"].backtrack) + + let doCleanup = false + + // if this request is executed due to a step back in history + // and we have configured to destroy active page when we go back + // in history or lazyDestory is enabled + if (isFromHistory && (destroyOnBack || lazyDestroy)) { + doCleanup = true + } + + // clean up if lazyDestroy is enabled and the keepAlive flag + // in navigation register is false + if (lazyDestroy && !keepAlive) { + doCleanup = true + } + + // if the current and new request share the same route blueprint + if (activeRoute === request.route.path) { + doCleanup = true + } + + if (doCleanup) { + // grab original class constructor if + // statemachine routed else store constructor + storeComponent(route, page._routedType || page.constructor) + + // actual remove of page from memory + pagesHost.remove(page) + + // force texture gc() if configured + // so we can cleanup textures in the same tick + if (routerConfig.get('gcOnUnload')) { + stage.gc() + } + } else { + // If we're not removing the page we need to + // reset it's properties + page.patch({ + x: 0, + y: 0, + scale: 1, + visible: false, + alpha: 1, + }) + } +} + +const getActiveHash = () => { + return activeHash +} + +const setActiveHash = hash => { + activeHash = hash +} + +const setActivePage = page => { + activePage = page +} + +const getActivePage = () => { + return activePage +} + +const getActiveRoute = () => { + return activeRoute +} + +const getLastHash = () => { + return lastAcceptedHash +} + +const setLastHash = hash => { + lastAcceptedHash = hash +} + +const setPreviousState = state => { + previousState = state +} + +const getPreviousState = () => { + return previousState +} + +const routeExists = key => { + return routes.has(key) +} + +const getRootHash = () => { + return rootHash +} + +const getBootRequest = () => { + return bootRequest +} + +const getRouterConfig = () => { + return routerConfig +} + +const getRoutes = () => { + return routes +} + + +/***/ }), + +/***/ "./node_modules/@lightningjs/sdk/src/Router/utils/transition.js": +/*!**********************************************************************!*\ + !*** ./node_modules/@lightningjs/sdk/src/Router/utils/transition.js ***! + \**********************************************************************/ +/*! exports provided: executeTransition */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "executeTransition", function() { return executeTransition; }); +/* harmony import */ var _router__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./router */ "./node_modules/@lightningjs/sdk/src/Router/utils/router.js"); +/* harmony import */ var _helpers__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./helpers */ "./node_modules/@lightningjs/sdk/src/Router/utils/helpers.js"); +/* harmony import */ var _transitions__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../transitions */ "./node_modules/@lightningjs/sdk/src/Router/transitions.js"); +/* + * If not stated otherwise in this file or this component's LICENSE file the + * following copyright and licenses apply: + * + * Copyright 2020 Metrological + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + + + +/** + * execute transition between new / old page and + * toggle the defined widgets + * @todo: platform override default transition + * @param pageIn + * @param pageOut + */ +const executeTransition = (pageIn, pageOut = null) => { + const transition = pageIn.pageTransition || pageIn.easing + const hasCustomTransitions = !!(pageIn.smoothIn || pageIn.smoothInOut || transition) + const transitionsDisabled = Object(_router__WEBPACK_IMPORTED_MODULE_0__["getRouterConfig"])().get('disableTransitions') + + if (pageIn.easing) { + console.warn('easing() method is deprecated and will be removed. Use pageTransition()') + } + + // default behaviour is a visibility toggle + if (!hasCustomTransitions || transitionsDisabled) { + pageIn.visible = true + if (pageOut) { + pageOut.visible = false + } + return Promise.resolve() + } + + if (transition) { + let type + try { + type = transition.call(pageIn, pageIn, pageOut) + } catch (e) { + type = 'crossFade' + } + + if (Object(_helpers__WEBPACK_IMPORTED_MODULE_1__["isPromise"])(type)) { + return type + } + + if (Object(_helpers__WEBPACK_IMPORTED_MODULE_1__["isString"])(type)) { + const fn = _transitions__WEBPACK_IMPORTED_MODULE_2__["default"][type] + if (fn) { + return fn(pageIn, pageOut) + } + } + + // keep backwards compatible for now + if (pageIn.smoothIn) { + // provide a smooth function that resolves itself + // on transition finish + const smooth = (p, v, args = {}) => { + return new Promise(resolve => { + pageIn.visible = true + pageIn.setSmooth(p, v, args) + pageIn.transition(p).on('finish', () => { + resolve() + }) + }) + } + return pageIn.smoothIn({ pageIn, smooth }) + } + } + return _transitions__WEBPACK_IMPORTED_MODULE_2__["default"].crossFade(pageIn, pageOut) +} + + +/***/ }), + +/***/ "./node_modules/@lightningjs/sdk/src/Router/utils/widgets.js": +/*!*******************************************************************!*\ + !*** ./node_modules/@lightningjs/sdk/src/Router/utils/widgets.js ***! + \*******************************************************************/ +/*! exports provided: getReferences, updateWidgets, focusWidget, handleRemote, restoreFocus, getActiveWidget, setActiveWidget */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getReferences", function() { return getReferences; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "updateWidgets", function() { return updateWidgets; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "focusWidget", function() { return focusWidget; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "handleRemote", function() { return handleRemote; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "restoreFocus", function() { return restoreFocus; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getActiveWidget", function() { return getActiveWidget; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "setActiveWidget", function() { return setActiveWidget; }); +/* harmony import */ var _router__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./router */ "./node_modules/@lightningjs/sdk/src/Router/utils/router.js"); +/* harmony import */ var _helpers__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./helpers */ "./node_modules/@lightningjs/sdk/src/Router/utils/helpers.js"); +/* harmony import */ var _emit__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./emit */ "./node_modules/@lightningjs/sdk/src/Router/utils/emit.js"); +/* + * If not stated otherwise in this file or this component's LICENSE file the + * following copyright and licenses apply: + * + * Copyright 2020 Metrological + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + + + +let activeWidget = null + +const getReferences = () => { + if (!_router__WEBPACK_IMPORTED_MODULE_0__["widgetsHost"]) { + return + } + return _router__WEBPACK_IMPORTED_MODULE_0__["widgetsHost"].get().reduce((storage, widget) => { + const key = widget.ref.toLowerCase() + storage[key] = widget + return storage + }, {}) +} + +/** + * update the visibility of the available widgets + * for the current page / route + * @param page + */ +const updateWidgets = (widgets, page) => { + // force lowercase lookup + const configured = (widgets || []).map(ref => ref.toLowerCase()) + + _router__WEBPACK_IMPORTED_MODULE_0__["widgetsHost"].forEach(widget => { + widget.visible = configured.indexOf(widget.ref.toLowerCase()) !== -1 + if (widget.visible) { + Object(_emit__WEBPACK_IMPORTED_MODULE_2__["default"])(widget, ['activated'], page) + } + }) + if (_router__WEBPACK_IMPORTED_MODULE_0__["app"].state === 'Widgets' && activeWidget && !activeWidget.visible) { + _router__WEBPACK_IMPORTED_MODULE_0__["app"]._setState('') + } +} + +const getWidgetByName = name => { + name = Object(_helpers__WEBPACK_IMPORTED_MODULE_1__["ucfirst"])(name) + return _router__WEBPACK_IMPORTED_MODULE_0__["widgetsHost"].getByRef(name) || false +} + +/** + * delegate app focus to a on-screen widget + * @param name - {string} + */ +const focusWidget = name => { + const widget = getWidgetByName(name) + if (widget) { + setActiveWidget(widget) + + // if app is already in 'Widgets' state we can assume that + // focus has been delegated from one widget to another so + // we need to set the new widget reference and trigger a + // new focus calculation of Lightning's focuspath + if (_router__WEBPACK_IMPORTED_MODULE_0__["app"].state === 'Widgets') { + _router__WEBPACK_IMPORTED_MODULE_0__["app"].reload(activeWidget) + } else { + _router__WEBPACK_IMPORTED_MODULE_0__["app"]._setState('Widgets', [activeWidget]) + } + } +} + +const handleRemote = (type, name) => { + if (type === 'widget') { + focusWidget(name) + } else if (type === 'page') { + restoreFocus() + } +} + +const restoreFocus = () => { + activeWidget = null + _router__WEBPACK_IMPORTED_MODULE_0__["app"]._setState('') +} + +const getActiveWidget = () => { + return activeWidget +} + +const setActiveWidget = instance => { + activeWidget = instance +} + + +/***/ }), + +/***/ "./node_modules/@lightningjs/sdk/src/Settings/index.js": +/*!*************************************************************!*\ + !*** ./node_modules/@lightningjs/sdk/src/Settings/index.js ***! + \*************************************************************/ +/*! exports provided: initSettings, default */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "initSettings", function() { return initSettings; }); +/* + * If not stated otherwise in this file or this component's LICENSE file the + * following copyright and licenses apply: + * + * Copyright 2020 Metrological + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +const settings = {} +const subscribers = {} + +const initSettings = (appSettings, platformSettings) => { + settings['app'] = appSettings + settings['platform'] = platformSettings + settings['user'] = {} +} + +const publish = (key, value) => { + subscribers[key] && subscribers[key].forEach(subscriber => subscriber(value)) +} + +const dotGrab = (obj = {}, key) => { + if (obj === null) return undefined + const keys = key.split('.') + for (let i = 0; i < keys.length; i++) { + obj = obj[keys[i]] = obj[keys[i]] !== undefined ? obj[keys[i]] : {} + } + return typeof obj === 'object' && obj !== null ? (Object.keys(obj).length ? obj : undefined) : obj +} + +/* harmony default export */ __webpack_exports__["default"] = ({ + get(type, key, fallback = undefined) { + const val = dotGrab(settings[type], key) + return val !== undefined ? val : fallback + }, + has(type, key) { + return !!this.get(type, key) + }, + set(key, value) { + settings['user'][key] = value + publish(key, value) + }, + subscribe(key, callback) { + subscribers[key] = subscribers[key] || [] + subscribers[key].push(callback) + }, + unsubscribe(key, callback) { + if (callback) { + const index = subscribers[key] && subscribers[key].findIndex(cb => cb === callback) + index > -1 && subscribers[key].splice(index, 1) + } else { + if (key in subscribers) { + subscribers[key] = [] + } + } + }, + clearSubscribers() { + for (const key of Object.getOwnPropertyNames(subscribers)) { + delete subscribers[key] + } + }, +}); + + +/***/ }), + +/***/ "./node_modules/@lightningjs/sdk/src/Storage/index.js": +/*!************************************************************!*\ + !*** ./node_modules/@lightningjs/sdk/src/Storage/index.js ***! + \************************************************************/ +/*! exports provided: initStorage, default */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "initStorage", function() { return initStorage; }); +/* harmony import */ var _Settings__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Settings */ "./node_modules/@lightningjs/sdk/src/Settings/index.js"); +/* harmony import */ var localcookies_module_localCookie_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! localcookies/module/localCookie.js */ "./node_modules/localcookies/module/localCookie.js"); +/* + * If not stated otherwise in this file or this component's LICENSE file the + * following copyright and licenses apply: + * + * Copyright 2020 Metrological + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + + +let namespace +let lc + +const initStorage = () => { + namespace = _Settings__WEBPACK_IMPORTED_MODULE_0__["default"].get('platform', 'id') + // todo: pass options (for example to force the use of cookies) + lc = new localcookies_module_localCookie_js__WEBPACK_IMPORTED_MODULE_1__["default"]() +} + +const namespacedKey = key => (namespace ? [namespace, key].join('.') : key) + +/* harmony default export */ __webpack_exports__["default"] = ({ + get(key) { + try { + return JSON.parse(lc.getItem(namespacedKey(key))) + } catch (e) { + return null + } + }, + set(key, value) { + try { + lc.setItem(namespacedKey(key), JSON.stringify(value)) + return true + } catch (e) { + return false + } + }, + remove(key) { + lc.removeItem(namespacedKey(key)) + }, + clear() { + if (namespace) { + lc.keys().forEach(key => { + // remove the item if in the namespace + key.indexOf(namespace + '.') === 0 ? lc.removeItem(key) : null + }) + } else { + lc.clear() + } + }, +}); + + +/***/ }), + +/***/ "./node_modules/@lightningjs/sdk/src/Subtitles/SubtitleComponent.js": +/*!**************************************************************************!*\ + !*** ./node_modules/@lightningjs/sdk/src/Subtitles/SubtitleComponent.js ***! + \**************************************************************************/ +/*! exports provided: default */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return SubtitleComponent; }); +/* harmony import */ var _Lightning__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Lightning */ "./node_modules/@lightningjs/sdk/src/Lightning/index.js"); +/* + * If not stated otherwise in this file or this component's LICENSE file the + * following copyright and licenses apply: + * + * Copyright 2020 Metrological + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + +class SubtitleComponent extends _Lightning__WEBPACK_IMPORTED_MODULE_0__["default"].Component { + static _template() { + return { + visible: false, + rect: true, + color: 0x90000000, + shader: { type: _Lightning__WEBPACK_IMPORTED_MODULE_0__["default"].shaders.RoundedRectangle, radius: 5 }, + Text: { + y: 5, + x: 20, + text: { + textColor: 0xffffffff, + fontSize: 38, + lineHeight: 38 * 1.4, + textAlign: 'center', + wordWrap: true, + maxLines: 3, + shadow: true, + shadowColor: 0xff333333, + }, + }, + } + } + + _init() { + this._textTextureDefaults = new _Lightning__WEBPACK_IMPORTED_MODULE_0__["default"].textures.TextTexture(this.stage).cloneArgs() + + this.tag('Text').on('txLoaded', ({ _source }) => { + this.w = _source.w + this.tag('Text').x * 2 + this.h = _source.h + this.position() + }) + } + + get textFormat() { + const textTag = this.tag('Text').text + return { + fontFace: textTag.fontFace || 'sans-serif', + fontSize: textTag.fontSize, + lineHeight: textTag.lineHeight, + textAlign: textTag.textAlign, + wordWrap: true, + maxLines: textTag.maxLines, + } + } + + show() { + this.visible = true + } + + hide() { + this.visible = false + } + + position() { + this.x = this._calculateX(this.xPos) + this.y = this._calculateY(this.yPos) + } + + set viewportW(v) { + this._viewportW = v + this.x = this._calculateX(this.xPos) + } + + get viewportW() { + return this._viewportW || this.application.finalW + } + + set viewportH(v) { + this._viewportH = v + this.y = this._calculateY(this.yPos) + } + + get viewportH() { + return this._viewportH || this.application.finalH + } + + _calculateX(x) { + if (x === 'center') { + x = (this.viewportW - this.finalW) / 2 + } else if (x === 'left') { + x = 60 + } else if (x === 'right') { + x = this.viewportW - this.finalW - 60 + } + return x + } + + set xPos(v) { + this._x = v + this.x = this._calculateX(v) + } + + get xPos() { + return this._x || 'center' + } + + _calculateY(y) { + if (y === 'center') { + return (this.viewportH - this.finalH) / 2 + } else if (y === 'top') { + return 60 + } else if (y === 'bottom') { + return this.viewportH - this.finalH - 60 + } + return y + } + + set yPos(v) { + this._y = v + this.y = this._calculateY(v) + } + + get yPos() { + return this._y || 'bottom' + } + + set fontFamily(v) { + this.tag('Text').text.fontFace = v + } + + set fontSize(v) { + this.tag('Text').text.fontSize = v + this.tag('Text').text.lineHeight = v * 1.3 + } + + set fontColor(v) { + this.tag('Text').color = v + } + + set backgroundColor(v) { + this.color = v + } + + _defineBreakpoint(text, breakpoint) { + if (breakpoint >= this.maxWidth) return this.maxWidth + const info = _Lightning__WEBPACK_IMPORTED_MODULE_0__["default"].textures.TextTexture.renderer( + this.stage, + this.stage.platform.getDrawingCanvas(), + { + ...this._textTextureDefaults, + ...this.textFormat, + ...{ wordWrapWidth: breakpoint }, + text, + } + )._calculateRenderInfo() + + if (info.width <= breakpoint && info.lines.length <= 2) { + return breakpoint + } else { + return this._defineBreakpoint(text, breakpoint * 1.25) + } + } + + set text(v) { + this.alpha = 0 + if (v && v.length) { + const breakpoint = this._defineBreakpoint(v, 640) + + this.tag('Text').text.wordWrapWidth = breakpoint + this.tag('Text').text = v + this.alpha = 1 + } + } + + set textAlign(v) { + this._textAlign = v + this.tag('Text').text.textAlign = v + } + + set maxWidth(v) { + this._maxWidth = v + } + + get maxWidth() { + return (this._maxWidth || 1200) - this.tag('Text').x * 2 + } + + set maxLines(v) { + this.tag('Text').text.maxLines = v + } +} + + +/***/ }), + +/***/ "./node_modules/@lightningjs/sdk/src/Subtitles/index.js": +/*!**************************************************************!*\ + !*** ./node_modules/@lightningjs/sdk/src/Subtitles/index.js ***! + \**************************************************************/ +/*! exports provided: default */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var _Application__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Application */ "./node_modules/@lightningjs/sdk/src/Application/index.js"); +/* harmony import */ var _SubtitleComponent__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./SubtitleComponent */ "./node_modules/@lightningjs/sdk/src/Subtitles/SubtitleComponent.js"); +/* + * If not stated otherwise in this file or this component's LICENSE file the + * following copyright and licenses apply: + * + * Copyright 2020 Metrological + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + + +let subtitlesComponent +const getOrCreateSubtitlesComponent = () => { + return subtitlesComponent + ? subtitlesComponent + : (subtitlesComponent = + _Application__WEBPACK_IMPORTED_MODULE_0__["AppInstance"].application.tag('Subtitles') || + _Application__WEBPACK_IMPORTED_MODULE_0__["AppInstance"].application.childList.a( + _Application__WEBPACK_IMPORTED_MODULE_0__["AppInstance"].stage.c({ + ref: 'Subtitles', + type: _SubtitleComponent__WEBPACK_IMPORTED_MODULE_1__["default"], + forceZIndexContext: true, + zIndex: 2, + }) + )) +} + +/* harmony default export */ __webpack_exports__["default"] = ({ + show() { + const subtitles = getOrCreateSubtitlesComponent() + subtitles.show() + }, + hide() { + const subtitles = getOrCreateSubtitlesComponent() + subtitles.hide() + }, + styles(v) { + Object.keys(v).forEach(key => { + if (key in this && typeof this[key] === 'function') { + this[key](v[key]) + } + }) + }, + fontFamily(v) { + const subtitles = getOrCreateSubtitlesComponent() + subtitles.fontFamily = v + }, + fontSize(v) { + const subtitles = getOrCreateSubtitlesComponent() + subtitles.fontSize = v + }, + fontColor(v) { + const subtitles = getOrCreateSubtitlesComponent() + subtitles.fontColor = v + }, + backgroundColor(v) { + const subtitles = getOrCreateSubtitlesComponent() + subtitles.backgroundColor = v + }, + textAlign(v) { + const subtitles = getOrCreateSubtitlesComponent() + subtitles.textAlign = v + }, + textAlignVertical(v) { + const subtitles = getOrCreateSubtitlesComponent() + subtitles.textAlignVertical = v + }, + viewport(w, h) { + const subtitles = getOrCreateSubtitlesComponent() + subtitles.viewportW = w + subtitles.viewportH = h + }, + position(x, y) { + const subtitles = getOrCreateSubtitlesComponent() + subtitles.xPos = x + subtitles.yPos = y + }, + maxWidth(v) { + const subtitles = getOrCreateSubtitlesComponent() + subtitles.maxWidth = v + }, + maxLines(v) { + const subtitles = getOrCreateSubtitlesComponent() + subtitles.maxLines = v + }, + text(v) { + const subtitles = getOrCreateSubtitlesComponent() + subtitles.text = v + }, + clear() { + const subtitles = getOrCreateSubtitlesComponent() + subtitles.text = '' + } +}); + + +/***/ }), + +/***/ "./node_modules/@lightningjs/sdk/src/TV/index.js": +/*!*******************************************************!*\ + !*** ./node_modules/@lightningjs/sdk/src/TV/index.js ***! + \*******************************************************/ +/*! exports provided: default */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var _metrological_sdk__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @metrological/sdk */ "./node_modules/@metrological/sdk/index.js"); +/* + * If not stated otherwise in this file or this component's LICENSE file the + * following copyright and licenses apply: + * + * Copyright 2020 Metrological + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + +/* harmony default export */ __webpack_exports__["default"] = (_metrological_sdk__WEBPACK_IMPORTED_MODULE_0__["TV"]); + + +/***/ }), + +/***/ "./node_modules/@lightningjs/sdk/src/Utils/index.js": +/*!**********************************************************!*\ + !*** ./node_modules/@lightningjs/sdk/src/Utils/index.js ***! + \**********************************************************/ +/*! exports provided: initUtils, default, ensureUrlWithProtocol, makeFullStaticPath, cleanUpPathName */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "initUtils", function() { return initUtils; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ensureUrlWithProtocol", function() { return ensureUrlWithProtocol; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "makeFullStaticPath", function() { return makeFullStaticPath; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "cleanUpPathName", function() { return cleanUpPathName; }); +/* + * If not stated otherwise in this file or this component's LICENSE file the + * following copyright and licenses apply: + * + * Copyright 2020 Metrological + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +let basePath +let proxyUrl + +const initUtils = config => { + basePath = ensureUrlWithProtocol(makeFullStaticPath(window.location.pathname, config.path || '/')) + + if (config.proxyUrl) { + proxyUrl = ensureUrlWithProtocol(config.proxyUrl) + } +} + +/* harmony default export */ __webpack_exports__["default"] = ({ + asset(relPath) { + return basePath + relPath + }, + proxyUrl(url, options = {}) { + return proxyUrl ? proxyUrl + '?' + makeQueryString(url, options) : url + }, + makeQueryString() { + return makeQueryString(...arguments) + }, + // since imageworkers don't work without protocol + ensureUrlWithProtocol() { + return ensureUrlWithProtocol(...arguments) + }, +}); + +const ensureUrlWithProtocol = url => { + if (/^\/[^/]/i.test(url) && /^(?:file:)/i.test(window.location.protocol)) { + return window.location.protocol + '//' + url + } + if (/^\/\//.test(url)) { + return window.location.protocol + url + } + if (!/^(?:https?:)/i.test(url)) { + return window.location.origin + url + } + return url +} + +const makeFullStaticPath = (pathname = '/', path) => { + // ensure path has traling slash + path = path.charAt(path.length - 1) !== '/' ? path + '/' : path + + // if path is URL, we assume it's already the full static path, so we just return it + if (/^(?:https?:)?(?:\/\/)/.test(path)) { + return path + } + + if (path.charAt(0) === '/') { + return path + } else { + // cleanup the pathname (i.e. remove possible index.html) + pathname = cleanUpPathName(pathname) + + // remove possible leading dot from path + path = path.charAt(0) === '.' ? path.substr(1) : path + // ensure path has leading slash + path = path.charAt(0) !== '/' ? '/' + path : path + return pathname + path + } +} + +const cleanUpPathName = pathname => { + if (pathname.slice(-1) === '/') return pathname.slice(0, -1) + const parts = pathname.split('/') + if (parts[parts.length - 1].indexOf('.') > -1) parts.pop() + return parts.join('/') +} + +const makeQueryString = (url, options = {}, type = 'url') => { + // add operator as an option + options.operator = 'metrological' // Todo: make this configurable (via url?) + // add type (= url or qr) as an option, with url as the value + options[type] = url + + return Object.keys(options) + .map(key => { + return encodeURIComponent(key) + '=' + encodeURIComponent('' + options[key]) + }) + .join('&') +} + + +/***/ }), + +/***/ "./node_modules/@lightningjs/sdk/src/VersionLabel/index.js": +/*!*****************************************************************!*\ + !*** ./node_modules/@lightningjs/sdk/src/VersionLabel/index.js ***! + \*****************************************************************/ +/*! exports provided: default */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return VersionLabel; }); +/* harmony import */ var _Lightning__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Lightning */ "./node_modules/@lightningjs/sdk/src/Lightning/index.js"); +/* + * If not stated otherwise in this file or this component's LICENSE file the + * following copyright and licenses apply: + * + * Copyright 2020 Metrological + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + +class VersionLabel extends _Lightning__WEBPACK_IMPORTED_MODULE_0__["default"].Component { + static _template() { + return { + rect: true, + color: 0xbb0078ac, + h: 40, + w: 100, + x: w => w - 50, + y: h => h - 50, + mount: 1, + Text: { + w: w => w, + h: h => h, + y: 5, + x: 20, + text: { + fontSize: 22, + lineHeight: 26, + }, + }, + } + } + + _firstActive() { + this.tag('Text').text = `APP - v${this.version}\nSDK - v${this.sdkVersion}` + this.tag('Text').loadTexture() + this.w = this.tag('Text').renderWidth + 40 + this.h = this.tag('Text').renderHeight + 5 + } +} + + +/***/ }), + +/***/ "./node_modules/@lightningjs/sdk/src/VideoPlayer/index.js": +/*!****************************************************************!*\ + !*** ./node_modules/@lightningjs/sdk/src/VideoPlayer/index.js ***! + \****************************************************************/ +/*! exports provided: default */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var _metrological_sdk__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @metrological/sdk */ "./node_modules/@metrological/sdk/index.js"); + + +/* harmony default export */ __webpack_exports__["default"] = (_metrological_sdk__WEBPACK_IMPORTED_MODULE_0__["VideoPlayer"]); + + +/***/ }), + +/***/ "./node_modules/@lightningjs/sdk/src/helpers/fetchJson.js": +/*!****************************************************************!*\ + !*** ./node_modules/@lightningjs/sdk/src/helpers/fetchJson.js ***! + \****************************************************************/ +/*! exports provided: default */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* + * If not stated otherwise in this file or this component's LICENSE file the + * following copyright and licenses apply: + * + * Copyright 2020 Metrological + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* harmony default export */ __webpack_exports__["default"] = ((file) => { + return new Promise((resolve, reject) => { + var xhr = new XMLHttpRequest() + xhr.onreadystatechange = function() { + if (xhr.readyState == XMLHttpRequest.DONE) { + // file protocol returns 0 + // http(s) protocol returns 200 + if (xhr.status === 0 || xhr.status === 200) resolve(JSON.parse(xhr.responseText)) + else reject(xhr.statusText) + } + } + xhr.open('GET', file) + xhr.send(null) + }) +}); + + +/***/ }), + +/***/ "./node_modules/@lightningjs/ui-components/dist/lightning-ui-components.min.mjs": +/*!**************************************************************************************!*\ + !*** ./node_modules/@lightningjs/ui-components/dist/lightning-ui-components.min.mjs ***! + \**************************************************************************************/ +/*! exports provided: Arrow, Artwork, Badge, Base, Bubble, Button, ButtonSmall, Card, CardContent, CardContentHorizontal, CardContentHorizontalLarge, CardContentVertical, CardContentVerticalSmall, CardRadio, CardSection, CardTitle, Checkbox, CheckboxSmall, Circle, Column, Control, ControlRow, ControlSmall, FadeShader, FocusManager, Gradient, GridOverlay, Icon, InlineContent, Input, Key, Keyboard, KeyboardEmail, KeyboardFullscreen, KeyboardInput, KeyboardNumbers, KeyboardQwerty, KeyboardSearch, Knob, Label, Line, LinearGradient, ListItem, ListItemPicker, ListItemSlider, Marquee, MetadataBase, MetadataCard, MetadataCardContent, MetadataTile, NavigationManager, ProgressBar, Provider, Radio, RadioSmall, Row, ScrollWrapper, Shadow, SignalButton, Slider, SliderLarge, Speech, Surface, Tab, TabBar, TextBox, Tile, TitleRow, Toggle, ToggleSmall, Tooltip, context, defaultAbbrevConfig, generateAbbrevConfig, pool, updateManager, utils, withAnnouncer, withClassCache, withEditItems, withExtensions, withHandleKey, withLayout, withMarqueeSync, withSelections, withTags, withThemeStyles, withUpdates */ +/***/ (function(__webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Arrow", function() { return Arrow; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Artwork", function() { return Artwork; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Badge", function() { return Badge; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Base", function() { return Base$1; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Bubble", function() { return Bubble; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Button", function() { return Button; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ButtonSmall", function() { return ButtonSmall; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Card", function() { return Card; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CardContent", function() { return CardContent; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CardContentHorizontal", function() { return CardContentHorizontal; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CardContentHorizontalLarge", function() { return CardContentHorizontalLarge; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CardContentVertical", function() { return CardContentVertical; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CardContentVerticalSmall", function() { return CardContentVerticalSmall; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CardRadio", function() { return CardRadio; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CardSection", function() { return CardSection; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CardTitle", function() { return CardTitle; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Checkbox", function() { return Checkbox; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CheckboxSmall", function() { return CheckboxSmall; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Circle", function() { return Circle; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Column", function() { return Column; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Control", function() { return Control; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ControlRow", function() { return ControlRow; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ControlSmall", function() { return ControlSmall; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "FadeShader", function() { return FadeShader; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "FocusManager", function() { return FocusManager; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Gradient", function() { return Gradient; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "GridOverlay", function() { return GridOverlay; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Icon", function() { return Icon; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "InlineContent", function() { return InlineContent; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Input", function() { return Input; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Key", function() { return Key; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Keyboard", function() { return Keyboard; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "KeyboardEmail", function() { return KeyboardEmail; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "KeyboardFullscreen", function() { return KeyboardFullScreen; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "KeyboardInput", function() { return KeyboardInput; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "KeyboardNumbers", function() { return KeyboardNumbers; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "KeyboardQwerty", function() { return KeyboardQwerty; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "KeyboardSearch", function() { return KeyboardSearch; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Knob", function() { return Knob; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Label", function() { return Label; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Line", function() { return Line; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "LinearGradient", function() { return LinearGradient; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ListItem", function() { return ListItem; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ListItemPicker", function() { return ListItemPicker; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ListItemSlider", function() { return ListItemSlider; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Marquee", function() { return Marquee; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "MetadataBase", function() { return MetadataBase$1; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "MetadataCard", function() { return MetadataCard; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "MetadataCardContent", function() { return MetadataCardContent; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "MetadataTile", function() { return MetadataTile; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "NavigationManager", function() { return NavigationManager; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ProgressBar", function() { return ProgressBar; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Provider", function() { return Provider; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Radio", function() { return Radio; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "RadioSmall", function() { return RadioSmall; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Row", function() { return Row; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ScrollWrapper", function() { return ScrollWrapper; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Shadow", function() { return Shadow; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SignalButton", function() { return SignalButton; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Slider", function() { return Slider; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SliderLarge", function() { return SliderLarge; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Speech", function() { return Speech; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Surface", function() { return Surface; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Tab", function() { return Tab; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TabBar", function() { return TabBar; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TextBox", function() { return TextBox; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Tile", function() { return Tile; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TitleRow", function() { return TitleRow; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Toggle", function() { return Toggle; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ToggleSmall", function() { return ToggleSmall; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Tooltip", function() { return Tooltip; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "context", function() { return contextInstance; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "defaultAbbrevConfig", function() { return defaultAbbrevConfig; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "generateAbbrevConfig", function() { return generateAbbrevConfig; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "pool", function() { return index$2; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "updateManager", function() { return updateManager; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "utils", function() { return utils$1; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "withAnnouncer", function() { return withAnnouncer; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "withClassCache", function() { return index$1; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "withEditItems", function() { return index; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "withExtensions", function() { return withExtensions; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "withHandleKey", function() { return withHandleKey; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "withLayout", function() { return withLayout; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "withMarqueeSync", function() { return withMarqueeSync; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "withSelections", function() { return withSelections; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "withTags", function() { return withTags; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "withThemeStyles", function() { return withThemeStyles; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "withUpdates", function() { return withUpdates; }); +/* harmony import */ var _lightningjs_core__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @lightningjs/core */ "./node_modules/@lightningjs/core/dist/lightning.js"); +function asyncGeneratorStep(n, t, e, r, o, a, c) { + try { + var i = n[a](c), u = i.value; + } catch (n) { + return void e(n); + } + i.done ? t(u) : Promise.resolve(u).then(r, o); +} + +function _asyncToGenerator(n) { + return function() { + var t = this, e = arguments; + return new Promise((function(r, o) { + var a = n.apply(t, e); + function _next(n) { + asyncGeneratorStep(a, r, o, _next, _throw, "next", n); + } + function _throw(n) { + asyncGeneratorStep(a, r, o, _next, _throw, "throw", n); + } + _next(void 0); + })); + }; +} + +function ownKeys(e, r) { + var t = Object.keys(e); + if (Object.getOwnPropertySymbols) { + var o = Object.getOwnPropertySymbols(e); + r && (o = o.filter((function(r) { + return Object.getOwnPropertyDescriptor(e, r).enumerable; + }))), t.push.apply(t, o); + } + return t; +} + +function _objectSpread(e) { + for (var r = 1; r < arguments.length; r++) { + var t = null != arguments[r] ? arguments[r] : {}; + r % 2 ? ownKeys(Object(t), !0).forEach((function(r) { + _defineProperty(e, r, t[r]); + })) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach((function(r) { + Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); + })); + } + return e; +} + +function _defineProperty(e, r, t) { + return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { + value: t, + enumerable: !0, + configurable: !0, + writable: !0 + }) : e[r] = t, e; +} + +function _toPropertyKey(t) { + var i = _toPrimitive(t, "string"); + return "symbol" == typeof i ? i : i + ""; +} + +function _toPrimitive(t, r) { + if ("object" != typeof t || !t) return t; + var e = t[Symbol.toPrimitive]; + if (void 0 !== e) { + var i = e.call(t, r || "default"); + if ("object" != typeof i) return i; + throw new TypeError("@@toPrimitive must return a primitive value."); + } + return ("string" === r ? String : Number)(t); +} + + + +class Logger { + constructor() { + this._logCallback = undefined; + this._prefix = "LightningUI"; + this._debug = false; + } + get debug() { + return this._debug; + } + set debug(value) { + this._debug = Boolean(value); + } + get logCallback() { + return this._logCallback; + } + set logCallback(value) { + if ("function" !== typeof value) { + this.warn("logCallback value must be a function, instead received ".concat(typeof value)); + return; + } + this._logCallback = value; + } + log() { + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + if (this._logCallback) { + this._logCallback({ + level: "log", + payload: args + }); + } + if (this.debug) { + console.log(this._prefix, ...args); + } + } + info() { + for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { + args[_key2] = arguments[_key2]; + } + if (this._logCallback) { + this._logCallback({ + level: "info", + payload: args + }); + } + if (this.debug) { + console.info(this._prefix, ...args); + } + } + warn() { + for (var _len3 = arguments.length, args = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) { + args[_key3] = arguments[_key3]; + } + if (this._logCallback) { + this._logCallback({ + level: "warn", + payload: args + }); + } + if (this.debug) { + console.warn(this._prefix, ...args); + } + } + error() { + for (var _len4 = arguments.length, args = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) { + args[_key4] = arguments[_key4]; + } + if (this._logCallback) { + this._logCallback({ + level: "error", + payload: args + }); + } + if (this.debug) { + console.error(this._prefix, ...args); + } + } +} + +var loggerInstance = new Logger; + +function debounce(func, wait, immediate) { + var timeout, args, context, timestamp, result; + if (null == wait) wait = 100; + function later() { + var last = Date.now() - timestamp; + if (last < wait && last >= 0) { + timeout = setTimeout(later, wait - last); + } else { + timeout = null; + if (!immediate) { + result = func.apply(context, args); + context = args = null; + } + } + } + var debounced = function debounced() { + context = this; + args = arguments; + timestamp = Date.now(); + var callNow = immediate && !timeout; + if (!timeout) timeout = setTimeout(later, wait); + if (callNow) { + result = func.apply(context, args); + context = args = null; + } + return result; + }; + debounced.clear = function() { + if (timeout) { + clearTimeout(timeout); + timeout = null; + } + }; + debounced.flush = function() { + if (timeout) { + result = func.apply(context, args); + context = args = null; + clearTimeout(timeout); + timeout = null; + } + }; + return debounced; +} + +function getEuclideanDistance(xA, yA, xB, yB) { + var xDiff = xA - xB; + var yDiff = yA - yB; + return Math.sqrt(Math.pow(xDiff, 2) + Math.sqrt(Math.pow(yDiff, 2))); +} + +function getShortestDistance(coordinate, element) { + var [xA, yA] = coordinate; + var [xB, yB] = element.core ? element.core.getAbsoluteCoords(0, 0) : [ 0, 0 ]; + var distanceToStart = getEuclideanDistance(xA, yA, xB, yB); + var distanceToMiddle = getEuclideanDistance(xA, yA, xB + element.w / 2, yB + element.h / 2); + var distanceToEnd = getEuclideanDistance(xA, yA, xB + element.w, yB + element.h); + return Math.min(distanceToStart, distanceToMiddle, distanceToEnd); +} + +function isComponentOnScreen(component) { + var offsets = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + if (!component) return false; + var {w: w, h: h, core: {renderContext: {px: px, py: py}, _scissor: scissor = []} = {}} = component; + var stageH = component.stage.h / component.stage.getRenderPrecision(); + var stageW = component.stage.w / component.stage.getRenderPrecision(); + var finalX = px; + var finalY = py; + var relativeOffsetX = px - component.x; + var relativeOffsetY = py - component.y; + var offsetX = offsets.offsetX - relativeOffsetX || 0; + var offsetY = offsets.offsetY - relativeOffsetY || 0; + if (component.transition("x")) { + finalX = px - component.x + component.transition("x").targetValue; + } + if (component.transition("y")) { + finalY = py - component.y + component.transition("y").targetValue; + } + finalX += offsetX; + finalY += offsetY; + var wVis = finalX >= 0 && finalX + w <= stageW; + var hVis = finalY >= 0 && finalY + h <= stageH; + if (!wVis || !hVis) return false; + if (scissor && scissor.length) { + var [leftBounds = null, topBounds = null, clipWidth = null, clipHeight = null] = scissor; + var withinLeftClippingBounds = Math.round(finalX + w) >= Math.round(leftBounds); + var withinRightClippingBounds = Math.round(finalX) <= Math.round(leftBounds + clipWidth); + var withinTopClippingBounds = Math.round(finalY + h) >= Math.round(topBounds); + var withinBottomClippingBounds = Math.round(finalY + h) <= Math.round(topBounds + clipHeight); + return withinLeftClippingBounds && withinRightClippingBounds && withinTopClippingBounds && withinBottomClippingBounds; + } + return true; +} + +function getWidthByUpCount(theme) { + var upCount = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1; + var screenW = theme.layout.screenW; + var columnCount = theme.layout.columnCount; + var marginX = theme.layout.marginX; + var gutterX = theme.layout.gutterX; + if (upCount < 1 || upCount > columnCount) { + console.error("Column expects a number between 1 & ".concat(columnCount, ". Received ").concat(upCount)); + return; + } + var columnWidth = screenW - marginX * 2; + var columnGapTotal = (upCount - 1) * gutterX; + var totalColumnsWidth = columnWidth - columnGapTotal; + return totalColumnsWidth / upCount; +} + +function getWidthByColumnSpan(theme, columnSpan) { + var columnCount = theme.layout.columnCount; + var gutterX = theme.layout.gutterX; + return getWidthByUpCount(theme, columnCount) * columnSpan + gutterX * (columnSpan - 1); +} + +function getDimensions(theme) { + var obj = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + var fallback = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; + var {w: w, h: h, ratioX: ratioX, ratioY: ratioY, upCount: upCount} = obj; + var fallbackW = fallback.w || 0; + var fallbackH = fallback.h || 0; + var dimensions = {}; + if (w && h) { + dimensions = { + w: w, + h: h + }; + } else if (h && ratioX && ratioY) { + dimensions = { + w: Math.round(h * ratioX / ratioY), + h: h + }; + } else if (ratioX && ratioY && upCount) { + dimensions = getItemRatioDimensions(theme, ratioX, ratioY, upCount); + } else if (h && upCount) { + dimensions = { + w: Math.round(getWidthByUpCount(theme, upCount)), + h: h + }; + } else if (h) { + dimensions = { + w: fallbackW, + h: h + }; + } else if (w) { + dimensions = { + w: w, + h: fallbackH + }; + } else { + dimensions = { + w: fallbackW, + h: fallbackH + }; + } + dimensions = _objectSpread(_objectSpread({}, dimensions), {}, { + ratioX: ratioX, + ratioY: ratioY, + upCount: upCount + }); + return dimensions; +} + +function getItemRatioDimensions(theme, ratioX, ratioY, upCount) { + var w, h; + if (ratioX && ratioY && upCount) { + w = Math.round(getWidthByUpCount(theme, upCount)); + h = Math.round(w / ratioX * ratioY); + } else { + w = 0; + h = 0; + } + return { + w: w, + h: h + }; +} + +function getAspectRatioW(h) { + var ratio = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : "16:9"; + var seperator = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : ":"; + var [ratioW, ratioH] = ratio.split(seperator); + return h * (ratioW / ratioH); +} + +function getAspectRatioH(w) { + var ratio = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : "16:9"; + var seperator = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : ":"; + var [ratioW, ratioH] = ratio.split(seperator); + return w / (ratioW / ratioH); +} + +function getHexColor(hex) { + var alpha = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1; + if (!hex) { + return 0; + } + if (typeof hex === "number") { + hex = hex.toString(16).slice(2); + } + hex = hex.replace("#", ""); + var hexAlpha = Math.round(alpha * 255).toString(16); + var str = "0x".concat(hexAlpha).concat(hex); + return Number(str); +} + +function getValidColor(color) { + if (typeof color === "string" || typeof color === "number") { + if (/^0x[0-9a-fA-F]{8}/g.test(color)) { + return Number(color); + } else if (/^#[0-9a-fA-F]{6}/g.test(color)) { + return getHexColor(color.substr(1, 6)); + } else if (typeof color === "string" && /^[0-9]{8,10}/g.test(color)) { + return parseInt(color); + } else if (typeof color === "number" && /^[0-9]{8,10}/g.test(color.toString())) { + return color; + } else if (typeof color === "string" && color.indexOf("rgba") > -1) { + return rgba2argb(color); + } else if (typeof color === "string" && color.indexOf("rgb") > -1) { + var rgba = [ ...color.replace(/rgb\(|\)/g, "").split(","), "255" ]; + return _lightningjs_core__WEBPACK_IMPORTED_MODULE_0__.StageUtils.getArgbNumber(rgba); + } + } + return null; +} + +function simplifyFraction(_ref) { + var [numerator, denominator] = _ref; + for (var i = numerator; i > 0; i--) { + if (!(numerator % i) && !(denominator % i)) { + return [ numerator / i, denominator / i ]; + } + } +} + +function reduceFraction(string) { + return simplifyFraction(string.split("/").map((n => +n))).join("/"); +} + +var getValFromObjPath = (object, path) => { + if (typeof path === "string") path = path.split(".").filter((key => key.length)); + return path.reduce(((dive, key) => dive && dive[key]), object); +}; + +function rgba2argb(rgbaStr) { + var rgba = rgbaStr.replace(/rgba\(|\)/g, "").split(","); + rgba[3] = rgba[3] * 255; + return _lightningjs_core__WEBPACK_IMPORTED_MODULE_0__.StageUtils.getArgbNumber(rgba); +} + +function capitalizeFirstLetter(string) { + return string.charAt(0).toUpperCase() + string.slice(1); +} + +var RoundRect = { + getWidth(w) { + var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + var {padding: padding, paddingLeft: paddingLeft, paddingRight: paddingRight, strokeWidth: strokeWidth} = _objectSpread({ + padding: 0, + paddingLeft: 0, + paddingRight: 0, + strokeWidth: 0 + }, options); + if (!w) return 0; + return w - (paddingLeft || padding) - (paddingRight || padding) - strokeWidth; + }, + getHeight(h) { + var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + var {padding: padding, paddingBottom: paddingBottom, paddingTop: paddingTop, strokeWidth: strokeWidth} = _objectSpread({ + padding: 0, + paddingBottom: 0, + paddingTop: 0, + strokeWidth: 0 + }, options); + if (!h) return 0; + return h - (paddingBottom || padding) - (paddingTop || padding) - strokeWidth; + } +}; + +function clone(target, object) { + var _clone = Object.create(Object.getPrototypeOf(target)); + Object.defineProperties(_clone, Object.getOwnPropertyDescriptors(target)); + if (!object || target === object) return _clone; + for (var key in object) { + var value = object[key]; + if (target.hasOwnProperty(key)) { + _clone[key] = getMergeValue(key, target, object); + } else { + _clone[key] = value; + } + } + return _clone; +} + +function getMergeValue(key, target, object) { + var targetVal = target[key]; + var objectVal = object[key]; + var targetValType = typeof targetVal; + var objectValType = typeof objectVal; + if (targetValType !== objectValType || objectValType === "function" || Array.isArray(objectVal)) { + return objectVal; + } + if (objectVal && objectValType === "object") { + return clone(targetVal, objectVal); + } + return objectVal; +} + +function measureTextWidth() { + var text = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + var canvas = document.createElement("canvas"); + var ctx = canvas.getContext("2d"); + var {fontStyle: fontStyle, fontWeight: fontWeight, fontSize: fontSize, fontFamily: fontFamily = text.fontFace || "sans-serif"} = text; + var fontCss = [ fontStyle, fontWeight, fontSize ? "".concat(fontSize, "px") : "0", "'".concat(fontFamily, "'") ].filter(Boolean).join(" "); + ctx.font = fontCss; + var textMetrics = ctx.measureText(text.text || ""); + return Math.round(textMetrics.width); +} + +function getFirstNumber() { + for (var _len5 = arguments.length, numbers = new Array(_len5), _key5 = 0; _key5 < _len5; _key5++) { + numbers[_key5] = arguments[_key5]; + } + return numbers.find(Number.isFinite); +} + +function getDimension(prop, component) { + if (!component) return 0; + var transition = component.transition(prop); + if (transition.isRunning()) return transition.targetValue; + var renderProp = prop; + if (prop === "w") { + renderProp = "renderWidth"; + } else if (prop === "h") { + renderProp = "renderHeight"; + } + return component[renderProp] || component[prop]; +} + +var getX = component => getDimension("x", component); + +var getY = component => getDimension("y", component); + +var getW = component => getDimension("w", component); + +var getH = component => getDimension("h", component); + +function flatten(arr) { + return arr.reduce(((flat, toFlatten) => flat.concat(Array.isArray(toFlatten) ? flatten(toFlatten) : toFlatten)), []); +} + +function objectPropertyOf(object, path) { + return path.reduce(((obj, key) => obj && obj[key] !== "undefined" ? obj[key] : undefined), object); +} + +function stringifyCompare(objA, objB) { + return JSON.stringify(objA) === JSON.stringify(objB); +} + +function delayForAnimation(callback) { + var delay = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 16; + setTimeout(callback, delay); +} + +function downloadFile(content, fileName, contentType) { + var validContentTypes = [ "plain", "json" ]; + if (!validContentTypes.includes(contentType)) { + contentType = "plain"; + } + var dataStr = "data:text/".concat(contentType, ";charset=utf-8,") + encodeURIComponent(JSON.stringify(content)); + var dlAnchorElem = document.createElement("a"); + dlAnchorElem.setAttribute("href", dataStr); + dlAnchorElem.setAttribute("download", fileName); + dlAnchorElem.click(); +} + +var degreesToRadians = deg => deg * (Math.PI / 180); + +var MARKUP_STRING_PATTERN = /({ICON.*?}|{BADGE:.*?}|{NEWLINE}|{TEXT:.*?})/g; + +function isMarkupString() { + var str = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : ""; + if (typeof str !== "string") { + return false; + } + return MARKUP_STRING_PATTERN.test(str); +} + +function parseInlineContent() { + var str = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : ""; + var content = []; + if (str && typeof str === "string" || str.text) { + var string = typeof str === "string" ? str : str.text; + var iconRegEx = /^{ICON:(.*?)?\|(.*?)?}$/g; + var badgeRegEx = /^{BADGE:(.*?)}$/g; + var newlineRegEx = /^{NEWLINE}$/g; + var textRegEx = /^{TEXT:(.*?)?\|(.*?)?}$/g; + var splitStr = string.split(MARKUP_STRING_PATTERN); + if (splitStr && splitStr.length) { + splitStr.forEach((item => { + var formattedItem = item; + var badge = badgeRegEx.exec(item); + var icon = iconRegEx.exec(item); + var newline = newlineRegEx.exec(item); + var text = textRegEx.exec(item); + if (badge && badge[1]) { + formattedItem = { + badge: badge[1] + }; + } else if (icon && icon[1]) { + formattedItem = { + title: icon[1], + icon: icon[2] || icon[1] + }; + } else if (newline) { + formattedItem = { + newline: true + }; + } else if (text && text[1]) { + formattedItem = { + text: text[1], + style: text[2] + }; + } + content.push(formattedItem); + })); + } + } + return content; +} + +function max() { + if (!arguments) { + return; + } + var args = Array.from(arguments).filter((arg => !isNaN(arg) && arg != null)); + if (!args.length) { + return; + } + return Math.max(...args); +} + +function createConditionalZContext(component, zOffset) { + if (!component.zIndex && typeof zOffset !== "undefined" && zOffset !== 0) { + component.forceZIndexContext = true; + component.zIndex = 0; + } +} + +function watchForUpdates(_ref2) { + var _element$__core; + var {element: element, watchProps: watchProps = [], sideEffect: sideEffect = () => {}} = _ref2; + if (!(element !== null && element !== void 0 && element.isElement)) { + loggerInstance.error("watchForUpdates: Expected a Lightning Element passed to element parameter, received ".concat(typeof element)); + } + var initialOnAfterUpdate = (_element$__core = element.__core) === null || _element$__core === void 0 ? void 0 : _element$__core._onAfterUpdate; + element.onAfterUpdate = function(element) { + var hasChanged = false; + watchProps.forEach((prop => { + if (element.transition(prop) && element.transition(prop).isRunning()) { + return; + } + var prevValueKey = "__watchPrev".concat(prop); + var nextValue = element[prop]; + if (nextValue !== element[prevValueKey]) { + element[prevValueKey] = nextValue; + hasChanged = true; + } + })); + if (hasChanged) { + sideEffect(); + } + if (initialOnAfterUpdate) { + initialOnAfterUpdate(element); + } + }.bind(this); + return element; +} + +function convertTextAlignToFlexJustify(align) { + switch (align) { + case "left": + return "flex-start"; + + case "center": + return "center"; + + case "right": + return "flex-end"; + + default: + console.warn('Expected "textAlign" values are "left," "center," and "right," but instead, '.concat(align, ' was received and will fall back to "left."')); + return "flex-start"; + } +} + +function getMaxRoundRadius(radius, width, height) { + var offset = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 0; + var maxRadius = r => Math.max(0, Math.min(r, Math.min(width, height) / 2) + offset); + return Array.isArray(radius) ? radius.map((r => Number(maxRadius(r)) || 0)) : Number(maxRadius(radius)) || 0; +} + +var utils = { + isMarkupString: isMarkupString, + capitalizeFirstLetter: capitalizeFirstLetter, + degreesToRadians: degreesToRadians, + downloadFile: downloadFile, + delayForAnimation: delayForAnimation, + stringifyCompare: stringifyCompare, + objectPropertyOf: objectPropertyOf, + flatten: flatten, + getDimension: getDimension, + getFirstNumber: getFirstNumber, + measureTextWidth: measureTextWidth, + clone: clone, + getMergeValue: getMergeValue, + RoundRect: RoundRect, + rgba2argb: rgba2argb, + getValFromObjPath: getValFromObjPath, + reduceFraction: reduceFraction, + getValidColor: getValidColor, + getHexColor: getHexColor, + getAspectRatioH: getAspectRatioH, + getAspectRatioW: getAspectRatioW, + getWidthByUpCount: getWidthByUpCount, + getDimensions: getDimensions, + getWidthByColumnSpan: getWidthByColumnSpan, + createConditionalZContext: createConditionalZContext, + watchForUpdates: watchForUpdates, + convertTextAlignToFlexJustify: convertTextAlignToFlexJustify, + getMaxRoundRadius: getMaxRoundRadius +}; + +var utils$1 = utils; + +class Metrics { + constructor() { + this._keyMetricsCallback = undefined; + } + get keyMetricsCallback() { + return this._keyMetricsCallback; + } + set keyMetricsCallback(value) { + if (-1 < [ "undefined", "function" ].indexOf(typeof value)) { + this._keyMetricsCallback = value; + return; + } + loggerInstance.warn("context keyMetricsCallback expected a function. Received ".concat(typeof value)); + } +} + +var metricsInstance = new Metrics; + +var eventEmitterInstance = new _lightningjs_core__WEBPACK_IMPORTED_MODULE_0__.EventEmitter; + +var events = eventEmitterInstance; + +var baseTheme = { + name: "Base Lightning TV", + alpha: { + primary: 1, + secondary: .7, + tertiary: .1, + inactive: .5, + full: 1, + none: 0, + alpha1: .1, + alpha2: .3, + alpha3: .5, + alpha4: .7, + alpha5: .9 + }, + animation: { + duration: { + none: 0, + xfast: .1, + fast: .25, + normal: .5, + slow: .75, + xslow: .9 + }, + delay: { + none: 0, + xfast: .01, + fast: .025, + normal: .05, + slow: .075, + xslow: .09 + }, + expressive: { + timingFunction: "cubic-bezier(0, 0, 1, 1)", + delay: 0, + duration: .25 + }, + expressiveEntrance: { + timingFunction: "cubic-bezier(0, 0, 1, 1)", + delay: 0, + duration: .25 + }, + expressiveExit: { + timingFunction: "cubic-bezier(0, 0, 1, 1)", + delay: 0, + duration: .25 + }, + standard: { + timingFunction: "cubic-bezier(0, 0, 1, 1)", + delay: 0, + duration: .25 + }, + standardEntrance: { + timingFunction: "cubic-bezier(0, 0, 1, 1)", + delay: 0, + duration: .25 + }, + standardExit: { + timingFunction: "cubic-bezier(0, 0, 1, 1)", + delay: 0, + duration: .25 + }, + utility: { + timingFunction: "cubic-bezier(0, 0, 1, 1)", + delay: 0, + duration: .25 + }, + utilityEntrance: { + timingFunction: "cubic-bezier(0, 0, 1, 1)", + delay: 0, + duration: .25 + }, + utilityExit: { + timingFunction: "cubic-bezier(0, 0, 1, 1)", + delay: 0, + duration: .25 + } + }, + asset: { + arrowLeft: "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABgAAAAYCAYAAADgdz34AAAAAXNSR0IArs4c6QAAAERlWElmTU0AKgAAAAgAAYdpAAQAAAABAAAAGgAAAAAAA6ABAAMAAAABAAEAAKACAAQAAAABAAAAGKADAAQAAAABAAAAGAAAAADiNXWtAAAAi0lEQVRIDWNgGAWjIfD//38JID5Fk5AAGqwKxPeA+D/VLQCaaQLEr0CGgwBVLQCa5wbEn0EGwwDVLAAaGA3Ev2AGw2iqWAA0rBiI/8EMRaYptgBoWDeygehsci1gIlcjWfqArqZdEMFcBLSEdpGMZAntkimSJbTLaEiW0K6oQLKEdoUdzJJRemiHAAD4n+yzPWCs7QAAAABJRU5ErkJggg==", + arrowRight: "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABgAAAAYCAYAAADgdz34AAAAAXNSR0IArs4c6QAAAERlWElmTU0AKgAAAAgAAYdpAAQAAAABAAAAGgAAAAAAA6ABAAMAAAABAAEAAKACAAQAAAABAAAAGKADAAQAAAABAAAAGAAAAADiNXWtAAAAg0lEQVRIDWNgGAWjIYArBP7//38KiCVwyVMsDjQcBO4BsSrFhmEzAGw8hHgFpEywqaFIDMkCEPMzELtRZCC6ZjQLQNxfQByNro5sPhYLQEL/gLiYbEORNeKwACbcDVPLBGMMOhrmVDSapkFE00imaTKlaUajaVFB28Ju0CXrUQfhDAEAEgHss6NhpLQAAAAASUVORK5CYII=", + backspaceOutline: "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAJAAAACQCAYAAADnRuK4AAAAAXNSR0IArs4c6QAACmpJREFUeF7tnVmoZUcVhv/feY4gBEVEH/KgCCZxCK2itNo4xQQH+kUN0TjEiDGKKBqnaExwBjUaR6KY+NQgiQkOMSYhYEScIopGJOqDE2hHjfP0y4p1Oqdv33v2qr32Prv2Paug6Ye7Vu2qv75TtWvtGohMqUBAAQZ80zUVQAKUEIQUSIBC8qVzApQMhBRIgELypXMClAyEFEiAQvKlcwKUDIQUSIBC8qVzApQMhBRIgELypXMClAyEFEiAQvKlcwKUDIQUSIBC8qVzApQMhBRIgELypXMClAyEFEiAQvKlcwKUDIQUSIBC8qVzApQMhBRIgELypXMClAyEFEiAQvKlcwKUDIQUSIBC8qVzApQMhBRIgELypfPsAJJ0NYC92XRHKPB3AAfLv18BuBLAFSR/NKZWswJI0vkA3jCmILsw75sAvIfkR8eo22wAknQSgMvGEGFD8vwxgFeQvGrI+s4CIEnHAPgugHsMWfkNzevDAM4i+Z8h6t88QJLuXOB5yBAVzjxuVeBaAM8ieXNUjzkAdAmA50Yrmv5HKPATACeQ/GNEm6YBkvRyANblZhpHAXsfekpkOGsWIEmPAHA9gDuOo13mWhS4gOSZfdVoEiBJ9wFwA4D7961Y+lUpsK/v7KxVgL4K4ElOCS4l+Uyn7a41k3Q0gMcC2ANgH4CHV1T2OyStx69OzQEk6TwAZztr8lMAx5P8s9N+Y8wk2cTjfQDu66z080h+zml7yKwpgCSdCOByZyX+BuBRJH/otN84M0kWN/s0gOc4Kv8Nko922B1m0gxAkh4I4AcVwcL9JA/UVnjT7CXdHYD9yEzfVUkAjib5uxqNmgCoBAu/CeBhzsJ/kORZTtuNN5Nk70bXAZ0Hy59G8qIawVoB6LMAnu8suE3tH0/y3077NAMg6esAuoaoC0la7M2dJgdI0ssAXOgs8W8BHEvS/s9UoYCkdwN4bYfL5STto7U7TQpQZbDQehzreawHylSpgKSTAVza4XYDyeNqsp4MoB7BwteQfH9N5dL2NgWK3l0vyAdJWhDXnSYBSNLtANh3GO/KwgMk97trlYbbKiDJPpzea5U8JKuYqDIeql0kvQPAG5352ZLMR5L8q9M+zXZQYFcAJOnJAL7sbGWLMFuk2SLOmYIKzB6gEiz8HoB7O7U4meQXnLZp1qGApD8BuOcsh7AewcL3kuyadg4OjSSbhRxH0j4BjJok2Ufga0j+YdQHlcznDlBNsPAa+xpP8r/rEHbxjAKPbRuyHvKFY0Ik6QUALOprPfIT1gHRbAGSdDoA77aSX5Zg4e8nhGfx6FEgWoJn8Zy1QCTplq5vjc3NwnoEC/eQ/HYD8IwC0TbwrA2i2QHUI1h4JskLGoJnUIhWwLMWiGYFkCSLMX2t5WDhlneeLm5Dw5kDntEhkmRhEVvesWNqZgiTdC6AN3W1Svn72oOFkuxF+WcVIQUrai+IKuA5BBHJ453auc1mA1AJFn7Jsf7EKj9ZsLBHw1ZDtI5neAmaBUBzCxaO2cBj5u2FZtlO0l8A3K3ZIaxHsPB8kt5vYn00c/mM0dBj5OmqzAqjOQDUfLBwJ32HbPAh84pCM5seSNJLAHzcWeFJgoVdZRui4YfIo6ucff8uyVY03LW5IawyWPgvW5u77mChV/QIABFfb/kidk0CVKbDth3Huw35dJLeniqiV2/fniDYx1f7vlWTeoUFah6wZQhrqwcqwUKbrtsaH0+6mOQpHsOpbXpCVFPstcJjBZNkmzHv0swQJultAN7iVO375TyafzjtJzcbEaK1w9McQJXBQlvvYmtsfjE5FZUFGAGiSeBpCqDKYKFtmX0qya9Utl0z5gNCNBk8BSA7CtiODNwxjf4trEew8BySNtTNOg0A0aTwtARQTbDQeh3rfawXmn0KQDQ5PC0B9EkAL3LSkAD9X6hWALIJzJ3mNoSdS9I7U3NyuX6zQO+zKOzkEEmaHqDSFdpZM97tOfkSfRvvk0LUDEAFIgseetf85DS+AYgk/bPr1NvRZ2HLg4ektwI4xzmgZCBxYohaBMjWPeenDOcvaIvZ2oez5gAqQ5mtLbb3oa4z+Bb6nTHW1UP92vFIr54vzJ8BcGplGdYKkSRbCXGHSWdh2z1ckp1taGccroxyFt9cznG4iGuDqFmASk9kZxxakNGTckHZBBA1DVCB6BMAXuwhyA4VmGL/+05l6zlsbdt7DJmXU0uXmSQ7JvD2zQ1hiwJJsotRvlVxXO87SU5+heUYDT5Gni5KVhg1D1DphWqCjOYy6RlAYzb0mHn3gWkWABWIaoKMubHwSBpGebGWZNdc2vmUO6a1BhJXFUSSff/yLuOYamvzzwEcVfFr7tWwPXqi6uN2PXWYG0C1Qca1n8RaDlewl3kPRL3gWXo/XBwo1dXWdk/a3jEOnJoVQGUoqw0yvpLkh7oUHvLvTohC8FRANBo8pT3sxLeVJ/M2M4QtiVYTZJzkNPoOiAaBxwHRqPDMFqBS8Jog4yT3YewA0aDwrIBodHhmDVApvG0mtO3PnjTJjTxbIBoFnm0gWgs8pQ06lxY3N4QtCWZBRgPDezdnHvPr+alV2EiaL0DlF2Dbn20bdB40XtHwQ5nOHqAC0SyCjEM1Wkv57AqACkRvBvB2p7hrDzI6yzU7s90EUPNBxtnR4SjwrgGo9EK1Qca8cM4ByU4mkuz++F93ZHELyZX3iW31n+S+sKWZWfNBxkCbNeUq6ekArugo1I0kH1xT8EkBKj1R80HGGkFbtZVkZ3bb2d2r0tUkn1hTh8kBKhB9DMBLnQWfJMjoLFuTZpJsO/ONAB7UUcBLSHqvX781q1YAqg0yfoDkq5psrQYLJeldAF7nKFr1x+wmACq9kAUZLazvvTV4P8kDDlE22kTSQ4uuK9dCF5HuR/I3NYI1A1CBaB+AK50VsAMj7TJeixNl2kYBSccCsB/ZMQ6Brif5GIfdYSZNAVQg8rzsLSphl/Hapby2LDZTUaBcq/56ALb1fOVxLkuinULy4loRmwOoQGQX7T7DWZnPk3y203bXmkl6AIA91isDOBGADV3e1HsJbasA1QYZvUKl3fYKPI2knXFQnZoEqPRCNUHG6oqnwyEFLiJ5Wl89mgWoQFQTZOyrwSb7WUztcSRtu0+v1DRABaKPADijV+3SaZUCNgE5geTNEZnmAFBtkDGix6b4Xld2BNvJcaHUPEClF6oNMoZE2eXOtm3q1ZFha1mfWQBUINoL4Kqurbm7vPEj1bOAqx3udW0kk62+swGoQHQ2gPOGFGAD8roJgF0t+qkx6jorgApElwE4aQwxZp6n3YNxsPyzA7yst/4iSdvEMFqaHUCjKZEZ91IgAeolWzotFEiAkoWQAglQSL50ToCSgZACCVBIvnROgJKBkAIJUEi+dE6AkoGQAglQSL50ToCSgZACCVBIvnROgJKBkAIJUEi+dE6AkoGQAglQSL50ToCSgZACCVBIvnROgJKBkAIJUEi+dE6AkoGQAglQSL50ToCSgZACCVBIvnROgJKBkAIJUEi+dE6AkoGQAglQSL50ToCSgZACCVBIvnT+H0jPT81J3xWWAAAAAElFTkSuQmCC", + check: "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABIAAAAOCAYAAAAi2ky3AAAACXBIWXMAAAsTAAALEwEAmpwYAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAACtSURBVHgBvdPdDcIgEAfwoy8Nb45QN3AGF2s36Ahu4gpuIDoBfSgfpdoTlCbEWEMh6T8hFzjyg5AAkBHOcQe5UWqspRx435sDpMYj6IYQwwVSEiJ2MKVUBWuzLSLl2HL+uxmNCGFO8yaL7RHxve6qRZoAuS4hxac8735elWVx7jrtMKL1o0Gcat9jhExHSukN/kUIFZ7MpDRtzE1isDRkAUtDvrA8ZI597FUf8gWH9P0b4gko9wAAAABJRU5ErkJggg==" + }, + color: { + white: [ "#ffffff", 1 ], + black: [ "#000000", 1 ], + grey: [ "#929096", 1 ], + red: [ "#e74c3c", 1 ], + orange: [ "#dc7633", 1 ], + yellow: [ "#f7dc6f", 1 ], + green: [ "#2Ecc71", 1 ], + blue: [ "#93a9fd", 1 ], + purple: [ "#663399", 1 ], + palette: { + "grey-05": [ "#f8f7fa", 1 ], + "grey-40": [ "#929096", 1 ], + "grey-70": [ "#48474b", 1 ], + "grey-90": [ "#181819", 1 ], + "blue-20": [ "#becffe", 1 ], + "blue-40": [ "#93a9fd", 1 ], + "blue-90": [ "#000033", 1 ] + }, + material: [ "#181819", 1 ], + materialBrand: [ "#000033", 1 ], + overlay: [ "#181819", .7 ], + textNeutral: [ "#f8f7fa", 1 ], + textNeutralSecondary: [ "#f8f7fa", .7 ], + textNeutralTertiary: [ "#f8f7fa", .1 ], + textNeutralDisabled: [ "#f8f7fa", .5 ], + textInverse: [ "#181819", 1 ], + textInverseSecondary: [ "#181819", .7 ], + textInverseTertiary: [ "#181819", .1 ], + textInverseDisabled: [ "#181819", .5 ], + textBrand: [ "#93a9fd", 1 ], + textBrandSecondary: [ "#93a9fd", .7 ], + textBrandTertiary: [ "#93a9fd", .1 ], + textBrandDisabled: [ "#93a9fd", .5 ], + textPositive: [ "#2Ecc71", 1 ], + textNegative: [ "#e74c3c", 1 ], + textInfo: [ "#93a9fd", 1 ], + textCaution: [ "#dc7633", 1 ], + fillTransparent: [ "#ffffff", 0 ], + fillNeutral: [ "#f8f7fa", 1 ], + fillNeutralSecondary: [ "#f8f7fa", .7 ], + fillNeutralTertiary: [ "#f8f7fa", .1 ], + fillNeutralDisabled: [ "#f8f7fa", .5 ], + fillInverse: [ "#181819", 1 ], + fillInverseSecondary: [ "#181819", .7 ], + fillInverseTertiary: [ "#181819", .1 ], + fillInverseDisabled: [ "#181819", .5 ], + fillBrand: [ "#93a9fd", 1 ], + fillBrandSecondary: [ "#93a9fd", .7 ], + fillBrandTertiary: [ "#93a9fd", .1 ], + fillBrandDisabled: [ "#93a9fd", .5 ], + fillPositive: [ "#2Ecc71", 1 ], + fillNegative: [ "#e74c3c", 1 ], + fillInfo: [ "#93a9fd", 1 ], + fillCaution: [ "#dc7633", 1 ], + strokeNeutral: [ "#f8f7fa", 1 ], + strokeNeutralSecondary: [ "#f8f7fa", .7 ], + strokeNeutralTertiary: [ "#f8f7fa", .1 ], + strokeNeutralDisabled: [ "#f8f7fa", .5 ], + strokeInverse: [ "#181819", 1 ], + strokeInverseSecondary: [ "#181819", .7 ], + strokeInverseTertiary: [ "#181819", .1 ], + strokeInverseDisabled: [ "#181819", .5 ], + strokeBrand: [ "#93a9fd", 1 ], + strokeBrandSecondary: [ "#93a9fd", .7 ], + strokeBrandTertiary: [ "#93a9fd", .1 ], + strokeBrandDisabled: [ "#93a9fd", .5 ], + strokePositive: [ "#2Ecc71", 1 ], + strokeNegative: [ "#e74c3c", 1 ], + strokeInfo: [ "#93a9fd", 1 ], + strokeCaution: [ "#dc7633", 1 ], + interactiveNeutral: [ "#ffffff", .1 ], + interactiveNeutralFocus: [ "#ffffff", 1 ], + interactiveNeutralFocusSoft: [ "#ffffff", .1 ], + interactiveInverse: [ "#48474b", undefined ], + interactiveInverseFocus: [ "#48474b", 1 ], + interactiveInverseFocusSoft: [ "#48474b", .1 ], + interactiveBrand: [ "#becffe", .1 ], + interactiveBrandFocus: [ "#becffe", 1 ], + interactiveBrandFocusSoft: [ "#becffe", .1 ], + shadowNeutral: [ "#000000", .7 ], + shadowNeutralFocus: [ "#000000", .7 ], + shadowNeutralFocusSoft: [ "#000000", .7 ], + shadowNeutralText: [ "#000000", 1 ], + shadowInverse: [ "#000000", .7 ], + shadowInverseFocus: [ "#000000", .7 ], + shadowInverseFocusSoft: [ "#000000", .7 ], + shadowInverseText: [ "#000000", 1 ], + shadowBrand: [ "#000000", .7 ], + shadowBrandFocus: [ "#000000", .7 ], + shadowBrandFocusSoft: [ "#000000", .7 ], + shadowBrandText: [ "#000000", 1 ] + }, + componentConfig: { + Keyboard: { + style: { + keyProps: { + delete: { + title: null, + icon: "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAJAAAACQCAYAAADnRuK4AAAAAXNSR0IArs4c6QAACmpJREFUeF7tnVmoZUcVhv/feY4gBEVEH/KgCCZxCK2itNo4xQQH+kUN0TjEiDGKKBqnaExwBjUaR6KY+NQgiQkOMSYhYEScIopGJOqDE2hHjfP0y4p1Oqdv33v2qr32Prv2Paug6Ye7Vu2qv75TtWvtGohMqUBAAQZ80zUVQAKUEIQUSIBC8qVzApQMhBRIgELypXMClAyEFEiAQvKlcwKUDIQUSIBC8qVzApQMhBRIgELypXMClAyEFEiAQvKlcwKUDIQUSIBC8qVzApQMhBRIgELypXMClAyEFEiAQvKlcwKUDIQUSIBC8qVzApQMhBRIgELypXMClAyEFEiAQvKlcwKUDIQUSIBC8qVzApQMhBRIgELypfPsAJJ0NYC92XRHKPB3AAfLv18BuBLAFSR/NKZWswJI0vkA3jCmILsw75sAvIfkR8eo22wAknQSgMvGEGFD8vwxgFeQvGrI+s4CIEnHAPgugHsMWfkNzevDAM4i+Z8h6t88QJLuXOB5yBAVzjxuVeBaAM8ieXNUjzkAdAmA50Yrmv5HKPATACeQ/GNEm6YBkvRyANblZhpHAXsfekpkOGsWIEmPAHA9gDuOo13mWhS4gOSZfdVoEiBJ9wFwA4D7961Y+lUpsK/v7KxVgL4K4ElOCS4l+Uyn7a41k3Q0gMcC2ANgH4CHV1T2OyStx69OzQEk6TwAZztr8lMAx5P8s9N+Y8wk2cTjfQDu66z080h+zml7yKwpgCSdCOByZyX+BuBRJH/otN84M0kWN/s0gOc4Kv8Nko922B1m0gxAkh4I4AcVwcL9JA/UVnjT7CXdHYD9yEzfVUkAjib5uxqNmgCoBAu/CeBhzsJ/kORZTtuNN5Nk70bXAZ0Hy59G8qIawVoB6LMAnu8suE3tH0/y3077NAMg6esAuoaoC0la7M2dJgdI0ssAXOgs8W8BHEvS/s9UoYCkdwN4bYfL5STto7U7TQpQZbDQehzreawHylSpgKSTAVza4XYDyeNqsp4MoB7BwteQfH9N5dL2NgWK3l0vyAdJWhDXnSYBSNLtANh3GO/KwgMk97trlYbbKiDJPpzea5U8JKuYqDIeql0kvQPAG5352ZLMR5L8q9M+zXZQYFcAJOnJAL7sbGWLMFuk2SLOmYIKzB6gEiz8HoB7O7U4meQXnLZp1qGApD8BuOcsh7AewcL3kuyadg4OjSSbhRxH0j4BjJok2Ufga0j+YdQHlcznDlBNsPAa+xpP8r/rEHbxjAKPbRuyHvKFY0Ik6QUALOprPfIT1gHRbAGSdDoA77aSX5Zg4e8nhGfx6FEgWoJn8Zy1QCTplq5vjc3NwnoEC/eQ/HYD8IwC0TbwrA2i2QHUI1h4JskLGoJnUIhWwLMWiGYFkCSLMX2t5WDhlneeLm5Dw5kDntEhkmRhEVvesWNqZgiTdC6AN3W1Svn72oOFkuxF+WcVIQUrai+IKuA5BBHJ453auc1mA1AJFn7Jsf7EKj9ZsLBHw1ZDtI5neAmaBUBzCxaO2cBj5u2FZtlO0l8A3K3ZIaxHsPB8kt5vYn00c/mM0dBj5OmqzAqjOQDUfLBwJ32HbPAh84pCM5seSNJLAHzcWeFJgoVdZRui4YfIo6ucff8uyVY03LW5IawyWPgvW5u77mChV/QIABFfb/kidk0CVKbDth3Huw35dJLeniqiV2/fniDYx1f7vlWTeoUFah6wZQhrqwcqwUKbrtsaH0+6mOQpHsOpbXpCVFPstcJjBZNkmzHv0swQJultAN7iVO375TyafzjtJzcbEaK1w9McQJXBQlvvYmtsfjE5FZUFGAGiSeBpCqDKYKFtmX0qya9Utl0z5gNCNBk8BSA7CtiODNwxjf4trEew8BySNtTNOg0A0aTwtARQTbDQeh3rfawXmn0KQDQ5PC0B9EkAL3LSkAD9X6hWALIJzJ3mNoSdS9I7U3NyuX6zQO+zKOzkEEmaHqDSFdpZM97tOfkSfRvvk0LUDEAFIgseetf85DS+AYgk/bPr1NvRZ2HLg4ektwI4xzmgZCBxYohaBMjWPeenDOcvaIvZ2oez5gAqQ5mtLbb3oa4z+Bb6nTHW1UP92vFIr54vzJ8BcGplGdYKkSRbCXGHSWdh2z1ckp1taGccroxyFt9cznG4iGuDqFmASk9kZxxakNGTckHZBBA1DVCB6BMAXuwhyA4VmGL/+05l6zlsbdt7DJmXU0uXmSQ7JvD2zQ1hiwJJsotRvlVxXO87SU5+heUYDT5Gni5KVhg1D1DphWqCjOYy6RlAYzb0mHn3gWkWABWIaoKMubHwSBpGebGWZNdc2vmUO6a1BhJXFUSSff/yLuOYamvzzwEcVfFr7tWwPXqi6uN2PXWYG0C1Qca1n8RaDlewl3kPRL3gWXo/XBwo1dXWdk/a3jEOnJoVQGUoqw0yvpLkh7oUHvLvTohC8FRANBo8pT3sxLeVJ/M2M4QtiVYTZJzkNPoOiAaBxwHRqPDMFqBS8Jog4yT3YewA0aDwrIBodHhmDVApvG0mtO3PnjTJjTxbIBoFnm0gWgs8pQ06lxY3N4QtCWZBRgPDezdnHvPr+alV2EiaL0DlF2Dbn20bdB40XtHwQ5nOHqAC0SyCjEM1Wkv57AqACkRvBvB2p7hrDzI6yzU7s90EUPNBxtnR4SjwrgGo9EK1Qca8cM4ByU4mkuz++F93ZHELyZX3iW31n+S+sKWZWfNBxkCbNeUq6ekArugo1I0kH1xT8EkBKj1R80HGGkFbtZVkZ3bb2d2r0tUkn1hTh8kBKhB9DMBLnQWfJMjoLFuTZpJsO/ONAB7UUcBLSHqvX781q1YAqg0yfoDkq5psrQYLJeldAF7nKFr1x+wmACq9kAUZLazvvTV4P8kDDlE22kTSQ4uuK9dCF5HuR/I3NYI1A1CBaB+AK50VsAMj7TJeixNl2kYBSccCsB/ZMQ6Brif5GIfdYSZNAVQg8rzsLSphl/Hapby2LDZTUaBcq/56ALb1fOVxLkuinULy4loRmwOoQGQX7T7DWZnPk3y203bXmkl6AIA91isDOBGADV3e1HsJbasA1QYZvUKl3fYKPI2knXFQnZoEqPRCNUHG6oqnwyEFLiJ5Wl89mgWoQFQTZOyrwSb7WUztcSRtu0+v1DRABaKPADijV+3SaZUCNgE5geTNEZnmAFBtkDGix6b4Xld2BNvJcaHUPEClF6oNMoZE2eXOtm3q1ZFha1mfWQBUINoL4Kqurbm7vPEj1bOAqx3udW0kk62+swGoQHQ2gPOGFGAD8roJgF0t+qkx6jorgApElwE4aQwxZp6n3YNxsPyzA7yst/4iSdvEMFqaHUCjKZEZ91IgAeolWzotFEiAkoWQAglQSL50ToCSgZACCVBIvnROgJKBkAIJUEi+dE6AkoGQAglQSL50ToCSgZACCVBIvnROgJKBkAIJUEi+dE6AkoGQAglQSL50ToCSgZACCVBIvnROgJKBkAIJUEi+dE6AkoGQAglQSL50ToCSgZACCVBIvnROgJKBkAIJUEi+dE6AkoGQAglQSL50ToCSgZACCVBIvnT+H0jPT81J3xWWAAAAAElFTkSuQmCC" + } + } + } + } + }, + font: [], + layout: { + columnCount: 10, + focusScale: 1.2, + gutterX: 20, + gutterY: 20, + marginX: 150, + marginY: 150, + safe: 50, + screenW: 1920, + screenH: 1080 + }, + radius: { + none: 0, + xs: 2, + sm: 4, + md: 8, + lg: 16, + xl: 24 + }, + spacer: { + none: 0, + xxs: 2, + xs: 4, + sm: 8, + md: 10, + lg: 20, + xl: 30, + xxl: 40, + xxxl: 50 + }, + stroke: { + none: 0, + sm: 2, + md: 4, + lg: 6, + xl: 8 + }, + typography: { + display1: { + fontFamily: "Arial", + fontSize: 75, + lineHeight: 85, + fontStyle: "500", + verticalAlign: "middle", + textBaseline: "bottom" + }, + display2: { + fontFamily: "Arial", + fontSize: 50, + lineHeight: 60, + fontStyle: "500", + verticalAlign: "middle", + textBaseline: "bottom" + }, + headline1: { + fontFamily: "Arial", + fontSize: 35, + fontStyle: "500", + lineHeight: 48, + verticalAlign: "middle", + textBaseline: "bottom" + }, + headline2: { + fontFamily: "Arial", + fontSize: 30, + fontStyle: "500", + lineHeight: 40, + verticalAlign: "middle", + textBaseline: "bottom" + }, + headline3: { + fontFamily: "Arial", + fontSize: 25, + fontStyle: "500", + lineHeight: 36, + verticalAlign: "middle", + textBaseline: "bottom" + }, + body1: { + fontFamily: "Arial", + fontSize: 25, + fontStyle: "300", + lineHeight: 40, + verticalAlign: "middle", + textBaseline: "bottom" + }, + body2: { + fontFamily: "Arial", + fontSize: 22, + fontStyle: "300", + lineHeight: 32, + verticalAlign: "middle", + textBaseline: "bottom" + }, + body3: { + fontFamily: "Arial", + fontSize: 20, + fontStyle: "300", + lineHeight: 32, + verticalAlign: "middle", + textBaseline: "bottom" + }, + button1: { + fontFamily: "Arial", + fontSize: 25, + fontStyle: "500", + lineHeight: 32, + verticalAlign: "middle", + textBaseline: "bottom" + }, + button2: { + fontFamily: "Arial", + fontSize: 20, + fontStyle: "500", + lineHeight: 32, + verticalAlign: "middle", + textBaseline: "bottom" + }, + callout1: { + fontFamily: "Arial", + fontSize: 20, + fontStyle: "500", + lineHeight: 32, + verticalAlign: "middle", + textBaseline: "bottom" + }, + caption1: { + fontFamily: "Arial", + fontSize: 15, + fontStyle: "500", + lineHeight: 24, + verticalAlign: "middle", + textBaseline: "bottom" + }, + tag1: { + fontFamily: "Arial", + fontSize: 20, + fontStyle: "500", + lineHeight: 24, + verticalAlign: "middle", + textBaseline: "bottom" + }, + footnote1: { + fontFamily: "Arial", + fontSize: 22, + fontStyle: "300", + lineHeight: 30, + verticalAlign: "middle", + textBaseline: "bottom" + } + } +}; + +var customFontFaces = []; + +var fontLoader = fonts => { + var promises = []; + var _loop = function _loop() { + var {family: family, src: src, descriptors: descriptors} = fonts[i]; + var fontSrc = src && Array.isArray(src) && src.length ? src.map((url => url.substr(0, 5) === "local" ? url : "url(".concat(url, ")"))).join(",") : "url(" + src + ")"; + var fontFace = new FontFace(family, fontSrc, descriptors || {}); + loggerInstance.info("Loading font", family); + document.fonts.add(fontFace); + promises.push(new Promise((resolve => { + fontFace.load().then((() => { + customFontFaces.push(fontFace); + resolve(family); + })).catch((err => { + resolve(new Error("".concat(family, ": ").concat(err.message))); + })); + }))); + }; + for (var i = 0; i < fonts.length; i++) { + _loop(); + } + return Promise.all(promises).then((fontsLoaded => { + var loaded = fontsLoaded.filter((font => !(font instanceof Error))).join(", "); + if (loaded) { + loggerInstance.log("Fonts loaded: ".concat(loaded)); + } + var failed = fontsLoaded.filter((font => font instanceof Error)).map((item => item.message)).join(", "); + if (failed) { + loggerInstance.error("Unable to load fonts: ".concat(failed)); + } + })); +}; + +var cleanupFonts = function() { + var _ref3 = _asyncToGenerator((function*(fonts) { + if (document.fonts && "delete" in document.fonts) { + if (!customFontFaces.length) return; + customFontFaces = customFontFaces.filter((fontFace => { + if (!fonts.find((font => font.family === fontFace.family))) { + loggerInstance.info("Removing font", fontFace.family); + document.fonts.delete(fontFace); + return false; + } else { + return fontFace; + } + })); + } else { + loggerInstance.info("Unable to remove manually-added fonts"); + } + })); + return function cleanupFonts(_x) { + return _ref3.apply(this, arguments); + }; +}(); + +var THEME_KEY_REPLACER = { + fontFamily: "fontFace" +}; + +var merge = { + all: objArray => { + var result = {}; + for (var i = 0; i < objArray.length; i++) { + result = clone(result, objArray[i]); + } + return result; + } +}; + +var base64Cache = []; + +var isSubTheme = themeName => "subTheme" === themeName.slice(0, 8); + +function getMimeTypeFromDataUri(dataUri) { + var matches = dataUri.match(/^data:(.*?);base64,/); + if (matches && matches.length === 2) { + return matches[1]; + } + return null; +} + +function checkBase64EncodedImage(str) { + var regex = /^data:image\/(jpeg|jpg|png|gif);base64,/; + var isImage = regex.test(str); + var mimeType = isImage ? getMimeTypeFromDataUri(str.match(regex)[0]) : null; + return { + isImage: isImage, + mimeType: mimeType + }; +} + +function base64ToBlobURL(base64String, mimeType) { + var byteCharacters = atob(base64String.substring(base64String.indexOf(",") + 1)); + var byteArrays = []; + try { + for (var offset = 0; offset < byteCharacters.length; offset += 512) { + var slice = byteCharacters.slice(offset, offset + 512); + var byteNumbers = new Array(slice.length); + for (var i = 0; i < slice.length; i++) { + byteNumbers[i] = slice.charCodeAt(i); + } + var byteArray = new Uint8Array(byteNumbers); + byteArrays.push(byteArray); + } + var blob = new Blob(byteArrays, { + type: mimeType + }); + var blobURL = URL.createObjectURL(blob); + return blobURL; + } catch (error) { + loggerInstance.info("Unable to convert base64 image to URL"); + return null; + } +} + +class ThemeManager { + constructor() { + this._cache = new Map; + if (typeof window === "undefined") return; + if (!window.LUI) { + window.LUI = {}; + } + if (!window.LUI.themeManagerInstances) { + window.LUI.themeManagerInstances = [ { + themeManager: this, + events: events + } ]; + } else { + window.LUI.themeManagerInstances.push({ + themeManager: this, + events: events + }); + } + } + _setCache(key, payload) { + if (typeof window === "undefined") return; + window.LUI.themeManagerInstances.forEach((_ref4 => { + var {themeManager: themeManager} = _ref4; + if (themeManager) themeManager._cache.set(key, payload); + })); + } + _deleteCache(key) { + if (typeof window === "undefined") return; + window.LUI.themeManagerInstances.forEach((_ref5 => { + var {themeManager: themeManager} = _ref5; + if (themeManager) themeManager._cache.delete(key); + })); + } + _emit(key, payload) { + if (typeof window === "undefined") return; + window.LUI.themeManagerInstances.forEach((_ref6 => { + var {events: events} = _ref6; + events.emit(key, payload); + })); + } + getTheme() { + if (this._cache.has("theme")) { + return this._cache.get("theme"); + } + var theme = this._processTheme.call(this); + this._setCache("theme", theme); + return theme; + } + setTheme(themeConfig) { + var _this = this; + return _asyncToGenerator((function*() { + var value; + if (Array.isArray(themeConfig)) { + value = merge.all(themeConfig); + } else { + value = themeConfig; + } + if ("object" !== typeof value || null === value) { + loggerInstance.warn("context theme expected an object. Received ".concat(typeof value)); + return; + } + _this._clearCache(); + var theme = _this._processTheme.call(_this, [ value ], value.extensions); + _this._setCache("theme", theme); + yield cleanupFonts(theme.font); + if (theme.font && theme.font.length) { + yield _this._loadFonts(theme.font); + } + _this._refreshSubThemes(); + _this._emit("themeExtensionsUpdate"); + _this._emit("themeUpdate"); + return theme; + }))(); + } + getSubTheme(subThemeName) { + if (this._cache.has("subTheme".concat(subThemeName))) { + return this._cache.get("subTheme".concat(subThemeName)).result; + } + return; + } + setSubTheme(subThemeName, value) { + var _arguments = arguments, _this2 = this; + return _asyncToGenerator((function*() { + var triggerUpdate = _arguments.length > 2 && _arguments[2] !== undefined ? _arguments[2] : true; + if (!subThemeName) { + loggerInstance.warn("Sub theme name not specified"); + return; + } + if ("string" !== typeof subThemeName) { + loggerInstance.warn("Sub theme name must be a string. Received an ".concat(typeof subThemeName)); + return; + } + if ("object" !== typeof value || !Object.keys(value).length) { + loggerInstance.warn("Could not set subTheme ".concat(subThemeName, ", value should be an object with properties. Received an ").concat(typeof value)); + return; + } + var globalTheme = _this2.getTheme(); + var subTheme = _this2._processTheme.call(_this2, [ globalTheme, value ]); + if (subTheme.font && subTheme.font.length) { + yield _this2._loadFonts(subTheme.font); + } + _this2._setCache("subTheme".concat(subThemeName), { + original: value, + result: subTheme + }); + if (triggerUpdate) _this2._emit("themeUpdate".concat(subThemeName)); + return subTheme; + }))(); + } + _refreshSubThemes() { + [ ...this._cache.keys() ].forEach((key => { + if ("string" === typeof key && isSubTheme(key)) { + var _cache = this._cache.get(key); + if (_cache.original) this.updateSubTheme(key.replace(/^subTheme/, ""), _cache.original); + } + })); + } + _loadFonts(fontArray) { + return _asyncToGenerator((function*() { + try { + yield fontLoader(fontArray); + } catch (err) { + loggerInstance.error("Unable to load font: ".concat(err)); + } + }))(); + } + updateTheme(themeConfig) { + var _this3 = this; + return _asyncToGenerator((function*() { + var value; + if (Array.isArray(themeConfig)) { + value = merge.all(themeConfig); + } else { + value = themeConfig; + } + var currentTheme = {}; + if (_this3._cache.has("theme")) { + currentTheme = _this3._cache.get("theme"); + } + _this3._clearCache(); + var theme = _this3._processTheme.call(_this3, [ currentTheme, value ], value.extensions || currentTheme.extensions); + _this3._setCache("theme", theme); + if (theme.font && theme.font.length) { + yield _this3._loadFonts(theme.font); + } + _this3._refreshSubThemes(); + if (value.extensions) _this3._emit("themeExtensionsUpdate"); + _this3._emit("themeUpdate"); + return theme; + }))(); + } + _clearCache() { + base64Cache.filter((image => { + if (window.URL && typeof window.URL.revokeObjectURL === "function") URL.revokeObjectURL(image); + return false; + })); + this._cache.forEach(((value, key) => { + if ("string" !== typeof key || !isSubTheme(key)) { + this._deleteCache(key); + } + })); + this._cache.forEach(((value, key) => { + if ("string" === typeof key && isSubTheme(key)) { + this.setSubTheme(key.replace("subTheme", ""), value.original, false); + } + })); + } + updateSubTheme(subThemeName, value) { + var _arguments2 = arguments, _this4 = this; + return _asyncToGenerator((function*() { + var triggerUpdate = _arguments2.length > 2 && _arguments2[2] !== undefined ? _arguments2[2] : true; + if (!subThemeName) { + loggerInstance.warn("Sub theme name not specified"); + return; + } + if ("object" !== typeof value || !Object.keys(value).length) { + loggerInstance.warn("Could not update subTheme ".concat(subThemeName, " due to invalid value")); + return; + } + var globalTheme = _this4.getTheme(); + var currentTheme = {}; + if (_this4._cache.has("subTheme".concat(subThemeName))) { + currentTheme = _this4._cache.get("subTheme".concat(subThemeName)).original; + } + var subTheme = _this4._processTheme.call(_this4, [ globalTheme, currentTheme, value ]); + if (subTheme.font && subTheme.font.length) { + yield _this4._loadFonts(subTheme.font); + } + _this4._setCache("subTheme".concat(subThemeName), { + original: clone(currentTheme, value), + result: subTheme + }); + if (triggerUpdate) _this4._emit("themeUpdate".concat(subThemeName)); + return subTheme; + }))(); + } + removeSubTheme(subThemeName) { + if (this._cache.has("subTheme".concat(subThemeName))) { + this._deleteCache("subTheme".concat(subThemeName)); + } + this._emit("themeUpdate".concat(subThemeName)); + } + _getComponentUUID(id) { + return "componentStyle".concat(id); + } + _processTheme() { + var themeArray = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : []; + var extensions = arguments.length > 1 ? arguments[1] : undefined; + if (!Array.isArray(themeArray)) { + throw new Error("context processTheme expected an array. Received ".concat(typeof themeArray)); + } + var theme = merge.all([ baseTheme, ...themeArray ]); + var themeFunctions = {}; + var themeString = JSON.stringify(theme, ((key, originalValue) => { + var value = originalValue; + if (value && typeof value === "object") { + var replacement = originalValue; + for (var k in value) { + if (Object.hasOwnProperty.call(value, k) && THEME_KEY_REPLACER[k]) { + replacement[k && THEME_KEY_REPLACER[k]] = value[k]; + delete replacement[k]; + } + } + value = replacement; + } + var {isImage: isImage, mimeType: mimeType} = checkBase64EncodedImage(value); + if (window.URL && typeof window.URL.createObjectURL === "function" && isImage) { + try { + var blobURL = base64ToBlobURL(value, mimeType); + base64Cache.push(blobURL); + return blobURL; + } catch (error) { + return value; + } + } + if (Array.isArray(value) && 2 === value.length && !value[0].targetComponent && value[0].length && typeof value[0] === "string" && value[0].substr(0, 1) === "#" && typeof value[1] === "number") { + return getHexColor(value[0], value[1]); + } else if ("extensions" === key || "function" === typeof value || "object" === typeof value && value !== null && "Object" !== value.constructor.name && !Array.isArray(value)) { + themeFunctions[key] = value; + return; + } else if ("string" === typeof value && value.includes("theme.")) { + var themeValue = getValFromObjPath({ + theme: theme + }, value); + if (themeValue) { + return themeValue; + } else { + return value; + } + } else { + var validColor = getValidColor(value); + if (validColor) { + return validColor; + } + return value; + } + })); + return _objectSpread(_objectSpread(_objectSpread({}, JSON.parse(themeString)), themeFunctions), {}, { + extensions: extensions + }); + } +} + +var themeManagerInstance = new ThemeManager; + +class Context { + get theme() { + return themeManagerInstance.getTheme(); + } + set theme(value) { + loggerInstance.warn("Context.theme must be set using context.setTheme or context.updateTheme"); + } + get keyMetricsCallback() { + return metricsInstance.keyMetricsCallback; + } + set keyMetricsCallback(value) { + loggerInstance.warn("Context.keyMetricsCallback must be set using context.setKeyMetricsCallback"); + } + get debug() { + return loggerInstance.debug; + } + set debug(value) { + loggerInstance.debug = value; + } + on() { + return events.on(...arguments); + } + off() { + return events.off(...arguments); + } + emit() { + return events.emit(...arguments); + } + log() { + loggerInstance.log(...arguments); + } + info() { + loggerInstance.info(...arguments); + } + warn() { + loggerInstance.warn(...arguments); + } + error() { + for (var _len6 = arguments.length, args = new Array(_len6), _key6 = 0; _key6 < _len6; _key6++) { + args[_key6] = arguments[_key6]; + } + loggerInstance.error(args); + } + setTheme(value) { + return themeManagerInstance.setTheme(value); + } + updateTheme(value) { + return themeManagerInstance.updateTheme(value); + } + getSubTheme(subThemeName) { + return themeManagerInstance.getSubTheme(subThemeName); + } + setSubThemes(subThemesObj) { + if ("object" !== typeof subThemesObj) { + loggerInstance.warn("subThemes must be an object"); + return; + } + for (var subTheme in subThemesObj) { + themeManagerInstance.setSubTheme(subTheme, subThemesObj[subTheme]); + } + } + setSubTheme(subThemeName, value) { + return themeManagerInstance.setSubTheme(subThemeName, value); + } + updateSubTheme(subThemeName, value) { + return themeManagerInstance.updateSubTheme(subThemeName, value); + } + removeSubTheme(subThemeName) { + themeManagerInstance.removeSubTheme(subThemeName); + } + setLogCallback(value) { + loggerInstance.logCallback = value; + } + setKeyMetricsCallback(value) { + metricsInstance.keyMetricsCallback = value; + } + config() { + var config = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + var configKeys = Object.keys(config); + for (var i = 0; i < configKeys.length; i++) { + var setMethod = this["set" + capitalizeFirstLetter(configKeys[i])]; + if (setMethod) { + setMethod(config[configKeys[i]]); + } + } + return this; + } +} + +var contextInstance = new Context; + +class GlobalUpdateManager { + constructor() { + this._updateThemeSet = new Set; + this._requestUpdateSet = new Set; + this._timeout = null; + this._runUpdatesTimeoutHandler = this._runUpdatesTimeoutHandler.bind(this); + } + _runUpdatesTimeoutHandler() { + this._timeout = null; + this._updateThemeSet.forEach((component => { + try { + component._updateThemeComponent(); + } catch (e) { + contextInstance.error("Error updating component themes", e); + } + })); + this._updateThemeSet.clear(); + this._requestUpdateSet.forEach((component => { + try { + component.requestUpdate(); + } catch (e) { + contextInstance.error("Error updating component", e); + } + })); + this._requestUpdateSet.clear(); + } + flush() { + if (!this._timeout) return; + clearTimeout(this._timeout); + this._runUpdatesTimeoutHandler(); + } + addUpdateTheme(component) { + this._updateThemeSet.add(component); + if (!this._timeout) { + this._timeout = setTimeout(this._runUpdatesTimeoutHandler, 0); + } + } + deleteUpdateTheme(component) { + this._updateThemeSet.delete(component); + } + addRequestUpdate(component) { + this._requestUpdateSet.add(component); + if (!this._timeout) { + this._timeout = setTimeout(this._runUpdatesTimeoutHandler, 0); + } + } + deleteRequestUpdate(component) { + this._requestUpdateSet.delete(component); + } + hasQueuedRequestFor(component) { + return this._requestUpdateSet.has(component); + } +} + +var updateManager = new GlobalUpdateManager; + +function capital(str) { + return str.charAt(0).toUpperCase() + str.slice(1); +} + +function mergeProps(componentConfigProp, prop) { + var _result; + var result = prop; + if (typeof componentConfigProp === "object" && Object.keys(componentConfigProp).length && typeof prop === "object") { + result = clone(componentConfigProp, prop); + } + return (_result = result) !== null && _result !== void 0 ? _result : componentConfigProp; +} + +function getPropertyDescriptor$1(name, key) { + return { + get() { + var _this$__componentConf3; + var customGetter = this["_get".concat(capital(name))]; + if (customGetter && typeof customGetter === "function") { + var _this$__componentConf, _this$__componentConf2; + var value = customGetter.call(this, this[key]); + this[key] = value || ((_this$__componentConf = this.__componentConfigProps) === null || _this$__componentConf === void 0 ? void 0 : _this$__componentConf[name]); + return mergeProps((_this$__componentConf2 = this.__componentConfigProps) === null || _this$__componentConf2 === void 0 ? void 0 : _this$__componentConf2[name], value); + } + return mergeProps((_this$__componentConf3 = this.__componentConfigProps) === null || _this$__componentConf3 === void 0 ? void 0 : _this$__componentConf3[name], this[key]); + }, + set(value) { + var oldValue = this[key]; + if (value !== oldValue) { + var changeHandler = this["_set".concat(capital(name))]; + if (changeHandler && typeof changeHandler === "function") { + value = changeHandler.call(this, value); + } + var newValue = key === "style" ? clone(this[key], value) : value; + if (typeof this[key] === "object" && this[key] !== null && this[key].style) { + var style = clone(this[key].style, value.style || {}); + newValue.style = style; + } + this[key] = newValue; + this.queueRequestUpdate(); + } + }, + configurable: true, + enumerable: true + }; +} + +function getAliasPropertyDescriptor(prev, curr) { + var deprecationWarning = 'The property "'.concat(prev, '" is deprecated and will be removed in a future release. Please use "').concat(curr, '" instead.'); + return { + get() { + console.warn(deprecationWarning); + return this[curr]; + }, + set(value) { + console.warn(deprecationWarning); + this[curr] = value; + } + }; +} + +function withUpdates(Base) { + return class extends Base { + static get name() { + return Base.name; + } + _construct() { + var prototype = Object.getPrototypeOf(this); + if (!prototype._withUpdatesInitialized) { + var props = this.constructor.properties || []; + props.forEach((name => { + var key = "_" + name; + var descriptor = getPropertyDescriptor$1(name, key); + if (descriptor !== undefined) { + Object.defineProperty(prototype, name, descriptor); + } + })); + var aliasProps = this.constructor.aliasProperties || []; + aliasProps.forEach((alias => { + if (alias && typeof alias.prev === "string" && typeof alias.curr === "string") { + var descriptor = getAliasPropertyDescriptor(alias.prev, alias.curr); + if (descriptor !== undefined) { + Object.defineProperty(prototype, alias.prev, descriptor); + } + } + })); + prototype._withUpdatesInitialized = true; + } + this._whenEnabled = new Promise((resolve => { + this._whenEnabledResolver = resolve; + })); + super._construct && super._construct(); + } + queueRequestUpdate() { + if (!this._isAttached()) return; + updateManager.addRequestUpdate(this); + } + _firstEnable() { + this._readyForUpdates = true; + this._whenEnabledResolver(); + updateManager.deleteRequestUpdate(this); + this.requestUpdate(); + super._firstEnable && super._firstEnable(); + } + requestEarlyUpdate() { + this._readyForUpdates = true; + if (updateManager.hasQueuedRequestFor(this)) { + updateManager.deleteRequestUpdate(this); + this._readyForUpdates = true; + this.requestUpdate(); + return true; + } + return false; + } + _detach() { + super._detach(); + updateManager.deleteRequestUpdate(this); + } + requestUpdate() { + var force = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false; + if (this._readyForUpdates || force) { + var result = this._update(); + if (typeof result === "object" && result !== null && result.catch) { + result.catch((e => { + contextInstance.error("asyncronous _update() error in '".concat(this.constructor.__componentName, "'"), this, e); + })); + } + } + } + logPropTable() { + console.table(this._propTable); + } + get _propTable() { + return this.constructor.properties.reduce(((acc, prop) => { + acc[prop] = this[prop]; + return acc; + }), {}); + } + }; +} + +function getPropertyDescriptor(path) { + return { + get() { + return this.tag(path); + }, + configurable: true, + enumerable: true + }; +} + +function withTags(Base) { + return class extends Base { + static get name() { + return Base.name; + } + _construct() { + var prototype = Object.getPrototypeOf(this); + if (!prototype._withTagsInitialized) { + var tags = this.constructor.tags || []; + tags.forEach((tag => { + if (typeof tag === "object") { + var {name: name, path: path} = tag; + } else { + var name = tag; + var path = tag; + } + var key = "_" + name; + var descriptor = getPropertyDescriptor(path); + Object.defineProperty(prototype, key, descriptor); + })); + prototype._withTagsInitialized = true; + } + super._construct && super._construct(); + } + }; +} + +function withHandleKey(Base) { + return class extends Base { + static get name() { + return Base.name; + } + _handleKey(keyEvent) { + return this._processEvent(keyEvent); + } + _handleKeyRelease(keyEvent) { + return this._processEvent(keyEvent, "Release"); + } + _processEvent(keyEvent) { + var suffix = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : ""; + var keyMap = this.stage.application.__keymap || {}; + var key = keyMap[keyEvent.keyCode]; + if (!key) { + key = keyEvent.key; + } + if (key && typeof this["on".concat(key).concat(suffix)] === "function") { + this._invokeKeyPayloadCallback(key + suffix); + return this["on".concat(key).concat(suffix)].call(this, this, keyEvent); + } + return false; + } + _invokeKeyPayloadCallback(key) { + if (this.metricsPayload && typeof contextInstance.keyMetricsCallback === "function") { + contextInstance.keyMetricsCallback(key, this.metricsPayload); + } + } + }; +} + +function withLayout(Base) { + return class extends Base { + _construct() { + super._construct && super._construct(); + this._previousDimensionData = null; + } + get itemLayout() { + return this._itemLayout; + } + set itemLayout(v) { + var componentName = this.constructor._componentName || this.constructor.name; + var itemLayout; + if (v) { + itemLayout = JSON.parse(JSON.stringify(v, ((k, v) => { + if (k !== "circle" && v < 0) { + contextInstance.error("itemLayout for ".concat(componentName, " received an invalid value of ").concat(v, " for ").concat(k)); + return; + } else if (k === "circle") { + return Boolean(v); + } + return v; + }))); + } + if (!stringifyCompare(this._itemLayout, itemLayout)) { + if (itemLayout && !itemLayout.upCount) { + this._originalW = this.w; + this._originalH = this.h; + this._itemLayout = _objectSpread({ + w: this._originalW, + h: this._originalH + }, itemLayout); + } else { + this._itemLayout = itemLayout; + } + this._updateItemLayout(); + } + } + _allowUpdate() { + var {w: w = "", h: h = "", circle: circle = "", ratioX: ratioX = "", ratioY: ratioY = "", upCount: upCount = ""} = this._itemLayout || {}; + var layoutString = Object.values(contextInstance.theme.layout).join("") + "".concat(w).concat(h).concat(circle ? 1 : 0).concat(ratioX).concat(ratioY).concat(upCount); + if (layoutString !== this._previousDimensionData) { + this._previousDimensionData = layoutString; + return true; + } + return false; + } + _updateItemLayout() { + if (!this._allowUpdate()) return; + var {w: w, h: h} = getDimensions(this.theme, this._itemLayout); + if (h || w) { + var width = contextInstance.theme.layout.screenW; + var height = contextInstance.theme.layout.screenH; + var calculatedWidth = w || h * (width / height); + var calculatedHeight = h || w * (height / width); + this.w = this._itemLayout && this._itemLayout.circle ? calculatedHeight : calculatedWidth; + this.h = calculatedHeight; + if (this._itemLayout && this._itemLayout.circle && this.style.radius) { + this._circleSet = true; + this._originalRadius = this.style.radius; + this.style = _objectSpread(_objectSpread({}, this.style), {}, { + radius: calculatedHeight / 2 + }); + } else if (this._circleSet) { + this.style = _objectSpread(_objectSpread({}, this.style), {}, { + radius: this._originalRadius + }); + this._originalRadius = undefined; + this._circleSet = false; + } + this.queueRequestUpdate && this.queueRequestUpdate(); + this.fireAncestors("$itemChanged"); + } + } + }; +} + +var getCharacterValue = (char, index) => char.charCodeAt(0) * (index + 1); + +var sortObject = obj => { + var sortedObj = {}; + Object.keys(obj).sort().forEach((key => { + if (typeof obj[key] === "object" && obj[key] !== null && !Array.isArray(obj[key])) { + sortedObj[key] = sortObject(obj[key]); + } else { + sortedObj[key] = obj[key]; + } + })); + return sortedObj; +}; + +var getCharacterSum = obj => { + var sortedObj = sortObject(obj); + var str = JSON.stringify(sortedObj).replace(/[{}:",\s]/g, ""); + var sum = 0; + for (var i = 0; i < str.length; i++) { + sum += getCharacterValue(str[i], i); + } + return sum; +}; + +var getHash = obj => { + var str = JSON.stringify(obj); + return str.length + "-" + getCharacterSum(obj); +}; + +function executeWithContextRecursive(objOrFunction, theme) { + if (typeof objOrFunction === "function") { + var result = objOrFunction(theme); + return executeWithContextRecursive(result, theme); + } else if (Array.isArray(objOrFunction)) { + return objOrFunction.map((item => executeWithContextRecursive(item, theme))); + } else if (typeof objOrFunction === "object" && objOrFunction !== null) { + var _result2 = {}; + for (var key in objOrFunction) { + if (objOrFunction.hasOwnProperty(key)) { + _result2[key] = executeWithContextRecursive(objOrFunction[key], theme); + } + } + return _result2; + } else { + return objOrFunction; + } +} + +function isPlainObject(value) { + return typeof value === "object" && value !== null && !Array.isArray(value) && !(value instanceof Date) && !(value instanceof RegExp) && !(value instanceof Function) && !(value instanceof Error); +} + +var getSubTheme = obj => { + while (obj && (!obj.subTheme || typeof obj.subTheme !== "string")) { + obj = obj.p; + } + return obj ? obj.subTheme : undefined; +}; + +var getComponentConfig = obj => { + var _obj$theme; + if (!isPlainObject(obj)) return {}; + return (obj === null || obj === void 0 || (_obj$theme = obj.theme) === null || _obj$theme === void 0 || (_obj$theme = _obj$theme.componentConfig) === null || _obj$theme === void 0 ? void 0 : _obj$theme[obj.constructor.__componentName]) || {}; +}; + +function removeEmptyObjects(obj) { + for (var key in obj) { + if (obj.hasOwnProperty(key) && isPlainObject(obj[key])) { + removeEmptyObjects(obj[key]); + if (Object.keys(obj[key]).length === 0) { + delete obj[key]; + } + } + } + return obj; +} + +function createSharedReferences() { + var obj = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + var seenObjects = new Map; + function hash(object) { + return JSON.stringify(object, Object.keys(object).sort()); + } + function process(currentObj) { + for (var key in currentObj) { + if (currentObj.hasOwnProperty(key)) { + var value = currentObj[key]; + if (typeof value === "object" && value !== null) { + var valueHash = hash(value); + if (seenObjects.has(valueHash)) { + currentObj[key] = seenObjects.get(valueHash); + } else { + seenObjects.set(valueHash, value); + process(value); + } + } + } + } + } + process(obj); + return obj; +} + +function getUniqueProperties() { + var defaultProps = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : []; + if (!Array.isArray(defaultProps)) { + throw new TypeError("Expected defaultProps to be an array of strings."); + } + return [ ...new Set(defaultProps) ]; +} + +function generatePayload(base, defaultStyle, toneItem, modeItem, tone, mode) { + var _tone$toneItem, _mode$modeItem; + var payload = clone(defaultStyle, base); + payload = clone(payload, tone === null || tone === void 0 ? void 0 : tone[toneItem]); + payload = clone(payload, mode === null || mode === void 0 ? void 0 : mode[modeItem]); + payload = clone(payload, (tone === null || tone === void 0 || (_tone$toneItem = tone[toneItem]) === null || _tone$toneItem === void 0 || (_tone$toneItem = _tone$toneItem.mode) === null || _tone$toneItem === void 0 ? void 0 : _tone$toneItem[modeItem]) || {}); + payload = clone(payload, (mode === null || mode === void 0 || (_mode$modeItem = mode[modeItem]) === null || _mode$modeItem === void 0 || (_mode$modeItem = _mode$modeItem.tone) === null || _mode$modeItem === void 0 ? void 0 : _mode$modeItem[toneItem]) || {}); + return payload; +} + +function findNestedKeys(obj, keyToFind) { + var nestedKeys = []; + function searchNestedKeys(obj) { + if (typeof obj === "object" && obj !== null) { + for (var key in obj) { + if (obj.hasOwnProperty(key)) { + nestedKeys.push(key); + } + } + } + } + function searchForKey(obj) { + if (typeof obj === "object" && obj !== null) { + for (var key in obj) { + if (obj.hasOwnProperty(key)) { + if (key === keyToFind) { + searchNestedKeys(obj[key]); + break; + } + searchForKey(obj[key]); + } + } + } + } + searchForKey(obj); + return nestedKeys; +} + +var generateSolution = function generateSolution(_ref7) { + var {base: base = {}, tone: tone = {}, mode: mode = {}, defaultStyle: defaultStyle = {}} = _ref7; + var modeKeys = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : []; + var toneKeys = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : []; + var solution = {}; + var uniqueModes = getUniqueProperties([ "focused", "disabled", ...modeKeys, "unfocused" ]); + var uniqueTones = getUniqueProperties([ "neutral", "inverse", "brand", ...toneKeys ]); + for (var modeItem of uniqueModes) { + for (var toneItem of uniqueTones) { + var payload = generatePayload(base, defaultStyle, toneItem, modeItem, tone, mode); + solution["".concat(modeItem, "_").concat(toneItem)] = payload; + } + } + return solution; +}; + +var DEFAULT_KEYS = [ "unfocused_neutral", "unfocused_inverse", "unfocused_brand", "focused_neutral", "focused_inverse", "focused_brand", "disabled_neutral", "disabled_inverse", "disabled_brand" ]; + +function enforceContract(inputObj) { + var result = {}; + for (var key of [ ...DEFAULT_KEYS, ...Object.keys(inputObj) ]) { + if (!inputObj.hasOwnProperty(key)) { + var fallbackKey = DEFAULT_KEYS.find((fallback => inputObj.hasOwnProperty(fallback))); + if (fallbackKey) { + var fallback = inputObj[fallbackKey]; + result[key] = typeof fallback !== "object" ? {} : fallback; + } else { + result[key] = {}; + } + } else { + if (typeof inputObj[key] !== "object") { + result[key] = {}; + } else { + result[key] = inputObj[key]; + } + } + } + return result; +} + +var generateComponentStyleSource = function generateComponentStyleSource() { + var {theme: theme = {}, styleChain: styleChain = [], inlineStyle: inlineStyle = {}, alias: alias = []} = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + if (typeof theme !== "object") { + throw new Error("Expected theme to be an object"); + } + if (!Array.isArray(styleChain)) { + throw new Error("Expected styleChain to be an array"); + } + if (typeof inlineStyle !== "object") { + throw new Error("Expected inlineStyle to be an object"); + } + if (!Array.isArray(alias)) { + throw new Error("Expected alias to be an array"); + } + var componentDefault = styleChain.map((_ref8 => { + var {style: style} = _ref8; + if (typeof style === "object" && !style.base && !style.mode && !style.tone && !style.default) { + return { + base: style + }; + } else { + var {base: _base = {}, mode: _mode = {}, tone: _tone = {}} = style; + var componentConfigDefaultStyle; + if (style) { + var defaultStyle = JSON.parse(JSON.stringify(style)); + delete defaultStyle.base; + delete defaultStyle.tone; + delete defaultStyle.mode; + componentConfigDefaultStyle = defaultStyle; + } + return { + defaultStyle: componentConfigDefaultStyle || {}, + base: _base, + mode: _mode, + tone: _tone + }; + } + })); + var localDefaultStyle; + if (inlineStyle) { + var defaultStyle = JSON.parse(JSON.stringify(inlineStyle)); + delete defaultStyle.base; + delete defaultStyle.tone; + delete defaultStyle.mode; + localDefaultStyle = defaultStyle; + } + var local = { + defaultStyle: localDefaultStyle || {}, + base: (inlineStyle === null || inlineStyle === void 0 ? void 0 : inlineStyle.base) || {}, + mode: (inlineStyle === null || inlineStyle === void 0 ? void 0 : inlineStyle.mode) || {}, + tone: (inlineStyle === null || inlineStyle === void 0 ? void 0 : inlineStyle.tone) || {} + }; + var merged = [ ...componentDefault, local ]; + var parsedStyles = merged.map((style => executeWithContextRecursive(style, theme))); + var modeKeys = findNestedKeys(parsedStyles, "mode"); + var toneKeys = findNestedKeys(parsedStyles, "tone"); + var solution = parsedStyles.reduce(((acc, style) => clone(acc, generateSolution(style, modeKeys, toneKeys))), {}); + var final = formatStyleObj(removeEmptyObjects(colorParser({ + theme: theme + }, solution)) || {}, alias); + var cleanObj = createSharedReferences(final); + return enforceContract(cleanObj); +}; + +var colorParser = (targetObject, styleObj) => { + if (typeof targetObject !== "object" || targetObject === null) { + throw new TypeError("targetObject must be an object."); + } + if (typeof styleObj !== "object" || styleObj === null) { + throw new TypeError("styleObj must be an object."); + } + var processedStyle = JSON.stringify(styleObj, ((_, value) => { + if (-1 < [ "tone", "mode" ].indexOf(_)) return value; + if (typeof value === "string" && value.startsWith("theme.")) { + return getValFromObjPath(targetObject, value); + } + function isValidColor(num) { + return num >= 0 && num <= 4294967295; + } + if (Array.isArray(value) && value.length === 2 && (typeof value[0] === "string" && value[0].startsWith("#") || typeof value[0] === "number" && isValidColor(value[0])) && typeof value[1] === "number") { + return getHexColor(value[0], value[1]) || value; + } + return value; + })); + return JSON.parse(processedStyle || {}); +}; + +var generateStyle = function generateStyle(component) { + var componentStyleSource = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + if (!isPlainObject(component)) return {}; + var {mode: mode = "unfocused", tone: tone = "neutral"} = component; + return componentStyleSource["".concat(mode, "_").concat(tone)] || componentStyleSource["unfocused_neutral"] || {}; +}; + +function generateNameFromPrototypeChain(obj) { + var _proto$constructor; + var name = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : ""; + if (!obj) return name; + var proto = Object.getPrototypeOf(obj); + if (!proto || !proto.constructor) return name; + var componentName = "".concat(name ? name + "." : "").concat((proto === null || proto === void 0 || (_proto$constructor = proto.constructor) === null || _proto$constructor === void 0 ? void 0 : _proto$constructor.__componentName) || "").replace(/\.*$/, "").trim(); + var result = generateNameFromPrototypeChain(proto, componentName); + return result; +} + +var styleChainCache = {}; + +var clearStyleChainCache = () => { + for (var key in styleChainCache) { + if (styleChainCache.hasOwnProperty(key)) { + delete styleChainCache[key]; + } + } +}; + +var getStyleChainMemoized = componentObj => { + var cacheKey = generateNameFromPrototypeChain(componentObj); + if (styleChainCache[cacheKey]) { + return styleChainCache[cacheKey]; + } + var styleChain = getStyleChain(componentObj); + styleChainCache[cacheKey] = styleChain; + return styleChain; +}; + +var getStyleChain = componentObj => { + var styleMap = new Map; + var proto; + do { + var _proto; + proto = !proto ? componentObj : Object.getPrototypeOf(proto); + if (((_proto = proto) === null || _proto === void 0 ? void 0 : _proto.constructor) === Object) break; + if (proto && typeof proto === "object" && proto.hasOwnProperty("constructor")) { + var {style: componentConfigStyle} = getComponentConfig(proto); + if (Object.keys(componentConfigStyle || {}).length) { + if (!styleMap.has(componentConfigStyle)) { + styleMap.set(componentConfigStyle, { + style: componentConfigStyle + }); + } + } + var themeStyle = proto.constructor.hasOwnProperty("__themeStyle") && proto.constructor.__themeStyle; + if (Object.keys(themeStyle || {}).length) { + if (!styleMap.has(themeStyle)) { + styleMap.set(themeStyle, { + style: _objectSpread({}, themeStyle) + }); + } + } else if (typeof themeStyle === "function") { + if (!styleMap.has(themeStyle)) { + styleMap.set(themeStyle, { + style: themeStyle + }); + } + } + var mixinStyle = proto.constructor.hasOwnProperty("__mixinStyle") && proto.constructor.__mixinStyle; + if (Object.keys(mixinStyle || {}).length) { + if (!styleMap.has(mixinStyle)) { + styleMap.set(mixinStyle, { + style: mixinStyle + }); + } + } + } + } while (proto); + var uniqueStyles = Array.from(styleMap.values()); + return uniqueStyles.map((style => style)).reverse(); +}; + +var formatStyleObj = function formatStyleObj(originalObj) { + var aliasStyles = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : []; + if (typeof originalObj !== "object" || originalObj === null) { + throw new Error("The originalObj parameter must be an object."); + } + var formatters = new Set; + formatters.add([ replaceAliasValues, [ aliasStyles ] ]); + var formattersArray = Array.from(formatters); + return formattersArray.reduce(((obj, _ref9) => { + var [func, args] = _ref9; + return func(obj, ...args); + }), originalObj); +}; + +var replaceAliasValues = function replaceAliasValues(value) { + var aliasStyles = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : []; + if (typeof value !== "object" || value === null) { + throw new Error("Value must be an object"); + } + if (!Array.isArray(aliasStyles)) { + throw new Error("Alias styles must be an array"); + } + var str = JSON.stringify(value); + var aliasProps = [ { + prev: "height", + curr: "h", + skipWarn: true + }, { + prev: "width", + curr: "w", + skipWarn: true + }, ...aliasStyles || [] ]; + aliasProps.forEach((alias => { + if (alias && typeof alias.prev === "string" && typeof alias.curr === "string") { + !alias.skipWarn && str.search('"'.concat(alias.prev, '":')) >= 0 && loggerInstance.warn('The style property "'.concat(alias.prev, '" is deprecated and will be removed in a future release. Please use "').concat(alias.curr, '" instead.')); + str = str.replace(new RegExp('"'.concat(alias.prev, '":'), "gi"), '"'.concat(alias.curr, '":')); + } + })); + return JSON.parse(str); +}; + +var themeStyleCache = new Map; + +contextInstance.on("themeUpdate", (() => { + themeStyleCache.clear(); +})); + +var cache = themeStyleCache; + +class StyleManager extends _lightningjs_core__WEBPACK_IMPORTED_MODULE_0__.EventEmitter { + constructor() { + var {component: component = {}} = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + super(...arguments); + this.init(component); + } + init(component) { + this.isActive = true; + this.component = component; + this.setupListeners(); + this._style = {}; + this.update(); + } + setupListeners() { + this._boundThemeUpdate = this._onThemeUpdate.bind(this); + this._hasSubTheme = Boolean(this.component._targetSubTheme); + if (!this.component._targetSubTheme) { + contextInstance.on("themeUpdate", this._boundThemeUpdate); + } else { + contextInstance.on("themeUpdate".concat(this.component._targetSubTheme), this._boundThemeUpdate); + } + } + clearListeners() { + if (!this._boundThemeUpdate) return; + if (!this.component._targetSubTheme) { + contextInstance.off("themeUpdate", this._boundThemeUpdate); + } else { + contextInstance.off("themeUpdate".concat(this.component._targetSubTheme), this._boundThemeUpdate); + } + } + destroy() { + this.isActive = false; + this._cleanupCache(); + this.clearListeners(); + this._styleCache = null; + this._boundThemeUpdate = null; + this.component = null; + } + _onThemeUpdate() { + clearStyleChainCache(); + this.clearSourceCache(); + this.clearStyleCache(); + this.update(); + } + clearStyleChainCache() { + clearStyleChainCache(); + } + clearSourceCache() { + if (!this.component) return; + var sourceKey = this._generateCacheKey("styleSource"); + this._removeCache(sourceKey); + } + clearStyleCache() { + if (!this.component) return; + var {tone: tone, mode: mode} = this.component; + var styleKey = this._generateCacheKey("style_".concat(mode, "_").concat(tone)); + cache.delete(styleKey); + } + _generateCacheKey(name) { + var cacheKey = [ name, this.component._targetSubTheme, this.component.constructor.__componentName, this._customStyleHash ].filter(Boolean).join("_"); + return cacheKey; + } + _addCache(name, payload) { + var key = this._generateCacheKey(name); + var existing = cache.get(key); + cache.set(key, { + ids: [ ...new Set([ ...(existing === null || existing === void 0 ? void 0 : existing.ids) || [], this.component.__id ]) ], + payload: payload + }); + } + _cleanupCache() { + if (!this.component) return; + cache.forEach(((_ref10, name) => { + var {ids: ids, payload: payload} = _ref10; + var removeIndex = ids && ids.length && ids.indexOf(this.component.__id); + if (removeIndex > -1 && ids.length > 1) { + cache.set(name, { + ids: ids.slice(0, removeIndex).concat(ids.slice(removeIndex + 1)), + payload: payload + }); + } else if (removeIndex > -1) { + cache.delete(name); + } + })); + } + _removeCache(name) { + cache.delete(name); + } + _getCache(name) { + var key = this._generateCacheKey(name); + return cache.get(key); + } + update() { + if (!this.component) return; + var {mode: mode, tone: tone} = this.component; + try { + var _this$_getCache, _this$_getCache2; + var styleSource = (_this$_getCache = this._getCache("styleSource")) === null || _this$_getCache === void 0 ? void 0 : _this$_getCache.payload; + if (!styleSource) { + styleSource = generateComponentStyleSource({ + alias: this.component.constructor.aliasStyles, + inlineStyle: this.component._componentLevelStyle, + styleChain: getStyleChainMemoized(this.component), + theme: this.component.theme + }); + this._addCache("styleSource", styleSource); + } + var style = (_this$_getCache2 = this._getCache("style_".concat(mode, "_").concat(tone))) === null || _this$_getCache2 === void 0 ? void 0 : _this$_getCache2.payload; + if (!style) { + style = generateStyle(this.component, styleSource); + this._addCache("style_".concat(mode, "_").concat(tone), style); + } + this._style = style; + this.emit("styleUpdate", this.style); + } catch (error) { + contextInstance.error("styleManager: ", error.message); + } + } + set style(v) { + contextInstance.warn("styleManager: Cannot mutate style directly"); + } + get style() { + return this._style; + } + set props(v) { + contextInstance.warn("styleManager: Cannot mutate props directly"); + } + get props() { + return Object.keys(this.component._componentConfig).reduce(((acc, key) => { + if (![ "base", "tone", "mode", "style", "styleConfig" ].includes(key)) { + acc[key] = this.component._componentConfig[key]; + } + return acc; + }), {}); + } + get _customStyleHash() { + var hasCustomStyle = Boolean(Object.keys(this.component.constructor.__mixinStyle || {}).length) || Boolean(Object.keys(this.component._componentLevelStyle || {}).length); + if (hasCustomStyle) { + return getHash(clone(this.component.constructor.__mixinStyle || {}, this.component._componentLevelStyle || {})); + } + return undefined; + } +} + +function mergeObjectsWithSecondDominant(firstObj, secondObj) { + if (firstObj !== null && typeof firstObj === "object") { + if (Array.isArray(firstObj)) { + return firstObj.map(((item, index) => mergeObjectsWithSecondDominant(item, Array.isArray(secondObj) ? secondObj[index] : undefined))); + } else { + var result = {}; + var allKeys = new Set([ ...Object.keys(firstObj), ...Object.keys(secondObj) ]); + allKeys.forEach((key => { + if (typeof firstObj[key] === "object" && firstObj[key] !== null) { + result[key] = mergeObjectsWithSecondDominant(firstObj[key], secondObj[key] || {}); + } else if (typeof secondObj[key] === "object" && secondObj[key] !== null) { + result[key] = mergeObjectsWithSecondDominant(firstObj[key] || {}, secondObj[key]); + } else { + result[key] = secondObj.hasOwnProperty(key) ? secondObj[key] : undefined; + } + })); + return result; + } + } else { + return firstObj; + } +} + +function withThemeStyles(Base) { + var mixinStyle = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + return class extends Base { + _construct() { + if (this._withThemeStylesSetupComplete) { + super._construct(); + return; + } + this._hSetByUser = false; + this._wSetByUser = false; + this._styleManager = new StyleManager({ + component: this + }); + this._style = this._styleManager.style; + this._updatePropDefaults(); + this._styleManager.on("styleUpdate", (() => { + this._style = this._styleManager.style; + this._updatePropDefaults(); + this.queueThemeUpdate(); + })); + this._withThemeStylesSetupComplete = true; + super._construct(); + } + _setup() { + super._setup && super._setup(); + this._targetSubTheme = getSubTheme(this); + if (this._targetSubTheme) { + this._styleManager.clearListeners(); + this._styleManager.setupListeners(); + this._styleManager.clearStyleChainCache(); + this._styleManager.clearStyleCache(); + this._styleManager.clearSourceCache(); + this._styleManager.update(); + } + } + _updatePropDefaults() { + if (!Object.keys(this._styleManager.props).length || JSON.stringify(this._styleManager.props) === JSON.stringify(this._prevComponentConfigProps)) { + return; + } + var payload = this._prevComponentConfigProps ? mergeObjectsWithSecondDominant(this._prevComponentConfigProps || {}, this._styleManager.props || {}) : this._styleManager.props || {}; + this._prevComponentConfigProps = this._styleManager.props && JSON.parse(JSON.stringify(this._styleManager.props)); + this.__componentConfigProps = payload; + } + _attach() { + super._attach(); + if (!this._styleManager.isActive) { + this._styleManager.init(this); + } + } + _detach() { + super._detach(); + this._styleManager.destroy(); + } + _unfocus() { + if (this._isFocusedMode) this.mode = "unfocused"; + super._unfocus(); + } + _focus() { + if (!this._isDisabledMode) this.mode = "focused"; + super._focus(); + } + _checkDimensionUpdates() { + var dimensionUpdateRequired = false; + if (!this._wSetByUser && this.style.w && this._w !== this.style.w) { + this._w = this.style.w; + dimensionUpdateRequired = true; + } + if (!this._hSetByUser && this.style.h && this._h !== this.style.h) { + this._h = this.style.h; + dimensionUpdateRequired = true; + } + if (dimensionUpdateRequired) { + this._updateDimensions(); + } + } + _updateThemeComponent() { + if (!this.style) return; + if (!this._isAttached()) return; + this._checkDimensionUpdates(); + this.queueRequestUpdate ? this.queueRequestUpdate() : this._update && this._update(); + this._updateItemLayout && this._updateItemLayout(); + } + queueThemeUpdate() { + updateManager.addUpdateTheme(this); + } + static get name() { + return Base.name; + } + static get __componentName() { + if (!super.__componentName) { + throw new Error("A valid static __componentName property is required for theming to work properly. Please add this to the ".concat(this.constructor.name, " class.")); + } + return super.__componentName; + } + static get __mixinStyle() { + return mixinStyle; + } + get theme() { + var subTheme = this._targetSubTheme && contextInstance.getSubTheme(this._targetSubTheme); + return subTheme || contextInstance.theme; + } + set style(v) { + if (Object.prototype.toString.call(v) !== "[object Object]") { + contextInstance.error("style must be an object"); + return; + } + this._componentLevelStyle = v; + this._styleManager.clearStyleCache(); + this._styleManager.update(); + } + get style() { + return this._style; + } + get _componentStyle() { + contextInstance.info("_componentStyle will soon be deprecated. Please use Component.style"); + return this._style; + } + set styleConfig(v) { + contextInstance.info("style config is deprecated. Please use style = { base: {}, tone: {}, mode: {} }"); + this._styleConfig = v; + this._styleManager.update(); + } + get styleConfig() { + return this._styleConfig; + } + get _componentConfig() { + return getComponentConfig(this); + } + get mode() { + var _this$_componentConfi; + return this._mode || ((_this$_componentConfi = this._componentConfig) === null || _this$_componentConfi === void 0 ? void 0 : _this$_componentConfi.mode) || "unfocused"; + } + set mode(v) { + if (typeof v !== "string" || this._mode === v) return; + this._mode = v; + var event = this["on".concat(capitalizeFirstLetter(v))]; + if (event && typeof event === "function") event.call(this); + this._styleManager.update(); + } + get tone() { + return this._tone || this._componentConfig.tone || "neutral"; + } + set tone(v) { + if (typeof v !== "string" || this._tone === v) return; + this._tone = v; + this._styleManager.update(); + } + get w() { + var _this$style; + return this._wSetByUser && this._w || ((_this$style = this.style) === null || _this$style === void 0 ? void 0 : _this$style.w) || 0; + } + set w(v) { + if (this._w === v) return; + super.w = v; + this._wSetByUser = true; + this._updateThemeComponent(); + } + get h() { + var _this$style2; + return this._hSetByUser && this._h || ((_this$style2 = this.style) === null || _this$style2 === void 0 ? void 0 : _this$style2.h) || this._h || 0; + } + set h(v) { + if (this._h === v) return; + super.h = v; + this._hSetByUser = true; + this._updateThemeComponent(); + } + }; +} + +var SUFFIX = "__original"; + +function withExtensions(Base) { + if (Base.prototype.constructor._withExtensionsApplied) { + return Base; + } + return class extends Base { + static get name() { + return Base.name; + } + static get __componentName() { + if (!super.__componentName) { + throw new Error("A valid static __componentName property is required for theming to work properly. Please add this to the ".concat(this.constructor.name, " class.")); + } + return super.__componentName; + } + static get _withExtensionsApplied() { + return true; + } + get _prototypeChain() { + if (this.__prototypeChain) return this.__prototypeChain; + var prototypeChain = new Set; + var proto = this; + do { + proto = Object.getPrototypeOf(proto); + if (null !== proto && typeof proto === "object") { + try { + if (proto.constructor.__componentName) prototypeChain.add(proto.constructor.__componentName); + } catch (error) {} + } + } while (proto); + this.__prototypeChain = prototypeChain; + return prototypeChain; + } + get _extensions() { + var extensions = contextInstance && contextInstance.theme && contextInstance.theme.extensions; + if (!extensions || !Array.isArray(extensions) || Array.isArray(extensions) && !extensions.length) return []; + return extensions.filter((_ref11 => { + var {targetComponent: targetComponent, extension: extension} = _ref11; + return (typeof targetComponent === "string" || Array.isArray(targetComponent)) && typeof extension === "function"; + })).slice().reverse() || []; + } + get _componentExtensions() { + return this._extensions.filter((_ref12 => { + var {targetComponent: targetComponent} = _ref12; + if (typeof targetComponent === "string") { + return targetComponent === this.constructor.__componentName || this._prototypeChain.has(targetComponent); + } else if (Array.isArray(targetComponent)) { + return targetComponent.find((pattern => { + if (pattern.startsWith("/") && pattern.endsWith("/")) { + var ComponentRegExp = new RegExp(pattern.slice(1, -1)); + return Array.from(this._prototypeChain).some((name => ComponentRegExp.test(name))); + } else { + return this._prototypeChain.has(pattern); + } + })); + } + return false; + })).reduce(((acc, _ref13) => { + var {extension: extension} = _ref13; + acc.push(extension); + return acc; + }), []); + } + get _extensionApplied() { + return this._currentComponentExtensionLength === this._appliedExtensionLength; + } + _construct() { + this._appliedExtensionLength = 0; + this._extendedList = {}; + this._extensionInstance = {}; + this._setupExtensionBound = this._setupExtension.bind(this); + contextInstance.on("themeUpdate", this._setupExtensionBound); + this._currentComponentExtensionLength = this._calculateComponentExtensionLength(); + this._createExtension(); + super._construct(); + } + _detach() { + super._detach(); + contextInstance.off("themeUpdate", this._setupExtensionBound); + } + _setupExtension() { + this._currentComponentExtensionLength = this._calculateComponentExtensionLength(); + this._createExtension.call(this); + } + _resetComponent() { + this._extensionInstance._extensionCleanup && this._extensionInstance._extensionCleanup.call(this); + (Object.keys(this._extendedList) || []).forEach((prop => { + delete this[prop]; + delete this[prop + SUFFIX]; + })); + this._extensionInstance = {}; + this._extendedList = {}; + } + _calculateComponentExtensionLength() { + var extensionLength = this._componentExtensions.reduce(((acc, extensionMixin) => { + acc += extensionMixin.toString().length; + return acc; + }), 0); + return extensionLength; + } + _createExtension() { + if (this._extensionApplied) return; + this._resetComponent(); + var ExtendedClass = this._createExtensionClass(); + var instance = new ExtendedClass; + this._extendedList = this._createExtensionAliases(instance); + this._extensionInstance = instance; + this._setComponentAliases(this._extendedList); + } + _createExtensionClass() { + function ExtensionBase() {} + var ExtendedClass = this._componentExtensions.reduce(((acc, extension) => extension(acc)), ExtensionBase); + this._appliedExtensionLength = this._calculateComponentExtensionLength(); + return ExtendedClass; + } + _createExtensionAliases(obj) { + var baseProto = obj; + for (var i = 0; i < this._componentExtensions.length + 1; i++) { + baseProto = Object.getPrototypeOf(baseProto); + } + var extended = {}; + var extensionOverrides = this._componentExtensions.reduce(((acc, extension) => { + var extensionClass = new extension(class FakeClass {}); + var instance = new extensionClass; + var originalComponentDescriptors = Object.getOwnPropertyDescriptors(Object.getPrototypeOf(instance)); + Object.keys(originalComponentDescriptors).forEach((prop => { + if ([ "constructor" ].includes(prop)) return; + if (originalComponentDescriptors[prop].get || originalComponentDescriptors[prop].set) { + extended[prop] = { + type: "accessor" + }; + acc[prop] = { + get: function get() { + return this[prop + SUFFIX]; + }, + set: function set(v) { + this[prop + SUFFIX] = v; + } + }; + return; + } + extended[prop] = { + type: "method" + }; + acc[prop] = { + value: function value() { + this[prop + SUFFIX] && this[prop + SUFFIX](); + } + }; + })); + return acc; + }), {}); + Object.defineProperties(baseProto, extensionOverrides); + Object.setPrototypeOf(baseProto, this); + return extended; + } + _setComponentAliases(aliasObj) { + Object.keys(aliasObj).forEach((prop => { + this[prop + SUFFIX] = this[prop]; + if (aliasObj[prop].type === "method") { + this[prop] = this._extensionInstance[prop]; + } else if (aliasObj[prop].type === "accessor") { + Object.defineProperty(this, prop, { + configurable: true, + get() { + return this._extensionInstance[prop]; + }, + set(v) { + this._extensionInstance[prop] = v; + } + }); + } + })); + } + }; +} + +class Base extends _lightningjs_core__WEBPACK_IMPORTED_MODULE_0__.Component { + static get __componentName() { + return "Base"; + } + _construct() { + this.constructor.__componentName; + this.skipPlinko = false; + this.centerInParent = false; + if (!this.loaded) this.loaded = Promise.resolve(); + } + _init() { + this.queueRequestUpdate(); + } + _resetLoadedPromise() { + this.loaded = new Promise(((resolve, reject) => { + this._resolveLoadedPromise = resolve; + this._rejectLoadedPromise = reject; + })); + } + _update() {} + _focus() { + this._updateShouldSmooth(); + this.queueRequestUpdate(); + } + _unfocus() { + this.queueRequestUpdate(); + } + _updateShouldSmooth() { + if (this.shouldSmooth === undefined) this.shouldSmooth = true; + } + applySmooth(ref, patch, smooth) { + if (this.shouldSmooth) { + ref.smooth = smooth || patch; + } else { + ref.patch(patch); + } + } + get announce() { + return this._announce; + } + set announce(announce) { + this._announce = announce; + } + get announceContext() { + return this._announceContext; + } + set announceContext(announce) { + this._announceContext = announce; + } + get shouldSmooth() { + return this._shouldSmooth; + } + set shouldSmooth(shouldSmooth) { + this._shouldSmooth = shouldSmooth; + } + get _isDisabledMode() { + return this.mode === "disabled"; + } + get _isUnfocusedMode() { + return this.mode === "unfocused"; + } + get _isFocusedMode() { + return this.mode === "focused"; + } + isFullyOnScreen(offsets) { + return isComponentOnScreen(this, offsets); + } + getFocusScale() { + return contextInstance.theme.layout.focusScale; + } + getUnfocusScale() { + return 1; + } +} + +function withMixins(baseComponent) { + return withExtensions(withLayout(withThemeStyles(withUpdates(withTags(withHandleKey(baseComponent)))))); +} + +var Base$1 = withMixins(Base); + +var base$R = theme => ({ + gradientTop: theme.color.fillTransparent, + radius: theme.radius.none +}); + +var tone$p = theme => ({ + neutral: { + gradientColor: theme.color.material + }, + inverse: { + gradientColor: theme.color.fillNeutral + }, + brand: { + gradientColor: theme.color.fillBrand + } +}); + +var styles$S = Object.freeze({ + __proto__: null, + base: base$R, + tone: tone$p +}); + +class Gradient extends Base$1 { + static get __componentName() { + return "Gradient"; + } + static get __themeStyle() { + return styles$S; + } + _update() { + this.patch({ + rect: true, + rtt: true, + colorTop: this.style.gradientTop, + colorBottom: this.style.gradientColor, + texture: _lightningjs_core__WEBPACK_IMPORTED_MODULE_0__.Tools.getRoundRect(this.w, this.h, getMaxRoundRadius(this.style.radius, this.w, this.h)) + }); + } +} + +var base$Q = theme => ({ + animationBlurEntrance: theme.animation.utilityEntrance, + animationBlurExit: theme.animation.utilityExit, + animationComponentEntrance: theme.animation.utilityEntrance, + animationGradientEntrance: theme.animation.utilityEntrance, + animationGradientExit: theme.animation.utilityExit, + animationImageScaleEntrance: theme.animation.standardEntrance, + animationImageScaleExit: theme.animation.standardEntrance, + blur: 4, + centerImageRadius: theme.radius.md, + fallbackSrc: undefined, + fillColor: theme.color.overlay, + gradientColor: theme.color.material, + imageScale: 1, + imageScalePivotX: .5, + imageScalePivotY: .5, + padding: theme.spacer.md, + radius: 0, + zIndexSet: { + image: 1, + blur: 2, + centerImage: 3, + fill: 4, + gradient: 5, + foreground: 6 + } +}); + +var styles$R = Object.freeze({ + __proto__: null, + base: base$Q +}); + +function checkFileType(str) { + if (str.startsWith(" { + canvas.width = w; + canvas.height = h; + ctx.drawImage(img, 0, 0, canvas.width, canvas.height); + cb(null, { + source: canvas, + w: w, + h: h + }); + }; + img.onerror = err => { + cb(err); + }; + if (!_lightningjs_core__WEBPACK_IMPORTED_MODULE_0__.Utils.isPS4) { + img.crossOrigin = "Anonymous"; + } + img.src = url; +} + +function imageLoader(_ref14, cb) { + var {src: src} = _ref14; + var image = new Image; + if (!(src.substr(0, 5) == "data:") && !_lightningjs_core__WEBPACK_IMPORTED_MODULE_0__.Utils.isPS4) { + image.crossOrigin = "Anonymous"; + } + image.onerror = function() { + if (image.src) { + return cb("Image load error"); + } + }; + image.onload = function() { + cb(null, { + source: image, + renderInfo: { + src: src, + compressed: false + }, + hasAlpha: true + }); + }; + image.src = src; + return function() { + image.onerror = null; + image.onload = null; + image.removeAttribute("src"); + }; +} + +class CustomImageTexture extends _lightningjs_core__WEBPACK_IMPORTED_MODULE_0__.Texture { + constructor(stage) { + super(stage); + this._src = undefined; + this._hasAlpha = false; + } + get src() { + return this._src; + } + set src(v) { + if (this._src !== v) { + this._src = v; + this._changed(); + } + } + get hasAlpha() { + return this._hasAlpha; + } + set hasAlpha(v) { + if (this._hasAlpha !== v) { + this._hasAlpha = v; + this._changed(); + } + } + get w() { + return this._w; + } + set w(l) { + this._w = l; + this._changed(); + } + get h() { + return this._h; + } + set h(l) { + this._h = l; + this._changed(); + } + _getIsValid() { + return !!this._src; + } + _getLookupId() { + return this._src; + } + _getSourceLoader() { + var w = this._w; + var h = this._h; + var src = this._src; + var hasAlpha = this._hasAlpha; + if (this.stage.getOption("srcBasePath")) { + var fc = src.charCodeAt(0); + if (src.indexOf("//") === -1 && (fc >= 65 && fc <= 90 || fc >= 97 && fc <= 122 || fc == 46)) { + src = this.stage.getOption("srcBasePath") + src; + } + } + return cb => { + var fileType = checkFileType(src); + switch (fileType) { + case "SVG": + return createSvg(cb, this.stage, "data:image/svg+xml,".concat(encodeURIComponent(src)), w, h); + + case "Blob": + return imageLoader({ + src: src + }, cb); + + default: + return this.stage.platform.loadSrcTexture({ + src: src, + hasAlpha: hasAlpha + }, cb); + } + }; + } + getNonDefaults() { + var obj = super.getNonDefaults(); + if (this._src) { + obj.src = this._src; + } + return obj; + } +} + +class Artwork extends Base$1 { + static get __componentName() { + return "Artwork"; + } + static get __themeStyle() { + return styles$R; + } + static get properties() { + return [ "blur", "fallbackSrc", "foregroundHeight", "foregroundSrc", "foregroundWidth", "gradient", "format", "src", "fill", "shouldScale", "srcCallback", "srcCallbackAspectRatios" ]; + } + static get tags() { + return [ "Blur", "CenterImage", "FillColor", "ForegroundImage", "Gradient", "Image", "Item" ]; + } + static get aliasProperties() { + return [ { + prev: "foregroundH", + curr: "foregroundHeight" + }, { + prev: "foregroundW", + curr: "foregroundWidth" + } ]; + } + static _template() { + return { + rtt: true, + Image: {} + }; + } + get _shouldBlur() { + var shouldBur = this._blur || this._hasCenterImage; + this._Image.rtt = shouldBur; + return shouldBur; + } + get _hasCenterImage() { + return -1 < [ "circle", "square" ].indexOf(this.format) || "contain" === this.format && !this._aspectRatioEqual; + } + set w(v) { + if (v === super.w) return; + super.w = v; + this._componentSrc = this._generatePromise(); + } + get w() { + return super.w; + } + set h(v) { + if (v === super.h) return; + super.h = v; + this._componentSrc = this._generatePromise(); + } + get h() { + return super.h; + } + get _actualAspectRatio() { + if (!this.w || !this.h) return null; + return reduceFraction("".concat(this.w, "/").concat(this.h)).replace("/", "x"); + } + get _supportedAspectRatioHeights() { + return this.srcCallbackAspectRatios.map((ratio => { + var [rw, rh] = ratio.split("x").map((v => parseInt(v))); + var calcHeight = this.w / rw * rh; + return calcHeight; + })); + } + get _closestSupportedAspectRatio() { + var closest = this._supportedAspectRatioHeights.reduce(((prev, curr) => Math.abs(curr - this.h) < Math.abs(prev - this.h) ? curr : prev)); + return this.srcCallbackAspectRatios[this._supportedAspectRatioHeights.indexOf(closest)]; + } + get _processedImageSrc() { + var src = this.src || this.fallbackSrc; + if (src !== this.fallbackSrc && this.srcCallback && typeof this.srcCallback === "function") { + src = this.srcCallback({ + closestAspectRatio: this._closestSupportedAspectRatio, + aspectRatio: this._actualAspectRatio, + src: this.src, + w: this.w, + h: this.h + }); + } + return src && src.then ? src : Promise.resolve(src); + } + get _gradientPatch() { + return { + alpha: !this._Gradient && this.shouldSmooth ? .001 : 1, + style: { + gradientColor: getValidColor(this.style.gradientColor) + }, + h: this.h + 4, + type: Gradient, + w: this.w + 4, + x: -2, + y: -2, + zIndex: this.core.findZContext().zIndex + this.style.zIndexSet.gradient + }; + } + _construct() { + super._construct(); + this._srcCallbackAspectRatios = [ "16x9", "3x4", "4x3", "2x1", "1x1" ]; + } + _setSrc(v) { + this._componentSrc = this._generatePromise(); + return v; + } + _getFallbackSrc() { + return this._fallbackSrc || this.style && this.style.fallbackSrc; + } + _generatePromise() { + var resolvePromise, rejectPromise; + var complete = new Promise((function(resolve, reject) { + resolvePromise = resolve; + rejectPromise = reject; + })); + return { + complete: complete, + resolve: resolvePromise, + reject: rejectPromise + }; + } + _setup() { + this.alpha = .001; + this._componentSrc = this._generatePromise(); + this._aspectRatioEqual = false; + this._Image.on("txLoaded", this._resolveLoading.bind(this)); + this._Image.on("txError", this._rejectLoading.bind(this)); + } + _resolveLoading() { + this._aspectRatioEqual = this._Image.texture.source ? parseFloat(this.finalW / this.finalH).toFixed(2) === parseFloat(this._Image.texture.source.w / this._Image.texture.source.h).toFixed(2) : false; + this._componentSrc.resolve && this._componentSrc.resolve(); + this.signal("imageLoaded"); + } + _rejectLoading(error) { + this._componentSrc.reject && this._componentSrc.reject(error); + this.signal("imageLoadFailed"); + } + _update() { + var _this5 = this; + return _asyncToGenerator((function*() { + _this5._updateRadius(); + _this5._updateGradient(); + yield _this5._updateImage(); + _this5._updateFillColor(); + _this5._updateForegroundImage(); + if (!_this5.src) { + _this5._showComponent(); + return; + } + try { + yield _this5._componentSrc.complete; + yield _this5._updateCenterImage(); + _this5._updateBlur(); + _this5._showComponent(); + _this5._updateScale(); + } catch (e) { + _this5._handleImageLoadError(); + } + if (_this5.shouldSmooth === undefined) _this5.shouldSmooth = true; + }))(); + } + _updateScale() { + if (this.shouldScale) { + var imageScale; + switch (typeof this.style.imageScale) { + case "function": + imageScale = this.style.imageScale(this.w); + break; + + case "number": + imageScale = this.style.imageScale; + break; + + default: + imageScale = 1; + } + this._Image.smooth = { + pivotX: this.style.imageScalePivotX, + pivotY: this.style.imageScalePivotY, + scale: [ imageScale, this._Image.scale < imageScale ? this.style.animationImageScaleEntrance : this.style.animationImageScaleExit ] + }; + } else { + var scale = 1; + this._Image.smooth = { + scale: [ scale, this.style.animationImageScaleExit ] + }; + } + } + _handleImageLoadError() { + if (this.src === this.fallbackSrc) return; + contextInstance.error("Image ".concat(this._src, " failed to load")); + if (this.fallbackSrc && this.fallbackSrc !== this.src) { + this.src = this.fallbackSrc; + } + } + _showComponent() { + this.smooth = { + alpha: [ 1, this.style.animationComponentEntrance ] + }; + } + _updateForegroundImage() { + var _this6 = this; + return _asyncToGenerator((function*() { + if (!_this6._foregroundSrc) { + if (_this6._ForegroundImage) { + _this6.patch({ + ForegroundImage: undefined + }); + } + return; + } + var foregroundImagePatch = { + mount: .5, + x: _this6.w / 2, + y: _this6.h / 2, + zIndex: _this6.core.findZContext().zIndex + _this6.style.zIndexSet.foreground, + texture: { + type: CustomImageTexture, + src: _this6._foregroundSrc, + hasAlpha: true + } + }; + if (_this6.foregroundWidth && _this6.foregroundHeight) { + foregroundImagePatch.h = _this6.foregroundHeight; + foregroundImagePatch.w = _this6.foregroundWidth; + _this6.patch({ + ForegroundImage: foregroundImagePatch + }); + } else if (_this6.foregroundWidth || _this6.foregroundHeight) { + _this6.patch({ + ForegroundImage: _objectSpread(_objectSpread({}, foregroundImagePatch), {}, { + alpha: .001 + }) + }); + _this6._ForegroundImage.once("txLoaded", (() => { + var imageW = _this6._ForegroundImage.texture.getRenderWidth(); + var imageH = _this6._ForegroundImage.texture.getRenderHeight(); + _this6._ForegroundImage.patch({ + alpha: 1, + w: _this6.foregroundHeight ? _this6.foregroundHeight * (imageW / imageH) : _this6.foregroundWidth, + h: _this6.foregroundWidth ? _this6.foregroundWidth * (imageH / imageW) : _this6.foregroundHeight + }); + })); + } + _this6.patch({ + ForegroundImage: foregroundImagePatch + }); + }))(); + } + _updateBlur() { + if ((!this._shouldBlur || this._Image && this._Image.texture && this._Image.texture.src === this.fallbackSrc) && this._Blur) { + if (this.shouldSmooth) { + this._Blur._getTransition("alpha").once("finish", (() => { + this.patch({ + Blur: undefined + }); + })); + this._Blur.smooth = { + alpha: [ 0, this.style.animationBlurExit ] + }; + } else { + this.patch({ + Blur: undefined + }); + } + return; + } + if (!this._srcFailed && this._shouldBlur) { + this.patch({ + Blur: { + alpha: !this._Blur && this.shouldSmooth ? .001 : 1, + amount: this.style.blur, + zIndex: this.core.findZContext().zIndex + this.style.zIndexSet.blur, + content: { + Image: { + h: this.h, + texture: this._Image.getTexture(), + w: this.w + } + }, + h: this.h, + rtt: true, + type: _lightningjs_core__WEBPACK_IMPORTED_MODULE_0__.components.FastBlurComponent, + w: this.w + } + }); + if (this._Blur.alpha < 1) { + this._Blur.smooth = { + alpha: [ 1, this.style.animationBlurEntrance ] + }; + } + } + } + _updateCenterImage() { + if (this.format === "contain") { + this._updateFormatContain(); + } else if (this.format === "circle" || this.format === "square") { + this._updateFormatSquareCircle(); + } else if (this._CenterImage) { + this.patch({ + CenterImage: undefined + }); + } + } + _updateFormatContain() { + var _this7 = this; + return _asyncToGenerator((function*() { + if (_this7._CenterImage && _this7._CenterImage.mode !== _this7.format || _this7.src === _this7.fallbackSrc || _this7._aspectRatioEqual) { + _this7.patch({ + CenterImage: undefined + }); + if (_this7.src === _this7.fallbackSrc || _this7._aspectRatioEqual) { + _this7._Image.alpha = 1; + return; + } + } + var imageW; + var imageH; + var ratioW = Math.abs(_this7._Image.texture.source.w / _this7._Image.texture.source.h); + var ratioH = Math.abs(_this7._Image.texture.source.h / _this7._Image.texture.source.w); + if (_this7._Image.texture.source.w < _this7._Image.texture.source.h) { + if (_this7.h * ratioW < _this7.w) { + imageW = _this7.h * ratioW; + imageH = _this7.h; + } else { + imageW = _this7.w; + imageH = _this7.w * ratioH; + } + } else if (_this7._Image.texture.source.w > _this7._Image.texture.source.h) { + if (_this7.w * ratioH < _this7.h) { + imageW = _this7.w; + imageH = _this7.w * ratioH; + } else { + imageW = _this7.h * ratioW; + imageH = _this7.h; + } + } else { + imageW = Math.min(_this7.w, _this7.h); + imageH = imageW; + } + var src = yield _this7._processedImageSrc; + _this7.patch({ + CenterImage: { + format: _this7.format, + mount: .5, + w: imageW, + h: imageH, + x: _this7.w / 2, + y: _this7.h / 2, + zIndex: _this7.core.findZContext().zIndex + _this7.style.zIndexSet.centerImage, + texture: { + src: src, + resizeMode: { + h: imageH, + type: "cover", + w: imageW + }, + type: CustomImageTexture + } + } + }); + }))(); + } + _updateFormatSquareCircle() { + if (this._CenterImage && this._CenterImage.mode !== this.format || this.src === this.fallbackSrc) { + this.patch({ + CenterImage: undefined + }); + if (this.src === this.fallbackSrc) return; + } + var imageSize = Math.min(this.w, this.h) - this.style.padding * 2; + this.patch({ + CenterImage: { + format: this.format, + h: imageSize, + shader: { + radius: "circle" === this.format ? imageSize / 2 : this.style.centerImageRadius, + type: _lightningjs_core__WEBPACK_IMPORTED_MODULE_0__.shaders.RoundedRectangle + }, + w: imageSize, + zIndex: this.core.findZContext().zIndex + this.style.zIndexSet.centerImage, + Image: { + h: imageSize, + mount: .5, + rtt: true, + w: imageSize, + x: this.w / 2, + y: this.h / 2, + texture: { + src: this._Image.texture.src, + resizeMode: { + h: imageSize, + type: "cover", + w: imageSize + }, + type: CustomImageTexture + } + } + } + }); + } + _updateGradient() { + if (!this.gradient) { + if (this._Gradient) { + if (this.shouldSmooth) { + this._Gradient._getTransition("alpha").once("finish", (() => { + var transition = this._Gradient && this._Gradient._getTransition("alpha"); + if (!this.gradient && transition && transition.p === 1) this.patch({ + Gradient: undefined + }); + })); + this._Gradient.patch(this._gradientPatch); + this._Gradient.smooth = { + alpha: [ 0, this.style.animationGradientExit ] + }; + } else { + this.patch({ + Gradient: undefined + }); + } + } + return; + } + this._createGradient(); + } + _createGradient() { + this.patch({ + Gradient: this._gradientPatch + }); + if (this.shouldSmooth) { + this.applySmooth(this._Gradient, { + alpha: [ 1, this.style.animationGradientEntrance ] + }); + } + } + _updateImage() { + var _this8 = this; + return _asyncToGenerator((function*() { + _this8._aspectRatioEqual = false; + if (!_this8._processedImageSrc) { + if (_this8._Image) { + _this8._Image.texture = undefined; + } + return; + } + var src = yield _this8._processedImageSrc; + _this8._Image.patch({ + alpha: _this8.src !== _this8.fallbackSrc && (_this8._blur || _this8._hasCenterImage) ? .001 : 1, + h: _this8.h, + texture: { + type: CustomImageTexture, + src: src, + resizeMode: { + type: "cover", + w: _this8.w, + h: _this8.h + } + }, + w: _this8.w, + zIndex: _this8.core.findZContext().zIndex + _this8.style.zIndexSet.image + }); + }))(); + } + _updateFillColor() { + if (!this.fill) { + this.patch({ + FillColor: undefined + }); + } else { + this.patch({ + FillColor: { + rect: true, + w: this.w, + h: this.h, + color: this.style.fillColor, + zIndex: 5 + } + }); + } + } + _updateRadius() { + this.patch(this.style.radius ? { + shader: { + type: _lightningjs_core__WEBPACK_IMPORTED_MODULE_0__.shaders.RoundedRectangle, + radius: getMaxRoundRadius(this.style.radius, this.w, this.h) + } + } : { + shader: undefined + }); + } +} + +var tone$o = theme => ({ + neutral: { + color: theme.color.fillNeutral + }, + inverse: { + color: theme.color.fillInverse + }, + brand: { + color: theme.color.fillBrand + } +}); + +var styles$Q = Object.freeze({ + __proto__: null, + tone: tone$o +}); + +class Icon extends Base$1 { + static get __componentName() { + return "Icon"; + } + static get __themeStyle() { + return styles$Q; + } + static get properties() { + return [ "icon", "fixed", "color" ]; + } + _init() { + this.on("txLoaded", (() => { + if (!this.fixed) { + this._notify.bind(this)(); + } + })); + this.on("txError", this._handleTxtError.bind(this)); + } + _getColor() { + return this._color || this.style.color; + } + _notify() { + this.w = this.finalW; + this.h = this.finalH; + this.signal("itemChanged", this); + this.fireAncestors("$itemChanged"); + } + _handleTxtError() { + contextInstance.error("Unable to load icon ".concat(this._icon)); + this._icon = null; + this.texture = null; + } + _update() { + if (!this._icon) { + this.texture = null; + return; + } + this.patch(this._iconPatch); + } + get _iconPatch() { + var [isSvgTag, isSvgURI] = [ /^$/, /\.svg$/ ].map((regex => RegExp.prototype.test.bind(regex))); + var texture; + var svgTag = isSvgTag(this.icon); + var svgURI = isSvgURI(this.icon); + if (svgTag) { + texture = _lightningjs_core__WEBPACK_IMPORTED_MODULE_0__.Tools.getSvgTexture("data:image/svg+xml,".concat(encodeURIComponent(this.icon)), this.w, this.h); + } else if (svgURI) { + texture = _lightningjs_core__WEBPACK_IMPORTED_MODULE_0__.Tools.getSvgTexture(this.icon, this.w, this.h); + } else { + texture = { + type: CustomImageTexture, + w: this.w, + h: this.h, + src: this.icon + }; + } + var color = getValidColor(this._color || this.style.color); + var shader = this.radius || this.style.radius ? { + radius: this.radius || this.style.radius, + type: _lightningjs_core__WEBPACK_IMPORTED_MODULE_0__.shaders.RoundedRectangle + } : undefined; + return _objectSpread({ + texture: texture, + shader: shader + }, color ? { + colorUl: color, + colorUr: color, + colorBl: color, + colorBr: color + } : {}); + } +} + +var base$P = theme => ({ + contentSpacing: theme.spacer.xs, + offsetY: 1, + paddingX: theme.spacer.md, + paddingY: theme.spacer.xs, + radius: theme.radius.sm, + strokeWidth: theme.stroke.sm, + textStyle: _objectSpread(_objectSpread({}, theme.typography.tag1), {}, { + textAlign: "center" + }) +}); + +var tone$n = theme => ({ + neutral: { + backgroundColor: theme.color.fillInverseSecondary, + iconColor: theme.color.textNeutral, + textStyle: { + textColor: theme.color.textNeutral + }, + strokeColor: theme.color.strokeNeutralSecondary + }, + inverse: { + backgroundColor: theme.color.fillNeutralSecondary, + iconColor: theme.color.textInverse, + textStyle: { + textColor: theme.color.textInverse + }, + strokeColor: theme.color.strokeInverseSecondary + }, + brand: { + backgroundColor: theme.color.fillBrand, + iconColor: theme.color.textNeutral, + textStyle: { + textColor: theme.color.textNeutral + }, + strokeColor: theme.color.strokeInverseSecondary + } +}); + +var styles$P = Object.freeze({ + __proto__: null, + base: base$P, + tone: tone$n +}); + +class Badge extends Base$1 { + static _template() { + return { + Text: { + mountY: .5 + }, + Icon: { + type: Icon, + mountY: .5, + signals: { + itemChanged: "_updateLayout" + } + } + }; + } + static get __componentName() { + return "Badge"; + } + static get __themeStyle() { + return styles$P; + } + static get properties() { + return [ "title", "icon", "iconAlign", "iconWidth", "iconHeight" ]; + } + static get tags() { + return [ "Background", "Text", "Icon" ]; + } + _init() { + this._Text.on("txLoaded", this._updateLayout.bind(this)); + super._init(); + } + _update() { + this._updateText(); + this._updateIcon(); + this._updateLayout(); + this._updateVisibility(); + } + _updateVisibility() { + this.alpha = this.title || this.icon ? 1 : 0; + } + _updateLayout() { + this._updateWidth(); + this._updateBackground(); + this._updatePositions(); + this.signal("loadedBadge", this); + } + _updateBackground() { + var height = Math.max(this._Text.renderHeight, this._Icon.h) + this.style.paddingY * 2; + this.patch({ + h: height, + texture: _lightningjs_core__WEBPACK_IMPORTED_MODULE_0__.Tools.getRoundRect(this.w, height, getMaxRoundRadius(this.style.radius, this.w, height), this.style.strokeWidth, this.style.strokeColor, true, this.style.backgroundColor) + }); + } + _updateText() { + if (this._Text) { + this._Text.patch({ + text: _objectSpread(_objectSpread({}, this.style.textStyle), {}, { + text: this.title || "" + }) + }); + } + } + _updateIcon() { + this._Icon.patch({ + icon: this.icon, + w: this.iconWidth, + h: this.iconHeight, + style: { + color: getHexColor(this.style.iconColor) + } + }); + } + _updateWidth() { + var width = 0; + if (this.title && this.icon) { + width = this._Text.renderWidth + this._Icon.finalW + this.style.contentSpacing + this.style.paddingX * 2; + } else if (this.title) { + width = this._Text.renderWidth + this.style.paddingX * 2; + } else if (this.icon) { + width = this._Icon.finalW + this.style.paddingX * 2; + } + this.w = width; + } + _updatePositions() { + this._Icon.y = this.h / 2; + if (this.iconAlign === "left" && this.title && this.icon) { + this._Icon.x = this.style.paddingX; + this._Text.x = this._Icon.x + this._Icon.finalW + this.style.contentSpacing; + } else if (this.iconAlign === "right" && this.title && this.icon) { + this._Text.x = this.style.paddingX; + this._Icon.x = this._Text.x + this._Text.renderWidth + this.style.contentSpacing; + } else { + this._Text.x = this.style.paddingX; + this._Icon.x = this.style.paddingX; + } + this._Text.y = this._h / 2 + this.style.offsetY; + } + _getIconHeight() { + if (this.icon) { + return !this._Icon.finalH && this._Text ? this._Text.text.lineHeight : this._Icon.finalH; + } + return 0; + } + set announce(announce) { + super.announce = announce; + } + get announce() { + return this._announce || this.title; + } +} + +var base$O = theme => ({ + width: 0, + justify: "center", + minWidth: getWidthByColumnSpan(theme, 3), + paddingX: theme.spacer.xxxl, + paddingXNoTitle: theme.spacer.xl, + paddingY: theme.spacer.xl, + radius: theme.radius.sm, + contentSpacing: theme.spacer.md, + itemSpacing: theme.spacer.md, + textStyle: _objectSpread(_objectSpread({}, theme.typography.button1), {}, { + maxLines: 1, + textColor: theme.color.textNeutral + }), + contentColor: theme.color.fillNeutral +}); + +var mode$g = theme => ({ + focused: { + textStyle: { + textColor: theme.color.textInverse + }, + contentColor: theme.color.fillInverse, + tone: { + inverse: { + textStyle: { + textColor: theme.color.textNeutral + }, + contentColor: theme.color.fillNeutral + }, + brand: { + contentColor: theme.color.fillNeutral + } + } + }, + disabled: { + textStyle: { + textColor: theme.color.textNeutralDisabled + }, + contentColor: theme.color.fillNeutralDisabled + } +}); + +var styles$O = Object.freeze({ + __proto__: null, + base: base$O, + mode: mode$g +}); + +class FocusManager extends Base$1 { + static get __componentName() { + return "FocusManager"; + } + static get tags() { + return [ "Items" ]; + } + static get properties() { + return [ "direction", "wrapSelected" ]; + } + _construct() { + super._construct(); + this._selectedIndex = 0; + this._itemPosX = 0; + this._itemPosY = 0; + this.direction = this.direction || "row"; + } + _init() { + this._checkSkipFocus(); + } + get Items() { + if (!this.tag("Items")) { + this.patch({ + Items: {} + }); + } + return this._Items; + } + _setDirection(direction) { + var state = { + none: "None", + column: "Column", + row: "Row" + }[direction]; + if (state) { + this._setState(state); + } + return direction; + } + _getItems() { + return this._Items.children; + } + get items() { + return this.Items.children; + } + set items(items) { + this._resetItems(); + this._selectedIndex = 0; + this.appendItems(items); + this._checkSkipFocus(); + } + set itemPosX(x) { + this.Items.x = this._itemPosX = x; + } + get itemPosX() { + return this._itemPosX; + } + set itemPosY(y) { + this.Items.y = this._itemPosY = y; + } + get itemPosY() { + return this._itemPosY; + } + _resetItems() { + this.Items.childList.clear(); + this.Items.patch({ + w: 0, + h: 0, + x: this.itemPosX, + y: this.itemPosY + }); + if (this._lazyItems) { + this._lazyItems = null; + } + } + _appendLazyItem(item) { + this.appendItems([ item ]); + } + appendItems() { + var items = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : []; + this.Items.childList.a(items); + this._refocus(); + } + appendItemsAt() { + var items = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : []; + var idx = arguments.length > 1 ? arguments[1] : undefined; + var addIndex = Number.isInteger(idx) ? idx : this.Items.children.length; + this.shouldSmooth = false; + this._lastAppendedIdx = addIndex; + items.forEach(((item, itemIdx) => { + this.Items.childList.addAt(_objectSpread(_objectSpread({}, item), {}, { + parentFocus: this.hasFocus() + }), addIndex + itemIdx); + })); + if (this.selectedIndex >= this._lastAppendedIdx) { + this._selectedIndex += items.length; + } + this.requestUpdate(); + this._refocus(); + } + prependItems(items) { + this.appendItemsAt(items, 0); + } + removeItemAt(index) { + this.shouldSmooth = false; + this.Items.childList.removeAt(index); + if (this.selectedIndex > index || this.selectedIndex === this.Items.children.length) { + this._selectedIndex--; + } + this.requestUpdate(); + this._refocus(); + } + _checkSkipFocus() { + var initialSelection = this.Items.children[this.selectedIndex]; + if (initialSelection && initialSelection.skipFocus) { + this.selectNext(false); + } + } + get selected() { + return this.Items.children[this.selectedIndex]; + } + get selectedIndex() { + return this._selectedIndex; + } + set selectedIndex(index) { + this.prevSelected = this.selected; + if (!this.Items.children.length || !this.Items.children[index] || !this.Items.children[index].skipFocus) { + if (index !== this._selectedIndex) { + this._selectedIndex = index; + } + if (this.selected) { + this._selectedChange(this.selected, this.prevSelected); + } + this._refocus(); + } + } + _selectedChange(selected, prevSelected) { + this._render(selected, prevSelected); + this.signal("selectedChange", selected, prevSelected); + } + _render() {} + _firstFocusableIndex() { + if (!this.items.length) return 0; + var firstItem = this.items.reduce(((acc, item, idx) => { + if (!item.skipFocus) { + acc.push(_objectSpread(_objectSpread({}, item), {}, { + originalIdx: idx + })); + } + return acc; + }), []).shift(); + return firstItem.originalIdx; + } + _lastFocusableIndex() { + if (!this.items.length) return 0; + var lastItem = this.items.reduce(((acc, item, idx) => { + if (!item.skipFocus) { + acc.push(_objectSpread(_objectSpread({}, item), {}, { + originalIdx: idx + })); + } + return acc; + }), []).pop(); + return lastItem.originalIdx; + } + selectPrevious() { + this.shouldSmooth = true; + var hasFocusable = !!(this.items || []).filter((i => !i.skipFocus)).length; + if (this.selectedIndex === 0 && !this.wrapSelected || !hasFocusable) { + return false; + } + var previousItemIndex = this.items.map((item => !!item.skipFocus)).lastIndexOf(false, this._selectedIndex - 1); + if (previousItemIndex > -1) { + this.selectedIndex = previousItemIndex; + return true; + } else if (this.wrapSelected) { + this.selectedIndex = this._lastFocusableIndex(); + return true; + } + return false; + } + selectNext(shouldSmoothOverride) { + if (this._lazyItems && this._lazyItems.length) { + this._appendLazyItem(this._lazyItems.splice(0, 1)[0]); + } + this.shouldSmooth = shouldSmoothOverride !== null && shouldSmoothOverride !== void 0 ? shouldSmoothOverride : true; + var hasFocusable = !!(this.items || []).filter((i => !i.skipFocus)).length; + if (this.selectedIndex === this.Items.children.length - 1 && !this.wrapSelected || !hasFocusable) { + return false; + } + var nextIndex = this.items.findIndex(((item, idx) => !item.skipFocus && idx > this._selectedIndex)); + if (nextIndex > -1) { + this.selectedIndex = nextIndex; + return true; + } else if (this.wrapSelected) { + this.selectedIndex = this._firstFocusableIndex(); + return true; + } + return false; + } + _getIndexOfItemNear(selected, prev) { + var prevItem = prev.selected; + if (!selected || !selected.items || !selected.items.length || !prevItem) { + return 0; + } + var [itemX, itemY] = prevItem.core.getAbsoluteCoords(0, 0); + var prevMiddle = [ itemX + prevItem.w / 2, itemY + prevItem.h / 2 ]; + var selectedCoordArray = selected.items.map(((item, index) => ({ + index: index, + distance: !item.skipFocus ? getShortestDistance(prevMiddle, item) : null + }))).filter((item => null !== item.distance)).sort((function(a, b) { + return a.distance - b.distance; + })); + return selectedCoordArray[0].index; + } + _focus() { + super._focus(); + this.items.forEach((item => item.parentFocus = true)); + } + _unfocus() { + super._unfocus(); + this.items.forEach((item => item.parentFocus = false)); + } + _updateShouldSmooth() {} + _getFocused() { + var {selected: selected} = this; + if (selected) { + if (selected.focusRef) { + return selected.tag(selected.focusRef); + } else if (selected.cparent) { + return selected; + } + } + return this; + } + _updateTransitionTarget(element, property, newValue) { + if (element && element.transition(property) && !element.transition(property).isRunning() && element.transition(property).targetValue !== newValue) { + element.transition(property).updateTargetValue(newValue); + } + } + get onScreenItems() { + return this.Items.children.filter((child => this._isOnScreen(child))); + } + _isOnScreenCompletely(child) { + return child.isFullyOnScreen ? child.isFullyOnScreen() : isComponentOnScreen(child); + } + get fullyOnScreenItems() { + return this.Items.children.reduce(((rv, item) => { + if (item instanceof FocusManager) { + return [ ...rv, ...item.Items.children.filter(this._isOnScreenCompletely) ]; + } else if (this._isOnScreenCompletely(item)) { + return [ ...rv, item ]; + } else { + return rv; + } + }), []); + } + _isOnScreen() { + throw new Error("'_isOnScreen' must be implemented by 'row'/'column'"); + } + _isComponentHorizontallyVisible(child) { + var x = getX(child); + if (!Number.isFinite(x)) return false; + var transitionX = this.getTransitionXTargetValue(); + var px = this.core.renderContext.px; + var itemX = px + transitionX + x; + var [leftBounds = null, , clipWidth = null] = this.core._scissor || []; + var stageW = this.stage.w / this.stage.getRenderPrecision(); + var {w: w} = child; + var withinLeftStageBounds = itemX >= 0; + var withinRightStageBounds = itemX + w <= stageW; + if (!withinLeftStageBounds || !withinRightStageBounds) return false; + var withinLeftClippingBounds = true; + var withinRightClippingBounds = true; + if (Number.isFinite(leftBounds)) { + withinLeftClippingBounds = Math.round(itemX + w) >= Math.round(leftBounds); + withinRightClippingBounds = Math.round(itemX) <= Math.round(leftBounds + clipWidth); + } + return withinLeftClippingBounds && withinRightClippingBounds; + } + _isComponentVerticallyVisible(child) { + var y = getY(child); + if (!Number.isFinite(y)) return false; + var transitionY = this.getTransitionYTargetValue(); + var py = this.core.renderContext.py; + var [, topBounds = null, , clipHeight = null] = this.core._scissor || []; + var {h: h} = child; + var itemY = py + transitionY + y; + var stageH = this.stage.h / this.stage.getRenderPrecision(); + var withinTopStageBounds = itemY + h >= 0; + var withingBottomStageBounds = itemY <= stageH; + if (!withinTopStageBounds || !withingBottomStageBounds) return false; + var withinTopClippingBounds = true; + var withinBottomClippingBounds = true; + if (Number.isFinite(topBounds)) { + withinTopClippingBounds = Math.round(itemY + h) > Math.round(topBounds); + withinBottomClippingBounds = Math.round(itemY) < Math.round(topBounds + clipHeight); + } + return withinTopClippingBounds && withinBottomClippingBounds; + } + getTransitionXTargetValue() { + return this.Items.transition("x").targetValue; + } + getTransitionYTargetValue() { + return this.Items.transition("y").targetValue; + } + static _states() { + return [ class None extends(this){}, class Row extends(this){ + _handleLeft() { + return typeof this.onLeft === "function" ? this.onLeft(this) : this.selectPrevious(); + } + _handleRight() { + return typeof this.onRight === "function" ? this.onRight(this) : this.selectNext(); + } + }, class Column extends(this){ + _handleUp() { + return typeof this.onUp === "function" ? this.onUp(this) : this.selectPrevious(); + } + _handleDown() { + return typeof this.onDown === "function" ? this.onDown(this) : this.selectNext(); + } + } ]; + } +} + +var base$N = theme => ({ + alwaysScroll: false, + itemSpacing: theme.layout.gutterX, + itemTransition: theme.animation.utility, + neverScroll: false, + scrollIndex: 0 +}); + +var styles$N = Object.freeze({ + __proto__: null, + base: base$N +}); + +var directionPropNames = { + row: { + axis: "x", + crossAxis: "y", + lengthDimension: "w", + crossDimension: "h", + innerLengthDimension: "innerW", + innerCrossDimension: "innerH" + }, + column: { + axis: "y", + crossAxis: "x", + lengthDimension: "h", + crossDimension: "w", + innerLengthDimension: "innerH", + innerCrossDimension: "innerW" + } +}; + +class NavigationManager extends FocusManager { + static get __componentName() { + return "NavigationManager"; + } + static get __themeStyle() { + return styles$N; + } + static get properties() { + return [ ...super.properties, "alwaysScroll", "neverScroll", "scrollIndex", "autoResizeWidth", "autoResizeHeight", "lazyUpCount", "lazyUpCountBuffer", "waitForDimensions" ]; + } + _construct() { + super._construct(); + this.shouldSmooth = false; + this._lazyUpCountBuffer = 2; + } + _init() { + var {lengthDimension: lengthDimension, axis: axis} = this._directionPropNames; + if (!this[lengthDimension]) { + this._initComponentSize(); + } + this.Items.transition(axis).on("finish", this._transitionListener.bind(this)); + super._init(); + } + _initComponentSize() { + var {lengthDimension: lengthDimension} = this._directionPropNames; + if ((this === null || this === void 0 ? void 0 : this.parent.parent) instanceof NavigationManager && this !== null && this !== void 0 && this.parent.parent[lengthDimension]) { + this[lengthDimension] = this.parent.parent[lengthDimension]; + } else { + var parent = this.parent; + while (parent && !parent[lengthDimension]) { + parent = parent.parent; + } + this[lengthDimension] = parent && parent[lengthDimension] || this.stage.h / this.stage.getRenderPrecision(); + } + } + _update() { + this._updateLayout(); + } + _updateLayout() { + var {lengthDimension: lengthDimension, crossDimension: crossDimension, crossAxis: crossAxis, innerCrossDimension: innerCrossDimension} = this._directionPropNames; + var nextPosition = 0; + var maxCrossDimensionSize = 0; + var maxInnerCrossDimensionSize = 0; + var childrenToCenter = []; + var loadingChildren = []; + for (var i = 0; i < this.Items.children.length; i++) { + var child = this.Items.children[i]; + if (child.requestEarlyUpdate) { + var updateDidRun = child.requestEarlyUpdate(); + if (!updateDidRun && (child.w === 0 || child.h === 0)) { + child._updateLayout && child._updateLayout(); + } + } + var childCrossDimensionSize = this._calcCrossDimensionSize(child); + if (this.waitForDimensions && (!childCrossDimensionSize || !child[lengthDimension])) { + loadingChildren.push(child); + } + maxCrossDimensionSize = max(maxCrossDimensionSize, childCrossDimensionSize); + maxInnerCrossDimensionSize = max(maxInnerCrossDimensionSize, child[innerCrossDimension] || 0); + this.updatePositionOnAxis(child, nextPosition); + nextPosition += child[lengthDimension]; + if (i < this.Items.children.length - 1) { + var extraItemSpacing = child.extraItemSpacing || 0; + nextPosition += this.style.itemSpacing + extraItemSpacing; + } + if (child.centerInParent) { + var _childCrossDimensionSize = child.Items && child.Items[crossDimension] || child[crossDimension]; + if (_childCrossDimensionSize < this[crossDimension] || !this.Items[innerCrossDimension]) { + childrenToCenter.push({ + childIdx: i, + childCrossDimensionSize: _childCrossDimensionSize + }); + } + } else { + child[crossAxis] = 0; + } + } + var itemChanged = this.Items[crossDimension] !== maxCrossDimensionSize || this.Items[lengthDimension] !== nextPosition; + if (this.waitForDimensions) { + this.Items.alpha = loadingChildren.length ? .001 : 1; + } + this.Items.patch({ + [crossDimension]: maxCrossDimensionSize, + [innerCrossDimension]: maxInnerCrossDimensionSize || maxCrossDimensionSize, + [lengthDimension]: nextPosition + (this._totalAddedWidth || 0) + }); + this._autoResize(); + this._centerItemsInParent(childrenToCenter); + this._updateLastScrollIndex(); + if (itemChanged) { + this._performRender(); + this.fireAncestors("$itemChanged"); + } + } + _centerItemsInParent(items) { + var {crossDimension: crossDimension, crossAxis: crossAxis, innerCrossDimension: innerCrossDimension} = this._directionPropNames; + if (items.length) { + var sizes = [ this.Items[crossDimension], this.Items[innerCrossDimension] ]; + if (this.children.length === 1) { + sizes.push(this[crossDimension]); + } + var crossDimensionSize = Math.max(...sizes); + items.forEach((_ref15 => { + var {childIdx: childIdx, childCrossDimensionSize: childCrossDimensionSize} = _ref15; + this.Items.children[childIdx][crossAxis] = (crossDimensionSize - childCrossDimensionSize) / 2; + })); + } + } + _autoResize() { + if (this.autoResizeWidth) { + this.w = this.Items.w; + } + if (this.autoResizeHeight) { + this.h = this.Items.h; + } + } + _updateLastScrollIndex() { + var {axis: axis, lengthDimension: lengthDimension} = this._directionPropNames; + if (this.alwaysScroll) { + this._lastScrollIndex = this.Items.children.length - 1; + return; + } + var itemPos = this._isRow ? this.itemPosX : this.itemPosY; + var scrollOffset = (this.Items.children[this.scrollIndex] || { + [axis]: 0 + })[axis] + itemPos; + var lastChild = this.Items.childList.last; + var endOfLastChild = lastChild ? this._calcAxisPosition(lastChild) + lastChild[lengthDimension] : 0; + if (endOfLastChild > this[lengthDimension]) { + var lastScrollIndex; + for (var i = this.Items.children.length - 1; i >= 0; i--) { + var childPosition = this._calcAxisPosition(this.Items.children[i]); + var canScrollToChild = childPosition + this[lengthDimension] - scrollOffset > endOfLastChild; + if (canScrollToChild) { + lastScrollIndex = i; + } else { + break; + } + } + this._lastScrollIndex = lastScrollIndex; + return; + } + if (this._lastScrollIndex > this.items.length) { + this._lastScrollIndex = this.items.length - 1; + } + } + _calcCrossDimensionSize(comp) { + if (this._isRow) { + return getH(comp); + } + if (this._isColumn) { + return getW(comp); + } + } + _calcAxisPosition(comp) { + if (this._isRow) { + return getX(comp); + } + if (this._isColumn) { + return getY(comp); + } + } + _transitionListener() { + this.shouldSmooth = false; + this.transitionDone(); + } + _withAfterUpdate(element) { + return watchForUpdates({ + element: element, + watchProps: [ this._directionPropNames.crossAxis, "w", "h", "innerW", "innerH" ], + sideEffect: this.queueRequestUpdate.bind(this) + }); + } + _performRender() {} + _appendItem(item, shouldSmoothOverride) { + this.shouldSmooth = shouldSmoothOverride !== null && shouldSmoothOverride !== void 0 ? shouldSmoothOverride : false; + item.parentFocus = this.hasFocus(); + item = this.Items.childList.a(item); + var {crossDimension: crossDimension} = this._directionPropNames; + if (!item[crossDimension]) { + var itemCrossSize = this._isRow ? this.renderHeight : this.renderWidth; + item[crossDimension] = item[crossDimension] || itemCrossSize; + } + item = this._withAfterUpdate(item); + return item; + } + _appendLazyItem(item) { + var {lengthDimension: lengthDimension, axis: axis} = this._directionPropNames; + var lastChild = this._Items.children[this.items.length - 1]; + var nextPosition = lastChild[lengthDimension] + lastChild[axis] + (lastChild.extraItemSpacing || 0) + this.style.itemSpacing; + var appended = this._appendItem(item, true); + appended[axis] = nextPosition; + this._Items[lengthDimension] += nextPosition + item[lengthDimension]; + } + $itemChanged() { + this.queueRequestUpdate(); + } + appendItems() { + var items = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : []; + this.shouldSmooth = false; + if (this._lazyItems) { + this._lazyItems.push(...items); + return; + } + if (items.length > this.lazyUpCount + this.lazyUpCountBuffer) { + this._lazyItems = items.splice(this.lazyUpCount + this.lazyUpCountBuffer); + } + items.forEach((item => this._appendItem(item))); + this.requestUpdate(); + this._refocus(); + } + appendItemsAt() { + var items = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : []; + var idx = arguments.length > 1 ? arguments[1] : undefined; + if (this._lazyItems && idx > this.items.length - 1) { + var addAtIdx = idx - this.items.length; + this._lazyItems.splice(addAtIdx, 0, ...items); + return; + } + var {crossDimension: crossDimension, lengthDimension: lengthDimension, innerLengthDimension: innerLengthDimension} = this._directionPropNames; + var addIndex = Number.isInteger(idx) ? idx : this.Items.children.length; + this.shouldSmooth = false; + this._lastAppendedIdx = addIndex; + this._totalAddedLength = 0; + items.forEach(((item, itemIdx) => { + var newItem = _objectSpread(_objectSpread({}, this._withAfterUpdate(item)), {}, { + parentFocus: this.hasFocus() + }); + if (!item[crossDimension]) { + newItem[crossDimension] = item[crossDimension] || this.Items[crossDimension]; + } + this.Items.childList.addAt(newItem, addIndex + itemIdx); + var itemLength = item[lengthDimension] || item[innerLengthDimension] || 0; + var extraItemSpacing = item.extraItemSpacing || 0; + this._totalAddedLength += itemLength + this.style.itemSpacing + extraItemSpacing; + })); + if (this.selectedIndex >= this._lastAppendedIdx) { + this._selectedPastAdded = true; + this._selectedIndex += items.length; + } + this.requestUpdate(); + this._refocus(); + } + updatePositionOnAxis(item, position) { + var {axis: axis} = this._directionPropNames; + this.applySmooth(item, { + [axis]: position + }, { + [axis]: [ position, this.style.itemTransition ] + }); + if (!this.shouldSmooth) { + this._updateTransitionTarget(item, axis, position); + } + } + scrollTo(index) { + var duration = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : this.style.itemTransition.duration * 100; + if (index == undefined) { + return; + } + if (duration === 0) { + this.selectedIndex = index; + return; + } + for (var i = 0; i !== Math.abs(this.selectedIndex - index); i++) { + setTimeout((() => { + this.selectedIndex > index ? this.selectPrevious() : this.selectNext(); + }), duration * i); + } + } + transitionDone() {} + shouldScrollLeft() { + return this._isRow && this._canScrollBack; + } + shouldScrollRight() { + return this._isRow && this._canScrollNext; + } + shouldScrollUp() { + return this._isColumn && this._canScrollBack; + } + shouldScrollDown() { + return this._isColumn && this._canScrollNext; + } + get _directionPropNames() { + return directionPropNames[this.direction]; + } + get _canScrollBack() { + var shouldScroll = false; + if (this._lastScrollIndex) { + shouldScroll = this.selectedIndex < this._lastScrollIndex; + if (this._prevLastScrollIndex !== undefined && this._prevLastScrollIndex !== this._lastScrollIndex) { + shouldScroll = true; + } + } else { + shouldScroll = this.selectedIndex >= this.scrollIndex; + } + var itemsStartCoord = this._isRow ? this._itemsX : this._itemsY; + return itemsStartCoord < (this._isRow ? this.itemPosX : this.itemPosY) && shouldScroll; + } + get _canScrollNext() { + var {axis: axis, lengthDimension: lengthDimension} = this._directionPropNames; + var lastChild = this.Items.childList.last; + var endOfItemsPosition; + if (this._isRow) { + endOfItemsPosition = Math.abs(this._itemsX - this.w); + } + if (this._isColumn) { + endOfItemsPosition = Math.abs(this._itemsY - this.h); + } + return this.selectedIndex > this.scrollIndex && endOfItemsPosition < lastChild[axis] + lastChild[lengthDimension]; + } + get _isColumn() { + return this.direction === "column"; + } + get _isRow() { + return this.direction === "row"; + } + get _itemsX() { + return getX(this.Items); + } + get _itemsY() { + return getY(this.Items); + } + _getAlwaysScroll() { + return this._alwaysScroll !== undefined ? this._alwaysScroll : this.style.alwaysScroll; + } + _getNeverScroll() { + if (this.alwaysScroll) { + return false; + } + return this._neverScroll !== undefined ? this._neverScroll : this.style.neverScroll; + } + _setScrollIndex(index) { + return index >= 0 ? index : 0; + } + _getScrollIndex() { + return this._scrollIndex !== undefined ? this._scrollIndex : this.style.scrollIndex; + } + _setLazyUpCountBuffer(buffer) { + if (buffer < 0) { + console.warn("lazyUpCountBuffer must be greater than or equal to 0. Setting to 0."); + buffer = 0; + } + return buffer; + } + isFullyOnScreen() { + var _this$parent; + var {offsetX: offsetX = 0, offsetY: offsetY = 0} = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + var focusmanager = (_this$parent = this.parent) === null || _this$parent === void 0 ? void 0 : _this$parent.parent; + if (focusmanager instanceof FocusManager) { + offsetX += focusmanager.Items.transition("x").targetValue || 0; + offsetY += focusmanager.Items.transition("y").targetValue || 0; + } + return super.isFullyOnScreen({ + offsetX: offsetX, + offsetY: offsetY + }); + } +} + +var base$M = theme => ({ + itemSpacing: theme.layout.gutterX, + scrollIndex: 0, + alwaysScroll: false, + neverScroll: false, + itemTransition: _objectSpread(_objectSpread({}, theme.animation.standardEntrance), {}, { + duration: theme.animation.duration.fast + }) +}); + +var styles$M = Object.freeze({ + __proto__: null, + base: base$M +}); + +class Row extends NavigationManager { + static get __componentName() { + return "Row"; + } + static get __themeStyle() { + return styles$M; + } + static _template() { + return _objectSpread(_objectSpread({}, super._template()), {}, { + direction: "row" + }); + } + static get properties() { + return [ ...super.properties, "lazyScroll", "startLazyScrollIndex", "stopLazyScrollIndex" ]; + } + _isOnScreenForScrolling(child) { + if (!child) return false; + var x = getX(child); + if (!Number.isFinite(x)) return false; + var itemsTransitionX = this.getTransitionXTargetValue(); + var rowX = this.core.renderContext.px; + var itemX = rowX + itemsTransitionX + x; + var xModifier; + if (child.transition("x")) { + xModifier = child.x - child.transition("x").targetValue; + itemX = itemX - xModifier; + } + return itemX >= rowX && itemX + child.w <= rowX + this.w; + } + _shouldScroll() { + var prevIndex = this.Items.childList.getIndex(this.prevSelected); + if (this.alwaysScroll || this.lazyScroll && (this.selectedIndex < this.startLazyScrollIndex || this.selectedIndex > this.stopLazyScrollIndex || prevIndex < this.startLazyScrollIndex && this.selectedIndex === this.startLazyScrollIndex || prevIndex > this.stopLazyScrollIndex && this.selectedIndex === this.stopLazyScrollIndex)) { + return true; + } + var shouldScroll = this._selectedPastAdded; + if (!shouldScroll && !this.neverScroll) { + var isCompletelyOnScreen = this._isOnScreenForScrolling(this.selected); + if (this.lazyScroll) { + shouldScroll = !isCompletelyOnScreen; + } else { + var lastChild = this.Items.childList.last; + shouldScroll = lastChild && (this.shouldScrollLeft() || this.shouldScrollRight() || !isCompletelyOnScreen); + } + } + return shouldScroll; + } + _getPrependedOffset() { + this._selectedPastAdded = false; + return this.Items.x - this._totalAddedWidth; + } + _getLazyScrollX(prev) { + var prevIndex = this.Items.childList.getIndex(this.prevSelected); + if (this._selectedPastAdded) { + return this._getPrependedOffset(); + } + if (this.selectedIndex <= this.startLazyScrollIndex) { + return this._getScrollX(); + } else if (this.selectedIndex >= this.stopLazyScrollIndex && this.selectedIndex < prevIndex) { + var currItemsX = this.Items.x; + return currItemsX + (this.prevSelected.w + this.style.itemSpacing + (this.selected.extraItemSpacing || 0)); + } else if (prev && this.selectedIndex > this.stopLazyScrollIndex) { + var prevX = prev.x; + return -prevX + this.prevSelected.w + this.style.itemSpacing + (this.selected.extraItemSpacing || 0) + this.itemPosX; + } else if (prev) { + var itemsContainerX; + var _prevIndex = this.Items.childList.getIndex(prev); + var selectedX = this.selected.x; + if (_prevIndex === -1) { + return; + } + if (_prevIndex > this.selectedIndex) { + itemsContainerX = -selectedX + this.itemPosX; + } else if (_prevIndex < this.selectedIndex) { + itemsContainerX = this.w - selectedX - this.selected.w; + } + return itemsContainerX; + } + return this._getScrollX(); + } + _getScrollX() { + if (this._selectedPastAdded) { + return this._getPrependedOffset(); + } + var itemsContainerX; + var itemIndex = this.selectedIndex - this.scrollIndex; + itemIndex = itemIndex < 0 ? 0 : itemIndex; + if (itemIndex === this._firstFocusableIndex()) { + itemIndex = 0; + } + if (this.Items.children[itemIndex]) { + itemsContainerX = this.Items.children[itemIndex].transition("x") ? -this.Items.children[itemIndex].transition("x").targetValue + this.itemPosX : -this.Items.children[itemIndex].x + this.itemPosX; + } + return itemsContainerX; + } + _render(next, prev) { + if (this.plinko && prev && prev.selected) { + next.selectedIndex = this._getIndexOfItemNear(next, prev); + } + this._prevLastScrollIndex = this._lastScrollIndex; + var itemsContainerX; + if (!this.Items.children.length) { + itemsContainerX = this.itemPosX; + } else if (this._shouldScroll()) { + itemsContainerX = this.lazyScroll && prev ? this._getLazyScrollX(prev) : this._getScrollX(); + } + if (itemsContainerX !== undefined) { + this.updatePositionOnAxis(this.Items, itemsContainerX); + } + this.onScreenEffect(this.onScreenItems); + } + _performRender() { + this._render(this.selected, this.prevSelected); + } + _isOnScreen(child) { + if (!child) return false; + return this._isComponentHorizontallyVisible(child); + } + onScreenEffect() {} + get _totalAddedWidth() { + return this._totalAddedLength; + } + _getLazyScroll() { + if (this.alwaysScroll) { + return false; + } + return this._lazyScroll !== undefined ? this._lazyScroll : this.style.lazyScroll; + } + _getNeverScroll() { + if (this.alwaysScroll || this.lazyScroll) { + return false; + } + return this._neverScroll !== undefined ? this._neverScroll : this.style.neverScroll; + } +} + +var base$L = theme => ({ + backgroundColor: theme.color.interactiveNeutral, + radius: theme.radius.md, + animation: {} +}); + +var tone$m = theme => ({ + inverse: { + backgroundColor: theme.color.interactiveInverse + } +}); + +var mode$f = theme => ({ + focused: { + backgroundColor: theme.color.interactiveNeutralFocus, + tone: { + inverse: { + backgroundColor: theme.color.interactiveInverseFocus + } + } + }, + disabled: { + backgroundColor: theme.color.fillNeutralDisabled + } +}); + +var styles$L = Object.freeze({ + __proto__: null, + base: base$L, + mode: mode$f, + tone: tone$m +}); + +class Surface extends Base$1 { + static _template() { + return { + Background: {} + }; + } + static get __componentName() { + return "Surface"; + } + static get __themeStyle() { + return styles$L; + } + static get properties() { + return []; + } + static get tags() { + return [ "Background" ]; + } + get innerH() { + return this.h; + } + get innerW() { + return this.w; + } + get _radius() { + return getMaxRoundRadius(this.style.radius, this.w, this.h); + } + _update() { + this._updateLayout(); + this._updateScale(); + } + _updateLayout() { + this._Background.patch({ + texture: _lightningjs_core__WEBPACK_IMPORTED_MODULE_0__.Tools.getRoundRect(this.innerW - 2, this.innerH - 2, this._radius, 0, null, true, this.style.backgroundColor) + }); + } + _updateScale() { + var scale = this._isFocusedMode ? this.getFocusScale(this.w, this.h) : this.getUnfocusScale(this.w, this.h); + this.applySmooth(this, { + scale: scale + }, { + scale: [ scale, this.style.animation ] + }); + } +} + +var base$K = theme => ({ + offsetY: theme.spacer.xxs, + offsetX: 0, + textStyle: theme.typography.body1 +}); + +var tone$l = theme => ({ + neutral: { + textStyle: { + textColor: theme.color.fillNeutral + } + }, + inverse: { + textStyle: { + textColor: theme.color.fillInverse + } + }, + brand: { + textStyle: { + textColor: theme.color.fillBrand + } + } +}); + +var styles$K = Object.freeze({ + __proto__: null, + base: base$K, + tone: tone$l +}); + +var base$J = theme => ({ + textY: 0, + iconWidth: theme.spacer.xxl + theme.spacer.xs, + iconHeight: theme.spacer.xxl + theme.spacer.xs, + contentSpacing: theme.spacer.md, + marginBottom: 0, + strikethroughRatio: .08, + strikethroughColor: theme.color.textNeutral, + textStyle: _objectSpread({}, theme.typography.body1), + maxLines: 1, + justify: "flex-start" +}); + +var styles$J = Object.freeze({ + __proto__: null, + base: base$J +}); + +var isText = item => typeof item === "string" || !!item.text; + +var isIcon = item => !!item.icon; + +var isBadge = item => !!item.badge; + +class InlineContent extends Base$1 { + static get properties() { + return [ "content", "contentProperties", "badgeY", "badgeProperties", "justify", "contentWrap", "customStyleMappings", "maxLines", "maxLinesSuffix" ]; + } + static get __componentName() { + return "InlineContent"; + } + static get __themeStyle() { + return styles$J; + } + static get aliasStyles() { + return [ { + prev: "iconH", + curr: "iconHeight" + }, { + prev: "iconW", + curr: "iconWidth" + } ]; + } + _construct() { + super._construct(); + this._maxLinesSuffix = ".."; + } + _update() { + this._updateContent(); + this._waitForComponentLoad(); + } + _updateContent() { + this.childList.clear(); + if (this._shouldTruncate) { + this.alpha = .001; + } + if (this._parsedContent && this._parsedContent.length) { + this.patch({ + flex: { + direction: "row", + wrap: !!this.contentWrap, + justifyContent: this.justify != undefined ? this.justify : this.style.justify + } + }); + this._parsedContent.forEach(((item, index) => { + var isLast = index === this._parsedContent.length - 1; + var base = { + flexItem: _objectSpread(_objectSpread({}, this.contentProperties), {}, { + marginBottom: isLast ? 0 : this._marginBottom, + marginRight: isLast ? 0 : this.contentProperties.marginRight || this.style.contentSpacing + }) + }; + if (isText(item)) { + var nextItem = this._parsedContent[index + 1]; + if (nextItem && isText(nextItem) || this.contentWrap && nextItem && nextItem.newline && this._parsedContent[index + 2] && isText(this._parsedContent[index + 2])) { + base.flexItem.marginRight = 0; + } + this.childList.a(this._createText(base, item)); + } else if (isIcon(item)) { + this.childList.a(this._createIcon(base, item)); + } else if (isBadge(item)) { + this.childList.a(this._createBadge(base, item.badge)); + } else if (item.newline && this.contentWrap) { + this.childList.a({ + h: 0, + w: this.w + }); + } + })); + } + } + _waitForComponentLoad() { + if (this.children.length) { + Promise.all(this.children.map((child => new Promise((resolve => { + if (child.h === 0 && child.w === this.w) { + resolve(); + } else { + child.on("txLoaded", resolve); + } + }))))).finally((() => this._contentLoaded())); + } else { + this.h = 0; + this._contentLoaded(); + } + } + _notifyAncestors() { + this.fireAncestors("$loadedInlineContent", this); + this.signal("loadedInlineContent", this.finalW, this.multiLineHeight); + } + _contentLoaded() { + if (this.children.length) { + setTimeout((() => { + this.multiLineHeight = this.finalH; + if (this.flex && this.flex._layout && this.flex._layout._lineLayouter && this.flex._layout._lineLayouter._lines) { + var totalHeight = 0; + this.flex._layout._lineLayouter._lines.forEach((line => { + totalHeight += Object.entries(line.items).slice(line.startIndex, line.endIndex + 1).sort(((a, b) => b[1].h - a[1].h))[0][1].h; + })); + this.multiLineHeight = totalHeight; + if (this._shouldTruncate) { + this._renderMaxLines(); + } + this._notifyAncestors(); + } else { + this._contentLoaded(); + } + }), 10); + } else { + this._notifyAncestors(); + } + } + _renderMaxLines() { + var childrenDimensions = this._calcChildrenDimensions(); + this.childList.clear(); + var renderedLastElement = false; + childrenDimensions.forEach(((child, index) => { + if (renderedLastElement) { + return; + } + var nextChild = childrenDimensions[index + 1]; + if (!nextChild) { + this.childList.add(child.component); + return; + } + var isOnLastLine = child.line === this.maxLines; + var isLastBeforeMaxLines = isOnLastLine && nextChild.line > this.maxLines; + var canRenderLastWithSuffix = isLastBeforeMaxLines && child.hasSpaceForSuffix; + var isLastWithSpaceForSuffix = isOnLastLine && child.hasSpaceForSuffix && !nextChild.hasSpaceForSuffix; + var isLast = !nextChild || canRenderLastWithSuffix || isLastWithSpaceForSuffix; + if (child.line <= this.maxLines) { + if (isLast && index !== childrenDimensions.length - 1) { + this.childList.add(this._addSuffix(child)); + renderedLastElement = true; + } else { + this.childList.add(child.component); + } + } + })); + this.alpha = 1; + } + _calcChildrenDimensions() { + var suffixW = measureTextWidth(_objectSpread(_objectSpread({}, this.style.textStyle), {}, { + text: this.maxLinesSuffix + })); + var contentEndX = 0; + var line = 1; + return this.children.reduce(((acc, child) => { + var component = child; + var type, content, w; + var isNewLineElement = child.w == this.w && child.h === 0; + if (isNewLineElement) { + line++; + contentEndX = 0; + var _data = { + type: "linebreak", + component: component, + content: content, + line: line, + hasSpaceForSuffix: true + }; + acc.push(_data); + return acc; + } + if (isText(child)) { + type = "text"; + content = child.text.text; + w = child.texture.getRenderWidth(); + } else if (isIcon(child)) { + type = "icon"; + w = child.w; + } else if (child.constructor.__componentName === "Badge") { + type = "badge"; + w = child.w; + } + contentEndX += w; + contentEndX += child.flexItem.marginRight; + if (Math.ceil(contentEndX) >= this.w) { + line++; + contentEndX = w; + } + var hasSpaceForSuffix = Math.ceil(contentEndX) + suffixW <= this.w; + var data = { + type: type, + component: component, + content: content, + line: line, + hasSpaceForSuffix: hasSpaceForSuffix + }; + acc.push(data); + return acc; + }), []); + } + _addSuffix(_ref16) { + var {type: type, component: component, content: content} = _ref16; + var negatedRightMargin = component.flexItem.marginRight * -1; + var suffix; + if (type === "text") { + var {fontFace: fontFace, fontSize: fontSize, fontStyle: fontStyle, lineHeight: lineHeight, verticalAlign: verticalAlign} = component.text; + suffix = this._createText({ + flexItem: this.contentProperties + }, { + text: "".concat(content.trim()).concat(this.maxLinesSuffix), + style: { + fontFace: fontFace, + fontSize: fontSize, + fontStyle: fontStyle, + lineHeight: lineHeight, + verticalAlign: verticalAlign + } + }); + } else { + this.childList.add(component); + suffix = this._createText({ + flexItem: _objectSpread(_objectSpread({}, this.contentProperties), {}, { + marginLeft: negatedRightMargin + }) + }, this.maxLinesSuffix); + } + return suffix; + } + _createIcon(base, iconProps) { + var y = (this.textHeight > this.style.textStyle.lineHeight ? this.textHeight : this.style.textStyle.lineHeight) - this.style.iconHeight; + return _objectSpread(_objectSpread({}, base), {}, { + type: Icon, + y: y, + w: this.style.iconWidth, + h: this.style.iconHeight, + signals: { + itemChanged: "_updateIconPosition" + } + }, iconProps); + } + _createText(base, text) { + var textOverrideStyles = typeof text.style === "string" ? this.customStyleMappings[text.style] : text.style; + var textComponent = _objectSpread(_objectSpread({}, base), {}, { + y: this.textY !== undefined ? this.textY : this.style.textY, + h: (textOverrideStyles === null || textOverrideStyles === void 0 ? void 0 : textOverrideStyles.lineHeight) || (textOverrideStyles === null || textOverrideStyles === void 0 ? void 0 : textOverrideStyles.fontSize) || this.textHeight, + text: _objectSpread(_objectSpread(_objectSpread({}, this.style.textStyle), textOverrideStyles), {}, { + text: text.text || text + }) + }); + if ((textOverrideStyles === null || textOverrideStyles === void 0 ? void 0 : textOverrideStyles.textDecoration) === "line-through") { + var textWidth = measureTextWidth(_objectSpread(_objectSpread(_objectSpread({}, this.style.textStyle), textOverrideStyles), {}, { + text: text.text || text + })); + var strikethroughLine = { + rect: true, + w: textWidth, + color: this.style.strikethroughColor || (textOverrideStyles === null || textOverrideStyles === void 0 ? void 0 : textOverrideStyles.textColor) || this.style.textStyle.textColor, + h: textComponent.h * this.style.strikethroughRatio, + y: textComponent.h / 2, + mountY: 1 + }; + return { + type: _lightningjs_core__WEBPACK_IMPORTED_MODULE_0__.Component, + w: textWidth + textComponent.flexItem.marginRight, + h: textComponent.h, + children: [ _objectSpread({}, textComponent), _objectSpread({}, strikethroughLine) ] + }; + } + return textComponent; + } + _createBadge(base, badge) { + return _objectSpread(_objectSpread(_objectSpread({}, base), {}, { + y: this.badgeY || 0 + }, this.badgeProperties), {}, { + type: Badge, + title: badge, + signals: { + loadedBadge: "_loadedBadge" + } + }); + } + _updateIconPosition(icon) { + icon.y = this.style.textStyle.lineHeight - icon.h; + } + _loadedBadge(badge) { + if (this.badgeY === undefined) { + badge.y = this.style.textStyle.lineHeight - badge.h; + } + } + _formatSpaces(parsedContent) { + var whitespace = /(.+?\s+)/; + return flatten((parsedContent || []).reduce(((acc, item) => { + var parsed = item; + if (isText(item)) { + if (typeof item === "object") { + var formattedWords = item.text.split(whitespace).map((word => word && _objectSpread(_objectSpread({}, item), {}, { + text: word + }))); + acc.push(...formattedWords); + return acc; + } + parsed = item.split(whitespace); + } + acc.push(parsed); + return acc; + }), [])).map(((item, index, arr) => { + if (item === " ") return false; + if (arr[index + 1] === " ") return item + " "; + return item; + })).filter(Boolean); + } + _setContent(content) { + if (content !== this._content) { + this._content = content; + var parsedContent = this._content; + if (content && !Array.isArray(content)) { + parsedContent = parseInlineContent(content); + } + this._parsedContent = this._formatSpaces(parsedContent); + } + return content; + } + _setBadgeProperties(badgeProperties) { + if (typeof badgeProperties === "object") { + return badgeProperties; + } + } + _getBadgeProperties() { + return this._badgeProperties || {}; + } + _setContentProperties(contentProperties) { + if (typeof contentProperties === "object") { + return contentProperties; + } + } + _getContentProperties() { + return this._contentProperties || {}; + } + _setCustomStyleMappings(customStyleMappings) { + if (typeof customStyleMappings === "object") { + return customStyleMappings; + } + } + _getCustomStyleMappings() { + return this._customStyleMappings || {}; + } + _setMaxLines(maxLines) { + return maxLines >= 1 ? Math.floor(maxLines) : 0; + } + get textHeight() { + return this.style.textStyle.lineHeight || this.style.textStyle.fontSize; + } + get _marginBottom() { + if (this.contentProperties.marginBottom !== undefined) { + return this.contentProperties.marginBottom; + } + if (this.style.marginBottom) { + return this.style.marginBottom; + } + return 0; + } + get _shouldTruncate() { + return this.contentWrap && this.maxLines; + } + set announce(announce) { + super.announce = announce; + } + get announce() { + if (this._announce) { + return this._announce; + } + var announce = this._parsedContent && this._parsedContent.reduce(((announce, item) => { + if (typeof item === "string") { + announce += item; + } else if (item.announce) { + announce += item.announce; + } else if (item.text) { + var _item$style; + announce += item.text; + if (((_item$style = item.style) === null || _item$style === void 0 ? void 0 : _item$style.textDecoration) === "line-through") { + announce += "strikethrough"; + } + } else if (item.title) { + announce += item.title; + } else if (item.badge) { + announce += item.badge; + } + return announce + " "; + }), ""); + return announce ? announce.replace(/\s+(?=\s)|\s$/g, "") : ""; + } +} + +var base$I = theme => ({ + fadeWidth: 100, + offset: theme.spacer.xxl, + shouldSmooth: false, + textStyle: theme.typography.body1 +}); + +var styles$I = Object.freeze({ + __proto__: null, + base: base$I +}); + +class FadeShader extends _lightningjs_core__WEBPACK_IMPORTED_MODULE_0__.shaders.WebGLDefaultShader { + constructor(context) { + super(context); + this._margin = { + left: 0, + right: 0 + }; + } + set positionLeft(v) { + this._positionLeft = v; + } + set positionRight(v) { + this._positionRight = v; + } + setupUniforms(operation) { + super.setupUniforms(operation); + var owner = operation.shaderOwner; + if (this._positionLeft === 0) { + this._positionLeft = .001; + } + if (this._positionRight === 0) { + this._positionRight = .001; + } + var renderPrecision = this.ctx.stage.getRenderPrecision(); + this._setUniform("margin", [ this._positionLeft * renderPrecision, this._positionRight * renderPrecision ], this.gl.uniform1fv); + this._setUniform("resolution", new Float32Array([ owner._w * renderPrecision, owner._h * renderPrecision ]), this.gl.uniform2fv); + } +} + +FadeShader.fragmentShaderSource = "\n #ifdef GL_ES\n # ifdef GL_FRAGMENT_PRECISION_HIGH\n precision highp float;\n # else\n precision lowp float;\n # endif\n #endif\n\n #define PI 3.14159265359\n\n varying vec2 vTextureCoord;\n varying vec4 vColor;\n\n uniform sampler2D uSampler;\n uniform vec2 resolution;\n uniform float margin[2];\n\n void main() {\n vec4 color = texture2D(uSampler, vTextureCoord) * vColor;\n vec2 halfRes = 0.5 * resolution.xy;\n vec2 point = vTextureCoord.xy * resolution;\n\n\n vec2 pos1 = vec2(point.x, point.y);\n vec2 pos2 = pos1;\n pos2.x += margin[0];\n\n vec2 d = pos2 - pos1;\n float t = dot(pos1, d) / dot(d, d);\n t = smoothstep(0.0, 1.0, clamp(t, 0.0, 1.0));\n\n vec2 pos3 = vec2(vTextureCoord.x * resolution.x, vTextureCoord.y);\n pos3.x -= resolution.x - margin[1];\n vec2 pos4 = vec2(vTextureCoord.x + margin[1], vTextureCoord.y);\n\n vec2 d2 = pos4 - pos3;\n float t2 = dot(pos3, d2) / dot(d2, d2);\n t2 = smoothstep(0.0, 1.0, clamp(t2, 0.0, 1.0));\n\n color = mix(vec4(0.0), color, t);\n color = mix(color, vec4(0.0), t2);\n\n gl_FragColor = color;\n }\n"; + +class Marquee extends Base$1 { + static _template() { + return { + ContentClipper: { + boundsMargin: [], + ContentBox: { + Content: {}, + ContentLoopTexture: {} + } + } + }; + } + static get __componentName() { + return "Marquee"; + } + static get __themeStyle() { + return styles$I; + } + static get tags() { + return [ "ContentClipper", { + name: "ContentBox", + path: "ContentClipper.ContentBox" + }, { + name: "Content", + path: "ContentClipper.ContentBox.Content" + }, { + name: "ContentLoopTexture", + path: "ContentClipper.ContentBox.ContentLoopTexture" + } ]; + } + static get properties() { + return [ "autoStart", "title", "contentTexture", "color", "centerAlign", "delay", "repeat", "overrideLoopX" ]; + } + static get aliasStyles() { + return [ { + prev: "fadeW", + curr: "fadeWidth" + } ]; + } + _construct() { + super._construct(); + this._scrolling = false; + this._autoStart = false; + this._centerAlign = false; + } + _init() { + this._Content.on("txLoaded", this._updateContentTexture.bind(this)); + super._init(); + } + _updateContentTexture() { + var restartScrolling = this._restartScrolling; + this.stopScrolling(); + if (!this._currentTexture.h) { + this._ContentClipper.h = this._currentTexture.text && this._currentTexture.text.lineHeight ? this._currentTexture.text.lineHeight : this._Content.finalH; + } + if (this._shouldClip) { + this._updateShader(); + } else { + this._ContentClipper.shader = null; + this._positionTexture(); + } + restartScrolling && this.startScrolling(); + this.signal("marqueeContentLoaded"); + } + _update() { + this._updateColor(); + this._updateTexture(); + this._updateShader(); + this._restartScrolling && this.startScrolling(); + } + get _restartScrolling() { + return this.autoStart || this._scrolling || this._shouldTryScrolling; + } + _updateColor() { + if (this.color) { + this._Content.smooth = { + color: utils$1.getValidColor(this.color) + }; + } + } + get _currentTexture() { + return this._Content.text || this._Content.texture || {}; + } + _updateTexture() { + var content = { + rtt: true + }; + if (this.contentTexture) { + content.texture = this.contentTexture; + } else if (this.title) { + content.text = _objectSpread(_objectSpread(_objectSpread({}, this.style.textStyle), this.title), {}, { + text: this.textContent + }); + } + this.patch({ + ContentClipper: { + w: this.w + 14, + ContentBox: { + Content: content, + ContentLoopTexture: {} + } + } + }); + this.signal("marqueeContentLoaded"); + } + _updateShader() { + this._ContentClipper.patch({ + w: this.w > 0 ? this.w + this.style.fadeWidth / 2 : 0, + shader: { + type: FadeShader, + positionLeft: 0, + positionRight: this.style.fadeWidth + }, + rtt: true + }); + } + _updateAnimation() { + this._scrollAnimation && this._scrollAnimation.stopNow(); + this._scrollAnimation = this.animation({ + duration: this._loopWidth / 50, + delay: isNaN(this.delay) ? 1.5 : this.delay, + repeat: isNaN(this.repeat) ? -1 : this.repeat, + actions: [ { + t: "ContentBox", + p: "x", + v: { + sm: 0, + 0: { + v: 0 + }, + .5: { + v: -(this._loopWidth + this.style.offset) + } + } + }, { + t: "ContentClipper", + p: "shader.positionLeft", + v: { + sm: 0, + 0: { + v: 0 + }, + .1: { + v: this.style.fadeWidth + }, + .4: { + v: this.style.fadeWidth + }, + .5: { + v: 0 + } + } + } ] + }); + } + _positionTexture() { + var x = this._shouldCenter() ? (this.w - this._textRenderedW) / 2 : 0; + if (this.style.shouldSmooth) { + this._ContentBox.smooth = { + x: x + }; + } else { + this._ContentBox.x = x; + } + } + startScrolling() { + this._Content.off("txLoaded", this.startScrolling.bind(this)); + this._shouldTryScrolling = true; + if (this._textRenderedW === 0) { + this._Content.on("txLoaded", this.startScrolling.bind(this)); + } + if (this._shouldClip) { + this._scrolling = true; + this._ContentLoopTexture.x = this._loopWidth + this.style.offset; + this._ContentLoopTexture.texture = this._Content.getTexture(); + this._updateAnimation(); + this._scrollAnimation.start(); + } else { + this._scrolling = false; + } + } + stopScrolling() { + this._shouldTryScrolling = false; + this._scrolling = false; + if (this._scrollAnimation) { + this._scrollAnimation.stopNow(); + this._ContentLoopTexture.texture = null; + } + } + get _shouldClip() { + return this._textRenderedW > this.w - this.style.fadeWidth / 4; + } + _shouldCenter() { + return this._centerAlign || this._Content.text && this._Content.text.textAlign === "center"; + } + _setAutoStart(autoStart) { + if (this.autoStart && !autoStart) { + this._updateContentTexture(); + } + return autoStart; + } + _setCenterAlign(center) { + this._centerAlign = center; + this._updateContentTexture(); + return center; + } + get textContent() { + var _ref17, _this$title$text, _this$title; + return (_ref17 = (_this$title$text = (_this$title = this.title) === null || _this$title === void 0 ? void 0 : _this$title.text) !== null && _this$title$text !== void 0 ? _this$title$text : this.title) !== null && _ref17 !== void 0 ? _ref17 : ""; + } + get _loopWidth() { + return this.overrideLoopX || this._textRenderedW; + } + get _textRenderedW() { + return this._Content.renderWidth; + } + set announce(announce) { + super.announce = announce; + } + get announce() { + return this._announce || this.title && this.title.text; + } +} + +var lightningTextDefaults = Object.entries(Object.getOwnPropertyDescriptors(_lightningjs_core__WEBPACK_IMPORTED_MODULE_0__.textures.TextTexture.prototype)).reduce(((acc, _ref18) => { + var [prop] = _ref18; + var value = _lightningjs_core__WEBPACK_IMPORTED_MODULE_0__.textures.TextTexture.prototype[prop]; + if (prop.startsWith("_") || [ "undefined", "function" ].includes(typeof value)) return acc; + return _objectSpread({ + [prop]: value + }, acc); +}), {}); + +class TextBox extends Base$1 { + static _template() { + return { + alpha: .001 + }; + } + static get __componentName() { + return "TextBox"; + } + static get __themeStyle() { + return styles$K; + } + static get tags() { + return [ "InlineContent", "Marquee", "Text" ]; + } + static get properties() { + return [ ...InlineContent.properties, "content", "fixed", "marquee", "marqueeProps", "hideOnLoad" ]; + } + _setDimensions(w, h) { + var width = w; + var height = h; + if (!this._isInlineContent) { + width = this._Text.texture.getRenderWidth(); + height = this._Text.texture.getRenderHeight(); + } + var sizeChanged = this.w !== width || this.h !== height; + if (width && height && sizeChanged) { + this.h = height; + if (!this.fixed) { + this.w = width; + } + if (!this.hideOnLoad && this.alpha < 1) { + this.alpha = 1; + } + this._notifyAncestors(); + } + } + _setContent(content) { + this._isInlineContent = false; + if (Array.isArray(content) || utils$1.isMarkupString(content)) { + this._isInlineContent = true; + } + if ("string" !== typeof content && !this._isInlineContent) { + return ""; + } + return content; + } + get title() { + return this._content; + } + _notifyAncestors() { + var w = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : this.w; + var h = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : this.h; + this.fireAncestors("$itemChanged"); + this.signal("textBoxChanged", { + w: w, + h: h + }); + } + _construct() { + super._construct(); + this._marqueeContentListenerAttached = false; + this._marqueeOverrideLoopX = undefined; + this._resetMarqueePromise(); + } + _update() { + if (!this.content) { + if (this._Text || this._InlineContent) { + this.w = this.h = 0; + this._notifyAncestors(); + this._updateMarquee(); + this.patch({ + Text: undefined, + InlineContent: undefined + }); + } + return; + } + this._isInlineContent ? this._updateInlineContent() : this._updateText(); + this._updateMarquee(); + } + _updateInlineContent() { + this.patch({ + Text: undefined + }); + var inlineContentPatch = InlineContent.properties.reduce(((acc, prop) => { + if (this[prop] != undefined) { + acc[prop] = this[prop]; + } + return acc; + }), { + style: _objectSpread(_objectSpread({}, this.style), {}, { + textStyle: this._textStyleSet + }) + }); + if (this._textStyleSet.wordWrapWidth) { + inlineContentPatch.w = this._textStyleSet.wordWrapWidth; + inlineContentPatch.rtt = true; + } + if (this._textStyleSet.maxLines) { + inlineContentPatch.maxLines = this._textStyleSet.maxLines; + } + if (this._textStyleSet.maxLinesSuffix) { + inlineContentPatch.maxLinesSuffix = this._textStyleSet.maxLinesSuffix; + } + this.patch({ + alpha: 1, + InlineContent: _objectSpread(_objectSpread({ + type: InlineContent, + w: this.w + }, inlineContentPatch), {}, { + signals: { + loadedInlineContent: "_setDimensions" + } + }) + }); + } + _updateText() { + this.patch({ + InlineContent: undefined + }); + if (!this._Text) { + this.patch({ + Text: {} + }); + this._Text.on("txLoaded", this._setDimensions.bind(this)); + } + var fontStyle = this._textStyleSet; + if (this._Text) { + this._Text.patch({ + y: this.style.offsetY, + x: this.style.offsetX, + text: _objectSpread(_objectSpread({}, lightningTextDefaults), fontStyle) + }); + } + } + set marqueeOverrideLoopX(v) { + this._marqueeOverrideLoopX = v; + if (this._Marquee) this._Marquee.overrideLoopX = this._marqueeOverrideLoopX; + this._resolveAwaitMarqueeOverrideX(); + } + get marqueeOverrideLoopX() { + return this._marqueeOverrideLoopX; + } + _resetMarqueePromise() { + this._awaitMarqueeOverrideX = new Promise(((resolve, reject) => { + this._resolveAwaitMarqueeOverrideX = resolve; + this._rejectAwaitMarqueeOverrideX = reject; + })); + } + _loadedMarqueeContent() { + this.signal("willMarquee", this._Marquee); + } + _updateMarquee() { + if (this._Marquee && !this.marquee) { + this._toggleMarquee(this._contentTag); + } + if (this.marquee) { + this._resetMarqueePromise(); + var marqueePatch = _objectSpread(_objectSpread({}, this.marqueeProps), {}, { + w: this._textStyleSet.wordWrapWidth || this.w, + h: this.h, + y: this.style.offsetY, + x: this.style.offsetX, + signals: { + marqueeContentLoaded: "_loadedMarqueeContent" + } + }); + if (!this._Marquee) { + marqueePatch.type = Marquee; + } + if (this._isInlineContent) { + this._InlineContent.w = 0; + marqueePatch.title = undefined; + marqueePatch.contentTexture = this._contentTag.getTexture(); + marqueePatch.w = this._textStyleSet.wordWrapWidth || this.w; + } else { + marqueePatch.contentTexture = undefined; + marqueePatch.title = _objectSpread(_objectSpread({ + text: this._contentTag.text.text + }, this._textStyleSet), {}, { + wordWrapWidth: 0, + maxLines: 1 + }); + } + this.patch({ + Marquee: marqueePatch + }); + if (!this._marqueeContentListenerAttached) { + this._marqueeContentListenerAttached = true; + } + if ("undefined" !== typeof this._marqueeOverrideLoopX) { + this._awaitMarqueeOverrideX.then((() => { + this._toggleMarquee(this._contentTag); + })); + } else { + this._toggleMarquee(this._contentTag); + } + } + } + _getMarqueeProps() { + var _this$_marqueeProps; + return (_this$_marqueeProps = this._marqueeProps) !== null && _this$_marqueeProps !== void 0 ? _this$_marqueeProps : {}; + } + get _textStyleSet() { + var fontStyle = _objectSpread(_objectSpread({}, this.theme.typography.body1), null !== this.style.textStyle && "object" === typeof this.style.textStyle && Object.keys(this.style.textStyle) ? this.style.textStyle : this.theme.typography[this.style.textStyle]); + this.constructor.properties.forEach((prop => { + if ("fontStyle" !== prop && "undefined" !== typeof this["_".concat(prop)]) { + var key = "content" === prop ? "text" : prop; + fontStyle[key] = this["_".concat(prop)]; + } + })); + if (this.w && !this._isInlineContent && !this.style.textStyle.wordWrapWidth && this.fixed) { + fontStyle.wordWrapWidth = this.w; + } + return fontStyle; + } + get _contentTag() { + return this._isInlineContent ? this._InlineContent : this._Text; + } + _toggleMarquee(contentTag) { + if (this.marquee) { + if (contentTag) { + contentTag.alpha = .001; + } + if (this._Marquee) { + this._Marquee.alpha = 1; + this._Marquee.startScrolling(); + } + } else { + if (contentTag) { + contentTag.alpha = 1; + } + if (this._Marquee) { + this._Marquee.alpha = .001; + this._Marquee.stopScrolling(); + } + } + } + toggleMarquee() { + this._toggleMarquee(this._contentTag); + } + get announce() { + return this._announce || (this._isInlineContent && this._InlineContent ? this._InlineContent.announce : this.content); + } + set announce(announce) { + super.announce = announce; + } + set smooth(v) { + contextInstance.warn("warning: value smoothing is known to cause bugs with the TextBox - patch updated values instead."); + super.smooth = v; + } +} + +class Button extends Surface { + static get __componentName() { + return "Button"; + } + static get __themeStyle() { + return styles$O; + } + static get properties() { + return [ "fixed", "justify", "prefix", "suffix", "title" ]; + } + static get aliasStyles() { + return [ { + prev: "titlePadding", + curr: "contentSpacing" + } ]; + } + static get tags() { + return [ ...super.tags, "Content", { + name: "TextWrapper", + path: "Content.TextWrapper" + }, { + name: "Title", + path: "Content.TextWrapper.Title" + }, { + name: "Prefix", + path: "Content.Prefix" + }, { + name: "Suffix", + path: "Content.Suffix" + } ]; + } + static _template() { + return _objectSpread(_objectSpread({}, super._template()), {}, { + Content: { + mount: .5, + x: w => w / 2, + y: h => h / 2, + zIndex: 2 + } + }); + } + _update() { + this._updatePrefix(); + this._updateTitle(); + this._updateSuffix(); + this._updateAllPositioning(); + this._updateTruncation(); + } + _updateAllPositioning() { + this._updatePositions(); + this._updateContentDimensions(); + this._updateSurfaceDimensions(); + this._updateContentPosition(); + super._update(); + } + $itemChanged() { + this._updateAllPositioning(); + this._updateTruncation(); + } + _onTitleTextBoxChanged() { + this._updateAllPositioning(); + } + _updatePositions() { + if (this._hasPrefix && this._Prefix !== undefined) { + this._Prefix.x = this._prefixX; + } + if (this._hasTitle) { + this._TextWrapper.x = this._titleX; + } + if (this._hasSuffix && this._Suffix !== undefined) { + this._Suffix.x = this._suffixX; + } + } + _updatePrefix() { + var prefixString = JSON.stringify(this.prefix); + if (this.prefix) { + var prefixPatch = { + style: { + itemSpacing: this.style.itemSpacing + } + }; + if (!this._Prefix) { + prefixPatch = _objectSpread(_objectSpread({}, this._rowProps), prefixPatch); + } + this._Content.patch({ + Prefix: prefixPatch + }); + this._updatePrefixSuffixStyles("prefix"); + } else { + this._Content.patch({ + Prefix: undefined + }); + } + this._prevPrefix = prefixString; + } + _updatePrefixSuffixStyles() { + var type = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : "prefix"; + var map = { + prefix: { + tag: this._Prefix, + prop: this.prefix, + prevProp: this._prevPrefix + }, + suffix: { + tag: this._Suffix, + prop: this.suffix, + prevProp: this._prevSuffix + } + }; + var {tag: tag, prop: prop} = map[type]; + var {prevProp: prevProp} = map[type]; + var propString = JSON.stringify(prop); + if (propString !== prevProp) { + prevProp = propString; + tag.items = this._addButtonProps(prop); + } else { + tag.Items.children.forEach(((item, idx) => { + item.color = Array.isArray(prop) ? prop[idx].color : prop.color; + item.style = _objectSpread(_objectSpread({}, item.style), {}, { + color: this.style.contentColor + }); + })); + } + } + _updateTitle() { + if (this._hasTitle) { + var titlePatch = { + content: this.title, + style: { + textStyle: this.style.textStyle + } + }; + if (!this._Title) { + titlePatch = _objectSpread({ + type: TextBox, + mountY: .5, + y: h => h / 2, + signals: { + textBoxChanged: "_onTitleTextBoxChanged" + } + }, titlePatch); + } + this._Content.patch({ + TextWrapper: { + mountY: .5, + Title: titlePatch + } + }); + } else { + this._Content.patch({ + TextWrapper: { + Title: undefined + } + }); + } + } + _updateSuffix() { + if (this.suffix) { + var suffixPatch = { + style: { + itemSpacing: this.style.itemSpacing + } + }; + if (!this._Suffix) { + suffixPatch = _objectSpread(_objectSpread({}, this._rowProps), suffixPatch); + } + this._Content.patch({ + Suffix: suffixPatch + }); + this._updatePrefixSuffixStyles("suffix"); + } else { + this._Content.patch({ + Suffix: undefined + }); + } + } + _updateTruncation() { + if (this._Title) { + this._Title.patch({ + style: { + textStyle: _objectSpread(_objectSpread({}, this.style.textStyle), {}, { + wordWrap: this.fixed, + wordWrapWidth: this.fixed ? this._fixedWordWrapWidth : 0 + }) + } + }); + } + } + _updateContentDimensions() { + var contentDimensionsPatch = {}; + var y = this.h / 2; + if (this._Content.transition("w").targetValue !== this._contentW) { + this._Content.w = this._contentW; + } + if (this._Content.y !== y) { + contentDimensionsPatch.y = y; + } + if (Object.keys(contentDimensionsPatch).length > 0) { + this._Content.patch(contentDimensionsPatch); + } + } + _updateContentPosition() { + this._Content.patch(this._contentProps); + } + _updateSurfaceDimensions() { + var newWidth = this.w; + if (this.fixed) { + newWidth = this._w; + } else { + newWidth = this._calcDynamicWidth(); + } + if (newWidth !== this.w) { + this.w = newWidth; + } + if (!this._hSetByUser && !this.style.h) { + this._h = this.style.textStyle.lineHeight + this.style.paddingY * 2; + } + this.fireAncestors("$itemChanged"); + } + _calcDynamicWidth() { + return !this._hasTitle && (this._hasPrefix || this._hasSuffix) || this._Title && !this._Title.visible && (this._hasPrefix || this._hasSuffix) ? this._contentW + this._paddingX : Math.max(this._contentW + this._paddingX, this.style.minWidth); + } + _addButtonProps(arr) { + var items = Array.isArray(arr) ? arr : [ arr ]; + return items.map((item => _objectSpread(_objectSpread(_objectSpread({}, this._buttonProps), item), {}, { + style: _objectSpread({ + color: this.style.contentColor + }, item.style) + }))); + } + _getJustify() { + return !!this._justify ? this._justify : this.style.justify; + } + get _contentProps() { + var mountX; + var x; + switch (this.justify) { + case "left": + mountX = 0; + x = this._paddingLeft; + break; + + case "right": + mountX = 1; + x = this.w - this._paddingRight; + break; + + case "center": + default: + mountX = .5; + x = this.w / 2; + break; + } + return { + mountX: mountX, + x: x + }; + } + get _buttonProps() { + return { + centerInParent: true, + mode: this.mode + }; + } + get _hasPrefix() { + return !!(this.prefix && Object.keys(this.prefix).length); + } + get _prefixW() { + return this._hasPrefix && this._Prefix !== undefined ? this._Prefix.w : 0; + } + get _prefixX() { + return 0; + } + get _hasTitle() { + return !!this.title; + } + get _titleW() { + if (this._hasTitle && this._Title && this._Title._Text && this._Title.visible) { + return this._Title.w; + } + return 0; + } + get _titleX() { + return this._hasPrefix ? this._prefixW + this.style.contentSpacing : 0; + } + get _hasSuffix() { + return !!(this.suffix && Object.keys(this.suffix).length); + } + get _suffixW() { + return this._hasSuffix && this._Suffix !== undefined ? this._Suffix.w : 0; + } + get _suffixX() { + if (this._hasTitle) { + return this._titleW + this._TextWrapper.x + this.style.contentSpacing; + } else if (this._hasPrefix) { + return this._prefixW + this.style.itemSpacing; + } + return 0; + } + get _contentW() { + if (this._hasSuffix) { + return this._suffixX + this._suffixW; + } else if (this._hasTitle && this._Title && this._Title.visible) { + return this._titleX + this._titleW; + } else if (this._hasPrefix) { + return this._prefixX + this._prefixW; + } + return 0; + } + get _rowProps() { + return { + type: Row, + mountY: .5, + autoResizeHeight: true, + autoResizeWidth: true + }; + } + get _totalTitlePaddingX() { + var totalTitlePadding = 0; + if (this._hasPrefix) { + totalTitlePadding += this.style.contentSpacing; + } + if (this._hasSuffix) { + totalTitlePadding += this.style.contentSpacing; + } + return totalTitlePadding; + } + get _fixedWordWrapWidth() { + var {w: w, _paddingX: _paddingX, _prefixW: _prefixW, _suffixW: _suffixW, _totalTitlePaddingX: _totalTitlePaddingX} = this; + var nonTextSpace = _paddingX + _prefixW + _suffixW + _totalTitlePaddingX; + return Math.max(1, w - nonTextSpace); + } + set announce(announce) { + super.announce = announce; + } + get announce() { + if (this._announce) { + return this._announce; + } + var announce = []; + if (this.title) { + announce.push(this.title); + } + announce.push(this._announceComponentName); + if (this._hasPrefix && this._Prefix.items.length) { + announce.push(...this._Prefix.items.map((item => item.announce))); + } + if (this._hasSuffix && this._Suffix.items.length) { + announce.push(...this._Suffix.items.map((item => item.announce))); + } + return announce; + } + get _announceComponentName() { + return Button.__componentName; + } + get _paddingX() { + return this._paddingLeft + this._paddingRight; + } + get _paddingLeft() { + return this._hasTitle ? this.style.paddingX : this.style.paddingXNoTitle; + } + get _paddingRight() { + return this._hasTitle ? this.style.paddingX : this.style.paddingXNoTitle; + } +} + +var base$H = theme => ({ + minWidth: getWidthByColumnSpan(theme, 1), + paddingX: theme.spacer.xxl, + paddingXNoTitle: theme.spacer.lg, + paddingY: theme.spacer.lg, + textStyle: theme.typography.button2 +}); + +var styles$H = Object.freeze({ + __proto__: null, + base: base$H +}); + +class ButtonSmall extends Button { + static get __componentName() { + return "ButtonSmall"; + } + static get __themeStyle() { + return styles$H; + } +} + +var base$G = theme => ({ + height: theme.spacer.xxl * 12, + paddingHorizontal: theme.spacer.xl, + paddingVertical: theme.spacer.xl, + radius: theme.radius.md, + titleTextStyle: _objectSpread(_objectSpread({}, theme.typography.headline1), {}, { + wordWrap: true, + maxLines: 2, + textColor: theme.color.textNeutral + }), + width: utils$1.getWidthByUpCount(theme, 6) +}); + +var mode$e = theme => ({ + focused: { + tone: { + neutral: { + backgroundColor: theme.color.interactiveNeutralFocusSoft + }, + inverse: { + backgroundColor: theme.color.interactiveInverseFocusSoft + }, + brand: { + backgroundColor: theme.color.interactiveBrandFocusSoft + } + } + }, + disabled: { + titleTextStyle: { + textColor: theme.color.textNeutralDisabled + } + } +}); + +var styles$G = Object.freeze({ + __proto__: null, + base: base$G, + mode: mode$e +}); + +class Card extends Surface { + static get __componentName() { + return "Card"; + } + static get __themeStyle() { + return styles$G; + } + static get properties() { + return [ ...super.properties, "title" ]; + } + static get tags() { + return [ ...super.tags, "Title" ]; + } + static _template() { + return _objectSpread(_objectSpread({}, super._template()), {}, { + Title: { + type: TextBox, + signals: { + textBoxChanged: "_updatePositions" + } + } + }); + } + _update() { + super._update(); + this._updateTitle(); + this._updatePositions(); + } + _updatePositions() { + this._updateTitlePosition(); + } + _updateTitle() { + this._Title.patch({ + content: this.title, + style: { + textStyle: _objectSpread(_objectSpread({}, this.style.titleTextStyle), {}, { + wordWrapWidth: this._calculateTextWidth() + }) + } + }); + } + _calculateTextWidth() { + return this.w - this.style.paddingHorizontal * 2; + } + _updateTitlePosition() { + this._Title.x = this.style.paddingHorizontal; + this._Title.y = this.style.paddingVertical; + } + set announce(announce) { + super.announce = announce; + } + get announce() { + return this._announce || this._Title && this._Title.announce; + } +} + +var base$F = theme => ({ + titleTextStyle: _objectSpread(_objectSpread({}, theme.typography.headline3), {}, { + wordWrap: true, + maxLines: 2, + textColor: theme.color.textNeutral + }), + descriptionTextStyle: _objectSpread(_objectSpread({}, theme.typography.body2), {}, { + textColor: theme.color.textNeutral, + wordWrap: true, + maxLines: 3 + }), + detailsTextStyle: _objectSpread(_objectSpread({}, theme.typography.body3), {}, { + textColor: theme.color.textNeutral, + wordWrap: true, + maxLines: 1 + }) +}); + +var mode$d = theme => ({ + disabled: { + descriptionTextStyle: { + textColor: theme.color.textNeutralDisabled + }, + detailsTextStyle: { + textColor: theme.color.textNeutralDisabled + } + } +}); + +var styles$F = Object.freeze({ + __proto__: null, + base: base$F, + mode: mode$d +}); + +class CardTitle extends Card { + static get __componentName() { + return "CardTitle"; + } + static get __themeStyle() { + return styles$F; + } + static get tags() { + return [ ...super.tags, "Description", "Details" ]; + } + static get properties() { + return [ ...super.properties, "description", "details" ]; + } + static _template() { + return _objectSpread(_objectSpread({}, super._template()), {}, { + Description: { + type: TextBox, + signals: { + textBoxChanged: "_updatePositions" + } + }, + Details: { + type: TextBox, + mountY: 1 + } + }); + } + _update() { + super._update(); + this._updateDescription(); + this._updateDetails(); + this._updatePositions(); + } + _updatePositions() { + super._updatePositions(); + this._updateDescriptionPosition(); + this._updateDetailsPosition(); + } + _updateDescription() { + this._Description.patch({ + content: this.description, + style: { + textStyle: _objectSpread(_objectSpread({}, this.style.descriptionTextStyle), {}, { + wordWrapWidth: this._calculateTextWidth() + }) + } + }); + } + _updateDescriptionPosition() { + this._Description.x = this.style.paddingHorizontal; + this._Description.y = this.style.paddingVertical + this._Title.h; + } + _updateDetails() { + this._Details.patch({ + content: this.details, + style: { + textStyle: _objectSpread(_objectSpread({}, this.style.detailsTextStyle), {}, { + wordWrapWidth: this._calculateTextWidth() + }) + } + }); + } + _updateDetailsPosition() { + this._Details.x = this.style.paddingHorizontal; + this._Details.y = this.h - this.style.paddingVertical; + } + set announce(announce) { + super.announce = announce; + } + get announce() { + return this._announce || [ this._Title && this._Title.announce, this._Description && this._Description.announce, this._Details && this._Details.announce ]; + } +} + +var base$E = theme => ({ + descriptionTextStyle: _objectSpread(_objectSpread({}, theme.typography.body2), {}, { + textColor: theme.color.textNeutralSecondary, + wordWrap: true, + maxLines: 8 + }), + height: theme.spacer.xxxl * 15, + subtitleTextStyle: _objectSpread(_objectSpread({}, theme.typography.body3), {}, { + maxLines: 2, + textColor: theme.color.textNeutral, + wordWrap: true + }), + width: utils$1.getWidthByColumnSpan(theme, 4) +}); + +var mode$c = theme => ({ + disabled: { + descriptionTextStyle: { + textColor: theme.color.textNeutralDisabled + }, + subtitleTextStyle: { + textColor: theme.color.textNeutralDisabled + } + } +}); + +var styles$E = Object.freeze({ + __proto__: null, + base: base$E, + mode: mode$c +}); + +var base$D = theme => { + var size = theme.spacer.xxl; + return { + alpha: theme.alpha.primary, + width: size, + height: size, + knobHeight: size / 2, + knobWidth: size / 2, + radius: size / 2, + strokeWidth: theme.stroke.sm + }; +}; + +var tone$k = theme => ({ + neutral: { + backgroundColor: theme.color.fillInverseSecondary, + backgroundColorChecked: theme.color.fillNeutral, + knobColor: theme.color.fillInverse, + strokeColor: theme.color.strokeNeutralSecondary + }, + inverse: { + backgroundColor: theme.color.fillNeutralSecondary, + backgroundColorChecked: theme.color.fillInverse, + knobColor: theme.color.fillNeutral, + strokeColor: theme.color.strokeInverseSecondary + }, + brand: { + backgroundColor: theme.color.fillNeutralSecondary, + backgroundColorChecked: theme.color.fillBrand, + knobColor: theme.color.fillInverse, + strokeColor: theme.color.strokeNeutralSecondary + } +}); + +var mode$b = theme => ({ + disabled: { + alpha: theme.alpha.inactive + } +}); + +var styles$D = Object.freeze({ + __proto__: null, + base: base$D, + mode: mode$b, + tone: tone$k +}); + +class Radio extends Base$1 { + static get __componentName() { + return "Radio"; + } + static get __themeStyle() { + return styles$D; + } + static _template() { + var center = { + mount: .5, + x: w => w / 2, + y: h => h / 2 + }; + return { + Body: _objectSpread(_objectSpread({ + rtt: true + }, center), {}, { + Knob: _objectSpread(_objectSpread({}, center), {}, { + alpha: 0 + }) + }), + Stroke: center + }; + } + static get tags() { + return [ "Knob", "Body", "Stroke" ]; + } + static get properties() { + return [ "checked" ]; + } + _update() { + this._updateBody(); + this._updateStroke(); + this._updateKnob(); + if (this._checkedChanged) { + this.fireAncestors("$announce", this.announce); + this._checkedChanged = false; + } + this._updateOpacity(); + } + _updateBody() { + var bodyColor = this.checked ? this.style.backgroundColorChecked : this.style.backgroundColor; + var width = this.w - this.style.strokeWidth * 2 - 2; + var height = this.h - this.style.strokeWidth * 2 - 2; + this._Body.patch({ + texture: _lightningjs_core__WEBPACK_IMPORTED_MODULE_0__.Tools.getRoundRect(width, height, getMaxRoundRadius(this.style.radius, width, height, this.style.strokeWidth * 2 - 2), null, null, true, bodyColor) + }); + } + _updateStroke() { + this._Stroke.patch({ + texture: _lightningjs_core__WEBPACK_IMPORTED_MODULE_0__.Tools.getRoundRect(this.w - 2, this.h - 2, getMaxRoundRadius(this.style.radius, this.w, this.h), this.style.strokeWidth, this.style.strokeColor, false) + }); + } + _updateKnob() { + this._Knob.patch({ + texture: _lightningjs_core__WEBPACK_IMPORTED_MODULE_0__.Tools.getRoundRect(this.style.knobWidth, this.style.knobHeight, this.style.knobWidth / 2, null, null, true, this.style.knobColor) + }); + this.applySmooth(this._Knob, { + alpha: this.checked ? 1 : 0 + }); + } + _updateOpacity() { + this.applySmooth(this, { + alpha: this.style.alpha + }); + } + _setChecked(checked) { + this._checkedChanged = checked !== this._checked; + return checked; + } + toggle() { + if (!this._isDisabledMode) { + this.checked = !this.checked; + } + return this; + } + _handleEnter() { + if (typeof this.onEnter === "function") { + return this.onEnter(this); + } else { + this.toggle(); + } + return false; + } + set announce(announce) { + super.announce = announce; + } + get announce() { + return this._announce || (this.checked ? "Checked" : "Unchecked"); + } +} + +var base$C = theme => { + var size = theme.spacer.xl; + return { + width: size, + height: size, + knobHeight: size / 2, + knobWidth: size / 2, + radius: size / 2 + }; +}; + +var styles$C = Object.freeze({ + __proto__: null, + base: base$C +}); + +class RadioSmall extends Radio { + static get __componentName() { + return "RadioSmall"; + } + static get __themeStyle() { + return styles$C; + } +} + +class CardRadio extends CardTitle { + static get __componentName() { + return "CardRadio"; + } + static get __themeStyle() { + return styles$E; + } + static get properties() { + return [ ...super.properties, "radio", "subtitle" ]; + } + static get tags() { + return [ ...super.tags, "Radio", "Subtitle" ]; + } + static _template() { + return _objectSpread(_objectSpread({}, super._template()), {}, { + Subtitle: { + type: TextBox, + signals: { + textBoxChanged: "_updatePositions" + } + } + }); + } + _update() { + super._update(); + this._updateRadio(); + this._updateSubtitle(); + this._updatePositions(); + } + _updatePositions() { + super._updatePositions(); + this._updateSubtitlePosition(); + } + _updateSubtitle() { + this._Subtitle.patch({ + content: this.subtitle, + style: { + textStyle: _objectSpread(_objectSpread({}, this.style.subtitleTextStyle), {}, { + wordWrapWidth: this._calculateTextWidth() + }) + } + }); + } + _updateRadio() { + var radioPatch = _objectSpread(_objectSpread({}, this.radio), {}, { + mode: this.mode, + mountX: 1, + x: this.w - this.style.paddingHorizontal, + y: this.style.paddingVertical + }); + if (!this._Radio) { + radioPatch.type = Radio; + } + this.patch({ + Radio: radioPatch + }); + } + _updateSubtitlePosition() { + this._Subtitle.x = this.style.paddingHorizontal; + this._Subtitle.y = this.style.paddingVertical + this._Title.h; + } + _updateDescriptionPosition() { + this._Description.x = this.style.paddingHorizontal; + this._Description.y = this.style.paddingVertical * 2 + this._Title.h + this._Subtitle.h; + } + set announce(announce) { + super.announce = announce; + } + get announce() { + return this._announce || [ this._Title && this._Title.announce, this._Subtitle && this._Subtitle.announce, this._Description && this._Description.announce, this._Details && this._Details.announce ]; + } +} + +var base$B = theme => ({ + height: theme.spacer.xxl * 5, + iconWidth: theme.spacer.xxl, + iconHeight: theme.spacer.xxl, + width: utils$1.getWidthByColumnSpan(theme, 3) +}); + +var styles$B = Object.freeze({ + __proto__: null, + base: base$B +}); + +class CardSection extends Card { + static get __componentName() { + return "CardSection"; + } + static get __themeStyle() { + return styles$B; + } + static get tags() { + return [ ...super.tags, "Icon" ]; + } + static get properties() { + return [ ...super.properties, "iconWidth", "iconHeight", "iconSrc" ]; + } + _update() { + super._update(); + this._updateIcon(); + } + _updateIcon() { + var {iconWidth: iconWidth, iconHeight: iconHeight} = this.style; + var iconObject = { + w: iconWidth, + h: iconHeight, + icon: this.iconSrc, + x: this.w - iconWidth - this.style.paddingHorizontal, + y: (this._Title.style.textStyle.lineHeight - iconHeight) / 2 + this.style.paddingVertical + }; + if (!this._Icon) { + iconObject.type = Icon; + } + this.patch({ + Icon: iconObject + }); + } + _calculateTextWidth() { + var textWidth = this.w - this.style.paddingHorizontal * 2; + return this.iconSrc ? textWidth - this.iconWidth : textWidth; + } +} + +var base$A = theme => { + var strokeWidth = theme.stroke.sm; + var size = theme.spacer.xxl; + return { + alpha: theme.alpha.primary, + width: size, + height: size, + iconWidth: theme.spacer.lg, + iconHeight: theme.spacer.lg, + icon: theme.asset.check, + radius: theme.radius.xs, + strokeWidth: strokeWidth + }; +}; + +var tone$j = theme => ({ + neutral: { + strokeColor: theme.color.strokeNeutralSecondary, + checkColor: theme.color.fillInverse, + backgroundColor: theme.color.fillInverseSecondary, + backgroundColorChecked: theme.color.fillNeutral + }, + inverse: { + strokeColor: theme.color.strokeInverseSecondary, + checkColor: theme.color.fillNeutral, + backgroundColor: theme.color.fillNeutralSecondary, + backgroundColorChecked: theme.color.fillInverse + }, + brand: { + strokeColor: theme.color.strokeNeutralSecondary, + checkColor: theme.color.fillInverse, + backgroundColor: theme.color.fillNeutralSecondary, + backgroundColorChecked: theme.color.fillBrand + } +}); + +var mode$a = theme => ({ + disabled: { + alpha: theme.alpha.inactive + } +}); + +var styles$A = Object.freeze({ + __proto__: null, + base: base$A, + mode: mode$a, + tone: tone$j +}); + +class Checkbox extends Base$1 { + static get __componentName() { + return "Checkbox"; + } + static get __themeStyle() { + return styles$A; + } + static _template() { + var center = { + mount: .5, + x: w => w / 2, + y: h => h / 2 + }; + return { + Body: _objectSpread(_objectSpread({ + rtt: true + }, center), {}, { + Check: _objectSpread(_objectSpread({ + type: Icon + }, center), {}, { + alpha: 0 + }) + }), + Stroke: center + }; + } + static get tags() { + return [ "Check", "Body", "Stroke" ]; + } + static get properties() { + return [ "checked" ]; + } + static get aliasStyles() { + return [ { + prev: "checkSrc", + curr: "icon" + }, { + prev: "checkH", + curr: "iconHeight" + }, { + prev: "checkW", + curr: "iconWidth" + }, { + prev: "checkHeight", + curr: "iconHeight" + }, { + prev: "checkWidth", + curr: "iconWidth" + } ]; + } + _update() { + this._updateBody(); + this._updateStroke(); + this._updateCheck(); + if (this._checkedChanged) { + this.fireAncestors("$announce", this.announce); + this._checkedChanged = false; + } + this._updateOpacity(); + } + _updateCheck() { + this._Check.patch({ + w: this.style.iconWidth, + h: this.style.iconHeight, + icon: this.style.icon, + style: { + color: this.style.checkColor + } + }); + var alphaPatch = { + alpha: this.checked ? 1 : 0 + }; + this.applySmooth(this._Check, alphaPatch); + } + _updateBody() { + var bodyColor = this.checked ? this.style.backgroundColorChecked : this.style.backgroundColor; + var width = this.w - this.style.strokeWidth * 2 - 2; + var height = this.h - this.style.strokeWidth * 2 - 2; + this._Body.patch({ + texture: _lightningjs_core__WEBPACK_IMPORTED_MODULE_0__.Tools.getRoundRect(width, height, getMaxRoundRadius(this.style.radius, width, height, this.style.strokeWidth * 2 - 2), 0, null, true, bodyColor) + }); + } + _updateStroke() { + this._Stroke.patch({ + texture: _lightningjs_core__WEBPACK_IMPORTED_MODULE_0__.Tools.getRoundRect(this.w - 2, this.h - 2, getMaxRoundRadius(this.style.radius, this.w - 2, this.h - 2), this.style.strokeWidth, this.style.strokeColor, false) + }); + } + _updateOpacity() { + this.applySmooth(this, { + alpha: this.style.alpha + }); + } + _setChecked(checked) { + this._checkedChanged = checked !== this._checked; + return checked; + } + toggle() { + if (!this._isDisabledMode) { + this.checked = !this.checked; + } + return this; + } + _handleEnter() { + if (typeof this.onEnter === "function") { + return this.onEnter(this); + } else { + this.toggle(); + } + return false; + } + set announce(announce) { + super.announce = announce; + } + get announce() { + return this._announce || (this.checked ? "Checked" : "Unchecked"); + } +} + +var base$z = theme => ({ + radius: [ theme.radius.md, theme.radius.md, theme.radius.md, theme.radius.none ], + paddingX: theme.spacer.lg, + paddingY: theme.spacer.md, + offsetY: theme.spacer.xxs, + textStyle: theme.typography.caption1 +}); + +var tone$i = theme => ({ + neutral: { + textStyle: { + textColor: theme.color.textInverse + }, + backgroundColor: theme.color.fillNeutral + }, + inverse: { + textStyle: { + textColor: theme.color.textNeutral + }, + backgroundColor: theme.color.fillInverse + }, + brand: { + textStyle: { + textColor: theme.color.textNeutral + }, + backgroundColor: theme.color.fillBrand + } +}); + +var styles$z = Object.freeze({ + __proto__: null, + base: base$z, + tone: tone$i +}); + +class Label extends Base$1 { + static _template() { + return { + Background: {}, + Text: { + mountY: .5, + mountX: .5, + text: {} + } + }; + } + static get __componentName() { + return "Label"; + } + static get __themeStyle() { + return styles$z; + } + static get properties() { + return [ "title" ]; + } + static get tags() { + return [ "Background", "Text" ]; + } + _init() { + this._Text.on("txLoaded", this._updateBackground.bind(this)); + super._init(); + } + _update() { + this._updateBackground(); + this._updateText(); + } + _updateText() { + if (this._Text) { + this._Text.patch({ + text: _objectSpread(_objectSpread({}, this.style.textStyle), {}, { + text: this.title + }) + }); + } + } + _updateBackground() { + this._Text.x = this.w / 2; + this._Text.y = this.h / 2 + this.style.offsetY; + this.h = !this.title ? 0 : this._Text.renderHeight + 2 * this.style.paddingY; + this.w = !this.title ? 0 : this._Text.renderWidth + 2 * this.style.paddingX; + this._Background.patch({ + texture: _lightningjs_core__WEBPACK_IMPORTED_MODULE_0__.Tools.getRoundRect(this.w - 2, this.h - 2, this.style.radius, 0, null, true, this.style.backgroundColor) + }); + this.signal("loadedLabel", this); + } + set announce(announce) { + super.announce = announce; + } + get announce() { + return this._announce || this._Text && this._Text.text.text; + } +} + +function withMarqueeSync(Base) { + return class extends Base { + static get name() { + return Base.name; + } + _init() { + super._init(); + if (this._shouldSync) { + this._updateSignals(); + } + } + _update() { + super._update(); + if (this._shouldSync) { + this._updateSignals(); + } else { + this._cleanupSyncValues(); + } + } + _cleanupSyncValues() { + this.syncArray.map((component => { + component.marqueeOverrideLoopX = undefined; + component.signals && component.signals.willMarquee && delete component.signals.willMarquee; + })); + } + _updateSignals() { + if (this.syncArray) { + this.syncArray.map((component => { + component.signals = _objectSpread(_objectSpread({}, component.signals), {}, { + willMarquee: "_willMarquee" + }); + })); + } + } + _willMarquee(compRef) { + if (this._shouldSync) { + this._longestMarqueeWidth = Math.max(compRef._textRenderedW || 0, this._longestMarqueeWidth || 0); + this.syncArray.map((component => { + component.marqueeOverrideLoopX = this._longestMarqueeWidth; + })); + } + } + get _shouldSync() { + if (this.style.marqueeSync === false) { + return false; + } + if (!this.syncArray) { + loggerInstance.warn("warning: components using MarqueeSync must have a syncArray getter defined."); + return false; + } else if (!Array.isArray(this.syncArray)) { + loggerInstance.warn("warning: syncArray must be typeof array."); + return false; + } else if (this.syncArray.length < 2) { + loggerInstance.warn("warning: syncArray must contain at least two component references."); + return false; + } else { + return true; + } + } + }; +} + +var base$y = theme => ({ + descriptionTextStyle: _objectSpread(_objectSpread({}, theme.typography.body2), {}, { + maxLines: 1 + }), + fadeWidth: 100, + logoWidth: theme.typography.body3.lineHeight, + logoHeight: theme.typography.body3.lineHeight, + logoPadding: theme.spacer.lg, + detailsTextStyle: theme.typography.body3, + subtitleTextStyle: theme.typography.body3, + titleTextStyle: _objectSpread(_objectSpread({}, theme.typography.headline1), {}, { + maxLines: 1 + }), + marqueeSync: true, + alpha: theme.alpha.primary +}); + +var mode$9 = theme => ({ + disabled: { + detailsTextStyle: { + textColor: theme.color.textNeutralDisabled + }, + alpha: theme.alpha.inactive + } +}); + +var tone$h = theme => ({ + neutral: { + titleTextStyle: { + textColor: theme.color.textNeutral + }, + subtitleTextStyle: { + textColor: theme.color.textNeutralSecondary + }, + detailsTextStyle: { + textColor: theme.color.textNeutral + }, + descriptionTextStyle: { + textColor: theme.color.textNeutralSecondary + }, + mode: { + disabled: { + titleTextStyle: { + textColor: theme.color.textNeutralDisabled + }, + detailsTextStyle: { + textColor: theme.color.textNeutralDisabled + }, + descriptionTextStyle: { + textColor: theme.color.textNeutralDisabled + } + } + } + }, + inverse: { + titleTextStyle: { + textColor: theme.color.textInverse + }, + subtitleTextStyle: { + textColor: theme.color.textInverseSecondary + }, + detailsTextStyle: { + textColor: theme.color.textInverse + }, + descriptionTextStyle: { + textColor: theme.color.textInverseSecondary + }, + mode: { + disabled: { + titleTextStyle: { + textColor: theme.color.textNeutralDisabled + }, + subtitleTextStyle: { + textColor: theme.color.textNeutralDisabled + }, + detailsTextStyle: { + textColor: theme.color.textNeutralDisabled + }, + descriptionTextStyle: { + textColor: theme.color.textNeutralDisabled + } + } + } + }, + brand: { + titleTextStyle: { + textColor: theme.color.textNeutral + }, + subtitleTextStyle: { + textColor: theme.color.textNeutralSecondary + }, + detailsTextStyle: { + textColor: theme.color.textNeutral + }, + descriptionTextStyle: { + textColor: theme.color.textNeutralSecondary + }, + mode: { + disabled: { + titleTextStyle: { + textColor: theme.color.textNeutralDisabled + }, + detailsTextStyle: { + textColor: theme.color.textNeutralDisabled + }, + descriptionTextStyle: { + textColor: theme.color.textNeutralDisabled + } + } + } + } +}); + +var styles$y = Object.freeze({ + __proto__: null, + base: base$y, + mode: mode$9, + tone: tone$h +}); + +class MetadataBase extends Base$1 { + static get __componentName() { + return "MetadataBase"; + } + static get __themeStyle() { + return styles$y; + } + static _template() { + return { + Text: { + flex: { + direction: "column", + justifyContent: "flex-start" + }, + DetailsWrapper: {} + } + }; + } + static get properties() { + return [ "description", "logo", "logoHeight", "logoPosition", "logoTitle", "logoWidth", "details", "subtitle", "title", "marquee" ]; + } + static get tags() { + return [ "Text", { + name: "Title", + path: "Text.Title" + }, { + name: "Subtitle", + path: "Text.Subtitle" + }, { + name: "DetailsWrapper", + path: "Text.DetailsWrapper" + }, { + name: "Details", + path: "Text.DetailsWrapper.Details" + }, { + name: "Description", + path: "Text.Description" + }, "Logo" ]; + } + _titleLoaded() { + this._updateLayout(); + } + _subtitleLoaded() { + this._updateLayout(); + } + _detailsLoaded(_ref19) { + var {w: w, h: h} = _ref19; + this._updateDetailsLayout({ + w: w, + h: h + }); + this._updateLayout(); + } + _descriptionLoaded() { + this._updateLayout(); + } + _updateDetailsLayout(_ref20) { + var {w: w, h: h} = _ref20; + if (!this.details && !this._Details) { + return; + } + if (this._DetailsWrapper) { + this._DetailsWrapper.alpha = this.style.alpha; + this._DetailsWrapper.w = w; + this._DetailsWrapper.h = h; + } + } + _update() { + this._updateLines(); + this._updateLayout(); + } + _updateLines() { + this._Text.w = this._textW(); + this._updateTitle(); + this._updateSubtitle(); + this._updateDetails(); + this._updateDescription(); + } + _updateLayout() { + this._Text.h = this._textH(); + this._updateMetadataHeight(); + this._updatePositions(); + this._updateLogo(); + } + _updatePositions() { + this._Text.x = this.logo && this.logoPosition === "left" ? this.logoWidth + this.style.logoPadding : 0; + this._Text.y = (this.h - this._Text.h) / 2; + } + _updateMetadataHeight() { + var newH = Math.max(this.logoHeight, this._Text.h); + if (this.h !== newH) { + this.h = newH; + this.signal("updateComponentDimensions"); + } + } + _updateTitle() { + if (!this.title && !this._Title) { + return; + } + if (!this._Title) { + this._Text.childList.addAt({ + ref: "Title", + type: TextBox, + signals: { + textBoxChanged: "_titleLoaded" + } + }, 0); + } + this._Title.patch({ + content: this.title, + marquee: this.marquee, + style: { + textStyle: _objectSpread(_objectSpread({}, this.style.titleTextStyle), {}, { + maxLines: 1, + wordWrap: true, + wordWrapWidth: this._Text.w + }) + } + }); + } + _updateSubtitle() { + if (!this.subtitle && !this._Subtitle) { + return; + } + if (!this._Subtitle) { + this._Text.childList.addAt({ + ref: "Subtitle", + type: TextBox, + signals: { + textBoxChanged: "_subtitleLoaded" + } + }, 1); + } + this._Subtitle.patch({ + content: this.subtitle, + marquee: this.marquee, + style: { + textStyle: _objectSpread(_objectSpread({}, this.style.subtitleTextStyle), {}, { + maxLines: 1, + wordWrap: true, + wordWrapWidth: this._Text.w + }) + } + }); + } + resetMarquee() { + if (this.marquee) { + if (this.title) { + if (!this._Title) { + this._updateTitle(); + } + this._Title.toggleMarquee(); + } + if (this.description) { + if (!this._Description) { + this._updateDescription(); + } + this._Description.toggleMarquee(); + } + } + } + _updateDetails() { + if (!this.details && !this._Details) { + return; + } + if (!this._Details) { + this._DetailsWrapper.patch({ + Details: { + type: TextBox, + signals: { + textBoxChanged: "_detailsLoaded" + } + } + }); + } + this._Details.patch({ + content: this.details, + style: { + textStyle: this.style.detailsTextStyle + } + }); + if (this._Details.finalW > this._textW()) { + this._Details.patch({ + w: this._textW() + this.style.fadeWidth / 2, + shader: { + type: FadeShader, + positionLeft: 0, + positionRight: this.style.fadeWidth + }, + rtt: true + }); + } else { + this._DetailsWrapper.shader = undefined; + } + this._DetailsWrapper.visible = this.details ? true : false; + this._DetailsWrapper.alpha = this.style.alpha; + } + _updateDescription() { + if (!this.description && !this._Description) { + return; + } + if (!this._Description) { + this._Text.childList.add({ + ref: "Description", + type: TextBox, + signals: { + textBoxChanged: "_descriptionLoaded" + } + }); + } + this._Description.patch({ + content: this.description, + marquee: this.marquee, + style: { + textStyle: _objectSpread(_objectSpread({}, this.style.descriptionTextStyle), {}, { + maxLines: 1, + wordWrap: true, + wordWrapWidth: this._Text.w + }) + } + }); + } + _updateLogo() { + if (!this.logo && !this._Logo) { + return; + } + if (!this._Logo) { + this.patch({ + Logo: { + flexItem: false, + type: Icon + } + }); + } + this.logoPosition = this.logoPosition || "right"; + var subtitleH = this.subtitle && this._Subtitle && this._Subtitle.h || 0; + this._Logo.patch({ + w: this.logoWidth, + h: this.logoHeight, + icon: this.logo, + alpha: this.style.alpha + }); + this._Logo.x = this.logoPosition === "left" ? 0 : this.w - this._Logo.w; + this._Logo.y = (this.h - this.logoHeight + subtitleH) / 2; + } + _textW() { + return this.w - (this.logo ? this.logoWidth + this.style.logoPadding : 0); + } + _textH() { + var titleH = this.title && this._Title && this._Title.h || 0; + var subtitleH = this.subtitle && this._Subtitle && this._Subtitle.h || 0; + var detailsH = this.details && this._DetailsWrapper && this._DetailsWrapper.h || 0; + var descriptionH = this.description && this._Description && this._Description.h || 0; + return titleH + subtitleH + detailsH + descriptionH; + } + _getLogoWidth() { + return this._logoWidth !== undefined ? this._logoWidth : this.style.logoWidth; + } + _setLogoWidth(w) { + return w !== undefined ? w : this.logoWidth; + } + _getLogoHeight() { + return this._logoHeight !== undefined ? this._logoHeight : this.style.logoHeight; + } + _setLogoHeight(h) { + return h !== undefined ? h : this.logoHeight; + } + get syncArray() { + return [ ...this._Title ? [ this._Title ] : [], ...this._Subtitle ? [ this._Subtitle ] : [], ...this._Description ? [ this._Description ] : [], ...this._Details ? [ this._Details ] : [] ]; + } + set announce(announce) { + super.announce = announce; + } + get announce() { + return this._announce || [ this._Title && this._Title.announce, this._Subtitle && this._Subtitle.announce, this._Details && this._Details.announce, this._Description && this._Description.announce, this.logoTitle ]; + } +} + +var MetadataBase$1 = withMarqueeSync(MetadataBase); + +var base$x = theme => ({ + titleTextStyle: theme.typography.headline3, + descriptionTextStyle: theme.typography.body3 +}); + +var tone$g = theme => ({ + neutral: { + detailsTextStyle: { + textColor: theme.color.textNeutralSecondary + }, + descriptionTextStyle: { + textColor: theme.color.textNeutral + }, + mode: { + disabled: { + detailsTextStyle: { + textColor: theme.color.textNeutralDisabled + }, + descriptionTextStyle: { + textColor: theme.color.textNeutralDisabled + } + } + } + }, + inverse: { + detailsTextStyle: { + textColor: theme.color.textInverseSecondary + }, + descriptionTextStyle: { + textColor: theme.color.textInverse + }, + mode: { + disabled: { + detailsTextStyle: { + textColor: theme.color.textNeutralDisabled + }, + descriptionTextStyle: { + textColor: theme.color.textNeutralDisabled + } + } + } + }, + brand: { + detailsTextStyle: { + textColor: theme.color.textNeutralSecondary + }, + descriptionTextStyle: { + textColor: theme.color.textNeutral + }, + mode: { + disabled: { + detailsTextStyle: { + textColor: theme.color.textNeutralDisabled + }, + descriptionTextStyle: { + textColor: theme.color.textNeutralDisabled + } + } + } + } +}); + +var styles$x = Object.freeze({ + __proto__: null, + base: base$x, + tone: tone$g +}); + +class MetadataTile extends MetadataBase$1 { + static get __componentName() { + return "MetadataTile"; + } + static get __themeStyle() { + return styles$x; + } + _updateDetails() { + if (!this.details && !this._Details) { + return; + } + if (this.description && this._Details) { + this._Details.patch({ + content: "" + }); + this._Details.alpha = 0; + this._Details.visible = false; + } else { + super._updateDetails(); + } + } + _updateDetailsLayout(_ref21) { + var {h: h} = _ref21; + if (!this.details && !this._Details) { + return; + } + if (this._Details && !this.description) { + this._DetailsWrapper.h = h; + this._DetailsWrapper.alpha = this.style.alpha; + } else { + this._DetailsWrapper.h = 0; + } + } + set announce(announce) { + super.announce = announce; + } + get announce() { + return this._announce || [ this._Title && this._Title.announce, this._Details && this._Details.announce || this._Description && this._Description.announce, this.logoTitle ]; + } + _textH() { + var titleH = this.title && this._Title && this._Title.h || 0; + var detailsH = this.details && this._Details && this._Details.visible && this._DetailsWrapper.h || 0; + var descriptionH = this.description && this._Description && this._Description.h || 0; + return titleH + detailsH + descriptionH; + } +} + +var base$w = theme => ({ + height: theme.spacer.md, + animation: theme.animation.utility, + radius: theme.radius.xs +}); + +var tone$f = theme => ({ + neutral: { + barColor: theme.color.fillNeutralTertiary, + progressColor: theme.color.fillNeutral + }, + inverse: { + barColor: theme.color.fillInverseTertiary, + progressColor: theme.color.fillInverse + }, + brand: { + barColor: theme.color.fillNeutralTertiary, + progressColor: theme.color.fillBrand + } +}); + +var styles$w = Object.freeze({ + __proto__: null, + base: base$w, + tone: tone$f +}); + +class ProgressBar extends Base$1 { + static _template() { + return { + Bar: { + zIndex: 1 + }, + Progress: { + alpha: 0, + zIndex: 2 + } + }; + } + static get __themeStyle() { + return styles$w; + } + static get __componentName() { + return "ProgressBar"; + } + static get properties() { + return [ "progress" ]; + } + static get tags() { + return [ "Bar", "Progress" ]; + } + _construct() { + super._construct && super._construct(); + this._progress = 0; + } + _update() { + this._updateTextures(); + this._updateProgress(); + if (this._progressChanged) { + this.fireAncestors("$announce", this.announce); + this._progressChanged = false; + } + } + _updateTextures() { + var w = this._getProgressWidth(); + var radius = getMaxRoundRadius(this.style.radius, this.w - 2, this.h); + this._Bar.texture = _lightningjs_core__WEBPACK_IMPORTED_MODULE_0__.Tools.getRoundRect(this.w - 2, this.h, radius, 0, 0, true, this.style.barColor); + this._Progress.texture = _lightningjs_core__WEBPACK_IMPORTED_MODULE_0__.Tools.getRoundRect(w + 1, this.h, radius, 0, 0, true, this.style.progressColor); + } + _updateProgress() { + var w = this._getProgressWidth(); + this._Progress.smooth = { + w: [ w, this.style.animation ], + alpha: Number(w > 0) + }; + } + _setProgress(progress) { + this._progressChanged = progress !== this._progress; + return progress; + } + set announce(announce) { + super.announce = announce; + } + get announce() { + if (this._announce !== undefined && this._announce !== null) { + return this._announce; + } + var progress = this.progress; + if (progress > 1) { + progress = 1; + } else if (progress < 0) { + progress = 0; + } + return "".concat(Math.round(progress * 100), "%"); + } + _getProgressWidth() { + var p = this.w * this._progress; + var w = p <= 0 ? 0 : Math.min(p, this.w); + return w; + } +} + +var base$v = theme => ({ + animationEntrance: theme.animation.standardEntrance, + animationExit: theme.animation.standardExit, + logoWidth: theme.spacer.lg * 5, + logoHeight: theme.spacer.xxl + theme.spacer.md, + metadataLocation: "standard", + paddingX: theme.spacer.xl, + paddingY: theme.spacer.lg, + paddingYProgress: theme.spacer.xl, + paddingYBetweenContent: theme.spacer.md, + radius: theme.radius.md, + alpha: theme.alpha.primary +}); + +var tone$e = theme => ({ + neutral: { + mode: { + focused: { + backgroundColor: theme.color.interactiveNeutralFocusSoft + } + } + }, + inverse: { + mode: { + focused: { + backgroundColor: theme.color.interactiveInverseFocusSoft + } + } + }, + brand: { + mode: { + focused: { + backgroundColor: theme.color.interactiveBrandFocusSoft + } + } + } +}); + +var mode$8 = theme => ({ + disabled: { + alpha: theme.alpha.inactive + } +}); + +var styles$v = Object.freeze({ + __proto__: null, + base: base$v, + mode: mode$8, + tone: tone$e +}); + +class Tile extends Surface { + static get __componentName() { + return "Tile"; + } + static get __themeStyle() { + return styles$v; + } + static _template() { + return _objectSpread(_objectSpread({}, super._template()), {}, { + Tile: { + Artwork: { + type: Artwork, + signals: { + imageLoaded: "_imageLoaded" + }, + mount: .5 + }, + Content: { + mount: .5 + } + } + }); + } + static get properties() { + return [ "artwork", "badge", "checkbox", "circle", "label", "logo", "metadata", "metadataLocation", "persistentMetadata", "progressBar", "src" ]; + } + static get aliasStyles() { + return [ { + prev: "iconHeight", + curr: "logoHeight" + }, { + prev: "iconWidth", + curr: "logoWidth" + } ]; + } + static get aliasProperties() { + return [ { + prev: "iconSrc", + curr: "logo" + } ]; + } + static get tags() { + return [ ...super.tags, "Artwork", "Content", "Tile", { + name: "Badge", + path: "Content.Badge" + }, { + name: "Checkbox", + path: "Content.Checkbox" + }, { + name: "Logo", + path: "Content.Logo" + }, { + name: "Metadata", + path: "Content.Metadata" + }, { + name: "ProgressBar", + path: "Content.ProgressBar" + }, { + name: "Label", + path: "Content.Label" + } ]; + } + set announce(announce) { + super.announce = announce; + } + get announce() { + return this._announce || [ this._Metadata && this._Metadata.announce, this._Badge && this._Badge.announce, this._Label && this._Label.announce, this._ProgressBar && this._ProgressBar.announce ]; + } + _update() { + super._update(); + this._updateTileColor(); + this._updateContent(); + this._updateArtwork(); + this._updateBadge(); + this._updateLabel(); + this._updateCheckbox(); + this._updateProgressBar(); + this._updateMetadata(); + this._updateLogo(); + } + _getRenderHeight() { + var _this$_Metadata; + return !this._isInsetMetadata ? this._h + (((_this$_Metadata = this._Metadata) === null || _this$_Metadata === void 0 ? void 0 : _this$_Metadata.h) + this.style.paddingY || 0) : super._getRenderHeight(); + } + get innerH() { + return this._h; + } + get _shouldShowGradient() { + var _this$progressBar; + return Boolean((this._isInsetMetadata && this._hasMetadata && this._shouldShowMetadata || ((_this$progressBar = this.progressBar) === null || _this$progressBar === void 0 ? void 0 : _this$progressBar.progress) > 0 || this._shouldShowLogo) && !this._isCircleLayout); + } + get _isCircleLayout() { + return Boolean(this._itemLayout && this._itemLayout.circle); + } + get _foregroundDefaultWidth() { + return parseFloat(this._w / this._h).toFixed(2) === parseFloat(16 / 9).toFixed(2) ? this.innerW * .5 : this.innerW * .75; + } + _updateTileColor() { + this._Tile.alpha = this.style.alpha; + } + _updateContent() { + var itemContainerPatch = { + h: this._h, + w: this._w, + x: this._w / 2, + y: this._h / 2 + }; + this.applySmooth(this._Content, itemContainerPatch, Object.keys(itemContainerPatch).reduce(((acc, prop) => { + acc[prop] = [ itemContainerPatch[prop], this._isFocusedMode ? this.style.animationEntrance : this.style.animationExit ]; + return acc; + }), {})); + } + _updateLogo() { + if (!this.logo) { + this.patch({ + Logo: undefined + }); + return; + } + var logoObject = { + w: this.style.logoWidth, + h: this.style.logoHeight, + icon: this.logo, + alpha: this._shouldShowLogo ? this.style.alpha : .001, + x: this.style.paddingX, + y: this._calculateLogoYPosition() + }; + if (!this._Logo) { + this.patch({ + Logo: _objectSpread({ + type: Icon, + mountY: 1 + }, logoObject) + }); + } else { + this.applySmooth(this._Logo, logoObject); + } + } + _calculateLogoYPosition() { + if (this._isInsetMetadata && this._Metadata) { + return this._metadataY - this._Metadata.h; + } + return this._progressBarY ? this._progressBarY - this.style.paddingYBetweenContent : this._h - this.style.paddingY; + } + get _shouldShowLogo() { + return this.logo && (this.persistentMetadata || this._isFocusedMode); + } + _updateArtwork() { + var _this$style3, _this$artwork; + this._Artwork.patch(_objectSpread(_objectSpread({ + mode: this.mode, + h: this._h, + w: this._w, + x: this._w / 2, + y: this._h / 2, + src: this.src + }, this.artwork || {}), {}, { + style: _objectSpread({ + radius: (_this$style3 = this.style) === null || _this$style3 === void 0 ? void 0 : _this$style3.radius + }, (_this$artwork = this.artwork) === null || _this$artwork === void 0 ? void 0 : _this$artwork.style), + gradient: this._shouldShowGradient, + shouldScale: this._isFocusedMode + })); + } + _getSrc() { + return this.artwork && this.artwork.src || this._src; + } + _imageLoaded() { + this._Background.alpha = 0; + } + _updateBadge() { + var _this$badge; + if (!((_this$badge = this.badge) !== null && _this$badge !== void 0 && _this$badge.title) || this._isCircleLayout) { + if (this._Badge) { + this._Content.patch({ + Badge: undefined + }); + } + return; + } + var badgePatch = _objectSpread(_objectSpread({}, this.badge), {}, { + mode: this.mode, + x: this.style.paddingX, + y: this.style.paddingY, + alpha: this._shouldShowBadgeLabel ? 1 : .001 + }); + if (!this._Badge) { + this._Content.patch({ + Badge: _objectSpread(_objectSpread({ + type: Badge + }, badgePatch), {}, { + signals: { + loadedBadge: "_updateBadge" + } + }) + }); + return; + } else { + this._Badge.patch(badgePatch); + } + this.applySmooth(this._Badge, badgePatch, _objectSpread(_objectSpread({}, badgePatch), this._badgeLabelTransitions)); + } + _updateLabel() { + var _this$label; + if (!((_this$label = this.label) !== null && _this$label !== void 0 && _this$label.title) || this._isCircleLayout) { + if (this._Label) { + this._Content.patch({ + Label: undefined + }); + } + return; + } + var labelPatch = _objectSpread(_objectSpread({}, this.label), {}, { + mode: this.mode, + x: this._w - this.style.paddingX, + y: this.style.paddingY, + alpha: this._shouldShowBadgeLabel ? 1 : .001 + }); + if (!this._Label) { + this._Content.patch({ + Label: _objectSpread(_objectSpread({ + type: Label, + mountX: 1 + }, labelPatch), {}, { + signals: { + loadedLabel: "_updateLabel" + } + }) + }); + return; + } else { + this._Label.patch(labelPatch); + } + this.applySmooth(this._Label, labelPatch, _objectSpread(_objectSpread({}, labelPatch), {}, { + x: [ labelPatch.x, this._shouldShowBadgeLabel ? this.style.animationEntrance : this.style.animationExit ] + }, this._badgeLabelTransitions)); + } + get _shouldShowBadgeLabel() { + return this.persistentMetadata || this._isFocusedMode && !this._isCircleLayout; + } + get _badgeLabelTransitions() { + return { + y: [ this._shouldShowBadgeLabel ? this.style.paddingY : 0, this._shouldShowBadgeLabel ? this.style.animationEntrance : this.style.animationExit ], + alpha: [ this._shouldShowBadgeLabel ? 1 : .001, this._shouldShowBadgeLabel ? this.style.animationEntrance : this.style.animationExit ] + }; + } + _updateCheckbox() { + var _this$checkbox; + if (!(typeof ((_this$checkbox = this.checkbox) === null || _this$checkbox === void 0 ? void 0 : _this$checkbox.checked) === "boolean" && this.checkbox.checked) || this._isCircleLayout) { + if (this._Checkbox) { + this._Content.patch({ + Checkbox: undefined + }); + } + return; + } + var checkboxPatch = _objectSpread(_objectSpread({}, this.checkbox), {}, { + mode: this.mode, + x: this._w - this.style.paddingX, + y: this._h - this.style.paddingY + }); + if (!this._Checkbox) { + this._Content.patch({ + Checkbox: _objectSpread(_objectSpread({}, checkboxPatch), {}, { + type: Checkbox, + mount: 1 + }) + }); + return; + } + this.applySmooth(this._Checkbox, checkboxPatch); + } + get _progressBarY() { + return (this._ProgressBar && this._ProgressBar._getTransition("alpha")._targetValue !== 0 ? this._ProgressBar._getTransition("y")._targetValue || this._ProgressBar.y : 0) || 0; + } + _updateProgressBar() { + var _this$progressBar2; + if (!(typeof ((_this$progressBar2 = this.progressBar) === null || _this$progressBar2 === void 0 ? void 0 : _this$progressBar2.progress) === "number" && this.progressBar.progress) || this._isCircleLayout) { + if (this._ProgressBar) { + if (this.shouldSmooth) { + this._ProgressBar._getTransition("alpha").once("finish", (() => { + this._removeProgressBar(); + })); + this._ProgressBar.smooth = { + alpha: 0 + }; + } else { + this._removeProgressBar(); + } + } + return; + } + if (this.progressBar.progress > 0) { + var progressPatch = _objectSpread(_objectSpread({}, this.progressBar), {}, { + mode: this.mode, + w: this._w - this.style.paddingX * 2, + x: this._w / 2, + y: this._h - this.style.paddingYProgress + }); + if (!this._ProgressBar) { + this._Content.patch({ + ProgressBar: _objectSpread(_objectSpread({}, progressPatch), {}, { + type: ProgressBar, + mountX: .5, + mountY: 1, + alpha: this._hasMetadata && this.shouldSmooth ? .001 : 1 + }) + }); + if (this.shouldSmooth) { + this._ProgressBar.smooth = { + alpha: [ 1, { + delay: this.style.animationEntrance.duration + } ] + }; + } + return; + } + this.applySmooth(this._ProgressBar, progressPatch, Object.keys(progressPatch).reduce(((acc, prop) => { + acc[prop] = [ progressPatch[prop], this._isFocusedMode ? this.style.animationEntrance : this.style.animationExit ]; + return acc; + }), {})); + } + } + _removeProgressBar() { + this._Content.patch({ + ProgressBar: undefined + }); + this._updateMetadata(); + } + get _shouldShowMetadata() { + return this._hasMetadata && (this.persistentMetadata && !this._isInsetMetadata || this._isFocusedMode && !this._isInsetMetadata || (this.persistentMetadata || this._isFocusedMode) && this._isInsetMetadata && !this._isCircleLayout); + } + get _isInsetMetadata() { + return this.metadataLocation === "inset"; + } + get _metadataTransitions() { + return { + y: [ this._metadataY, this._shouldShowMetadata ? this.style.animationEntrance : this.style.animationExit ], + alpha: [ this._metadataAlpha, this._shouldShowMetadata ? this.style.animationEntrance : this.style.animationExit ] + }; + } + get _hasMetadata() { + return MetadataTile.properties.some((prop => this.metadata && this.metadata[prop])); + } + get _metadataY() { + if (this._shouldShowMetadata) { + if (this._isInsetMetadata) { + return this._progressBarY ? this._progressBarY - this.style.paddingYBetweenContent : this._h - this.style.paddingY; + } + } + return this._h + this.style.paddingY; + } + get _metadataAlpha() { + return this._shouldShowMetadata ? 1 : .001; + } + get _metadataPatch() { + return { + alpha: this._metadataAlpha, + w: this._w - this.style.paddingX * 2, + x: this._w / 2, + y: this._metadataY + }; + } + get _nonSmoothingMetadataPatch() { + return _objectSpread({ + mode: this.mode, + mountX: .5, + mountY: this._isInsetMetadata ? 1 : 0, + marquee: this._isFocusedMode + }, this.metadata || {}); + } + _getMetadataLocation() { + var _this$_metadataLocati; + return (_this$_metadataLocati = this._metadataLocation) !== null && _this$_metadataLocati !== void 0 ? _this$_metadataLocati : this.style.metadataLocation; + } + _updateMetadata() { + if (!this._hasMetadata) { + this._Content.patch({ + Metadata: undefined + }); + return; + } + if (!this._Metadata && this._hasMetadata) { + this._Content.patch({ + Metadata: _objectSpread(_objectSpread({ + type: MetadataTile, + signals: { + updateComponentDimensions: "_metadataLoaded" + } + }, this._nonSmoothingMetadataPatch), this._metadataPatch) + }); + return; + } + this._Metadata.patch(this._nonSmoothingMetadataPatch); + this._animateMetadata(); + } + _animateMetadata() { + if (!this._Metadata) { + return; + } + this.applySmooth(this._Metadata, this._metadataPatch, this._metadataTransitions); + if (!this._isFocusedMode) { + this._resetMarqueeAnimation(); + } + } + _metadataLoaded() { + this._animateMetadata(); + this._updateLogo(); + this._updateDimensions(); + if (!this._isInsetMetadata) { + this.fireAncestors("$itemChanged"); + } + } + _resetMarqueeAnimation() { + var alphaTransition = this._Metadata._getTransition("alpha"); + if (alphaTransition) { + alphaTransition.on("finish", (() => { + if (this._Metadata) { + this._Metadata.resetMarquee(); + } + })); + } else { + this._Metadata.resetMarquee(); + } + } +} + +function base$u(theme) { + return { + alpha: theme.alpha.primary, + counterTextStyle: theme.typography.headline3, + itemSize: theme.layout.gutterX * 2, + itemSpacing: theme.spacer.md, + radius: theme.radius.sm + }; +} + +var mode$7 = theme => ({ + disabled: { + alpha: theme.alpha.inactive + } +}); + +var tone$d = theme => ({ + neutral: { + counterBackgroundColor: theme.color.fillInverseSecondary + }, + inverse: { + counterBackgroundColor: theme.color.fillNeutralSecondary + }, + brand: { + counterBackgroundColor: theme.color.fillInverseSecondary + } +}); + +var styles$u = Object.freeze({ + __proto__: null, + base: base$u, + mode: mode$7, + tone: tone$d +}); + +class Provider extends Base$1 { + static get __componentName() { + return "Provider"; + } + static get __themeStyle() { + return styles$u; + } + static _template() { + return { + Row: { + type: Row, + autoResizeWidth: true + } + }; + } + static get properties() { + return [ "disableRadius", "counterText", "providers", "visibleCount" ]; + } + static get tags() { + return [ "Row" ]; + } + get providersHidden() { + return this.providers.length - this._visibleCount; + } + _construct() { + this._providers = []; + super._construct(); + } + _update() { + this._updateProviders(); + this._updateCounter(); + } + _updateProviders() { + var providerList = []; + this.providers.slice(0, this.visibleCount).forEach((provider => { + var patch = { + centerInParent: true, + radius: this.disableRadius ? 0 : getMaxRoundRadius(this.style.radius, this.style.itemSize, this.style.itemSize), + alpha: this.style.alpha, + style: provider.style || {} + }; + if (provider.type === Icon && provider.icon && provider.w && provider.h) { + var ratio = provider.w / provider.h; + patch = _objectSpread(_objectSpread({ + type: Icon, + icon: provider.icon + }, provider), {}, { + w: this.style.itemSize * ratio, + h: this.style.itemSize + }, patch); + } else { + patch = _objectSpread({ + type: Icon, + w: this.style.itemSize, + h: this.style.itemSize + }, patch); + if (typeof provider === "object") { + patch = _objectSpread(_objectSpread({}, patch), provider); + } else { + patch.icon = provider; + } + } + providerList.push(patch); + })); + this._Row.patch({ + style: { + itemSpacing: this.style.itemSpacing + }, + items: providerList, + h: this.style.itemSize + }); + } + _updateCounter() { + if (this.providers.length > this.visibleCount) { + var remaining = this.providersHidden; + var counter = { + announce: "+".concat(remaining), + alpha: this.style.alpha, + w: this.style.itemSize, + h: this.style.itemSize, + centerInParent: true, + Background: { + w: this.style.itemSize, + h: this.style.itemSize, + texture: _lightningjs_core__WEBPACK_IMPORTED_MODULE_0__.Tools.getRoundRect(this.style.itemSize, this.style.itemSize, getMaxRoundRadius(this.style.radius, this.style.itemSize, this.style.itemSize), 0, null, true, this.style.counterBackgroundColor) + }, + Text: { + type: TextBox, + mountX: .5, + mountY: .5, + x: this.style.itemSize / 2, + y: this.style.itemSize / 2, + content: this.counterText || "+".concat(remaining), + style: { + textStyle: this.style.counterTextStyle + } + } + }; + this._Row.appendItems([ counter ]); + } + } + $itemChanged() { + this.signal("providerChanged"); + } + _getVisibleCount() { + var min = 1; + var max = this.providers.length; + var visibleCount = Math.min(Math.max(min, this._visibleCount), max); + if (this._visibleCount < min) { + console.warn("Warning: The specified visible count (".concat(this._visibleCount, ") is less than the minimum value (").concat(min, "). Setting it to ").concat(min, ".")); + } + if (this._visibleCount > max) { + console.warn("Warning: The specified visible count (".concat(this._visibleCount, ") is greater than the maximum value (").concat(max, "). Setting it to ").concat(max, ".")); + } + return visibleCount; + } + get w() { + return this._Row.w; + } + set announce(announce) { + super.announce = announce; + } + get announce() { + return this._announce || this._Row.items && this._Row.items.length && this._Row.items.map((item => item.announce)); + } +} + +var base$t = theme => ({ + detailsTextStyle: theme.typography.body3, + descriptionTextStyle: { + maxLines: 3 + }, + descriptionDetailsStyle: { + paddingY: 5 + }, + fadeWidth: theme.spacer.md * theme.spacer.md, + provider: { + itemSize: theme.spacer.xxxl + theme.spacer.md + } +}); + +var tone$c = theme => ({ + neutral: { + detailsTextStyle: { + textColor: theme.color.textNeutral + }, + mode: { + disabled: { + detailsTextStyle: { + textColor: theme.color.textNeutralDisabled + } + } + } + }, + inverse: { + detailsTextStyle: { + textColor: theme.color.textInverse + }, + mode: { + disabled: { + detailsTextStyle: { + textColor: theme.color.textNeutralDisabled + } + } + } + }, + brand: { + detailsTextStyle: { + textColor: theme.color.textNeutral + }, + mode: { + disabled: { + detailsTextStyle: { + textColor: theme.color.textNeutralDisabled + } + } + } + } +}); + +var styles$t = Object.freeze({ + __proto__: null, + base: base$t, + tone: tone$c +}); + +class MetadataCardContent extends MetadataBase$1 { + static get __componentName() { + return "MetadataCardContent"; + } + static get __themeStyle() { + return styles$t; + } + static _template() { + return { + Text: { + flex: { + direction: "column", + justifyContent: "flex-start" + }, + Title: { + type: TextBox + }, + Subtitle: { + type: TextBox + }, + Description: { + type: TextBox + }, + DescriptionDetails: { + type: TextBox + } + }, + DetailsWrapper: { + DetailsFader: { + Details: { + mountY: .5, + type: TextBox, + signals: { + textBoxChanged: "_resolveDetails" + } + } + }, + Provider: { + mount: 1, + type: Provider, + signals: { + providerChanged: "_resolveProvider" + } + } + } + }; + } + static get properties() { + return [ "description", "descriptionDetails", "details", "provider", "subtitle", "title" ]; + } + static get tags() { + return [ "Text", { + name: "Title", + path: "Text.Title" + }, { + name: "Subtitle", + path: "Text.Subtitle" + }, { + name: "Description", + path: "Text.Description" + }, { + name: "DescriptionDetails", + path: "Text.DescriptionDetails" + }, "DetailsWrapper", { + name: "DetailsFader", + path: "DetailsWrapper.DetailsFader" + }, { + name: "Details", + path: "DetailsWrapper.DetailsFader.Details" + }, { + name: "Provider", + path: "DetailsWrapper.Provider" + } ]; + } + _setDetails(details) { + if (details) { + this._detailsPromise = new Promise((resolve => { + this._detailsPromiseResolver = resolve; + })); + } else { + this._detailsPromise = undefined; + } + return details; + } + _setProvider(provider) { + if (provider) { + this._providerPromise = new Promise((resolve => { + this._providerPromiseResolver = resolve; + })); + } else { + this._providerPromise = undefined; + } + return provider; + } + _update() { + var _this9 = this; + return _asyncToGenerator((function*() { + _this9._updateLines(); + _this9._updateProvider(); + yield Promise.all([ _this9._detailsPromise, _this9._providerPromise ].filter(Boolean)); + _this9._updatePositions(); + }))(); + } + _updateLines() { + this._Text.w = this.w; + this._updateTitle(); + this._updateSubtitle(); + this._updateDescription(); + this._updateDescriptionDetails(); + this._updateDetails(); + } + _updateSubtitle() { + if (!this.subtitle && !this._Subtitle) { + return; + } + if (!this._Subtitle) { + this._Text.childList.addAt({ + ref: "Subtitle", + type: TextBox + }); + } + this._Subtitle.patch({ + content: this.subtitle, + style: { + textStyle: _objectSpread(_objectSpread({}, this.style.subtitleTextStyle), {}, { + maxLines: 1, + wordWrap: true, + wordWrapWidth: this._Text.w + }) + } + }); + } + _updateDescription() { + this._Description.patch({ + content: this.description, + style: { + textStyle: _objectSpread(_objectSpread({}, this.style.descriptionTextStyle), {}, { + wordWrap: true, + wordWrapWidth: this._Text.w + }) + } + }); + } + _updateDescriptionDetails() { + this._DescriptionDetails.patch({ + content: this.descriptionDetails, + style: { + textStyle: _objectSpread(_objectSpread({}, this.style.descriptionDetailsTextStyle), {}, { + maxLines: 1, + wordWrap: true, + wordWrapWidth: this._Text.w + }) + }, + y: this.style.descriptionDetailsStyle.paddingY + }); + } + _updateDetails() { + var maxWidth = this._detailsMaxW; + this._Details.patch({ + content: this.details, + style: { + textStyle: _objectSpread(_objectSpread({}, this.style.detailsTextStyle), {}, { + wordWrap: true, + maxLines: 1, + wordWrapWidth: maxWidth + this.style.fadeWidth / 2 + }) + } + }); + if (this._Details.finalW > maxWidth) { + this._DetailsFader.patch({ + w: maxWidth + this.style.fadeWidth / 2, + shader: { + type: FadeShader, + positionLeft: 0, + positionRight: this.style.fadeWidth + } + }); + } else { + this._DetailsFader.shader = undefined; + } + } + _resolveDetails() { + this._detailsPromiseResolver && this._detailsPromiseResolver(); + this._updatePositions(); + } + _updateProvider() { + if (this.provider) { + this._Provider.patch(_objectSpread(_objectSpread({ + mode: this.mode + }, this.provider), {}, { + style: this.style.provider + })); + } + } + _resolveProvider() { + this._providerPromiseResolver && this._providerPromiseResolver(); + this._updatePositions(); + this._updateDetails(); + } + _updatePositions() { + this._Text.h = this._textH; + this._Text.w = this._textW; + this._DetailsWrapper.w = this._textW; + this._DetailsWrapper.h = Math.max(this._providerH, this._Details.h); + this._DetailsWrapper.y = this.h - this._DetailsWrapper.h; + this._Details.y = this._DetailsWrapper.h / 2; + this._Provider.x = this._DetailsWrapper.w - this._providerW; + this._Provider.y = this._DetailsWrapper.h - this._providerH; + } + get _textW() { + return this.w; + } + get _textH() { + return this.h - this._providerH; + } + get _providerW() { + return this._Provider.w; + } + get _providerH() { + return this._Provider._Row._Items.h; + } + get _detailsMaxW() { + return this.w - this._providerW - this.style.fadeWidth / 2; + } + set announce(announce) { + super.announce = announce; + } + get announce() { + return this._announce || [ this._Title && this._Title.announce, this._Subtitle && this._Subtitle.announce, this._Description && this._Description.announce, this._DescriptionDetails && this._DescriptionDetails.announce, this._Details && this._Details.announce, this._Provider && this._Provider.announce ]; + } +} + +var base$s = theme => ({ + expandedWidth: utils$1.getWidthByUpCount(theme, 2), + expandedHeight: utils$1.getDimensions(theme, { + ratioX: 16, + ratioY: 9, + upCount: 4 + }).h, + imageSize: { + width: utils$1.getDimensions(theme, { + ratioX: 16, + ratioY: 9, + upCount: 4 + }).w, + height: utils$1.getDimensions(theme, { + ratioX: 16, + ratioY: 9, + upCount: 4 + }).h + }, + metadata: { + descriptionTextStyle: { + maxLines: 2 + } + }, + paddingVertical: theme.spacer.md * 1.5 +}); + +var styles$s = Object.freeze({ + __proto__: null, + base: base$s +}); + +class CardContent extends Card { + static get __componentName() { + return "CardContent"; + } + static get __themeStyle() { + return styles$s; + } + static _template() { + return _objectSpread(_objectSpread({}, super._template()), {}, { + Tile: { + type: Tile + } + }); + } + static get properties() { + return [ ...super.properties, "tile", "metadata", "orientation", "collapseToMetadata", "shouldCollapse", "src" ]; + } + static get tags() { + return [ ...super.tags, "Metadata", "Tile" ]; + } + static get aliasStyles() { + return [ { + prev: "expandedW", + curr: "expandedWidth" + }, { + prev: "expandedH", + curr: "expandedHeight" + } ]; + } + _update() { + this._updateSize(); + this._updateTile(); + this._updateMetadata(); + super._update(); + } + _updateTitle() {} + _updateTitlePosition() {} + _updateTile() { + var _tile; + var w = this.style.imageSize.w; + var h = this.style.expandedHeight; + var radius = Array.isArray(this.style.radius) && this.style.radius.length === 4 ? this.style.radius : Array(4).fill(this.style.radius); + var tileRadius = radius; + if (!this._collapse) { + tileRadius = this._orientation === "horizontal" ? [ radius[0], 0, 0, radius[3] ] : [ radius[0], radius[1], 0, 0 ]; + } + if (this._orientation !== "horizontal") { + w = this.style.expandedWidth; + h = this.style.imageSize.h; + } + var tile = this.tile; + if (this.src) { + tile = utils$1.clone({ + src: this.src + }, this.tile); + } + this._Tile.patch(_objectSpread(_objectSpread({ + w: w, + h: h + }, tile), {}, { + style: _objectSpread(_objectSpread({}, ((_tile = tile) === null || _tile === void 0 ? void 0 : _tile.style) || {}), {}, { + radius: tileRadius + }), + persistentMetadata: true, + alpha: this._shouldShowTile ? 1 : 0 + })); + } + _updateMetadata() { + var metadataPatch = _objectSpread(_objectSpread(_objectSpread(_objectSpread({}, this.metadata), this._metadataPosition), this._metadataDimensions), {}, { + mode: this.mode, + alpha: this._shouldShowMetadata ? 1 : 0, + style: this.style.metadata + }); + if (this.style.marqueeOnFocus) { + metadataPatch.marquee = this._isFocusedMode; + } + if (!this._Metadata) { + metadataPatch.type = MetadataCardContent; + } + this.patch({ + Metadata: metadataPatch + }); + } + _updateSize() { + var w = this.style.expandedWidth; + var h = this.style.expandedHeight; + if (this._collapse) { + if (this._orientation === "horizontal") { + w = this._collapseW; + } else { + h = this._collapseH; + } + } + this.w = w; + this.h = h; + } + _getSrc() { + return this.tile && (this.tile.artwork && this.tile.artwork.src || this.tile.src) || this._src; + } + get _metadataDimensions() { + var paddingHorizontal = this.style.paddingHorizontal * 2; + var paddingVertical = this.style.paddingVertical * 2; + var w = this.style.expandedWidth - this.style.imageSize.w - paddingHorizontal; + var h = this.style.expandedHeight - paddingVertical; + if (this.orientation !== "horizontal") { + w = this.style.expandedWidth - paddingHorizontal; + h = this.style.expandedHeight - this.style.imageSize.h - paddingVertical; + } + return { + w: w, + h: h + }; + } + get _metadataPosition() { + var paddingHorizontal = this.style.paddingHorizontal; + var paddingVertical = this.style.paddingVertical; + var x = paddingHorizontal + (this._collapse ? 0 : this.style.imageSize.w); + var y = paddingVertical; + if (this.orientation !== "horizontal") { + x = paddingHorizontal; + y = paddingVertical + (this._collapse ? 0 : this.style.imageSize.h); + } + return { + x: x, + y: y + }; + } + get _shouldShowMetadata() { + return !this._collapse || this.collapseToMetadata; + } + get _shouldShowTile() { + return !this._collapse || this._collapse && !this.collapseToMetadata; + } + get _collapse() { + return this.shouldCollapse && !this._isFocusedMode; + } + get _collapseW() { + return this.collapseToMetadata ? this.style.expandedWidth - this.style.imageSize.w : this.style.imageSize.w; + } + get _collapseH() { + return this.collapseToMetadata ? this.style.expandedHeight - this.style.imageSize.h : this.style.imageSize.h; + } + set announce(announce) { + super.announce = announce; + } + get announce() { + return this._announce || [ this._Metadata && this._Metadata.announce, this._Tile && this._Tile.announce ]; + } +} + +class CardContentHorizontal extends CardContent { + static get __componentName() { + return "CardContentHorizontal"; + } + static get __themeStyle() { + return styles$s; + } + _init() { + this._orientation = "horizontal"; + super._init(); + } +} + +var base$r = theme => { + var {w: w, h: h} = utils$1.getDimensions(theme, { + ratioX: 16, + ratioY: 9, + upCount: 3 + }); + return { + expandedWidth: utils$1.getWidthByColumnSpan(theme, 8), + expandedHeight: h, + imageSize: { + width: w, + height: h + }, + metadata: { + descriptionTextStyle: { + maxLines: 3 + } + } + }; +}; + +var styles$r = Object.freeze({ + __proto__: null, + base: base$r +}); + +class CardContentHorizontalLarge extends CardContentHorizontal { + static get __componentName() { + return "CardContentHorizontalLarge"; + } + static get __themeStyle() { + return styles$r; + } +} + +var base$q = theme => ({ + expandedWidth: utils$1.getWidthByUpCount(theme, 4), + expandedHeight: utils$1.getDimensions(theme, { + ratioX: 16, + ratioY: 9, + upCount: 4 + }).h + theme.spacer.xxxl * 7 + theme.spacer.lg + theme.spacer.xxs, + metadata: { + descriptionTextStyle: { + maxLines: 3 + } + }, + marqueeOnFocus: true +}); + +var styles$q = Object.freeze({ + __proto__: null, + base: base$q +}); + +class CardContentVertical extends CardContent { + static get __componentName() { + return "CardContentVertical"; + } + static get __themeStyle() { + return styles$q; + } + _init() { + this._orientation = "vertical"; + super._init(); + } +} + +var base$p = theme => ({ + expandedHeight: utils$1.getDimensions(theme, { + ratioX: 16, + ratioY: 9, + upCount: 4 + }).h + theme.spacer.md * 14, + metadata: { + descriptionTextStyle: { + maxLines: 1 + } + } +}); + +var styles$p = Object.freeze({ + __proto__: null, + base: base$p +}); + +class CardContentVerticalSmall extends CardContentVertical { + static get __componentName() { + return "CardContentVerticalSmall"; + } + static get __themeStyle() { + return styles$p; + } + _setMetadata(metadata) { + return _objectSpread(_objectSpread({}, metadata), {}, { + details: undefined, + provider: undefined + }); + } +} + +var base$o = theme => { + var strokeWidth = theme.stroke.sm; + var size = theme.spacer.xl; + return { + width: size, + height: size, + iconWidth: theme.spacer.md, + iconHeight: theme.spacer.md, + radius: theme.radius.xs, + strokeWidth: strokeWidth + }; +}; + +var styles$o = Object.freeze({ + __proto__: null, + base: base$o +}); + +class CheckboxSmall extends Checkbox { + static get __themeStyle() { + return styles$o; + } +} + +var base$n = theme => ({ + itemSpacing: theme.layout.gutterY, + scrollIndex: 0, + itemTransition: _objectSpread(_objectSpread({}, theme.animation.standardEntrance), {}, { + duration: theme.animation.duration.fast + }) +}); + +var styles$n = Object.freeze({ + __proto__: null, + base: base$n +}); + +class Column extends NavigationManager { + static get __componentName() { + return "Column"; + } + static get __themeStyle() { + return styles$n; + } + static _template() { + return _objectSpread(_objectSpread({}, super._template()), {}, { + direction: "column" + }); + } + _isOnScreenForScrolling(child) { + if (!child) return false; + var y = getY(child); + if (!Number.isFinite(y)) return false; + var itemsTransitionY = this.getTransitionYTargetValue(); + var columnY = this.core.renderContext.py; + var itemY = columnY + itemsTransitionY + y; + var yModifier; + if (child.transition("y")) { + yModifier = child.y - child.transition("y").targetValue; + itemY = itemY - yModifier; + } + return itemY >= columnY && itemY + child.h <= columnY + this.h; + } + _shouldScroll() { + if (this.alwaysScroll) { + return true; + } + var shouldScroll = false; + if (!this.neverScroll) { + var isCompletelyOnScreen = this._isOnScreenForScrolling(this.selected); + var lastChild = this.Items.childList.last; + shouldScroll = lastChild && (this.shouldScrollUp() || this.shouldScrollDown() || !isCompletelyOnScreen); + } + if (this.selectedIndex < this.scrollIndex) { + shouldScroll = false; + } + return shouldScroll; + } + _getScrollY() { + var itemsContainerY; + var itemIndex = this.selectedIndex - this.scrollIndex; + itemIndex = itemIndex < 0 ? 0 : itemIndex; + if (itemIndex === this._firstFocusableIndex()) { + itemIndex = 0; + } + if (this.Items.children[itemIndex]) { + itemsContainerY = this.Items.children[itemIndex].transition("y") ? -this.Items.children[itemIndex].transition("y").targetValue + this.itemPosY : -this.Items.children[itemIndex].y + this.itemPosY; + } + return itemsContainerY; + } + _render(next, prev) { + this._prevLastScrollIndex = this._lastScrollIndex; + if (this.plinko && prev && prev.selected && !(this.items.indexOf(prev) === 0 && prev.skipPlinko)) { + var prevPlinko = this.checkSkipPlinko(prev, next); + next.selectedIndex = this._getIndexOfItemNear(next, prevPlinko || prev); + } else if (next && !next.selectedIndex) { + next.selectedIndex = 0; + } + var itemsContainerY; + if (!this.Items.children.length) { + itemsContainerY = this.itemPosY; + } else if (this._shouldScroll()) { + itemsContainerY = this._getScrollY(); + } + if (itemsContainerY !== undefined) { + this.updatePositionOnAxis(this.Items, itemsContainerY); + } + this.onScreenEffect(this.onScreenItems); + } + _performRender() { + this._render(this.selected, this.prevSelected); + } + checkSkipPlinko(prev, next) { + if (!prev || !prev.skipPlinko || [ 0, this.items.length - 1 ].includes(this.items.indexOf(prev))) { + return null; + } + var prevIndex = this.items.indexOf(prev); + var direction = prevIndex - this.items.indexOf(next); + var up = direction > 0; + var prevItems = up ? this.items.slice(prevIndex).map((i => ({ + skipPlinko: i.skipPlinko, + index: this.items.indexOf(i) + }))) : this.items.slice(0, prevIndex + 1).map((i => ({ + skipPlinko: i.skipPlinko, + index: this.items.indexOf(i) + }))).reverse(); + var endOfMultiSkipPlinkos = prevItems.find((i => i.skipPlinko && !this.items[i.index + direction].skipPlinko)); + var prevPlinkoIndex = endOfMultiSkipPlinkos ? endOfMultiSkipPlinkos.index + direction : prevIndex + direction; + return this.items[prevPlinkoIndex]; + } + get _itemsY() { + return getY(this.Items); + } + $removeItem(item) { + if (item) { + var wasSelected = item === this.selected; + this.Items.childList.remove(item); + this.queueRequestUpdate(); + if (wasSelected || this.selectedIndex >= this.items.length) { + this.selectedIndex = this._selectedIndex; + } + if (!this.items.length) { + this.fireAncestors("$columnEmpty"); + } + } + } + $columnChanged() { + this.queueRequestUpdate(); + } + _isOnScreen(child) { + if (!child) return false; + return this._isComponentVerticallyVisible(child); + } + onScreenEffect() {} +} + +var base$m = theme => { + var paddingX = theme.spacer.lg; + var radius = theme.radius.xl; + var logoRadius = Math.max(radius - paddingX / 2, 0); + return { + height: theme.spacer.md * 8, + iconStyle: { + radius: radius, + width: theme.spacer.xxxl, + height: theme.spacer.xxxl + }, + logoStyle: { + radius: logoRadius, + width: theme.spacer.md * 7, + height: theme.spacer.md * 6 + }, + minWidth: theme.spacer.md * 9, + paddingX: paddingX, + paddingXNoTitle: theme.spacer.md, + prefixPadding: theme.spacer.md, + radius: radius, + contentSpacing: theme.spacer.md + }; +}; + +var styles$m = Object.freeze({ + __proto__: null, + base: base$m +}); + +class Control extends ButtonSmall { + static get __componentName() { + return "Control"; + } + static get __themeStyle() { + return styles$m; + } + static get properties() { + return [ ...super.properties, "icon", "logo", "shouldCollapse" ]; + } + static get aliasStyles() { + return [ { + prev: "titlePadding", + curr: "contentSpacing" + } ]; + } + _update() { + this._updatePrefixStyle(); + super._updateTitle(); + this._updateCollapseStatus(); + super._update(); + } + _updateCollapseStatus() { + if (this._Title) { + this._Title.visible = !this._collapse; + } + } + _updatePrefixStyle() { + if (this._prefix) { + if (this.logo) { + this._updatePrefixObj(this.logo, { + style: _objectSpread({ + color: undefined + }, this.style.logoStyle) + }); + } else if (this.icon) { + this._updatePrefixObj(this.icon, { + style: this.style.iconStyle + }); + } + } + } + _patchTitle(x, mountX) { + this._Title.patch({ + x: x, + mountX: mountX + }); + } + _updateContentPosition() { + if (this._prefix && this._Title) { + this._Content.patch({ + mountX: 0, + x: this._paddingLeft + }); + switch (this._justify) { + case "left": + this._patchTitle(0, 0); + break; + + case "right": + if (this.w < this._Prefix.w + this._Title.w) { + this._patchTitle(0, 0); + } else { + var leftOverSpace = this.w - (this._paddingLeft + this._paddingRight + this._Prefix.w + this.style.contentSpacing); + this._patchTitle(leftOverSpace, 1); + } + break; + + case "center": + default: + if (this.fixed) { + if (this.w < this._Prefix.w + this._Title.w) { + this._patchTitle(0, 0); + } else { + var middle = (this.w - (this._paddingLeft + this._Prefix.w + this._paddingRight)) / 2; + this._patchTitle(middle, .5); + } + } else if (this._Prefix !== undefined) { + var _middle = (this.w - (this._paddingLeft + this._Prefix.w + this.style.contentSpacing + this._paddingRight)) / 2; + this._patchTitle(_middle, .5); + } + break; + } + } else { + super._updateContentPosition(); + this._Title && this._patchTitle(0, 0); + } + } + _setPrefix() { + return; + } + _setSuffix() { + return; + } + _updatePrefixObj(icon) { + var props = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + this._prefix = _objectSpread({ + type: Icon, + icon: icon + }, props); + } + _setIcon(icon) { + if (!this.logo) { + if (icon) { + this._updatePrefixObj(icon, { + style: this.style.iconStyle + }); + } else { + this._prefix = icon; + } + } + return icon; + } + _setLogo(logo) { + if (logo) { + this._updatePrefixObj(logo, { + style: _objectSpread({ + color: undefined + }, this.style.logoStyle) + }); + } else if (this.icon) { + this._updatePrefixObj(this.icon, { + style: this.style.iconStyle + }); + } else { + this._prefix = logo; + } + return logo; + } + get _paddingLeft() { + return this.logo ? this.style.paddingXNoTitle : this.style.paddingX; + } + get _paddingRight() { + return this.logo && (!this._hasTitle || this._collapse) ? this.style.paddingXNoTitle : this.style.paddingX; + } + get _collapse() { + return this.shouldCollapse && !this._isFocusedMode; + } + get _announceComponentName() { + return Control.__componentName; + } +} + +var base$l = theme => { + var parentStyle = base$m(theme); + var height = theme.spacer.md * 7; + var radiusOffset = (parentStyle.height - height) / 2; + var radius = Math.max(parentStyle.radius - radiusOffset, 0); + var logoRadius = Math.max(radius - parentStyle.paddingX / 2, 0); + return { + height: height, + logoStyle: { + radius: logoRadius, + height: theme.spacer.md * 5, + width: theme.spacer.md * 6 + }, + radius: radius, + minWidth: theme.spacer.md * 8, + textStyle: theme.typography.button2 + }; +}; + +var styles$l = Object.freeze({ + __proto__: null, + base: base$l +}); + +class ControlSmall extends Control { + static get __componentName() { + return "ControlSmall"; + } + static get __themeStyle() { + return styles$l; + } +} + +var base$k = theme => ({ + width: getWidthByUpCount(theme, 1), + titleMarginBottom: theme.spacer.lg, + titleMarginLeft: theme.layout.gutterX, + titleTextStyle: _objectSpread(_objectSpread({}, theme.typography.headline1), {}, { + textColor: theme.color.textNeutral + }) +}); + +var tone$b = theme => ({ + neutral: { + titleTextStyle: { + textColor: theme.color.textNeutral + } + }, + inverse: { + titleTextStyle: { + textColor: theme.color.textInverse + } + }, + brand: { + titleTextStyle: { + textColor: theme.color.textNeutral + } + } +}); + +var styles$k = Object.freeze({ + __proto__: null, + base: base$k, + tone: tone$b +}); + +class TitleRow extends Row { + static get __componentName() { + return "TitleRow"; + } + static get __themeStyle() { + return styles$k; + } + static get properties() { + return [ ...super.properties, "title" ]; + } + static get tags() { + return [ ...super.tags, "Title" ]; + } + static get aliasStyles() { + return [ { + prev: "rowMarginTop", + curr: "titleMarginBottom" + } ]; + } + _titleLoaded() { + this._updateRow(); + } + _construct() { + super._construct(); + this._autoResizeHeight = true; + } + _update() { + super._update(); + this._updateTitle(); + this._updateRow(); + } + _autoResize() { + this.w = this.w || this.style.w; + this.h = this.autoResizeHeight ? this.Items.y + this.Items.h : this.h; + } + _updateTitle() { + if (!this.title) { + if (this._Title) { + this.patch({ + Title: undefined + }); + } + return; + } + var titlePatch = { + x: this.style.titleMarginLeft, + content: this.title, + style: { + textStyle: this.style.titleTextStyle + } + }; + if (!this._Title) { + titlePatch = _objectSpread(_objectSpread({}, this._titleFirstLoadProps), titlePatch); + } + this.patch({ + Title: titlePatch + }); + } + get _titleFirstLoadProps() { + return { + type: TextBox, + signals: { + textBoxChanged: "_titleLoaded" + } + }; + } + _updateRow() { + this.applySmooth(this.Items, { + y: this.title ? this._Title.finalH + this.style.titleMarginBottom : 0 + }); + } + set announce(announce) { + super.announce = announce; + } + get announce() { + return this._announce || this._Title && this._Title.announce; + } +} + +var base$j = theme => ({ + extraItemSpacing: theme.spacer.lg +}); + +var styles$j = Object.freeze({ + __proto__: null, + base: base$j +}); + +class ControlRow extends TitleRow { + static get __componentName() { + return "ControlRow"; + } + static get __themeStyles() { + return styles$j; + } + static _template() { + return _objectSpread(_objectSpread({}, super._template()), {}, { + alpha: 0, + lazyScroll: true, + signals: { + selectedChange: "_getMoreItems" + } + }); + } + static get properties() { + return [ ...super.properties, "extraItemSpacing" ]; + } + _construct() { + super._construct(); + this._leftControls = []; + this._contentItems = []; + this._rightControls = []; + this._lastLeftControlIndex = -1; + this._lastItemIndex = -1; + this._lazyLoadBuffer = 0; + } + _updateContent() { + var itemsToAppend = []; + if (this.leftControls.length) { + itemsToAppend.push(...this._withExtraSpacing(this.leftControls, true)); + } + if (this.contentItems.length) { + itemsToAppend.push(...this._withExtraSpacing(this.contentItems)); + } + if (this.rightControls.length) { + itemsToAppend.push(...this.rightControls); + } + if (itemsToAppend.length) { + this.patch({ + alpha: 1, + items: itemsToAppend, + selectedIndex: this.leftControls.length, + startLazyScrollIndex: this.leftControls.length, + stopLazyScrollIndex: this.leftControls.length + this.items.length - 1 + }); + } + } + _withExtraSpacing(items) { + var isControl = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; + var itemsCopy = [ ...items ]; + var prevItems = isControl ? this._prevLeftControls : this._prevItems; + if (prevItems && prevItems.length && itemsCopy[prevItems.length - 1]) { + itemsCopy[prevItems.length - 1].extraItemSpacing = 0; + } + itemsCopy[itemsCopy.length - 1].extraItemSpacing = this.extraItemSpacing == undefined ? this.style.extraItemSpacing : this.extraItemSpacing; + if (isControl) { + this._prevLeftControls = itemsCopy; + } else { + this._prevItems = itemsCopy; + } + return itemsCopy; + } + _getMoreItems() { + if (this.lazyLoadBuffer) { + var loadMoreIndex = this.contentItems.length - 1 - this.lazyLoadBuffer; + if (this.selectedIndex - this.leftControls.length >= loadMoreIndex && this.selectedIndex < this.leftControls.length + this.contentItems.length) { + this.loadMoreItems(); + } + } + } + loadMoreItems() { + this.signal("loadMoreItems"); + } + _selectedChange(selected, prevSelected) { + super._selectedChange(selected, prevSelected); + this._getMoreItems(); + } + _appendItemsAt(items, appendIndex, removeSpacingIndex) { + var itemsCopy = [ ...items ]; + if (removeSpacingIndex != undefined && removeSpacingIndex >= 0) { + this.items[removeSpacingIndex].extraItemSpacing = undefined; + itemsCopy[itemsCopy.length - 1].extraItemSpacing = this.extraItemSpacing == undefined ? this.style.extraItemSpacing : this.extraItemSpacing; + } + this.appendItemsAt(itemsCopy, appendIndex); + } + addContentItems(items) { + var lastSelected = this.selectedIndex; + var itemsToAdd = this._createContentItems(items); + var addIndex = this._lastItemIndex + 1; + this._appendItemsAt(itemsToAdd, addIndex, this._lastItemIndex); + this._lastItemIndex += itemsToAdd.length; + if (this._contentItems) { + this._contentItems = [ ...this.contentItems, ...itemsToAdd ]; + } + this._updateContent(); + this.selectedIndex = lastSelected; + this.patch({ + stopLazyScrollIndex: this.leftControls.length + this.items.length - 1 + }); + } + addContentItemsAt(items, itemIndex) { + var itemsToAdd = this._createContentItems(items); + var addIndex = this._lastLeftControlIndex + 1 + itemIndex; + if (addIndex === this._lastItemIndex + 1) { + this.addContentItems(itemsToAdd); + } else { + this._appendItemsAt(itemsToAdd, addIndex); + if (this._contentItems) { + this._contentItems.splice(addIndex, 0, ...itemsToAdd); + this._lastItemIndex = this.contentItems.length - 1; + } + this.patch({ + stopLazyScrollIndex: this.leftControls.length + this.items.length - 1 + }); + } + } + removeContentItemAt(index) { + var removeIndex = this._lastLeftControlIndex + 1 + index; + this.removeItemAt(removeIndex); + this._lastItemIndex--; + if (this._contentItems) { + this._contentItems.splice(index, 1); + } + this.patch({ + startLazyScrollIndex: this.leftControls.length, + stopLazyScrollIndex: this.leftControls.length + this.items.length - 1 + }); + } + addLeftControls(controls) { + var itemsToAdd = this._createControls(controls); + var addIndex = this._lastLeftControlIndex + 1; + this._appendItemsAt(itemsToAdd, addIndex, this._lastLeftControlIndex); + if (this._leftControls) { + this._leftControls = [ ...this._leftControls, ...controls ]; + this._lastLeftControlIndex = this._leftControls.length - 1; + this._lastItemIndex += controls.length; + } + this.patch({ + startLazyScrollIndex: this.leftControls.length, + stopLazyScrollIndex: this.leftControls.length + this.items.length - 1 + }); + } + addLeftControlsAt(controls, index) { + var itemsToAdd = this._createControls(controls); + if (index === this._lastLeftControlIndex + 1) { + this.addLeftControls(controls); + } else { + this._appendItemsAt(itemsToAdd, index); + if (this.leftControls) { + this._leftControls.splice(index, 0, ...controls); + this._lastLeftControlIndex = this._leftControls.length - 1; + this._lastItemIndex += controls.length; + } + this.patch({ + startLazyScrollIndex: this.leftControls.length, + stopLazyScrollIndex: this.leftControls.length + this.items.length - 1 + }); + } + } + removeLeftControlAt(index) { + this.removeItemAt(index); + this._lastLeftControlIndex--; + this._lastItemIndex--; + if (this.leftControls) { + this._leftControls.splice(index, 1); + } + this.patch({ + startLazyScrollIndex: this.leftControls.length, + stopLazyScrollIndex: this.leftControls.length + this.items.length - 1 + }); + } + addRightControls(controls) { + this._rightControls.push(...controls); + this._appendItemsAt(this._createControls(controls), this.items.length); + } + addRightControlsAt(controls, index) { + var appendIndex = this._leftControls.length + this._contentItems.length + index; + this._rightControls.splice(index, 0, ...controls); + this._appendItemsAt(this._createControls(controls), appendIndex); + } + removeRightControlAt(index) { + var removeIndex = this.leftControls.length + this.contentItems.length + index; + this.removeItemAt(removeIndex); + if (this.rightControls) { + this._rightControls.splice(index, 1); + } + } + _createControls(controls) { + return controls.map((controlProps => _objectSpread({ + backgroundType: "fill", + centerInParent: true + }, controlProps))); + } + _createContentItems(contentItems) { + var newContentItems = contentItems.map((itemProps => _objectSpread(_objectSpread({}, itemProps), {}, { + centerInParent: true + }))); + return newContentItems; + } + _setLeftControls(leftControls) { + this._leftControls = this._createControls(leftControls); + this._lastLeftControlIndex = leftControls.length - 1; + this._updateContent(); + } + _getLeftControls() { + return this._leftControls; + } + _setRightControls(rightControls) { + this._rightControls = this._createControls(rightControls); + this._updateContent(); + } + _getRightControls() { + return this._rightControls; + } + _getContentItems() { + return this._contentItems; + } + _setContentItems(items) { + this._contentItems = this._createContentItems(items); + this._lastItemIndex = this._lastLeftControlIndex + items.length; + this._updateContent(); + } + _getLeftControlItems() { + if (this.leftControls.length) { + return this.items.slice(0, this._lastLeftControlIndex + 1); + } + return []; + } + _getContentItemItems() { + if (this.contentItems.length) { + return this.items.slice(this._lastLeftControlIndex + 1, this._lastItemIndex + 1); + } + return []; + } + _getRightControlItems() { + if (this.rightControls.length) { + var leftSiblingIndex = this._lastItemIndex || this._lastLeftControlIndex; + return leftSiblingIndex ? this.items.slice(leftSiblingIndex + 1) : this.items; + } + return []; + } + set leftControls(leftControls) { + this._setLeftControls(leftControls); + } + get leftControls() { + return this._getLeftControls(); + } + set rightControls(rightControls) { + this._setRightControls(rightControls); + } + get rightControls() { + return this._getRightControls(); + } + set contentItems(items) { + this._setContentItems(items); + } + get contentItems() { + return this._getContentItems(); + } + set lazyLoadBuffer(lazyLoadBuffer) { + this._lazyLoadBuffer = lazyLoadBuffer; + this._getMoreItems(); + } + get lazyLoadBuffer() { + return this._lazyLoadBuffer; + } +} + +var base$i = theme => ({ + propertyTextStyle: _objectSpread(_objectSpread({}, theme.typography.headline1), {}, { + textColor: theme.color.textNeutral + }), + valueTextStyle: _objectSpread(_objectSpread({}, theme.typography.body1), {}, { + textColor: theme.color.textNeutral + }) +}); + +var styles$i = Object.freeze({ + __proto__: null, + base: base$i +}); + +class Spacer extends Base$1 { + static get __componentName() { + return "Spacer"; + } + static _template() { + return { + Line: { + h: Spacer._lineThickness, + rect: true, + mountY: .5, + TickLeft: _objectSpread(_objectSpread({}, Spacer._tick), {}, { + x: Spacer._lineThickness * -1 + }), + TickRight: Spacer._tick + } + }; + } + static get properties() { + return [ "lineColor" ]; + } + static get tags() { + return [ "Line", "TickLeft", "TickRight" ]; + } + static get _lineThickness() { + return 3; + } + static get _tickLength() { + return 25; + } + static get _tick() { + return { + rect: true, + mountY: .5, + w: Spacer._lineThickness, + h: Spacer._tickLength, + y: Spacer._lineThickness / 2 + }; + } + _update() { + this._Line.w = this.w; + this._TickRight.x = this._Line.w; + if (this.lineColor) { + this._Line.color = this._TickLeft.color = this._TickRight.color = this.lineColor; + } + this.rotation = this.vertical ? Math.PI / 2 : 0; + this.signal("spacerLoaded"); + } +} + +class GridOverlay extends Base$1 { + static get __componentName() { + return "GridOverlay"; + } + static get __themeStyle() { + return styles$i; + } + static _template() { + var textRow = { + type: Row, + autoResizeHeight: true, + Items: { + Property: { + type: TextBox, + signals: { + textBoxChanged: "_update" + } + }, + Value: { + type: TextBox, + signals: { + textBoxChanged: "_update" + }, + centerInParent: true + } + } + }; + return { + Columns: { + alpha: .001, + type: Row + }, + Margins: { + alpha: .001, + Horizontal: { + Left: { + type: Spacer, + signals: { + spacerLoaded: "_update" + } + }, + Right: { + type: Spacer, + signals: { + spacerLoaded: "_update" + } + } + }, + Vertical: { + Top: { + type: Spacer, + vertical: true + } + } + }, + Safe: { + alpha: .001, + Horizontal: { + Left: { + type: Spacer, + signals: { + spacerLoaded: "_update" + } + }, + Right: { + type: Spacer, + signals: { + spacerLoaded: "_update" + } + } + }, + Vertical: { + Top: { + type: Spacer, + vertical: true + }, + Bottom: { + type: Spacer, + vertical: true + } + } + }, + Gutters: { + alpha: .001, + Horizontal: { + type: Spacer, + signals: { + spacerLoaded: "_update" + } + } + }, + TextPanel: { + alpha: .001, + type: Column, + autoResizeHeight: true, + Items: { + ScreenW: textRow, + ScreenH: textRow, + ColumnCount: textRow, + MarginX: textRow, + MarginY: textRow, + GutterX: textRow, + GutterY: textRow, + Safe: textRow + } + } + }; + } + static get properties() { + return [ "showColumns", "showMargins", "showSafe", "showGutters", "showText" ]; + } + static get tags() { + return [ "Columns", "Margins", { + name: "MarginHorizontal", + path: "Margins.Horizontal" + }, { + name: "MarginLeft", + path: "Margins.Horizontal.Left" + }, { + name: "MarginRight", + path: "Margins.Horizontal.Right" + }, { + name: "MarginVertical", + path: "Margins.Vertical" + }, { + name: "MarginTop", + path: "Margins.Vertical.Top" + }, "Safe", { + name: "SafeHorizontal", + path: "Safe.Horizontal" + }, { + name: "SafeLeft", + path: "Safe.Horizontal.Left" + }, { + name: "SafeRight", + path: "Safe.Horizontal.Right" + }, { + name: "SafeVertical", + path: "Safe.Vertical" + }, { + name: "SafeTop", + path: "Safe.Vertical.Top" + }, { + name: "SafeBottom", + path: "Safe.Vertical.Bottom" + }, "Gutters", { + name: "GutterHorizontal", + path: "Gutters.Horizontal" + }, "TextPanel", { + name: "TextScreenW", + path: "TextPanel.Items.ScreenW" + }, { + name: "TextScreenH", + path: "TextPanel.Items.ScreenH" + }, { + name: "TextColumnCount", + path: "TextPanel.Items.ColumnCount" + }, { + name: "TextMarginX", + path: "TextPanel.Items.MarginX" + }, { + name: "TextMarginY", + path: "TextPanel.Items.MarginY" + }, { + name: "TextGutterX", + path: "TextPanel.Items.GutterX" + }, { + name: "TextGutterY", + path: "TextPanel.Items.GutterY" + }, { + name: "TextSafe", + path: "TextPanel.Items.Safe" + } ]; + } + _construct() { + super._construct(); + this._showColumns = this._showMargins = this._showSafe = this._showGutters = this._showText = true; + } + _update() { + this._updateGlobalThemeProps(); + this._updateMargins(); + this._updateSafe(); + this._updateColumns(); + this._updateGutters(); + this._updateText(); + this._updateVisibility(); + } + _updateVisibility() { + this._Columns.smooth = { + alpha: Number(this.showColumns) + }; + this._Margins.smooth = { + alpha: Number(this.showMargins) + }; + this._Safe.smooth = { + alpha: Number(this.showSafe) + }; + this._Gutters.smooth = { + alpha: Number(this.showGutters) + }; + this._TextPanel.smooth = { + alpha: Number(this.showText) + }; + } + _updateGlobalThemeProps() { + var {layout: layout, color: color} = contextInstance.theme; + var {screenW: screenW, screenH: screenH, columnCount: columnCount, marginX: marginX, marginY: marginY, gutterX: gutterX, gutterY: gutterY, safe: safe} = layout; + this._screenW = screenW; + this._screenH = screenH; + this._columnCount = columnCount; + this._marginX = marginX; + this._marginY = marginY; + this._safe = safe; + this._gutterX = gutterX; + this._gutterY = gutterY; + this._columnColor = color.interactiveNeutralFocusSoft; + this._marginColor = color.green; + this._safeColor = color.red; + this._gutterColor = color.blue; + } + _updateMargins() { + var marginPatch = { + lineColor: this._marginColor + }; + var marginHorizontalPatch = _objectSpread(_objectSpread({}, marginPatch), {}, { + w: this._marginX + }); + this._MarginHorizontal.y = this._screenH / 2; + this._MarginLeft.patch(marginHorizontalPatch); + this._MarginRight.patch(marginHorizontalPatch); + this._MarginRight.x = this._screenW - this._marginX; + var marginVerticalPatch = _objectSpread(_objectSpread({}, marginPatch), {}, { + w: this._marginY + }); + this._MarginVertical.x = this._marginX - marginVerticalPatch.w / 2; + this._MarginTop.patch(marginVerticalPatch); + this._MarginTop.patch(marginVerticalPatch); + this._MarginTop.y = marginVerticalPatch.w / 2; + } + _updateSafe() { + var safePatch = { + lineColor: this._safeColor, + w: this._safe + }; + this._SafeHorizontal.y = this._screenH / 4; + this._SafeLeft.patch(safePatch); + this._SafeRight.patch(safePatch); + this._SafeRight.x = this._screenW - this._safe; + this._SafeVertical.x = (this._screenW - safePatch.w) / 2; + this._SafeVertical.y = safePatch.w / 2; + this._SafeTop.patch(safePatch); + this._SafeBottom.patch(safePatch); + this._SafeBottom.y = this._screenH - this._safe; + } + _updateColumns() { + this._Columns.patch({ + w: this._screenW, + h: this._screenH, + x: this._marginX, + style: { + itemSpacing: this._gutterX + }, + items: this._columnRects + }); + } + get _columnRects() { + return Array.apply(null, { + length: this._columnCount + }).map((() => ({ + rect: true, + w: getWidthByColumnSpan(this.theme, 1), + h: this._screenH, + color: this._columnColor + }))); + } + _updateGutters() { + var gutterPatch = { + lineColor: this._gutterColor, + w: this._gutterY + }; + this._GutterHorizontal.patch(_objectSpread(_objectSpread({}, gutterPatch), {}, { + x: (this._screenW - gutterPatch.w) / 2, + y: this._screenH / 4 + })); + } + _updatePropertyTextStyle(textPanelName, color) { + var style = { + textStyle: _objectSpread({}, this.style.propertyTextStyle) + }; + if (color) { + style.textStyle.textColor = color; + } + textPanelName.Items.tag("Property").style = style; + } + _updateValueTextStyle(textPanelName) { + textPanelName.Items.tag("Value").style = { + textStyle: this.style.valueTextStyle + }; + } + _updateText() { + var prop = "Property"; + var val = "Value"; + this._TextPanel.x = this._screenW - this._marginX - getWidthByColumnSpan(this.theme, 3); + this._TextPanel.y = this._safe; + this._TextScreenW.Items.tag(prop).content = "Screen Width"; + this._TextScreenW.Items.tag(val).content = "".concat(this._screenW, "px"); + this._updatePropertyTextStyle(this._TextScreenW); + this._updateValueTextStyle(this._TextScreenW); + this._TextScreenH.Items.tag(prop).content = "Screen Height"; + this._TextScreenH.Items.tag(val).content = "".concat(this._screenH, "px"); + this._updatePropertyTextStyle(this._TextScreenH); + this._updateValueTextStyle(this._TextScreenH); + this._TextColumnCount.Items.tag(prop).content = "Columns"; + this._TextColumnCount.Items.tag(val).content = "".concat(this._columnCount, ", ").concat(Math.round(getWidthByColumnSpan(this.theme, 1)), "px each"); + this._updatePropertyTextStyle(this._TextColumnCount); + this._updateValueTextStyle(this._TextColumnCount); + this._TextMarginX.Items.tag(prop).content = "Margin-X"; + this._TextMarginX.Items.tag(val).content = "".concat(this._marginX, "px"); + this._updatePropertyTextStyle(this._TextMarginX, this._marginColor); + this._updateValueTextStyle(this._TextMarginX); + this._TextMarginY.Items.tag(prop).content = "Margin-Y"; + this._TextMarginY.Items.tag(val).content = "".concat(this._marginY, "px"); + this._updatePropertyTextStyle(this._TextMarginY, this._marginColor); + this._updateValueTextStyle(this._TextMarginY); + this._TextGutterX.Items.tag(prop).content = "Gutter-X"; + this._TextGutterX.Items.tag(val).content = "".concat(this._gutterX, "px"); + this._updatePropertyTextStyle(this._TextGutterX, this._gutterColor); + this._updateValueTextStyle(this._TextGutterX); + this._TextGutterY.Items.tag(prop).content = "Gutter-Y"; + this._TextGutterY.Items.tag(val).content = "".concat(this._gutterY, "px"); + this._updatePropertyTextStyle(this._TextGutterY, this._gutterColor); + this._updateValueTextStyle(this._TextGutterY); + this._TextSafe.Items.tag(prop).content = "Safe"; + this._TextSafe.Items.tag(val).content = "".concat(this._safe, "px"); + this._updatePropertyTextStyle(this._TextSafe, this._safeColor); + this._updateValueTextStyle(this._TextSafe); + } +} + +var base$h = theme => ({ + cursorStyle: { + textColor: theme.color.textNeutral, + blink: true, + width: theme.spacer.xs, + height: theme.spacer.xxl + }, + eyebrowTextStyle: _objectSpread(_objectSpread({}, theme.typography.caption1), {}, { + maxLines: 1, + textColor: theme.color.textNeutral + }), + textStyle: _objectSpread(_objectSpread({}, theme.typography.body1), {}, { + maxLines: 1, + textColor: theme.color.textNeutral + }), + helpTextStyle: _objectSpread(_objectSpread({}, theme.typography.caption1), {}, { + maxLines: 1, + textColor: theme.color.textNeutralSecondary + }), + minWidth: getWidthByUpCount(theme, 4), + paddingX: theme.spacer.xl, + paddingY: theme.spacer.xl, + backgroundColor: theme.color.interactiveNeutral +}); + +var mode$6 = theme => ({ + disabled: { + eyebrowTextStyle: { + textColor: theme.color.textNeutralDisabled + }, + helpTextStyle: { + textColor: theme.color.textNeutralDisabled + } + }, + focused: { + cursorStyle: { + textColor: theme.color.textInverse + }, + eyebrowTextStyle: { + textColor: theme.color.textNeutral + }, + helpTextStyle: { + textColor: theme.color.textNeutralSecondary + } + } +}); + +var tone$a = theme => ({ + inverse: { + mode: { + focused: { + eyebrowTextStyle: { + textColor: theme.color.textNeutral + }, + helpTextStyle: { + textColor: theme.color.textNeutral + } + } + } + } +}); + +var styles$h = Object.freeze({ + __proto__: null, + base: base$h, + mode: mode$6, + tone: tone$a +}); + +class Input extends Button { + static get __componentName() { + return "Input"; + } + static get __themeStyle() { + return styles$h; + } + static _template() { + return _objectSpread(_objectSpread({}, super._template()), {}, { + Eyebrow: { + type: TextBox + }, + HelpText: { + type: TextBox + } + }); + } + static get properties() { + return [ ...super.properties, "actualTitle", "cursor", "eyebrow", "helpText", "listening", "mask", "password", "position" ]; + } + static get tags() { + return [ ...super.tags, "Eyebrow", "HelpText", { + name: "Cursor", + path: "Content.Cursor" + }, { + name: "HiddenContent", + path: "Content.HiddenContent" + } ]; + } + _construct() { + super._construct(); + this._title = ""; + this.actualTitle = ""; + this.position = this.title ? this.title.length : 0; + this._justify = "left"; + this._fixed = true; + this.w = this.style.minWidth; + } + $itemChanged() { + super.$itemChanged(); + this._updateTextWrapper(); + this._updateHiddenContent(); + this._updateCursorPosition(); + this._updateTitleScrollPosition(); + } + _onTitleTextBoxChanged() { + this._updateHiddenContent(); + } + _onHiddenTextBoxChanged() { + this._updateCursorPosition(); + } + _update() { + this._updatePassword(); + super._update(); + this._updateEyebrow(); + this._updateHelpText(); + this._updateTextWrapper(); + this._updateHiddenContent(); + this._updateCursor(); + this._updateCursorListening(); + this._updateCursorBlink(); + this._updateCursorPosition(); + this._updateTitleScrollPosition(); + } + _updatePassword() { + this.title = this.password ? this.mask.repeat(this.actualTitle.length) : this.actualTitle; + } + _updateTruncation() { + if (this._Title) { + this._Title.patch({ + style: { + textStyle: _objectSpread(_objectSpread({}, this.style.textStyle), {}, { + wordWrap: false + }) + } + }); + } + } + _updateEyebrow() { + this._Eyebrow.patch({ + content: this.eyebrow, + style: { + textStyle: this.style.eyebrowTextStyle + }, + mountY: 1, + x: this.style.paddingX, + y: this.y - this.style.paddingY + }); + } + _updateHelpText() { + this._HelpText.patch({ + content: this.helpText, + style: { + textStyle: this.style.helpTextStyle + }, + x: this.style.paddingX, + y: this.y + this.innerH + this.style.paddingY + }); + } + _updateTextWrapper() { + this._TextWrapper.clipping = true; + this._TextWrapper.w = this._visibleContentWidth; + if (this._Title) { + this._TextWrapper.h = this._Title.h; + } + } + _updateHiddenContent() { + if (!this._HiddenContent) { + this._Content.patch({ + HiddenContent: { + type: TextBox, + mountY: .5, + y: h => h / 2, + signals: { + textBoxChanged: "_onHiddenTextBoxChanged" + } + } + }); + } + var {title: value = "", position: position, password: password, mask: mask} = this; + var textBeforeCursor = password ? mask.repeat(value.length).substring(0, position) : value.substring(0, position); + this._HiddenContent.patch({ + style: { + textStyle: this.style.textStyle + }, + content: textBeforeCursor + }); + this._HiddenContent._Text && this._HiddenContent._Text.patch({ + alpha: .001 + }); + } + _updateCursor() { + if (this.style.cursorStyle && this.style.cursorStyle.blink) { + if (!this._Cursor) { + this._Content.patch({ + Cursor: { + rect: true, + mountY: .5 + } + }); + this.cursorBlink = this._Cursor.animation({ + duration: 1.5, + repeat: -1, + actions: [ { + p: "alpha", + v: { + 0: 0, + .5: 1, + 1: 0 + } + } ] + }); + } + this._Cursor.patch(this.style.cursorStyle); + } + } + _updateCursorListening() { + if (!this._isDisabledMode) { + if (this.cursorBlink && !this.cursorBlink.isPlaying()) { + this.cursorBlink.start(); + } + } else { + if (this.cursorBlink) this.isCursorActive ? this.cursorBlink.start() : this.cursorBlink.stop(); + } + this._Cursor.smooth = { + color: this.style.cursorStyle.textColor + }; + } + _updateCursorBlink() { + if (this.cursorBlink) { + if (this.isCursorActive) { + this.cursorBlink.start(); + } else { + this.cursorBlink.stop(); + this._Cursor.patch({ + alpha: .001 + }); + } + } + } + _updateCursorPosition() { + this._Cursor.x = this._titleX + (this._isOverflow ? this._TextWrapper.w : this._HiddenContent.w); + } + _updateTitleScrollPosition() { + if (this._Title) { + this._Title.x = this._isOverflow ? this._visibleContentWidth - this._HiddenContent.w : 0; + if (this._HiddenContent && this._TextWrapper) { + this._HiddenContent.x = this._TextWrapper.x + this._Title.x; + } + } + } + get _suffixX() { + var suffixX = this._hasPrefix ? this.w - this._paddingLeft - this._paddingRight - this._prefixW : this.w - this._paddingLeft - this._paddingRight - this.style.paddingX; + return suffixX > 0 ? suffixX : 0; + } + get isCursorActive() { + return this.listening && (this._isFocusedMode || this._isUnfocusedMode); + } + get _isOverflow() { + return this._HiddenContent.w > this._visibleContentWidth; + } + get _visibleContentWidth() { + return this._fixedWordWrapWidth; + } + set value(value) { + this.title = this.actualTitle = value; + this.position = 0; + this._updatePassword(); + } + get value() { + return this.actualTitle; + } + clear() { + if (this.isCursorActive) { + this.title = this.actualTitle = ""; + this.position = 0; + } + } + insert(content) { + if (this.isCursorActive) { + this.actualTitle = this.actualTitle.slice(0, this.position) + content + this.actualTitle.slice(this.position); + this._updatePassword(); + this.position += content.length; + } + } + backspace() { + if (this.isCursorActive && this.position > 0) { + this.actualTitle = this.actualTitle.slice(0, this.position - 1) + this.actualTitle.slice(this.position); + this._updatePassword(); + this.position--; + } + } + _handleLeft() { + if (this._isDisabledMode) { + return false; + } + this.moveLeft(); + if (typeof this.onLeft === "function") { + return this.onLeft(this); + } + return true; + } + _handleRight() { + if (this._isDisabledMode) { + return false; + } + this.moveRight(); + if (typeof this.onRight === "function") { + return this.onRight(this); + } + return true; + } + moveLeft() { + var {position: position} = this; + if (position >= 0) { + this.position--; + return true; + } + return false; + } + moveRight() { + var {position: position, title: title} = this; + if (position < title.length) { + this.position++; + return true; + } + return false; + } + set announce(announce) { + super.announce = announce; + } + get announce() { + if (this._announce) { + return this._announce; + } + if (this.password) { + return [ this.eyebrow, this.helpText ]; + } else { + return [ this.eyebrow, "Input: " + this.title, this.helpText ]; + } + } +} + +var base$g = theme => { + var textStyle = theme.typography.headline2; + return { + height: theme.spacer.md * 9, + minWidth: theme.spacer.md * 7, + paddingX: theme.spacer.md, + textStyle: textStyle, + sizes: { + sm: 1, + md: 2, + lg: 3, + xl: 4, + xxl: 5 + }, + baseWidth: theme.spacer.md * 7, + iconWidth: textStyle.lineHeight, + iconHeight: textStyle.lineHeight + }; +}; + +var styles$g = Object.freeze({ + __proto__: null, + base: base$g +}); + +var isUpperCase = string => /^[A-Z]$/.test(string); + +var isAlphaChar = string => /^[A-Za-z]$/.test(string); + +var alphaNato = { + a: "alpha", + b: "bravo", + c: "charlie", + d: "delta", + e: "echo", + f: "foxtrot", + g: "golf", + h: "hotel", + i: "india", + j: "juliett", + k: "kilo", + l: "lima", + m: "mike", + n: "november", + o: "oscar", + p: "papa", + q: "quebec", + r: "romeo", + s: "sierra", + t: "tango", + u: "uniform", + v: "victor", + w: "whiskey", + x: "x-ray", + y: "yankee", + z: "zulu" +}; + +function getNato(title) { + if (isAlphaChar(title)) { + return "".concat(title, ", ").concat(alphaNato[title.toLowerCase()]); + } + return title; +} + +class Key extends Button { + static get __componentName() { + return "Key"; + } + static get __themeStyle() { + return styles$g; + } + static get properties() { + return [ ...super.properties, "icon", "size", "toggle", "keySpacing" ]; + } + static get aliasStyles() { + return [ { + prev: "iconH", + curr: "iconHeight" + }, { + prev: "iconW", + curr: "iconWidth" + } ]; + } + _construct() { + super._construct(); + this._size = "sm"; + this._keySpacing = 0; + } + _update() { + this._updatePrefixStyle(); + super._update(); + } + _calcDynamicWidth() { + var sizeMultiplier = this.style.sizes[this.size || "sm"]; + var baseSize = this.style.baseWidth * sizeMultiplier; + var padding = this.keySpacing * (sizeMultiplier - 1); + return baseSize + padding; + } + _updatePrefixStyle() { + if (this._prefix && this.icon) { + this._updatePrefixObj(this.icon, { + style: this.style.iconStyle + }); + } + } + _updatePrefixObj(icon) { + var props = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + this._prefix = _objectSpread({ + type: Icon, + icon: icon, + w: this.style.iconWidth, + h: this.style.iconHeight + }, props); + } + _setIcon(icon) { + if (icon) { + this._updatePrefixObj(icon, { + style: this.style.iconStyle + }); + } else { + this._prefix = icon; + } + return icon; + } + set announce(announce) { + super.announce = announce; + } + get announce() { + if (this._announce) { + return this._announce; + } + if (isUpperCase(this.title)) { + return "Capital ".concat(getNato(this.title), ", button"); + } + return getNato(this.title) + ", button"; + } + _handleEnter() { + if (typeof this.onEnter === "function") { + return this.onEnter(this); + } else { + if (this.toggle) { + this.fireAncestors("$toggleKeyboard", this.toggle); + } + this.fireAncestors("$onSoftKey", { + key: this.keyId || this.title, + toggle: this.toggle + }); + } + return false; + } +} + +var base$f = theme => ({ + keySpacing: theme.spacer.md, + screenW: theme.layout.screenW, + marginX: theme.layout.marginX, + inputSpacing: theme.spacer.md * 10 + theme.spacer.md, + inputStyle: { + radius: theme.radius.md + } +}); + +var styles$f = Object.freeze({ + __proto__: null, + base: base$f +}); + +var capitalize = string => string.charAt(0).toUpperCase() + string.slice(1); + +class Keyboard extends Base$1 { + static get __componentName() { + return "Keyboard"; + } + static get __themeStyle() { + return styles$f; + } + static get properties() { + return [ "formats", "centerKeyboard", "rowWrap", "centerKeys", "keyComponent" ]; + } + _init() { + this._setShouldUpdateThemeBound = this._setShouldUpdateTheme.bind(this); + contextInstance.on("themeUpdate", this._setShouldUpdateThemeBound); + super._init(); + } + _setShouldUpdateTheme() { + this.shouldUpdateTheme = true; + } + _detach() { + super._detach(); + contextInstance.off("themeUpdate", this._setShouldUpdateThemeBound); + } + _focus() { + super._focus(); + this.fireAncestors("$keyboardFocused", true); + } + _getFocused() { + return this._currentKeyboard || this; + } + _update() { + if (!this._currentFormat || this._shouldUpdateKeyboards) { + this._currentFormat = this.defaultFormat; + } + if (this.centerKeyboard) { + this.x = this.centeredXPos; + } else if (this.x === this.centeredXPos && !this.centerKeyboard) { + this.x = 0; + } else { + this.x == null && (this.x = 0); + } + this._shouldUpdateKeyboards && this._createKeyboardsFromFormats(); + this._formatKeys(); + } + _createKeyboardsFromFormats() { + this.childList.clear(); + Object.keys(this.formats).forEach((key => { + var format = this.formats[key]; + if (format) { + var keyboardData = this._formatKeyboardData(format); + this._createKeyboard(key, this._createRows(keyboardData, key)); + } + })); + this._formatsChanged = false; + } + _createKeyboard(key) { + var rows = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : []; + key = capitalize(key); + if (rows.length === 1) { + this.patch({ + [key]: rows[0] + }); + } else { + this.patch({ + [key]: { + type: Column, + plinko: true, + items: rows, + style: { + itemSpacing: this.style.keySpacing + }, + autoResizeWidth: true, + autoResizeHeight: true, + neverScroll: true, + alpha: key === capitalize(this._currentFormat) ? 1 : .001 + } + }); + } + } + _createRows() { + var rows = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : []; + var keyboard = arguments.length > 1 ? arguments[1] : undefined; + return rows.map((keys => { + var _this$_currentKeyboar; + return { + type: Row, + autoResizeHeight: true, + autoResizeWidth: true, + centerInParent: this.centerKeys, + neverScroll: true, + wrapSelected: this.rowWrap !== undefined ? this.rowWrap : true, + style: { + itemSpacing: this.style.keySpacing + }, + items: this._createKeys(keys, keyboard), + selectedIndex: ((_this$_currentKeyboar = this._currentKeyboard) === null || _this$_currentKeyboar === void 0 || (_this$_currentKeyboar = _this$_currentKeyboar.selected) === null || _this$_currentKeyboar === void 0 ? void 0 : _this$_currentKeyboar.selectedIndex) || 0 + }; + })); + } + _createKeys() { + var keys = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : []; + var keyboard = arguments.length > 1 ? arguments[1] : undefined; + return keys.map((keyProps => { + if (!keyProps) { + return { + type: this.keyComponent || Key, + keySpacing: this.style.keySpacing, + skipFocus: true, + alpha: .01 + }; + } + var key = { + type: this.keyComponent || Key, + keySpacing: this.style.keySpacing + }; + if (typeof keyProps === "object") { + var _this$style$keyProps, _this$style$keyProps2; + var keyName = keyProps.keyId || keyProps.title; + var keyOverrides = ((_this$style$keyProps = this.style.keyProps) === null || _this$style$keyProps === void 0 || (_this$style$keyProps = _this$style$keyProps[keyboard]) === null || _this$style$keyProps === void 0 ? void 0 : _this$style$keyProps[keyName]) || ((_this$style$keyProps2 = this.style.keyProps) === null || _this$style$keyProps2 === void 0 ? void 0 : _this$style$keyProps2[keyName]) || {}; + var keyPatch = _objectSpread(_objectSpread(_objectSpread({}, key), keyProps), keyOverrides); + if (keyOverrides !== null && keyOverrides !== void 0 && keyOverrides.icon) { + keyPatch.style = _objectSpread(_objectSpread({}, keyOverrides.style), {}, { + iconStyle: _objectSpread({}, keyOverrides.iconStyle) + }); + } + return keyPatch; + } + return _objectSpread(_objectSpread({}, key), {}, { + title: keyProps + }); + })); + } + _formatKeyboardData() { + var data = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : []; + if (Array.isArray(data) && data.length) { + if (!Array.isArray(data[0]) && !this.inline) { + var keyRows = []; + var idx, counter; + for (idx = 0, counter = -1; idx < data.length; idx++) { + if (idx % this.columnCount === 0) { + counter++; + keyRows[counter] = []; + } + keyRows[counter].push(data[idx]); + } + return keyRows; + } else if (this.inline) { + return [ data ]; + } + return data; + } + } + _formatKeys() { + Object.keys(this.formats).forEach((format => { + var element = this.tag(capitalize(format)); + if (element) { + element.patch({ + alpha: format === this._currentFormat ? 1 : .001, + style: { + itemSpacing: this.style.keySpacing + } + }); + element.items.forEach((row => { + row.patch({ + style: { + itemSpacing: this.style.keySpacing + }, + centerInParent: this.centerKeys, + wrapSelected: this.rowWrap !== undefined ? this.rowWrap : true + }); + })); + element.queueRequestUpdate(); + } + })); + } + $toggleKeyboard(next) { + var nextKeyboard = capitalize(next); + if (next !== this._currentFormat) { + var nextKeyboardTag = this.tag(nextKeyboard); + this.selectKeyOn(nextKeyboardTag); + this._currentKeyboard.alpha = .001; + nextKeyboardTag.alpha = 1; + this._currentFormat = next; + } + } + selectKeyOn(keyboard) { + var {row: row, column: column} = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : this.getSelectedKey(); + if (keyboard && keyboard.constructor) { + var type = keyboard.constructor.name; + if (type === "Row") { + keyboard.selectedIndex = column; + } else { + keyboard.selectedIndex = row; + keyboard.selected.selectedIndex = column; + } + } + } + getSelectedKey() { + var row, column; + var keyboard = this._currentKeyboard; + var type = keyboard.constructor.name; + if (type === "Row") { + row = 0; + column = keyboard.selectedIndex; + } else { + row = keyboard.selectedIndex; + column = keyboard.selected.selectedIndex; + } + return { + row: row, + column: column + }; + } + $itemChanged() { + this.w = this._currentKeyboard.w; + this.fireAncestors("$itemChanged"); + this.signal("keyboardWidthChanged"); + } + _setFormats() { + var formats = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + this._formatsChanged = true; + return formats; + } + get centeredXPos() { + return (this.style.screenW - this.w) / 2 - this.style.marginX; + } + get _shouldUpdateKeyboards() { + return this.shouldUpdateTheme || this._formatsChanged; + } + set defaultFormat(format) { + this._defaultFormat = format; + } + get defaultFormat() { + return this._defaultFormat || Object.keys(this.formats)[0]; + } + get _currentKeyboard() { + return this._currentFormat ? this.tag(capitalize(this._currentFormat)) : null; + } + set columnCount(columnCount) { + this._columnCount = columnCount; + } + get columnCount() { + if (this._columnCount) return this._columnCount; + if (this.rowCount) return this.formats[this.defaultFormat.toLowerCase()].length / this.rowCount; + if (this.inline) return this.formats[this.defaultFormat.toLowerCase()].length; else return 11; + } + set announce(announce) { + super.announce = announce; + } + get announce() { + if (this._announce) { + return this._announce; + } + return "Keyboard" + (this.title ? ", ".concat(this.title) : ""); + } + set announceContext(announceContext) { + super.announceContext = announceContext; + } + get announceContext() { + return this._announceContext || [ "PAUSE-2", "Use arrow keys to choose characters, press center to select" ]; + } +} + +class KeyboardEmail extends Keyboard { + static get __componentName() { + return "KeyboardEmail"; + } + static get __themeStyle() { + return styles$f; + } + _construct() { + super._construct(); + this.formats = this.emailFormat; + } + get emailFormat() { + return { + uppercase: [ [ "1", "2", "3", "4", "5", "6", "7", "8", "9", "0", { + title: "Delete", + size: "md", + keyId: "delete", + announce: "delete, button" + } ], [ "Q", "W", "E", "R", "T", "Y", "U", "I", "O", "P", { + title: "#@!", + size: "md", + toggle: "symbols", + announce: "symbol mode, button", + keyId: "symbols" + } ], [ "A", "S", "D", "F", "G", "H", "J", "K", "L", "@", { + title: "áöû", + size: "md", + toggle: "accents", + announce: "accents, button", + keyId: "accents" + } ], [ "Z", "X", "C", "V", "B", "N", "M", { + title: ".", + announce: "period, button" + }, { + title: "-", + announce: "dash, button" + }, { + title: "_", + announce: "underscore, button" + }, { + title: "shift", + size: "md", + toggle: "lowercase", + announce: "shift off, button", + keyId: "shift" + } ], [ { + title: ".com", + announce: "dot, com", + size: "md" + }, { + title: ".net", + announce: "dot, net", + size: "md" + }, { + title: ".edu", + announce: "dot, edu", + size: "md" + }, { + title: ".org", + announce: "dot, org", + size: "md" + }, { + title: ".co", + announce: "dot, co", + size: "md" + }, { + title: ".uk", + announce: "dot, uk", + size: "md" + } ], [ { + title: "Clear", + size: "lg", + keyId: "clear", + announce: "clear, button" + }, { + title: "Space", + size: "xl", + keyId: "space", + announce: "space, button" + }, { + title: "Done", + size: "lg", + keyId: "done", + announce: "done, button" + } ] ], + lowercase: [ [ "1", "2", "3", "4", "5", "6", "7", "8", "9", "0", { + title: "Delete", + size: "md", + keyId: "delete", + announce: "delete, button" + } ], [ "q", "w", "e", "r", "t", "y", "u", "i", "o", "p", { + title: "#@!", + size: "md", + toggle: "symbols", + announce: "symbol mode, button", + keyId: "symbols" + } ], [ "a", "s", "d", "f", "g", "h", "j", "k", "l", "@", { + title: "áöû", + size: "md", + toggle: "accents", + announce: "accents, button", + keyId: "accents" + } ], [ "z", "x", "c", "v", "b", "n", "m", { + title: "_", + announce: "underscore, button" + }, { + title: ".", + announce: "period, button" + }, { + title: "-", + announce: "dash, button" + }, { + title: "shift", + size: "md", + toggle: "uppercase", + announce: "shift on, button", + keyId: "shift" + } ], [ { + title: ".com", + announce: "dot, com", + size: "md" + }, { + title: ".net", + announce: "dot, net", + size: "md" + }, { + title: ".edu", + announce: "dot, edu", + size: "md" + }, { + title: ".org", + announce: "dot, org", + size: "md" + }, { + title: ".co", + announce: "dot, co", + size: "md" + }, { + title: ".uk", + announce: "dot, uk", + size: "md" + } ], [ { + title: "Clear", + size: "lg", + keyId: "clear", + announce: "clear, button" + }, { + title: "Space", + size: "xl", + keyId: "space", + announce: "space, button" + }, { + title: "Done", + size: "lg", + keyId: "done", + announce: "done, button" + } ] ], + accents: [ [ "1", "2", "3", "4", "5", "6", "7", "8", "9", "0", { + title: "Delete", + size: "md", + keyId: "delete", + announce: "delete, button" + } ], [ "ä", "ë", "ï", "ö", "ü", "ÿ", "à", "è", "ì", "ò", { + title: "#@!", + size: "md", + toggle: "symbols", + announce: "symbol mode, button", + keyId: "symbols" + } ], [ "ù", "á", "é", "í", "ó", "ú", "ý", "â", "ê", "@", { + title: "abc", + size: "md", + toggle: "lowercase", + announce: "alpha mode, button" + } ], [ "î", "ô", "û", "ã", "ñ", { + title: "_", + announce: "underscore, button" + }, { + title: ".", + announce: "period, button" + }, { + title: "-", + announce: "dash, button" + }, { + title: "shift", + size: "xl", + toggle: "accentsUpper", + announce: "shift off, button", + keyId: "shift" + } ], [ { + title: ".com", + announce: "dot, com", + size: "md" + }, { + title: ".net", + announce: "dot, net", + size: "md" + }, { + title: ".edu", + announce: "dot, edu", + size: "md" + }, { + title: ".org", + announce: "dot, org", + size: "md" + }, { + title: ".co", + announce: "dot, co", + size: "md" + }, { + title: ".uk", + announce: "dot, uk", + size: "md" + } ], [ { + title: "Clear", + size: "lg", + keyId: "clear", + announce: "clear, button" + }, { + title: "Space", + size: "xl", + keyId: "space", + announce: "space, button" + }, { + title: "Done", + size: "lg", + keyId: "done", + announce: "done, button" + } ] ], + accentsUpper: [ [ "1", "2", "3", "4", "5", "6", "7", "8", "9", "0", { + title: "Delete", + size: "md", + keyId: "delete", + announce: "delete, button" + } ], [ "Ä", "Ë", "Ï", "Ö", "Ü", "Ÿ", "À", "È", "Ì", "Ò", { + title: "#@!", + size: "md", + toggle: "symbols", + announce: "symbol mode, button", + keyId: "symbols" + } ], [ "Ù", "Á", "É", "Í", "Ó", "Ú", "Ý", "Â", "Ê", "@", { + title: "abc", + size: "md", + toggle: "lowercase", + announce: "alpha mode, button" + } ], [ "Î", "Ô", "Û", "Ã", "Ñ", { + title: ".", + announce: "period, button" + }, { + title: "-", + announce: "dash, button" + }, { + title: "_", + announce: "underscore, button" + }, { + title: "shift", + size: "xl", + toggle: "accents", + announce: "shift off, button", + keyId: "shift" + } ], [ { + title: ".com", + announce: "dot, com", + size: "md" + }, { + title: ".net", + announce: "dot, net", + size: "md" + }, { + title: ".edu", + announce: "dot, edu", + size: "md" + }, { + title: ".org", + announce: "dot, org", + size: "md" + }, { + title: ".co", + announce: "dot, co", + size: "md" + }, { + title: ".uk", + announce: "dot, uk", + size: "md" + } ], [ { + title: "Clear", + size: "lg", + keyId: "clear", + announce: "clear, button" + }, { + title: "Space", + size: "xl", + keyId: "space", + announce: "space, button" + }, { + title: "Done", + size: "lg", + keyId: "done", + announce: "done, button" + } ] ], + symbols: [ [ "1", "2", "3", "4", "5", "6", "7", "8", "9", "0", { + title: "Delete", + size: "md", + keyId: "delete", + announce: "delete, button" + } ], [ { + title: "!", + announce: "exclamation, button" + }, "@", "#", "$", "%", { + title: "^", + announce: "caret circumflex, button" + }, "&", "*", { + title: "(", + announce: "open parenthesis, button" + }, { + title: ")", + announce: "close parenthesis, button" + }, { + title: "abc", + size: "md", + toggle: "lowercase", + announce: "alpha mode, button" + } ], [ { + title: "{", + announce: "open brace, button" + }, { + title: "}", + announce: "close brace, button" + }, { + title: "[", + announce: "open bracket, button" + }, { + title: "]", + announce: "close bracket, button" + }, { + title: ";", + announce: "semicolon, button" + }, { + title: '"', + announce: "doublequote, button" + }, { + title: ",", + announce: "comma, button" + }, { + title: "|", + announce: "vertical bar, button" + }, { + title: "\\", + announce: "backslash, button" + }, { + title: "/", + announce: "forwardslash, button" + }, { + title: "áöû", + size: "md", + toggle: "accents", + announce: "accents, button", + keyId: "accents" + } ], [ { + title: "<", + announce: "less than, button" + }, { + title: ">", + announce: "greater than, button" + }, { + title: "?", + announce: "question mark, button" + }, { + title: "=", + announce: "equal sign, button" + }, { + title: "`", + announce: "grave accent, button" + }, { + title: "~", + announce: "tilde, button" + }, { + title: "_", + announce: "underscore, button" + }, { + title: ":", + announce: "colon, button" + }, { + title: "-", + announce: "dash, button" + }, { + title: "+", + announce: "plus sign, button" + } ], [ { + title: ".com", + announce: "dot, com", + size: "md" + }, { + title: ".net", + announce: "dot, net", + size: "md" + }, { + title: ".edu", + announce: "dot, edu", + size: "md" + }, { + title: ".org", + announce: "dot, org", + size: "md" + }, { + title: ".co", + announce: "dot, co", + size: "md" + }, { + title: ".uk", + announce: "dot, uk", + size: "md" + } ], [ { + title: "Clear", + size: "lg", + keyId: "clear", + announce: "clear, button" + }, { + title: "Space", + size: "xl", + keyId: "space", + announce: "space, button" + }, { + title: "Done", + size: "lg", + keyId: "done", + announce: "done, button" + } ] ] + }; + } +} + +class KeyboardFullScreen extends Keyboard { + static get __componentName() { + return "KeyboardFullScreen"; + } + static get __themeStyle() { + return styles$f; + } + _construct() { + super._construct(); + this.formats = this.fullscreenFormat; + } + get fullscreenFormat() { + return { + letters: [ [ "", "", "", "", "", "", "", "", "", { + title: "#@!", + size: "lg", + toggle: "symbols", + announce: "symbol mode, button", + keyId: "symbols" + }, { + title: "Space", + size: "lg", + keyId: "space", + announce: "space, button" + }, { + title: "Delete", + size: "md", + keyId: "delete", + announce: "delete, button" + }, "", "", "", "", "", "", "", "", "" ], [ "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z" ] ], + symbols: [ [ "", "", "", "", "", "", "", "", "", { + title: "ABC", + size: "lg", + toggle: "letters", + announce: "caps on, button" + }, { + title: "Space", + size: "lg", + keyId: "space", + announce: "space, button" + }, { + title: "Delete", + size: "md", + keyId: "delete", + announce: "delete, button" + }, "", "", "", "", "", "", "", "", "" ], [ "1", "2", "3", "4", "5", "6", "7", "8", "9", "0", { + title: "!", + announce: "exclamation, button" + }, "@", "#", "$", "%", { + title: "^", + announce: "caret circumflex, button" + }, "&", "*", { + title: "(", + announce: "open parenthesis, button" + }, { + title: ")", + announce: "close parenthesis, button" + }, { + title: "`", + announce: "grave accent, button" + }, "~", "_", ".", "-", "+" ] ] + }; + } +} + +class KeyboardNumbers extends Keyboard { + static get __componentName() { + return "KeyboardNumbers"; + } + static get __themeStyle() { + return styles$f; + } + _construct() { + super._construct(); + this.formats = this.numbersFormat; + } + get numbersFormat() { + return { + numbers: [ "1", "2", "3", "4", "5", "6", "7", "8", "9", "0" ], + dialpad: [ [ "1", "2", "3" ], [ "4", "5", "6" ], [ "7", "8", "9" ], [ "0" ] ], + dialpadExtended: [ [ "1", "2", "3" ], [ "4", "5", "6" ], [ "7", "8", "9" ], [ "0", { + title: "Delete", + size: "md", + keyId: "delete", + announce: "delete, button" + } ] ] + }; + } +} + +class KeyboardQwerty extends Keyboard { + static get __componentName() { + return "KeyboardQwerty"; + } + static get __themeStyle() { + return styles$f; + } + _construct() { + super._construct(); + this.formats = this.qwertyFormat; + } + get qwertyFormat() { + return { + uppercase: [ [ "1", "2", "3", "4", "5", "6", "7", "8", "9", "0", { + title: "Delete", + size: "md", + keyId: "delete", + announce: "delete, button" + } ], [ "Q", "W", "E", "R", "T", "Y", "U", "I", "O", "P", { + title: "#@!", + size: "md", + toggle: "symbols", + announce: "symbol mode, button", + keyId: "symbols" + } ], [ "A", "S", "D", "F", "G", "H", "J", "K", "L", "@", { + title: "áöû", + size: "md", + toggle: "accents", + announce: "accents, button", + keyId: "accents" + } ], [ "Z", "X", "C", "V", "B", "N", "M", { + title: "_", + announce: "underscore, button" + }, { + title: ".", + announce: "period, button" + }, { + title: "-", + announce: "dash, button" + }, { + title: "shift", + size: "md", + toggle: "lowercase", + announce: "shift off, button", + keyId: "shift" + } ], [ { + title: "Clear", + size: "lg", + keyId: "clear", + announce: "clear, button" + }, { + title: "Space", + size: "xl", + keyId: "space", + announce: "space, button" + }, { + title: "Done", + size: "lg", + keyId: "done", + announce: "done, button" + } ] ], + lowercase: [ [ "1", "2", "3", "4", "5", "6", "7", "8", "9", "0", { + title: "Delete", + size: "md", + keyId: "delete", + announce: "delete, button" + } ], [ "q", "w", "e", "r", "t", "y", "u", "i", "o", "p", { + title: "#@!", + size: "md", + toggle: "symbols", + announce: "symbol mode, button", + keyId: "symbols" + } ], [ "a", "s", "d", "f", "g", "h", "j", "k", "l", "@", { + title: "áöû", + size: "md", + toggle: "accents", + announce: "accents, button", + keyId: "accents" + } ], [ "z", "x", "c", "v", "b", "n", "m", { + title: "_", + announce: "underscore, button" + }, { + title: ".", + announce: "period, button" + }, { + title: "-", + announce: "dash, button" + }, { + title: "shift", + size: "md", + toggle: "uppercase", + announce: "shift on, button", + keyId: "shift" + } ], [ { + title: "Clear", + size: "lg", + keyId: "clear", + announce: "clear, button" + }, { + title: "Space", + size: "xl", + keyId: "space", + announce: "space, button" + }, { + title: "Done", + size: "lg", + keyId: "done", + announce: "done, button" + } ] ], + accents: [ [ "1", "2", "3", "4", "5", "6", "7", "8", "9", "0", { + title: "Delete", + size: "md", + keyId: "delete", + announce: "delete, button" + } ], [ "ä", "ë", "ï", "ö", "ü", "ÿ", "à", "è", "ì", "ò", { + title: "#@!", + size: "md", + toggle: "symbols", + announce: "symbol mode, button", + keyId: "symbols" + } ], [ "ù", "á", "é", "í", "ó", "ú", "ý", "â", "ê", "@", { + title: "abc", + size: "md", + toggle: "lowercase", + announce: "alpha mode, button" + } ], [ "î", "ô", "û", "ã", "ñ", { + title: "_", + announce: "underscore, button" + }, { + title: ".", + announce: "period, button" + }, { + title: "-", + announce: "dash, button" + }, { + title: "shift", + size: "xl", + toggle: "accentsUpper", + announce: "shift off, button", + keyId: "shift" + } ], [ { + title: "Clear", + size: "lg", + keyId: "clear", + announce: "clear, button" + }, { + title: "Space", + size: "xl", + keyId: "space", + announce: "space, button" + }, { + title: "Done", + size: "lg", + keyId: "done", + announce: "done, button" + } ] ], + accentsUpper: [ [ "1", "2", "3", "4", "5", "6", "7", "8", "9", "0", { + title: "Delete", + size: "md", + keyId: "delete", + announce: "delete, button" + } ], [ "Ä", "Ë", "Ï", "Ö", "Ü", "Ÿ", "À", "È", "Ì", "Ò", { + title: "#@!", + size: "md", + toggle: "symbols", + announce: "symbol mode, button", + keyId: "symbols" + } ], [ "Ù", "Á", "É", "Í", "Ó", "Ú", "Ý", "Â", "Ê", "@", { + title: "abc", + size: "md", + toggle: "lowercase", + announce: "alpha mode, button" + } ], [ "Î", "Ô", "Û", "Ã", "Ñ", { + title: ".", + announce: "period, button" + }, { + title: "-", + announce: "dash, button" + }, { + title: "_", + announce: "underscore, button" + }, { + title: "shift", + size: "xl", + toggle: "accents", + announce: "shift off, button", + keyId: "shift" + } ], [ { + title: "Clear", + size: "lg", + keyId: "clear", + announce: "clear, button" + }, { + title: "Space", + size: "xl", + keyId: "space", + announce: "space, button" + }, { + title: "Done", + size: "lg", + keyId: "done", + announce: "done, button" + } ] ], + symbols: [ [ "1", "2", "3", "4", "5", "6", "7", "8", "9", "0", { + title: "Delete", + size: "md", + keyId: "delete", + announce: "delete, button" + } ], [ { + title: "!", + announce: "exclamation, button" + }, "@", "#", "$", "%", { + title: "^", + announce: "caret circumflex, button" + }, "&", "*", { + title: "(", + announce: "open parenthesis, button" + }, { + title: ")", + announce: "close parenthesis, button" + }, { + title: "abc", + size: "md", + toggle: "lowercase", + announce: "alpha mode, button" + } ], [ { + title: "{", + announce: "open brace, button" + }, { + title: "}", + announce: "close brace, button" + }, { + title: "[", + announce: "open bracket, button" + }, { + title: "]", + announce: "close bracket, button" + }, { + title: ";", + announce: "semicolon, button" + }, { + title: '"', + announce: "doublequote, button" + }, { + title: ",", + announce: "comma, button" + }, { + title: "|", + announce: "vertical bar, button" + }, { + title: "\\", + announce: "backslash, button" + }, { + title: "/", + announce: "forwardslash, button" + }, { + title: "áöû", + size: "md", + toggle: "accents", + announce: "accents, button", + keyId: "accents" + } ], [ { + title: "<", + announce: "less than, button" + }, { + title: ">", + announce: "greater than, button" + }, { + title: "?", + announce: "question mark, button" + }, { + title: "=", + announce: "equal sign, button" + }, { + title: "`", + announce: "grave accent, button" + }, { + title: "~", + announce: "tilde, button" + }, { + title: "_", + announce: "underscore, button" + }, { + title: ":", + announce: "colon, button" + }, { + title: "-", + announce: "dash, button" + }, { + title: "+", + announce: "plus sign, button" + } ], [ { + title: "Clear", + size: "lg", + keyId: "clear", + announce: "clear, button" + }, { + title: "Space", + size: "xl", + keyId: "space", + announce: "space, button" + }, { + title: "Done", + size: "lg", + keyId: "done", + announce: "done, button" + } ] ] + }; + } +} + +class KeyboardInput extends Base$1 { + static get __componentName() { + return "KeyboardInput"; + } + static get properties() { + return [ "centerKeyboard", "defaultFormat", "input", "keyboardType" ]; + } + static get __themeStyle() { + return styles$f; + } + static _template() { + return { + Wrapper: { + type: Column, + neverScroll: true, + w: this.w, + items: [ { + type: Input, + ref: "Input" + }, { + type: Keyboard, + ref: "Keyboard", + passSignals: { + keyboardWidthChanged: true + } + } ], + selectedIndex: 1, + signals: { + keyboardWidthChanged: "_updateWidth" + } + } + }; + } + static get tags() { + return [ "Wrapper", { + name: "Input", + path: "Wrapper.Input" + }, { + name: "Keyboard", + path: "Wrapper.Keyboard" + } ]; + } + _update() { + this._Wrapper.style.itemSpacing = this.style.inputSpacing; + this._updateKeyboardType(); + this._updateInput(); + this._updateKeyboard(); + this._updateCenterKeyboard(); + } + _updateKeyboardType() { + if (this._Keyboard.constructor !== this.keyboardType) { + this._Wrapper._resetItems(); + this._Wrapper.items = [ { + type: Input, + ref: "Input" + }, { + type: this.keyboardType, + ref: "Keyboard", + passSignals: { + keyboardWidthChanged: true + } + } ]; + } + } + _updateInput() { + this._Input.patch(_objectSpread(_objectSpread({}, this.input), {}, { + centerInParent: this.centerKeyboard, + w: this._Keyboard.w, + style: _objectSpread({}, this.style.inputStyle), + listening: this._isFocusedMode + })); + } + _updateKeyboard() { + this._Keyboard.patch({ + defaultFormat: this.defaultFormat || "lowercase", + centerKeyboard: this.centerKeyboard + }); + } + _updateWidth() { + this._Input.w = this.w = this._Keyboard.w; + this.fireAncestors("$itemChanged"); + } + _updateCenterKeyboard() { + if (this.centerKeyboard) { + this.x = (this.style.screenW - this.w) / 2 - this.style.marginX; + } else { + this.x = 0; + } + } + $onSoftKey(_ref22) { + var {key: key = "", toggle: toggle} = _ref22; + if (toggle) { + return; + } + switch (key.toLowerCase()) { + case "delete": + this._Input.backspace(); + break; + + case "done": + break; + + case "space": + this._Input.insert(" "); + break; + + case "clear": + this._Input.clear(); + break; + + default: + this._Input.insert(key); + } + } + $keyboardFocused(focus) { + if (focus) { + this._Input.listening = true; + } else { + this._Input.listening = false; + } + } + _getFocused() { + return this._Wrapper || this; + } +} + +class KeyboardSearch extends Keyboard { + static get __componentName() { + return "KeyboardSearch"; + } + static get __themeStyle() { + return styles$f; + } + _construct() { + super._construct(); + this.formats = this.searchFormat; + } + get searchFormat() { + return { + uppercase: [ [ "A", "B", "C", "D", "E", "F" ], [ "G", "H", "I", "J", "K", "L" ], [ "M", "N", "O", "P", "Q", "R" ], [ "S", "T", "U", "V", "W", "X" ], [ "Y", "Z", { + title: "1", + keyId: "number" + }, { + title: "2", + keyId: "number" + }, { + title: "3", + keyId: "number" + }, { + title: "4", + keyId: "number" + } ], [ { + title: "5", + keyId: "number" + }, { + title: "6", + keyId: "number" + }, { + title: "7", + keyId: "number" + }, { + title: "8", + keyId: "number" + }, { + title: "9", + keyId: "number" + }, { + title: "0", + keyId: "number" + } ], [ { + title: "Space", + size: "xl", + keyId: "space", + announce: "space, button" + }, { + title: "Delete", + size: "md", + keyId: "delete", + announce: "delete, button" + } ] ] + }; + } +} + +var base$e = theme => { + var size = theme.spacer.lg; + return { + width: size, + height: size, + radius: size / 2 + }; +}; + +var tone$9 = theme => ({ + neutral: { + circleColor: theme.color.interactiveNeutralFocus, + mode: { + disabled: { + circleColor: theme.color.fillNeutralDisabled + } + } + }, + inverse: { + circleColor: theme.color.interactiveInverseFocus, + mode: { + disabled: { + circleColor: theme.color.fillInverseDisabled + } + } + }, + brand: { + circleColor: theme.color.interactiveBrandFocus, + mode: { + disabled: { + circleColor: theme.color.fillInverseDisabled + } + } + } +}); + +var styles$e = Object.freeze({ + __proto__: null, + base: base$e, + tone: tone$9 +}); + +class Knob extends Base$1 { + static get __componentName() { + return "Knob"; + } + static get __themeStyle() { + return styles$e; + } + static _template() { + return { + mount: .5 + }; + } + _update() { + this._updateLayout(); + } + _updateLayout() { + this.patch({ + texture: _lightningjs_core__WEBPACK_IMPORTED_MODULE_0__.Tools.getRoundRect(this.w, this.h, getMaxRoundRadius(this.style.radius, this.w, this.h), null, null, true, this.style.circleColor) + }); + } +} + +var base$d = theme => ({ + alpha: theme.alpha.primary, + descriptionTextStyle: _objectSpread(_objectSpread({}, theme.typography.body3), {}, { + maxLines: 1, + textColor: theme.color.textNeutralSecondary + }), + height: theme.spacer.xxl * 3, + logoStyle: { + width: theme.spacer.xxl * 2, + height: theme.spacer.xxl * 2, + radius: theme.radius.sm + }, + paddingX: theme.spacer.xl, + contentSpacing: theme.spacer.lg, + titleTextStyle: _objectSpread(_objectSpread({}, theme.typography.headline3), {}, { + maxLines: 1, + textColor: theme.color.textNeutral + }), + width: utils$1.getWidthByColumnSpan(theme, 3) +}); + +var mode$5 = theme => ({ + disabled: { + alpha: theme.alpha.inactive, + descriptionTextStyle: { + textColor: theme.color.textNeutralDisabled + }, + titleTextStyle: { + textColor: theme.color.textNeutralDisabled + } + }, + focused: { + descriptionTextStyle: { + textColor: theme.color.textInverseSecondary + }, + titleTextStyle: { + textColor: theme.color.textInverse + } + } +}); + +var tone$8 = theme => ({ + inverse: { + mode: { + focused: { + descriptionTextStyle: { + textColor: theme.color.textNeutral + }, + titleTextStyle: { + textColor: theme.color.textNeutral + } + } + } + } +}); + +var styles$d = Object.freeze({ + __proto__: null, + base: base$d, + mode: mode$5, + tone: tone$8 +}); + +class ListItem extends Button { + static get __componentName() { + return "ListItem"; + } + static get __themeStyle() { + return styles$d; + } + static _template() { + return _objectSpread(_objectSpread({}, super._template()), {}, { + justify: "left", + fixed: true, + Content: _objectSpread(_objectSpread({}, super._template().Content), {}, { + TextWrapper: { + mountY: .5, + flex: { + direction: "column" + }, + Title: { + type: TextBox, + signals: { + textBoxChanged: "_onTextBoxChanged" + } + } + } + }) + }); + } + static get properties() { + return [ ...super.properties, "description", "prefixLogo", "suffixLogo", "shouldCollapse" ]; + } + static get aliasStyles() { + return [ { + prev: "titlePadding", + curr: "contentSpacing" + } ]; + } + static get tags() { + return [ ...super.tags, { + name: "Description", + path: "Content.TextWrapper.Description" + } ]; + } + _onTextBoxChanged() { + this._updateTitle(); + this._updateDescription(); + this._updateTruncation(); + } + _update() { + this._updatePrefixLogo(); + this._updateSuffixLogo(); + super._update(); + this._updateDescription(); + } + _updateTitle() { + this._TextWrapper.patch({ + Title: { + content: this.title, + style: { + textStyle: this.style.titleTextStyle + } + } + }); + } + _updateDescription() { + if (this._hasDescription) { + var descriptionPatch = { + content: this.description, + style: { + textStyle: _objectSpread(_objectSpread({}, this.style.descriptionTextStyle), {}, { + wordWrap: true, + wordWrapWidth: this._fixedWordWrapWidth + }) + }, + visible: !this._collapse + }; + if (!this._Description) { + descriptionPatch = _objectSpread({ + type: TextBox, + signals: { + textBoxChanged: "_onTextBoxChanged" + } + }, descriptionPatch); + } + this._TextWrapper.patch({ + Description: descriptionPatch + }); + } else { + this._TextWrapper.patch({ + Description: undefined + }); + } + } + _updateTruncation() { + if (this._Title) { + this._Title.patch({ + style: { + textStyle: _objectSpread(_objectSpread({}, this.style.titleTextStyle), {}, { + wordWrap: this.fixed, + wordWrapWidth: this.fixed ? this._fixedWordWrapWidth : 0 + }) + } + }); + } + } + _updatePrefixLogo() { + if (this._hasPrefixLogo) { + this._prefix = this._addLogoProps(this._prefixLogo); + } + } + _updateSuffixLogo() { + if (this._hasSuffixLogo) { + this._suffix = this._addLogoProps(this._suffixLogo); + } + } + _addLogoProps(icon) { + return { + type: Icon, + icon: icon, + style: _objectSpread({ + color: undefined + }, this.style.logoStyle) + }; + } + get _hasPrefixLogo() { + return this.prefixLogo; + } + get _hasSuffixLogo() { + return this.suffixLogo; + } + get _rowProps() { + return _objectSpread(_objectSpread({}, super._rowProps), {}, { + autoResizeHeight: true + }); + } + get _buttonProps() { + return _objectSpread(_objectSpread({}, super._buttonProps), {}, { + alpha: this.style.alpha + }); + } + get _hasDescription() { + return !!this.description; + } + get _suffixX() { + return this.w - this._paddingRight - this._suffixW - this.style.paddingX; + } + get _collapse() { + return this.shouldCollapse && !this._isFocusedMode; + } + set announce(announce) { + super.announce = announce; + } + get announce() { + if (this._announce) { + return this._announce; + } + return this.title + this.description + ", List Item"; + } +} + +var base$c = () => ({ + showArrows: false, + showKnob: false +}); + +var mode$4 = () => ({ + focused: { + showArrows: true + } +}); + +var tone$7 = theme => ({ + neutral: { + mode: { + focused: { + arrowColor: theme.color.fillInverse, + progressBar: { + barColor: theme.color.fillInverseTertiary, + progressColor: theme.color.fillInverse + } + } + } + }, + inverse: { + mode: { + focused: { + arrowColor: theme.color.fillNeutral, + progressBar: { + barColor: theme.color.fillNeutralTertiary, + progressColor: theme.color.fillNeutral + } + } + } + }, + brand: { + mode: { + focused: { + arrowColor: theme.color.fillInverse, + progressBar: { + barColor: theme.color.fillBrandTertiary, + progressColor: theme.color.fillBrand + } + } + } + } +}); + +var styles$c = Object.freeze({ + __proto__: null, + base: base$c, + mode: mode$4, + tone: tone$7 +}); + +var base$b = theme => { + var size = theme.spacer.lg; + return { + arrowAlphaValue: theme.alpha.primary, + arrowAlphaValueLimit: theme.alpha.secondary, + arrowHeight: theme.spacer.xxl, + arrowSpacing: theme.spacer.md, + arrowWidth: theme.spacer.xxl, + arrowColor: theme.color.fillNeutral, + containerHeight: theme.spacer.lg + theme.spacer.xs, + iconLeftSrc: theme.asset.arrowLeft, + iconRightSrc: theme.asset.arrowRight, + minWidth: getWidthByColumnSpan(theme, 2), + progressBar: {}, + width: size, + height: size, + radius: size / 2, + showArrows: true, + showKnob: true, + circleAnimation: {} + }; +}; + +var mode$3 = () => ({ + disabled: { + arrowAlphaValue: 0 + } +}); + +var tone$6 = theme => ({ + neutral: { + arrowColor: theme.color.fillNeutral, + circleColor: theme.color.interactiveNeutralFocus + }, + inverse: { + arrowColor: theme.color.fillInverse, + circleColor: theme.color.interactiveInverseFocus + }, + brand: { + arrowColor: theme.color.fillNeutral, + circleColor: theme.color.interactiveNeutralFocus + } +}); + +var styles$b = Object.freeze({ + __proto__: null, + base: base$b, + mode: mode$3, + tone: tone$6 +}); + +class Slider extends Base$1 { + static get __componentName() { + return "Slider"; + } + static get __themeStyle() { + return styles$b; + } + static _template() { + return { + Container: { + mountY: .5, + y: h => h / 2, + Bar: { + mountY: .5, + SliderBar: { + type: ProgressBar, + progress: .5, + mountY: .5, + announce: "" + }, + Circle: { + type: Knob, + zIndex: 5 + } + }, + LeftArrow: { + type: Icon, + mountY: .5, + y: h => h / 2 + }, + RightArrow: { + type: Icon, + mountY: .5, + y: h => h / 2 + } + } + }; + } + static get properties() { + return [ "max", "min", "step", "value", "vertical" ]; + } + static get tags() { + return [ "Container", { + name: "Bar", + path: "Container.Bar" + }, { + name: "SliderBar", + path: "Container.Bar.SliderBar" + }, { + name: "Circle", + path: "Container.Bar.Circle" + }, { + name: "LeftArrow", + path: "Container.LeftArrow" + }, { + name: "RightArrow", + path: "Container.RightArrow" + } ]; + } + _construct() { + super._construct(); + this._min = 0; + this._max = 100; + this._step = 1; + this._value = 0; + this._vertical = false; + } + _update() { + this._updateDirection(); + this._updateSliderLayout(); + this._updatePositions(); + this._updateArrowAlpha(); + this._updateArrows(); + if (this._valueChanged) { + this.signal("onChange", this.value, this); + this.fireAncestors("$announce", this.announce); + this._valueChanged = false; + } + this._checkAndSignalSizeChange(); + } + _handleLeft() { + if (this._isDisabledMode) { + return false; + } + this._decrementValue(); + if (typeof this.onLeft === "function") { + return this.onLeft(this); + } + return true; + } + _handleRight() { + if (this._isDisabledMode) { + return false; + } + this._incrementValue(); + if (typeof this.onRight === "function") { + return this.onRight(this); + } + return true; + } + _updateDirection() { + this.patch({ + pivotX: 0, + rotation: this.vertical ? degreesToRadians(90) : 0, + mountY: this.vertical ? .5 : 0 + }); + } + _updateSliderLayout() { + var w = this.w || this.style.minWidth; + this._Container.patch({ + h: this.style.containerHeight, + w: w, + Bar: { + x: this._calculatedSliderX, + SliderBar: { + y: this.style.containerHeight / 2, + w: this._calculatedSliderWidth, + style: _objectSpread({ + duration: 0 + }, this.style.progressBar) + } + } + }); + this.h = Math.max(this.style.containerHeight, this.style.arrowHeight); + } + _checkAndSignalSizeChange() { + if (this.h !== this.prevH || this._Container.w !== this.prevW || this.rotation !== this.prevRotation) { + this.signal("onSizeChange", this); + } + this.prevH = this.h; + this.prevW = this._Container.w; + this.prevRotation = this.rotation; + } + _updatePositions() { + this._updateSliderProgress(); + this._updateCirclePosition(); + } + _updateSliderProgress() { + var progress = this.value < this.min ? this.min / this.max : this.value / this.max; + if (this.value > this.max || this.value - this.step > this.max) { + progress = this._calculatedSliderWidth; + } else if (this.min < 0 || this.max < 0) { + progress = (this.value - this.min) / (this.max - this.min); + } + this._SliderBar.progress = progress; + } + _updateCirclePosition() { + var xCirclePosition; + if (this.value < this.min || this.value + this.step < this.min) { + xCirclePosition = this.min / this.max * this._calculatedSliderWidth; + } else if (this.value > this.max || this.value - this.step > this.max) { + xCirclePosition = this._calculatedSliderWidth; + } else { + if (this.min < 0 || this.max < 0) { + xCirclePosition = (this.value - this.min) / (this.max - this.min) * this._calculatedSliderWidth; + } else { + xCirclePosition = this.value / this.max * this._calculatedSliderWidth; + } + } + if (this._Circle) { + this._Circle.patch({ + mode: this.mode, + style: { + radius: this.style.radius, + w: this.style.w, + h: this.style.h, + circleColor: this.style.circleColor + }, + y: this._SliderBar.y + 1, + alpha: this._isFocusedMode && this.style.showKnob ? 1 : 0 + }); + if (this.style.circleAnimation && Object.keys(this.style.circleAnimation).length) { + this._Circle.smooth = { + x: [ xCirclePosition, this.style.circleAnimation ] + }; + } else { + this._Circle.x = xCirclePosition; + } + } + } + _updateArrowAlpha() { + var leftAlpha; + var rightAlpha; + var offAlpha = .001; + var alpha = this.style.showArrows ? this.style.arrowAlphaValue : offAlpha; + var alphaLimit = this.style.showArrows ? this.style.arrowAlphaValueLimit : offAlpha; + leftAlpha = rightAlpha = alpha; + if (!this._isDisabledMode && this.value <= this.min) { + leftAlpha = alphaLimit; + rightAlpha = alpha; + } else if (!this._isDisabledMode && this.value >= this.max) { + leftAlpha = alpha; + rightAlpha = alphaLimit; + } + this._LeftArrow.smooth = { + alpha: leftAlpha + }; + this._RightArrow.smooth = { + alpha: rightAlpha + }; + } + _updateArrows() { + var arrowProps = { + w: this.style.arrowWidth, + h: this.style.arrowHeight, + style: { + color: this.style.arrowColor + } + }; + this._LeftArrow.patch(_objectSpread(_objectSpread({}, arrowProps), {}, { + icon: this.style.iconLeftSrc + })); + this._RightArrow.patch(_objectSpread(_objectSpread({}, arrowProps), {}, { + icon: this.style.iconRightSrc + })); + this._RightArrow.smooth = { + x: this.style.arrowSpacing + this._calculatedSliderWidth + this._Bar.x + }; + } + _decrementValue() { + var value = this.value - this.step; + this.value = value >= this.min ? value : this.min; + this._updatePositions(); + } + _incrementValue() { + var value = this.value + this.step; + this.value = value <= this.max ? value : this.max; + this._updatePositions(); + } + _handleUp() { + return false; + } + _handleDown() { + return false; + } + get _calculatedSliderX() { + return this.style.showArrows ? this.style.arrowSpacing + this.style.arrowWidth : 0; + } + get _calculatedSliderWidth() { + var totalArrowSize = this.style.showArrows ? this.style.arrowSpacing * 2 + this.style.arrowWidth * 2 : 0; + return this.w < totalArrowSize + this._circleW ? this.style.minWidth - totalArrowSize : this.w - totalArrowSize; + } + get _circleW() { + return this._Circle ? this._Circle.w : 0; + } + _setVertical(vertical) { + this._setState(vertical ? "VerticalSlider" : ""); + return vertical; + } + _setValue(value) { + this._valueChanged = value !== this._value; + return value; + } + _setMin(min) { + var value = this.value; + this.value = min > value ? min : value; + this._valueChanged = value !== this.value; + return min; + } + _setMax(max) { + var value = this.value; + this.value = max < value ? max : value; + this._valueChanged = value !== this.value; + return max; + } + set announce(announce) { + super.announce = announce; + } + get announce() { + if (this._announce !== undefined && this._announce !== null) { + return this._announce; + } + return this.value.toString(); + } + static _states() { + return [ class VerticalSlider extends(this){ + _handleLeft() { + return false; + } + _handleRight() { + return false; + } + _handleUp() { + if (this._isDisabledMode) { + return false; + } + this._decrementValue(); + if (typeof this.onUp === "function") { + return this.onUp(this); + } + return true; + } + _handleDown() { + if (this._isDisabledMode) { + return false; + } + this._incrementValue(); + if (typeof this.onDown === "function") { + return this.onDown(this); + } + return true; + } + } ]; + } +} + +class NestedSlider extends Slider { + static get __componentName() { + return "NestedSlider"; + } + static get __themeStyle() { + return styles$c; + } +} + +var base$a = theme => ({ + paddingY: theme.spacer.md + theme.spacer.xs, + valueTextStyle: _objectSpread(_objectSpread({}, theme.typography.headline3), {}, { + maxLines: 1, + textColor: theme.color.textNeutralSecondary + }) +}); + +var mode$2 = theme => ({ + disabled: { + valueTextStyle: { + textColor: theme.color.textNeutralDisabled + } + }, + focused: { + valueTextStyle: { + textColor: theme.color.textInverseSecondary + } + } +}); + +var tone$5 = theme => ({ + neutral: { + mode: { + focused: { + valueTextStyle: { + textColor: theme.color.textInverseSecondary + } + } + } + }, + inverse: { + mode: { + focused: { + valueTextStyle: { + textColor: theme.color.textNeutralSecondary + } + } + } + }, + brand: { + mode: { + focused: { + valueTextStyle: { + textColor: theme.color.textInverseSecondary + } + } + } + } +}); + +var styles$a = Object.freeze({ + __proto__: null, + base: base$a, + mode: mode$2, + tone: tone$5 +}); + +class ListItemSlider extends ListItem { + static get __componentName() { + return "ListItemSlider"; + } + static get __themeStyle() { + return styles$a; + } + static _template() { + var template = super._template; + return _objectSpread(_objectSpread({}, template()), {}, { + Content: _objectSpread(_objectSpread({}, template().Content), {}, { + flex: { + direction: "column" + }, + TextWrapper: _objectSpread(_objectSpread({}, template().Content.TextWrapper), {}, { + mountY: 0, + flex: undefined + }), + Slider: { + type: NestedSlider, + mountX: .5, + signals: { + onChange: "_onSliderChanged" + } + } + }) + }); + } + static get properties() { + return [ ...super.properties, "slider", "value", "max", "min" ]; + } + static get aliasStyles() { + return [ { + prev: "titlePadding", + curr: "contentSpacing" + } ]; + } + static get tags() { + return [ ...super.tags, { + name: "Slider", + path: "Content.Slider" + }, { + name: "Value", + path: "Content.TextWrapper.Value" + } ]; + } + _construct() { + super._construct(); + this.value = 50; + this.max = 100; + this.min = 0; + } + _update() { + super._update(); + this._updateSliderPosition(); + this._updateValue(); + } + _onTextBoxChanged() { + super._onTextBoxChanged(); + this._TextWrapper.h = Math.max(this._Title ? this._Title.h : 0, this._Value ? this._Value.h : 0); + } + _updateValue() { + if (this._hasValue) { + var valuePatch = { + content: this.value.toString(), + style: { + textStyle: _objectSpread({}, this.style.valueTextStyle) + }, + mountX: 1, + x: this.w - this._paddingX + }; + if (!this._Value) { + valuePatch = _objectSpread({ + type: TextBox, + signals: { + textBoxChanged: "_onTextBoxChanged" + } + }, valuePatch); + } + this._TextWrapper.patch({ + Value: valuePatch + }); + } else { + this._TextWrapper.patch({ + Value: undefined + }); + } + } + _updateSliderPosition() { + var w = this.w - this._paddingLeft - this._paddingRight; + var sliderProps = _objectSpread(_objectSpread({ + mode: this.mode, + tone: this.tone, + w: w, + x: w / 2, + visible: !this._collapse, + alpha: this.style.alpha + }, this.slider), {}, { + value: this.value, + max: this.max, + min: this.min + }); + this._Slider.patch(sliderProps); + } + get _hasValue() { + return this.value != undefined || this.value != null; + } + get _fixedWordWrapWidth() { + var titleWrapWidth = this.w - this._paddingLeft - this._paddingRight - this._paddingX; + return titleWrapWidth; + } + _onSliderChanged(value) { + this.value = value; + this._updateValue(); + this.signal("onSliderChange", value, this); + } + _handleLeft() { + if (typeof this.onLeft === "function") { + return this.onLeft(this); + } else if (this._Slider && !this._isDisabledMode) { + return this._Slider._handleLeft(); + } + return false; + } + _handleRight() { + if (typeof this.onRight === "function") { + return this.onRight(this); + } else if (this._Slider && !this._isDisabledMode) { + return this._Slider._handleRight(); + } + return false; + } + set announce(announce) { + super.announce = announce; + } + get announce() { + if (this._announce) { + return this._announce; + } + return this.title + this.value + ", List Item Slider"; + } +} + +var base$9 = theme => ({ + arrowAlphaValue: theme.alpha.primary, + arrowAlphaValueLimit: theme.alpha.secondary, + arrowWidth: theme.spacer.xxl, + arrowHeight: theme.spacer.xxl, + iconLeftSrc: theme.asset.arrowLeft, + iconRightSrc: theme.asset.arrowRight +}); + +var tone$4 = theme => ({ + neutral: { + mode: { + focused: { + arrowColor: theme.color.fillInverse + } + } + }, + inverse: { + mode: { + focused: { + arrowColor: theme.color.fillNeutral + } + } + }, + brand: { + mode: { + focused: { + arrowColor: theme.color.fillInverse + } + } + } +}); + +var styles$9 = Object.freeze({ + __proto__: null, + base: base$9, + tone: tone$4 +}); + +class ListItemPicker extends ListItem { + static get __componentName() { + return "ListItemPicker"; + } + static get __themeStyle() { + return styles$9; + } + static get properties() { + return [ ...super.properties, "options", "selectedIndex" ]; + } + static get tags() { + return [ ...super.tags, "LeftArrow", "RightArrow", { + name: "Picker", + path: "Content.TextWrapper.Picker" + } ]; + } + static get aliasStyles() { + return [ { + prev: "titlePadding", + curr: "contentSpacing" + } ]; + } + _onTextBoxChanged() { + super._onTextBoxChanged(); + this._alignPicker(); + } + _construct() { + super._construct(); + this._options = []; + this._selectedIndex = 0; + } + _update() { + super._update(); + this._updatePicker(); + this._updateArrows(); + this._updateArrowsAlpha(); + this._updateAlignment(); + } + _updateAlignment() { + if (this._isFocusedMode) { + this.patch({ + justify: "center" + }); + } else { + this.patch({ + justify: "left" + }); + } + } + _updateArrows() { + if (!this._isFocusedMode) { + var offAlpha = .001; + if (this._LeftArrow) { + this._LeftArrow.alpha = offAlpha; + } + if (this._RightArrow) { + this._RightArrow.alpha = offAlpha; + } + return; + } + var arrowProps = { + w: this.style.arrowWidth, + h: this.style.arrowHeight, + style: { + color: this.style.arrowColor + }, + alpha: this.style.arrowAlphaValue + }; + if (!this._LeftArrow) { + this.patch({ + LeftArrow: { + type: Icon, + mountY: .5, + y: h => h / 2 + } + }); + } + this._LeftArrow.patch(_objectSpread(_objectSpread({}, arrowProps), {}, { + icon: this.style.iconLeftSrc + })); + this._LeftArrow.smooth = { + x: this.style.paddingX + }; + if (!this._RightArrow) { + this.patch({ + RightArrow: { + type: Icon, + mountY: .5, + mountX: 1, + y: h => h / 2 + } + }); + } + this._RightArrow.patch(_objectSpread(_objectSpread({}, arrowProps), {}, { + icon: this.style.iconRightSrc + })); + this._RightArrow.smooth = { + x: this.w - this.style.paddingX + }; + } + _updatePicker() { + var w = this.w - this._paddingX - this.style.arrowWidth * 2; + if (!this._Picker) { + this._TextWrapper.patch({ + Picker: { + type: Row, + clipping: true, + alwaysScroll: true, + signals: { + selectedChange: "_updateArrowsAlpha" + } + } + }); + } + this._Picker.patch({ + visible: !this._collapse, + h: this.style.descriptionTextStyle.lineHeight, + w: w, + items: this.options.map((option => ({ + type: Marquee, + h: this.style.descriptionTextStyle.lineHeight, + w: w, + centerAlign: this._isFocusedMode, + title: _objectSpread(_objectSpread({}, this.style.descriptionTextStyle), {}, { + text: option + }) + }))), + selectedIndex: this.selectedIndex + }); + this._alignPicker(); + } + _alignPicker() { + this._Picker.patch({ + mountX: this._isFocusedMode ? .5 : 0, + x: this._isFocusedMode ? this._Title.w / 2 : 0 + }); + } + _updateArrowsAlpha() { + if (this._Picker) { + this._selectedIndex = this._Picker.selectedIndex; + } + var alpha = this._isFocusedMode ? this.style.arrowAlphaValue : 0; + if (this._RightArrow) { + this._RightArrow.alpha = this.selectedIndex === this.options.length - 1 && this._isFocusedMode ? this.style.arrowAlphaValueLimit : alpha; + } + if (this._LeftArrow) { + this._LeftArrow.alpha = this.selectedIndex === 0 && this._isFocusedMode ? this.style.arrowAlphaValueLimit : alpha; + } + this.fireAncestors("$announce", this.announce); + } + get _fixedWordWrapWidth() { + var wordWrapWidthFocused = this.w - this._paddingX - this.style.arrowWidth * 2 - 2 * this.style.contentSpacing; + var wordWrapWidth = this.w - this._paddingLeft - this._paddingRight; + return this._isFocusedMode ? wordWrapWidthFocused : wordWrapWidth; + } + get _collapse() { + return this.shouldCollapse && !this._isFocusedMode; + } + get selectedOption() { + return this._Picker.selected; + } + _handleLeft() { + if (typeof this.onLeft === "function") { + return this.onLeft(this); + } + this._Picker.selectPrevious(); + return true; + } + _handleRight() { + if (typeof this.onRight === "function") { + return this.onRight(this); + } + this._Picker.selectNext(); + return true; + } + set announce(announce) { + super.announce = announce; + } + get announce() { + if (this._announce) { + return this._announce; + } + return this.title + this.options[this.selectedIndex] + ", List Item"; + } +} + +class MetadataCard extends MetadataBase$1 { + static get __componentName() { + return "MetadataCard"; + } +} + +var base$8 = theme => ({ + textStyle: theme.typography.body2, + fadeHeight: 100, + scroll: { + timingFunction: "linear", + duration: theme.animation.duration.xfast + }, + contentMarginTop: theme.spacer.md, + contentMarginLeft: theme.spacer.xl, + sliderMarginLeft: theme.spacer.lg + theme.spacer.xxs +}); + +var styles$8 = Object.freeze({ + __proto__: null, + base: base$8 +}); + +var base$7 = theme => { + var {scroll: scroll} = base$8(theme); + return { + progressBar: { + animation: scroll + }, + circleAnimation: scroll + }; +}; + +var styles$7 = Object.freeze({ + __proto__: null, + base: base$7 +}); + +class ScrollSlider extends Slider { + static get __componentName() { + return "ScrollSlider"; + } + static get __themeStyle() { + return styles$7; + } +} + +class ScrollWrapper extends Base$1 { + static get __themeStyle() { + return styles$8; + } + static _template() { + return { + clipping: true, + FadeContainer: { + ScrollContainer: { + w: _w => _w, + wordWrap: true + } + }, + Slider: { + type: ScrollSlider, + vertical: true, + signals: { + onSizeChange: "_updateScrollContainerSize" + }, + announce: " " + } + }; + } + static get __componentName() { + return "ScrollWrapper"; + } + static get properties() { + return [ "autoScroll", "autoScrollDelay", "autoScrollSpeed", "content", "fadeContent", "scrollDuration", "scrollStep", "showScrollBar", "shouldWrap", "flexDirection" ]; + } + static get tags() { + return [ "FadeContainer", "Slider", { + name: "ScrollContainer", + path: "FadeContainer.ScrollContainer" + }, { + name: "ScrollableText", + path: "ScrollContainer.ScrollableText" + } ]; + } + _construct() { + super._construct(); + this._scrollStep = 10; + this._shouldWrap = false; + this._flexDirection = "column"; + this._fadeContent = true; + this._sliderWidth = 0; + } + _afterTextBoxUpdate(textBox) { + if (this._prevW !== textBox.finalW || this._prevH !== textBox.finalH) { + this._prevW = textBox.finalW; + this._prevH = textBox.finalH; + this._updateScrollWrapperLayout(); + this._updateAlpha(); + } + } + _resetFlexContainer() { + this._FadeContainer.patch({ + ScrollContainer: undefined + }); + this._FadeContainer.patch({ + ScrollContainer: { + w: _w2 => _w2, + wordWrap: true + } + }); + } + _update() { + if (this._contentChanged) { + this._resetFlexContainer(); + this._updateAutoScroll(); + } + this._updateScrollContainer(); + this._updateScrollWrapperLayout(); + this._updateAlpha(); + } + _updateAutoScroll() { + this.resetScroll(); + this._setupAutoScroll(); + this._contentChanged = false; + } + _updateScrollWrapperLayout() { + this._ScrollContainer.patch({ + w: this._contentWidth + }); + this._updateFadeContainer(); + this._updateSlider(); + } + _updateAlpha() { + this._Slider.smooth = { + alpha: this.showScrollBar && this._isFocusedMode ? 1 : 0 + }; + } + _updateFadeContainer() { + var isScrollable = this._ScrollContainer.finalH > this.h; + var shouldFade = this.fadeContent && isScrollable && !this._isEndContentVisible; + this._FadeContainer.patch({ + h: this.h, + w: this._contentWidth, + y: this.style.contentMarginTop, + x: this.style.contentMarginLeft, + rtt: true, + shader: shouldFade ? { + type: _lightningjs_core__WEBPACK_IMPORTED_MODULE_0__.shaders.FadeOut, + bottom: this.style.fadeHeight + } : undefined + }); + } + _scrollContainerLoaded(_ref23) { + var {h: h} = _ref23; + this._ScrollContainer.h = h; + this._updateScrollWrapperLayout(); + } + _updateScrollContainer() { + if (!this.content) return; + if (typeof this.content === "string") { + this._ScrollContainer.patch({ + flex: { + direction: "column" + }, + ScrollableText: { + h: 0, + w: this._contentWidth, + type: TextBox, + content: this.content, + style: { + textStyle: _objectSpread(_objectSpread({}, this.style.textStyle), {}, { + wordWrap: true, + wordWrapWidth: this._contentWidth + }) + }, + signals: { + textBoxChanged: "_scrollContainerLoaded" + }, + onAfterUpdate: this._afterTextBoxUpdate.bind(this) + } + }); + } else if (Array.isArray(this.content)) { + var content = {}; + this.content.forEach(((item, index) => { + var id = "ScrollText".concat(index); + content[id] = _objectSpread({ + w: this._contentWidth + }, item); + if (item.text) { + content[id] = { + type: TextBox, + content: item.text, + style: { + textStyle: _objectSpread(_objectSpread(_objectSpread({}, this.style.textStyle), item.style), {}, { + wordWrap: true, + wordWrapWidth: this._contentWidth + }) + }, + onAfterUpdate: this._afterTextBoxUpdate.bind(this) + }; + } + })); + this._ScrollContainer.patch(_objectSpread({ + flex: { + direction: this.flexDirection, + wrap: this.shouldWrap + } + }, content)); + } + } + _scrollDown() { + var hasContentToScrollTo = this._scrollContainerY + this._ScrollContainer.finalH > this.renderHeight; + if (hasContentToScrollTo) { + var targetY = this._scrollContainerY - this.scrollStep; + var canScrollByStepLength = targetY + this._ScrollContainer.finalH > this.renderHeight; + var scrollEndY = this.renderHeight - this._ScrollContainer.finalH - this.style.contentMarginTop; + this._ScrollContainer.patch({ + smooth: { + y: [ canScrollByStepLength ? targetY : scrollEndY, this._scrollAnimation ] + } + }); + var hasScrolledToEnd = this._scrollContainerY + this._ScrollContainer.finalH <= this.h; + if (hasScrolledToEnd) { + this._isEndContentVisible = true; + this._autoScrollComplete = true; + this.fireAncestors("$scrollChanged", "endDown", this); + this._updateFadeContainer(); + } + } else { + return false; + } + } + _scrollUp() { + var canScrollUp = this._scrollContainerY < 0; + if (canScrollUp) { + var targetY = this._scrollContainerY + this.scrollStep; + var canScrollByStepLength = targetY < 0; + this._ScrollContainer.patch({ + smooth: { + y: [ canScrollByStepLength ? targetY : 0, this._scrollAnimation ] + } + }); + var isScrollable = this._scrollContainerY + this._ScrollContainer.finalH > this.renderHeight; + if (isScrollable) { + this._autoScrollComplete = false; + } + if (this._scrollContainerY >= 0) { + this.fireAncestors("$scrollChanged", "endUp", this); + } + if (this._isEndContentVisible) { + this._isEndContentVisible = false; + this._updateFadeContainer(); + } + } else { + return false; + } + } + resetScroll() { + this._ScrollContainer.y = 0; + this._Slider.value = 0; + this._ScrollContainer.transition("y").finish(); + delete this._ScrollContainer._transitions; + this._autoScrollComplete = false; + } + _setAutoScroll(val) { + if (this._autoScroll !== val) { + this._autoScroll = val; + } + this._setupAutoScroll(); + return val; + } + _setupAutoScroll() { + clearTimeout(this._startAutoScroll); + clearTimeout(this._performAutoScrollTimer); + if (this.autoScroll) { + this._startAutoScroll = setTimeout((() => this._performAutoScroll()), isNaN(this.autoScrollDelay) ? 2e3 : this.autoScrollDelay); + } + } + _performAutoScroll() { + if (this.autoScroll && !this._autoScrollComplete) { + this._Slider._handleDown(); + this._performAutoScrollTimer = setTimeout((() => this._performAutoScroll()), isNaN(this.autoScrollSpeed) ? 200 : this.autoScrollSpeed); + } + } + _setContent(content) { + if (content !== this._content && this.enabled) { + this._contentChanged = true; + } + return content; + } + _updateScrollContainerSize(slider) { + if (this._sliderWidth !== slider._Container.h) { + this._sliderWidth = slider._Container.h; + this._updateScrollContainer(); + } + } + _updateSlider() { + var scrollHeight = Math.max(this._ScrollContainer.finalH - this.renderHeight, 0); + var contentScrollSteps = scrollHeight > 0 ? Math.ceil(scrollHeight / this.scrollStep) : 1; + var sliderMax = this.renderHeight; + var sliderStep = contentScrollSteps > 0 ? sliderMax / contentScrollSteps : sliderMax; + if (this._Slider) { + this._Slider.patch({ + x: this.w - this._sliderWidth, + w: sliderMax, + min: 0, + max: sliderMax, + step: sliderStep, + onUp: this._scrollUp.bind(this), + onDown: this._scrollDown.bind(this) + }); + } + } + get _contentWidth() { + return this.w - this.style.contentMarginLeft - this.style.sliderMarginLeft - this._sliderWidth; + } + get _scrollContainerY() { + return this._ScrollContainer.transition("y").targetValue; + } + get _scrollAnimation() { + var duration = isNaN(this.scrollDuration) ? this.style.scroll.duration : this.scrollDuration; + return _objectSpread(_objectSpread({}, this.style.scroll), {}, { + duration: duration + }); + } + _getFocused() { + return this._Slider; + } + set announce(announce) { + super.announce = announce; + } + get announce() { + if (this._announce) { + return this._announce; + } + if (Array.isArray(this.content)) { + if (this._ScrollContainer && this._ScrollContainer.children && this._ScrollContainer.children.length) { + return this._ScrollContainer.children.map((item => item.announce)); + } else { + return this.content.map((item => item.announce || item.text)); + } + } + return this.content; + } +} + +var base$6 = theme => ({ + alpha: theme.alpha.none, + animation: theme.animation.standardEntrance, + blur: theme.spacer.xxl, + color: theme.color.shadowNeutralFocus, + offsetX: 0, + offsetY: theme.spacer.lg, + radius: theme.radius.md, + spread: theme.spacer.md * -1, + maxOffsetY: theme.spacer.xxl, + maxOffsetX: 0 +}); + +var mode$1 = theme => ({ + focused: { + alpha: theme.alpha.secondary, + offsetY: theme.spacer.xxl + } +}); + +var tone$3 = theme => ({ + neutral: { + color: theme.color.shadowNeutralFocus + }, + inverse: { + color: theme.color.shadowInverseFocus + }, + brand: { + color: theme.color.shadowBrandFocus + } +}); + +var styles$6 = Object.freeze({ + __proto__: null, + base: base$6, + mode: mode$1, + tone: tone$3 +}); + +class Shadow extends Base$1 { + static get __componentName() { + return "Shadow"; + } + static get __themeStyle() { + return styles$6; + } + static get properties() { + return [ "maskShadow" ]; + } + static get tags() { + return [ "Frame", { + name: "Shadow", + path: "Frame.Shadow" + } ]; + } + _updateFocusStyle() { + if (!this._Shadow) return; + this.applySmooth(this._Shadow, { + alpha: this.style.alpha, + y: this.style.offsetY, + x: this.style.offsetX + }, { + alpha: [ this.style.alpha, this.style.animation ], + y: [ this.style.offsetY, this.style.animation ], + x: [ this.style.offsetX, this.style.animation ] + }); + } + _update() { + var shadowSize = this.style.spread + this.style.blur * 2; + var holepunchError = 4; + var extraBoundsY = this.style.maxOffsetY; + var extraBoundsX = this.style.maxOffsetX; + var radius = getMaxRoundRadius(this.style.radius, this.w, this.h); + this.patch({ + Frame: { + w: this.w + shadowSize * 2 + extraBoundsX, + h: this.h + shadowSize * 2 + extraBoundsY, + x: (this.w + extraBoundsX) / 2, + y: (this.h + extraBoundsY) / 2, + mount: .5, + rtt: this.maskShadow, + shader: this.maskShadow ? { + type: _lightningjs_core__WEBPACK_IMPORTED_MODULE_0__.shaders.Hole, + w: this.w - holepunchError, + h: this.h - holepunchError, + x: shadowSize + holepunchError / 2, + y: shadowSize + holepunchError / 2, + radius: radius + } : undefined, + Shadow: { + color: this.style.color, + texture: _lightningjs_core__WEBPACK_IMPORTED_MODULE_0__.Tools.getShadowRect(this.w + this.style.spread * 2, this.h + this.style.spread * 2, radius, this.style.blur) + } + } + }); + if (this.shouldSmooth === undefined) { + this.shouldSmooth = true; + } + this._updateFocusStyle(); + } +} + +var base$5 = theme => { + var size = theme.spacer.xxl; + return { + width: size, + height: size, + radius: size / 2 + }; +}; + +var styles$5 = Object.freeze({ + __proto__: null, + base: base$5 +}); + +class SliderLarge extends Slider { + static get __componentName() { + return "SliderLarge"; + } + static get __themeStyle() { + return styles$5; + } +} + +class ContentSwitcher extends Base$1 { + static get __componentName() { + return "ContentSwitcher"; + } + static get properties() { + return [ "selectedIndex" ]; + } + _construct() { + super._construct(); + this._selectedIndex = 0; + this._contentItems = []; + } + _update() { + super._update(); + this._updateSelected(); + } + _updateSelected() { + if (this._preveSelectedIndex !== this.selectedIndex) { + if (this._preveSelectedIndex !== undefined) { + var prevContent = this.tag("Content".concat(this._preveSelectedIndex)); + prevContent.smooth = { + alpha: 0 + }; + if (this._hasContent) { + prevContent._getTransition("alpha").once("finish", (() => { + this._fadeInContent(); + })); + } else if (this.selectedIndex !== undefined) { + this._fadeInContent(); + } + } else if (this._hasContent) { + this._fadeInContent(); + } + this._preveSelectedIndex = this.selectedIndex; + } + } + _fadeInContent() { + this._selectedContent.smooth = { + alpha: 1 + }; + this._selectedContent._getTransition("alpha").once("finish", (() => { + this.h = this._selectedContent.h; + this.signal("contentHeightChange", this.h); + })); + } + _updateContent() { + var allContent = this.contentItems.reduce(((acc, item, idx) => { + var component; + var tagName = "Content".concat(idx); + if (typeof item === "function") { + var componentLoader = item(); + if (componentLoader.then) { + this._loadAsyncComponent(componentLoader, idx); + } else { + component = componentLoader; + } + } else { + component = item; + } + if (component) { + acc[tagName] = _objectSpread(_objectSpread({}, component), {}, { + alpha: 0 + }); + } + return acc; + }), {}); + this.patch(allContent); + } + _loadAsyncComponent(componentLoader, idx) { + componentLoader.then((component => { + var tagName = "Content".concat(idx); + this.patch({ + [tagName]: _objectSpread(_objectSpread({}, component), {}, { + alpha: 0 + }) + }); + })); + } + set contentItems(contentItems) { + if (!stringifyCompare(contentItems, this._contentItems)) { + this._contentItems = contentItems; + this._updateContent(); + } + } + get contentItems() { + return this._contentItems; + } + get _hasContent() { + return this._selectedContent && this._selectedContent.children.length > 0; + } + get _selectedContent() { + return this.tag("Content".concat(this.selectedIndex)); + } + _getFocused() { + if (this._hasContent) { + return this._selectedContent; + } + } +} + +var base$4 = theme => ({ + tabSpacing: theme.spacer.lg, + tabsMarginBottom: theme.spacer.xxl +}); + +var styles$4 = Object.freeze({ + __proto__: null, + base: base$4 +}); + +class TabBar extends Base$1 { + static _template() { + return { + Tabs: { + type: Row, + autoResizeHeight: true, + signals: { + selectedChange: "_selectedTabChange" + } + }, + TabContent: { + type: ContentSwitcher, + signals: { + contentHeightChange: "_updateTabBarHeight" + } + } + }; + } + static get __themeStyle() { + return styles$4; + } + static get __componentName() { + return "TabBar"; + } + static get properties() { + return [ "alphaSelectedTab", "collapse", "reset", "tabs", "retainSelection", ...Row.properties ]; + } + static get tags() { + return [ "Tabs", "TabContent" ]; + } + _construct() { + super._construct(); + this._tabContent = []; + this._isTabsFocused = true; + } + _selectedTabChange(selected, prevSelected) { + this.fireAncestors("$tabChanged", selected, prevSelected, this); + if (typeof this._tabContent === "object" && typeof this._tabContent.then === "function") { + return this._tabContent.then(this.queueRequestUpdate); + } + return this.queueRequestUpdate(); + } + _update() { + this._updateTabsLayout(); + this._updateTabs(); + this._updateTabContent(); + this._updateTabBarHeight(); + } + _updateTabsLayout() { + var defaultLayout = { + style: { + itemSpacing: this.style.tabSpacing + } + }; + var tabsRowPatch = Row.properties.reduce(((patchObj, prop) => { + if (this[prop] != undefined) { + patchObj[prop] = this[prop]; + } + return patchObj; + }), defaultLayout); + this._Tabs.patch(tabsRowPatch); + } + _updateTabs() { + this._Tabs.wrapSelected = this.wrapSelected; + this._Tabs.items.forEach((tab => { + var isSelectedTab = tab === this._Tabs.selected; + if (this._isUnfocusedMode) { + tab.mode = isSelectedTab && this.retainSelection ? "selected" : "unfocused"; + } else if (this._isFocusedMode) { + if (this._isTabsFocused) { + tab.mode = isSelectedTab ? "focused" : "unfocused"; + } else { + tab.mode = isSelectedTab ? "selected" : "unfocused"; + } + } + })); + if (this.alphaSelectedTab) { + this._updateTabAlphas(); + } + } + _updateTabAlphas() { + if (this._isTabsFocused) { + this._Tabs.items.forEach((tab => { + tab.patch({ + alpha: 1 + }); + })); + } else { + this._Tabs.items.forEach((tab => { + tab.patch({ + alpha: tab === this._Tabs.selected ? 1 : .3 + }); + })); + } + } + _updateTabContent() { + var margin = this.style.tabsMarginBottom; + this._TabContent.patch({ + y: this._Tabs.h + margin, + contentItems: this._tabContent, + selectedIndex: this._isFocusedMode ? this._Tabs.selectedIndex : undefined + }); + } + $itemChanged() { + this._updateTabBarHeight(); + this._updateTabContent(); + } + _updateTabBarHeight() { + var h; + if (this.collapse) { + h = this._isFocusedMode && this._tabContent.filter((content => Object.keys(content).length)).length ? this._expandedHeight : this._collapsedHeight; + } else { + h = this._expandedHeight; + } + this._TabContent.smooth = { + alpha: !this.collapse || this._isFocusedMode ? 1 : .001 + }; + if (this.h !== h) { + this.h = h; + this.fireAncestors("$itemChanged"); + } + } + selectTabs() { + if (!this._isTabsFocused) { + this._isTabsFocused = true; + this._updateTabs(); + this._updateTabBarHeight(); + } + } + resetTabs() { + this._Tabs.selectedIndex = 0; + } + _handleDown() { + if (this._isTabsFocused && this._TabContent._hasContent) { + this._isTabsFocused = false; + this._updateTabs(); + this._updateTabBarHeight(); + } + return false; + } + _handleUp() { + this.selectTabs(); + return false; + } + _setTabs(tabs) { + this._tabContent = []; + this._tabContent = tabs.map((tab => tab.tabContent || {})); + this._Tabs.items = tabs; + return tabs; + } + _getTabs() { + return this._Tabs.items; + } + get selected() { + return this._Tabs.selected; + } + get selectedIndex() { + return this._Tabs.selectedIndex; + } + set selectedIndex(index) { + this._Tabs.selectedIndex = index; + } + get _collapsedHeight() { + return this._Tabs.h; + } + get _expandedHeight() { + return this._Tabs.h + this.style.tabsMarginBottom + this._TabContent.h; + } + _getFocused() { + return this._isTabsFocused ? this._Tabs : this._TabContent; + } + _unfocus() { + super._unfocus(); + if (this.reset) { + this.resetTabs(); + } + } +} + +var base$3 = theme => ({ + radius: theme.radius.xl, + paddingX: theme.spacer.xxxl + theme.spacer.xxs, + paddingY: theme.spacer.md + theme.spacer.xs, + paddingXNoTitle: theme.spacer.xl, + iconSize: theme.spacer.xxxl, + iconMarginRight: theme.spacer.md, + textStyle: _objectSpread(_objectSpread({}, theme.typography.headline3), {}, { + textColor: theme.color.textNeutral + }), + backgroundColor: theme.color.fillTransparent, + contentColor: theme.color.fillNeutral +}); + +var mode = theme => ({ + focused: { + backgroundColor: theme.color.interactiveNeutralFocus, + contentColor: theme.color.fillInverse, + textStyle: { + textColor: theme.color.textInverse + } + }, + selected: { + backgroundColor: theme.color.interactiveNeutralFocusSoft, + contentColor: theme.color.fillNeutral, + textStyle: { + textColor: theme.color.textNeutral + } + }, + disabled: { + backgroundColor: theme.color.fillTransparent, + contentColor: theme.color.fillNeutralDisabled, + textStyle: { + textColor: theme.color.textNeutralDisabled + } + } +}); + +var tone$2 = theme => ({ + neutral: {}, + inverse: { + mode: { + focused: { + contentColor: theme.color.fillNeutral, + textStyle: { + textColor: theme.color.textNeutral + } + } + } + }, + brand: { + mode: { + focused: { + contentColor: theme.color.fillNeutral, + textStyle: { + textColor: theme.color.textNeutral + } + } + } + } +}); + +var styles$3 = Object.freeze({ + __proto__: null, + base: base$3, + mode: mode, + tone: tone$2 +}); + +class Tab extends Surface { + static _template() { + return _objectSpread(_objectSpread({}, super._template()), {}, { + Content: { + mount: .5, + x: w => w / 2, + y: h => h / 2, + Text: { + type: TextBox, + mountY: .5, + signals: { + textBoxChanged: "_onTextBoxChanged" + } + } + } + }); + } + static get __themeStyle() { + return styles$3; + } + static get __componentName() { + return "Tab"; + } + static get properties() { + return [ "icon", "title" ]; + } + static get tags() { + return [ ...super.tags, "Content", { + name: "Icon", + path: "Content.Icon" + }, { + name: "Text", + path: "Content.Text" + } ]; + } + static get aliasStyles() { + return [ { + prev: "noTitlePaddingX", + curr: "paddingXNoTitle" + } ]; + } + _onTextBoxChanged() { + this._updateContent(); + this._updateTabSize(); + } + _update() { + super._update(); + this._updateIcon(); + this._updateText(); + this._updateContent(); + this._updateTabSize(); + } + _updateIcon() { + if (!this.icon) { + this._Content.patch({ + Icon: undefined + }); + return; + } + var iconPatch = { + icon: this.icon, + w: this.style.iconSize, + h: this.style.iconSize, + y: this._Content.h / 2, + style: { + color: this.style.contentColor + } + }; + if (this.title) { + iconPatch.x = 0; + iconPatch.mountX = 0; + } else { + iconPatch.x = this._Content.w / 2; + iconPatch.mountX = .5; + } + if (this._Icon) { + this._Icon.patch(iconPatch); + } else { + this._Content.patch({ + Icon: _objectSpread({ + type: Icon, + mountY: .5 + }, iconPatch) + }); + } + } + _updateText() { + var textPatch = { + content: this.title, + style: { + textStyle: this.style.textStyle + }, + y: this._Content.h / 2 + }; + if (this.icon) { + textPatch.x = this._iconW + this.style.iconMarginRight; + textPatch.mountX = 0; + } else { + textPatch.x = this._Content.w / 2; + textPatch.mountX = .5; + } + this._Text.patch(textPatch); + } + _updateContent() { + this._Content.patch({ + w: this._iconW + (this.title ? this.style.iconMarginRight : 0) + this._textW, + h: Math.max(this._iconH, this._Text.h) + }); + } + _updateTabSize() { + if (this.title || this.icon) { + this.patch({ + w: this._paddingX * 2 + this._Content.w, + h: this.style.paddingY * 2 + this._Content.h + }); + } else { + this.patch({ + w: 0, + h: 0 + }); + } + } + get _textW() { + return this.title ? this._Text.w : 0; + } + get _iconW() { + return this.icon && this._Icon !== undefined ? this._Icon.w : 0; + } + get _iconH() { + return this.icon && this._Icon !== undefined ? this._Icon.h : 0; + } + get _paddingX() { + return this.title ? this.style.paddingX : this.style.paddingXNoTitle; + } + set announce(announce) { + super.announce = announce; + } + get announce() { + return this._announce || this._Text && this._Text.announce; + } +} + +var base$2 = theme => { + var knobSize = theme.spacer.xl; + var knobPadding = theme.spacer.xs; + var strokeWidth = theme.stroke.sm; + return { + height: knobSize + (knobPadding + strokeWidth) * 2, + knobWidth: knobSize, + knobHeight: knobSize, + knobRadius: knobSize / 2, + knobPadding: knobPadding, + strokeWidth: strokeWidth, + width: (strokeWidth + knobPadding * 2 + knobSize) * 2 + }; +}; + +var tone$1 = theme => ({ + neutral: { + strokeColor: theme.color.fillNeutral, + backgroundColor: theme.color.fillInverseTertiary, + backgroundColorChecked: theme.color.fillNeutral, + knobColor: theme.color.fillNeutral, + knobColorChecked: theme.color.fillInverse, + mode: { + disabled: { + strokeColor: theme.color.fillNeutralDisabled, + backgroundColor: theme.color.fillInverseDisabled, + backgroundColorChecked: theme.color.fillNeutralDisabled, + knobColor: theme.color.fillNeutralDisabled, + knobColorChecked: theme.color.fillInverseDisabled + } + } + }, + inverse: { + strokeColor: theme.color.fillInverse, + backgroundColor: theme.color.fillNeutralTertiary, + backgroundColorChecked: theme.color.fillInverse, + knobColor: theme.color.fillInverse, + knobColorChecked: theme.color.fillNeutral, + mode: { + disabled: { + strokeColor: theme.color.fillInverseDisabled, + backgroundColor: theme.color.fillNeutralDisabled, + backgroundColorChecked: theme.color.fillInverseDisabled, + knobColor: theme.color.fillInverseDisabled, + knobColorChecked: theme.color.fillNeutralDisabled + } + } + }, + brand: { + strokeColor: theme.color.fillBrand, + backgroundColor: theme.color.fillBrandTertiary, + backgroundColorChecked: theme.color.fillBrand, + knobColor: theme.color.fillBrand, + knobColorChecked: theme.color.fillInverse, + mode: { + disabled: { + strokeColor: theme.color.fillNeutralDisabled, + backgroundColor: theme.color.fillInverseDisabled, + backgroundColorChecked: theme.color.fillNeutralDisabled, + knobColor: theme.color.fillNeutralDisabled, + knobColorChecked: theme.color.fillInverseDisabled + } + } + } +}); + +var styles$2 = Object.freeze({ + __proto__: null, + base: base$2, + tone: tone$1 +}); + +class Toggle extends Base$1 { + static get __componentName() { + return "Toggle"; + } + static get __themeStyle() { + return styles$2; + } + static _template() { + return { + Container: { + Stroke: {}, + Knob: {} + } + }; + } + static get tags() { + return [ "Container", { + name: "Knob", + path: "Container.Knob" + }, { + name: "Stroke", + path: "Container.Stroke" + } ]; + } + static get properties() { + return [ "checked" ]; + } + static get aliasStyles() { + return [ { + prev: "strokeWeight", + curr: "strokeWidth" + } ]; + } + _construct() { + super._construct && super._construct(); + this._checked = false; + } + _update() { + this._updateKnobPosition(); + this._updateColors(); + this._updateContainer(); + this._updateStroke(); + this._updateKnob(); + if (this._checkedChanged) { + this.fireAncestors("$announce", this.announce); + this._checkedChanged = false; + } + } + _updateKnobPosition() { + var {knobPadding: knobPadding, knobWidth: knobWidth, strokeWidth: strokeWidth} = this.style; + this.applySmooth(this._Knob, { + x: this.checked ? this.w - strokeWidth - knobPadding - knobWidth : strokeWidth + knobPadding + }); + } + _updateColors() { + var {backgroundColor: backgroundColor, backgroundColorChecked: backgroundColorChecked, knobColor: knobColor, knobColorChecked: knobColorChecked} = this.style; + var currentKnobColor = this.checked ? knobColorChecked : knobColor; + var containerColor = this.checked ? backgroundColorChecked : backgroundColor; + this.applySmooth(this._Knob, { + color: currentKnobColor + }); + this.applySmooth(this._Container, { + color: containerColor + }); + } + _updateContainer() { + var {knobRadius: knobRadius, knobPadding: knobPadding, strokeRadius: strokeRadius, strokeWidth: strokeWidth} = this.style; + var radius = strokeRadius !== undefined ? strokeRadius === 0 ? strokeRadius : Math.max(0, strokeRadius - strokeWidth) : Math.max(0, knobRadius + knobPadding + strokeWidth); + this._Container.patch({ + w: this.w, + h: this.h, + texture: _lightningjs_core__WEBPACK_IMPORTED_MODULE_0__.Tools.getRoundRect(this.w - strokeWidth * 2 - 2, this.h - strokeWidth * 2 - 2, getMaxRoundRadius(radius, this.w, this.h), strokeWidth, 0, true, false) + }); + } + _updateStroke() { + var {knobRadius: knobRadius, knobPadding: knobPadding, strokeColor: strokeColor, strokeRadius: strokeRadius, strokeWidth: strokeWidth} = this.style; + this._Stroke.patch({ + w: this.w, + h: this.h, + texture: _lightningjs_core__WEBPACK_IMPORTED_MODULE_0__.Tools.getRoundRect(this.w - 2, this.h - 2, strokeRadius !== undefined ? getMaxRoundRadius(strokeRadius, this.w, this.h) : getMaxRoundRadius(knobRadius, this.w - knobPadding * 2 - 2, this.h - knobPadding * 2 - 2) + knobPadding + strokeWidth, strokeWidth, strokeColor, false, false) + }); + } + _updateKnob() { + var {knobHeight: knobHeight, knobWidth: knobWidth, knobRadius: knobRadius} = this.style; + this._Knob.patch({ + zIndex: 2, + y: (this.h - knobHeight) / 2, + texture: _lightningjs_core__WEBPACK_IMPORTED_MODULE_0__.Tools.getRoundRect(knobWidth - 2, knobHeight - 2, getMaxRoundRadius(knobRadius, knobWidth - 2, knobHeight - 2), 0, 0, true, false) + }); + } + _setChecked(checked) { + this._checkedChanged = checked !== this._checked; + return checked; + } + toggle() { + if (!this._isDisabledMode) { + this.checked = !this.checked; + } + return this; + } + _handleEnter() { + if (typeof this.onEnter === "function") { + return this.onEnter(this); + } else { + this.toggle(); + } + return false; + } + set announce(announce) { + super.announce = announce; + } + get announce() { + return this._announce || (this.checked ? "Checked" : "Unchecked"); + } +} + +var base$1 = theme => { + var knobSize = theme.spacer.lg; + var knobPadding = theme.spacer.xxs; + var strokeWidth = theme.stroke.sm; + return { + height: knobSize + (knobPadding + strokeWidth) * 2, + knobWidth: knobSize, + knobHeight: knobSize, + knobRadius: knobSize / 2, + knobPadding: knobPadding, + strokeWidth: strokeWidth, + width: (strokeWidth + knobPadding * 2 + knobSize) * 2 + }; +}; + +var styles$1 = Object.freeze({ + __proto__: null, + base: base$1 +}); + +class ToggleSmall extends Toggle { + static get __componentName() { + return "ToggleSmall"; + } + static get __themeStyle() { + return styles$1; + } +} + +class Bubble extends _lightningjs_core__WEBPACK_IMPORTED_MODULE_0__.Texture { + constructor(stage) { + super(stage); + this._w = 0; + this._h = 0; + this._radius = 0; + this._pointerWidth = 0; + this._pointerHeight = 0; + this._strokeWidth = 0; + this._color = "white"; + } + set w(w) { + this._w = w; + this._changed(); + } + get w() { + return this._w; + } + set h(h) { + this._h = h; + this._changed(); + } + get h() { + return this._h; + } + set radius(radius) { + if (Array.isArray(radius)) { + this._radius = new Array(4).fill().map(((_, index) => radius[index] || 0)); + } else { + this._radius = radius; + } + this._changed(); + } + get radius() { + return this._radius; + } + set pointerWidth(pointerWidth) { + this._pointerWidth = pointerWidth; + this._changed(); + } + get pointerWidth() { + return this._pointerWidth; + } + set pointerHeight(pointerHeight) { + this._pointerHeight = pointerHeight; + this._changed(); + } + get pointerHeight() { + return this._pointerHeight; + } + set strokeWidth(strokeWidth) { + this._strokeWidth = strokeWidth; + this._changed(); + } + get strokeWidth() { + return this._strokeWidth; + } + set color(color) { + this._color = _lightningjs_core__WEBPACK_IMPORTED_MODULE_0__.StageUtils.getRgbaString(color); + this._changed(); + } + get color() { + return this._color; + } + createBubble(_ref24) { + var {stage: stage, w: w = 0, h: h = 0, radius: radius = 0, pointerWidth: pointerWidth = 0, pointerHeight: pointerHeight = 0, strokeWidth: strokeWidth = 1, color: color = "white"} = _ref24; + var canvas = stage.platform.getDrawingCanvas(); + var ctx = canvas.getContext("2d"); + canvas.width = w + strokeWidth + 4; + canvas.height = h + strokeWidth + 4; + ctx.imageSmoothingEnabled = true; + ctx.fillStyle = color; + ctx.strokeStyle = color; + ctx.lineWidth = strokeWidth; + ctx.lineCap = "round"; + ctx.lineJoin = "round"; + var initialCoord = .5 * strokeWidth + 1; + var leftX = initialCoord; + var rightX = leftX + w; + var topY = initialCoord; + var bottomY = topY + h; + var bottomBubbleY = bottomY - pointerHeight; + var isRadiusAnArray = Array.isArray(radius); + ctx.beginPath(); + ctx.moveTo(leftX + (isRadiusAnArray ? radius[0] : radius), topY); + ctx.lineTo(rightX - (isRadiusAnArray ? radius[0] : radius), topY); + ctx.arcTo(rightX, topY, rightX, topY + (isRadiusAnArray ? radius[1] : radius), isRadiusAnArray ? radius[1] : radius); + ctx.lineTo(rightX, bottomBubbleY - (isRadiusAnArray ? radius[2] : radius)); + ctx.arcTo(rightX, bottomBubbleY, rightX - (isRadiusAnArray ? radius[2] : radius), bottomBubbleY, isRadiusAnArray ? radius[2] : radius); + ctx.lineTo(w / 2 + pointerWidth / 2, bottomBubbleY); + ctx.arcTo(w / 2, bottomY, w / 2 - pointerWidth / 2, bottomBubbleY, 2); + ctx.lineTo(w / 2 - pointerWidth / 2, bottomBubbleY); + ctx.lineTo(leftX + (isRadiusAnArray ? radius[3] : radius), bottomBubbleY); + ctx.arcTo(leftX, bottomBubbleY, leftX, bottomBubbleY - (isRadiusAnArray ? radius[3] : radius), isRadiusAnArray ? radius[3] : radius); + ctx.lineTo(leftX, topY + (isRadiusAnArray ? radius[0] : radius)); + ctx.arcTo(leftX, topY, leftX + (isRadiusAnArray ? radius[0] : radius), topY, isRadiusAnArray ? radius[0] : radius); + ctx.stroke(); + ctx.fill(); + return canvas; + } + _getLookupId() { + var {w: w, h: h, radius: radius, pointerWidth: pointerWidth, pointerHeight: pointerHeight, color: color} = this; + return "__bubble_".concat(w, "x").concat(h, "_radius-").concat(radius, "_pointer-").concat(pointerWidth, "x").concat(pointerHeight, "_fill-").concat(color); + } + _getSourceLoader() { + return cb => { + cb(null, { + source: this.createBubble(this) + }); + }; + } +} + +var base = theme => ({ + marginBottom: theme.spacer.xl, + paddingX: theme.spacer.lg, + paddingY: theme.spacer.md, + pointerWidth: theme.spacer.xxl, + pointerHeight: theme.spacer.lg, + radius: theme.radius.sm, + textStyle: _objectSpread(_objectSpread({}, theme.typography.body3), {}, { + textColor: theme.color.textInverse + }), + transition: theme.animation.utility +}); + +var tone = theme => ({ + neutral: { + backgroundColor: theme.color.fillNeutral, + textStyle: { + textColor: theme.color.textInverse + } + }, + inverse: { + backgroundColor: theme.color.fillInverse, + textStyle: { + textColor: theme.color.textNeutral + } + }, + brand: { + backgroundColor: theme.color.fillBrand, + textStyle: { + textColor: theme.color.textNeutral + } + } +}); + +var styles = Object.freeze({ + __proto__: null, + base: base, + tone: tone +}); + +class Tooltip extends Base$1 { + static get __componentName() { + return "Tooltip"; + } + static get __themeStyle() { + return styles; + } + static _template() { + return { + alpha: 0, + scale: .5, + mountX: .5, + x: w => w / 2, + Background: { + Text: { + type: TextBox, + signals: { + textBoxChanged: "_textLoaded" + } + } + } + }; + } + static get properties() { + return [ "title", "delayVisible", "timeVisible" ]; + } + static get tags() { + return [ "Background", { + name: "Text", + path: "Background.Text" + } ]; + } + static get aliasStyles() { + return [ { + prev: "pointerH", + curr: "pointerHeight" + }, { + prev: "pointerW", + curr: "pointerWidth" + } ]; + } + _update() { + this._updateText(); + this._updateBackground(); + } + _updateText() { + if (this._Text) { + this._Text.patch({ + content: this.title, + style: { + textStyle: this.style.textStyle + } + }); + } + } + _textLoaded() { + this._updateBackgroundHeight(); + this._updateTextPosition(); + } + _updateBackground() { + this.patch({ + Background: { + texture: { + type: Bubble, + w: this._Background.w, + h: this._Background.h, + radius: getMaxRoundRadius(this.style.radius, this._Background.w - this.style.pointerHeight, this._Background.h - this.style.pointerHeight), + pointerWidth: this.style.pointerWidth, + pointerHeight: this.style.pointerHeight, + color: this.style.backgroundColor + } + } + }); + } + _updateBackgroundHeight() { + var backgroundH = this._Text.finalH + this.style.paddingY * 2 + this.style.pointerHeight; + var backgroundW = this._Text.finalW + this.style.paddingX * 2; + this.patch({ + w: backgroundW, + h: backgroundH, + mountY: 1, + y: -this.style.marginBottom, + Background: { + w: backgroundW, + h: backgroundH, + texture: { + type: Bubble, + w: backgroundW, + h: backgroundH + } + } + }); + } + _updateTextPosition() { + if (this._Text) { + this._Text.patch({ + mount: .5, + x: this._Background.w / 2, + y: (this._Background.h - this.style.pointerHeight) / 2 + }); + } + } + _clearTimers() { + clearTimeout(this._hideTimer); + clearTimeout(this._showTimer); + } + _transitionIn() { + var smooth = { + smooth: { + alpha: [ 1, this.style.transition ], + scale: [ 1, this.style.transition ] + } + }; + if (this.delayVisible) { + this._showTimer = setTimeout((() => { + this.patch({ + smooth: smooth + }); + }), this.delayVisible); + } else { + this._showTimer = undefined; + this.patch({ + smooth: smooth + }); + } + this._hideTimer = this.timeVisible ? setTimeout((() => { + this._unfocus(); + }), this.timeVisible + (this.delayVisible || 0)) : undefined; + } + _transitionOut() { + this.patch({ + smooth: { + alpha: [ 0, this.style.transition ], + scale: [ .5, this.style.transition ] + } + }); + } + _focus() { + this._clearTimers(); + this._transitionIn(); + } + _unfocus() { + this._clearTimers(); + this._transitionOut(); + } + set announce(announce) { + super.announce = announce; + } + get announce() { + return this._announce || this._Text && this._Text.announce; + } +} + +var pools = new Map; + +function get(key) { + if (pools.has(key)) { + var pool = pools.get(key); + var _index = pool.index; + if (_index >= pool.components.length) { + _index = 0; + } + pool.index = _index + 1; + return pool.components[_index]; + } + return false; +} + +function clear() { + pools.clear(); +} + +function create(_ref25) { + var {name: name, component: component, stage: stage, size: size = 2} = _ref25; + if (pools.has(name)) { + return get(name); + } + component = component || { + type: name + }; + var components = []; + for (var i = 0; i < size; i++) { + components.push(stage.c(component)); + } + pools.set(name, { + index: 0, + components: components + }); + return get(name); +} + +var index$2 = { + get: get, + create: create, + clear: clear +}; + +function flattenStrings() { + var series = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : []; + var flattenedSeries = []; + for (var i = 0; i < series.length; i++) { + if (typeof series[i] === "string" && !series[i].includes("PAUSE-")) { + flattenedSeries.push(series[i]); + } else { + break; + } + } + return [ flattenedSeries.join(",\b ") ].concat(series.slice(i)); +} + +function delay(pause) { + return new Promise((resolve => { + setTimeout(resolve, pause); + })); +} + +function speak(phrase, utterances) { + var lang = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : "en-US"; + var synth = window.speechSynthesis; + return new Promise(((resolve, reject) => { + var utterance = new SpeechSynthesisUtterance(phrase); + utterance.lang = lang; + utterance.onend = () => { + resolve(); + }; + utterance.onerror = e => { + reject(e); + }; + utterances.push(utterance); + synth.speak(utterance); + })); +} + +function speakSeries(series, lang) { + var root = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true; + var synth = window.speechSynthesis; + var remainingPhrases = flattenStrings(Array.isArray(series) ? series : [ series ]); + var nestedSeriesResults = []; + var utterances = []; + var active = true; + var seriesChain = _asyncToGenerator((function*() { + try { + while (active && remainingPhrases.length) { + var phrase = yield Promise.resolve(remainingPhrases.shift()); + if (!active) { + break; + } else if (typeof phrase === "string" && phrase.includes("PAUSE-")) { + var pause = phrase.split("PAUSE-")[1] * 1e3; + if (isNaN(pause)) { + pause = 0; + } + yield delay(pause); + } else if (typeof phrase === "string" && phrase.length) { + var totalRetries = 3; + var retriesLeft = totalRetries; + while (active && retriesLeft > 0) { + try { + yield speak(phrase, utterances, lang); + retriesLeft = 0; + } catch (e) { + if (e instanceof SpeechSynthesisErrorEvent) { + if (e.error === "network") { + retriesLeft--; + console.warn("Speech synthesis network error. Retries left: ".concat(retriesLeft)); + yield delay(500 * (totalRetries - retriesLeft)); + } else if (e.error === "canceled" || e.error === "interrupted") { + retriesLeft = 0; + } else { + throw new Error("SpeechSynthesisErrorEvent: ".concat(e.error)); + } + } else { + throw e; + } + } + } + } else if (typeof phrase === "function") { + var seriesResult = speakSeries(phrase(), lang, false); + nestedSeriesResults.push(seriesResult); + yield seriesResult.series; + } else if (Array.isArray(phrase)) { + var _seriesResult = speakSeries(phrase, lang, false); + nestedSeriesResults.push(_seriesResult); + yield _seriesResult.series; + } + } + } finally { + active = false; + } + }))(); + return { + series: seriesChain, + get active() { + return active; + }, + append: toSpeak => { + remainingPhrases.push(toSpeak); + }, + cancel: () => { + if (!active) { + return; + } + if (root) { + synth.cancel(); + } + nestedSeriesResults.forEach((nestedSeriesResults => { + nestedSeriesResults.cancel(); + })); + active = false; + } + }; +} + +var currentSeries; + +function Speech(toSpeak, lang) { + currentSeries && currentSeries.cancel(); + currentSeries = speakSeries(toSpeak, lang); + return currentSeries; +} + +var defaultAbbreviations = [ { + pattern: "TV-14", + replacer: "Rated TV-14" +}, { + pattern: "CC", + replacer: "Closed Captions available" +}, { + pattern: "HD", + replacer: "High Definition available" +}, { + pattern: /ENG(?!\+)/, + replacer: "English Available" +}, { + pattern: /ENG\+ES/, + replacer: "Available in English and Spanish" +}, { + pattern: "AD", + replacer: "Audio Description available" +}, { + pattern: "RT", + replacer: "Rotten Tomatoes" +}, { + pattern: /(S)+(\d+)+(E)+(\d+)+/, + replacer: (match, p1, p2, p3, p4) => "Season ".concat(p2, " Episode ").concat(p4) +} ]; + +var defaultAbbrevConfig = generateAbbrevConfig(defaultAbbreviations); + +function wrapWithBoundary(str) { + return "\\b".concat(str, "\\b"); +} + +function getNumberOfCaptureGroups(regExp) { + return new RegExp(regExp.toString() + "|").exec("").length - 1; +} + +function generateAbbrevConfig() { + var abbreviations = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : defaultAbbreviations; + var extendDefault = arguments.length > 1 ? arguments[1] : undefined; + var abbrev = extendDefault ? [ ...defaultAbbreviations, ...abbreviations ] : abbreviations; + var stringPatternMap = {}; + var regExpPatternMap = {}; + var abbreviationsPattern = ""; + var patternGroupOffset = 0; + abbrev.forEach(((_ref27, idx) => { + var {pattern: pattern, replacer: replacer} = _ref27; + var stringPattern; + if (pattern instanceof RegExp) { + var patternMapIdx = idx + patternGroupOffset; + regExpPatternMap[patternMapIdx] = { + pattern: pattern, + replacer: replacer + }; + stringPattern = wrapWithBoundary(pattern.source); + patternGroupOffset += getNumberOfCaptureGroups(pattern); + } else { + stringPatternMap[pattern] = { + replacer: replacer + }; + stringPattern = wrapWithBoundary(pattern); + } + abbreviationsPattern = abbreviationsPattern === "" ? "(".concat(stringPattern, ")") : "".concat(abbreviationsPattern, "|(").concat(stringPattern, ")"); + })); + abbreviationsPattern = new RegExp(abbreviationsPattern, "g"); + return { + abbreviationsPattern: abbreviationsPattern, + stringPatternMap: stringPatternMap, + regExpPatternMap: regExpPatternMap + }; +} + +var translateAbbrev = (phrase, translationConfig) => { + var {abbreviationsPattern: abbreviationsPattern, stringPatternMap: stringPatternMap, regExpPatternMap: regExpPatternMap} = translationConfig; + var translated = phrase.replace(abbreviationsPattern, (function(matched) { + if (stringPatternMap[matched]) { + return stringPatternMap[matched].replacer; + } + for (var _len7 = arguments.length, args = new Array(_len7 > 1 ? _len7 - 1 : 0), _key7 = 1; _key7 < _len7; _key7++) { + args[_key7 - 1] = arguments[_key7]; + } + var patternIdx = args.findIndex((arg => !!arg)); + var {pattern: pattern, replacer: replacer} = regExpPatternMap[patternIdx]; + if (typeof replacer === "string") { + return replacer; + } + if (typeof replacer === "function") { + return matched.replace(pattern, replacer); + } + })); + return translated; +}; + +var fiveMinutes = 300 * 1e3; + +function elmName(elm) { + return elm.ref || elm.constructor.name; +} + +var defaultOptions = { + voiceOutDelay: 500, + abbreviationsConfig: {} +}; + +function withAnnouncer(Base) { + var speak = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : Speech; + var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; + var announcerOptions = _objectSpread(_objectSpread({}, defaultOptions), options); + return class extends Base { + _construct() { + this._announceEndedTimeout; + this._currentlySpeaking = ""; + super._construct && super._construct(); + } + _voiceOut(toAnnounce) { + if (this._voiceOutDisabled) { + return; + } + var toSpeak = toAnnounce; + if (announcerOptions.abbreviationsConfig.abbreviationsPattern) { + toSpeak = Array.isArray(toAnnounce) ? toAnnounce.map((phrase => translateAbbrev(phrase, announcerOptions.abbreviationsConfig))) : translateAbbrev(toAnnounce, announcerOptions.abbreviationsConfig); + } + var speech = speak(toSpeak, options.language); + if (speech && speech.series) { + speech.series.then((() => { + this.stage.emit("announceEnded"); + })); + } + var toAnnounceStr = Array.isArray(toSpeak) ? toSpeak.concat().join(" ") : toSpeak; + var toAnnounceWords = toAnnounceStr.split(" "); + var timeoutDelay = toAnnounceWords.length * announcerOptions.voiceOutDelay; + clearTimeout(this._announceEndedTimeout); + this._announceEndedTimeout = setTimeout((() => { + this.stage.emit("announceTimeoutEnded"); + }), timeoutDelay); + return speech; + } + _build() { + super._build && super._build(); + this._debounceAnnounceFocusChanges = debounce(this._announceFocusChanges.bind(this), Number.isInteger(this.announcerFocusDebounce) ? this.announcerFocusDebounce : 400); + this.announcerTimeout = Number.isInteger(this.announcerTimeout) ? this.announcerTimeout : fiveMinutes; + this._resetFocusTimer = debounce((() => { + this._lastFocusPath = undefined; + }), this.announcerTimeout); + } + _firstEnable() { + super._firstEnable && super._firstEnable(); + this._focusChange(); + } + _disable() { + clearTimeout(this._announceEndedTimeout); + this.stage.emit("announceEnded"); + this.stage.emit("announceTimeoutEnded"); + } + set announcerEnabled(val) { + this._announcerEnabled = val; + this._focusChange(); + } + get announcerEnabled() { + return this._announcerEnabled; + } + _focusChange() { + if (!this._resetFocusTimer) { + return; + } + this._resetFocusTimer(); + this.$announcerCancel(); + this._debounceAnnounceFocusChanges(); + } + _announceFocusChanges() { + var focusPath = this.application.focusPath || []; + var lastFocusPath = this._lastFocusPath || []; + var loaded = focusPath.every((elm => !elm.loading)); + var focusDiff = focusPath.filter((elm => !lastFocusPath.includes(elm))); + if (!loaded) { + this._debounceAnnounceFocusChanges(); + return; + } + this._lastFocusPath = focusPath.slice(0); + this.focusDiffHook = focusDiff; + if (!this.announcerEnabled) { + return; + } + var toAnnounce = focusDiff.reduce(((acc, elm) => { + if (elm.announce) { + acc.push([ elmName(elm), "Announce", elm.announce ]); + } else if (elm.title) { + acc.push([ elmName(elm), "Title", elm.title || "" ]); + } + return acc; + }), []); + focusDiff.reverse().reduce(((acc, elm) => { + if (elm.announceContext) { + acc.push([ elmName(elm), "Context", elm.announceContext ]); + } else { + acc.push([ elmName(elm), "No Context", "" ]); + } + return acc; + }), toAnnounce); + if (this.debug) { + console.table(toAnnounce); + } + toAnnounce = toAnnounce.reduce(((acc, a) => { + var txt = a[2]; + txt && acc.push(txt); + return acc; + }), []); + if (toAnnounce.length) { + this.$announcerCancel(); + this._currentlySpeaking = this._voiceOut(toAnnounce.reduce(((acc, val) => acc.concat(val)), [])); + } + } + $announce(toAnnounce) { + var {append: append = false, notification: notification = false} = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + if (!toAnnounce || !toAnnounce.trim().length) { + return; + } + if (this.announcerEnabled) { + this._debounceAnnounceFocusChanges.flush(); + if (append && this._currentlySpeaking && this._currentlySpeaking.active) { + this._currentlySpeaking.append(toAnnounce); + } else { + this.$announcerCancel(); + this._currentlySpeaking = this._voiceOut(toAnnounce); + } + if (notification) { + this._voiceOutDisabled = true; + this._currentlySpeaking.series.finally((() => { + this._voiceOutDisabled = false; + this.$announcerRefresh(); + })); + } + } + } + $announcerCancel() { + this._currentlySpeaking && this._currentlySpeaking.cancel(); + } + $announcerRefresh(depth) { + if (depth) { + this._lastFocusPath = this._lastFocusPath.slice(0, depth); + } else { + this._lastFocusPath = undefined; + } + this._resetFocusTimer(); + this._focusChange(); + } + }; +} + +function index$1(classImp) { + var cache = new Map; + return base => { + if (cache.has(base)) { + return cache.get(base); + } + var classWithNewBase = classImp(base); + cache.set(base, classWithNewBase); + return classWithNewBase; + }; +} + +function withSelections(Base) { + var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + var defaultOpts = { + captureKey: "Enter", + defaultIndex: 0, + eventName: "onSelect", + keys: { + currentSelected: "currentSelected", + currentSelectedIndex: "currentSelectedIndex", + isSelected: "isSelected", + items: "items", + setSelected: "setSelected" + } + }; + var {captureKey: captureKey, defaultIndex: defaultIndex, eventName: eventName, keys: {currentSelected: currentSelected, currentSelectedIndex: currentSelectedIndex, isSelected: isSelected, items: items, setSelected: setSelected}} = _objectSpread(_objectSpread(_objectSpread({}, defaultOpts), options), {}, { + keys: _objectSpread(_objectSpread({}, defaultOpts.keys), options.keys) + }); + return class extends Base { + static get name() { + return Base.name; + } + _construct() { + super._construct(); + this[currentSelectedIndex] = defaultIndex; + } + _init() { + super._init(); + this[currentSelected][isSelected] = true; + } + [setSelected](selected, val) { + var prevSelected = (this[items] || [])[this[currentSelectedIndex]]; + if (selected && (selected !== prevSelected || selected[isSelected] !== val)) { + prevSelected && (prevSelected[isSelected] = false); + selected[isSelected] = val; + this[currentSelectedIndex] = Array.from(this[items] || []).indexOf(selected); + this.fireAncestors("$" + eventName, selected, val); + } + } + _captureKey(event) { + if (Array.isArray(captureKey) && captureKey.indexOf(event.key) > -1 || event.key === captureKey) { + var [selected] = this.stage.application.focusPath.slice(-1); + this[setSelected](selected, true); + } + return false; + } + ["$" + setSelected](selected, val) { + this[setSelected](selected, val); + } + get [currentSelected]() { + return this[items][this[currentSelectedIndex]]; + } + }; +} + +function index(Base) { + return class extends Base { + _init() { + super._init(); + this.isEditing = false; + } + toggleEdit() { + this.isEditing = !this.isEditing; + } + _unfocus() { + this.isEditing = false; + super._unfocus(); + } + _swapItemArrayPos(array, current, previous) { + [array[current], array[previous]] = [ array[previous], array[current] ]; + super.selectedIndex = current; + } + _getPositionValue(item, axis) { + return item.transition(axis) ? item.transition(axis).targetValue : item[axis]; + } + _waitForTransition(item, axis) { + return new Promise((resolve => item._getTransition(axis).on("finish", resolve))); + } + get selectedIndex() { + return super.selectedIndex; + } + set selectedIndex(index) { + var _this10 = this; + if (!this.isEditing || this.selectedIndex >= this.items.length - 1 && index > this.selectedIndex) { + if (!this.isEditing) { + super.selectedIndex = index; + } + return; + } + var currentItem = this.selected; + this.prevSelected = currentItem; + var nextItem = this.items[index]; + var previousIndex = this.selectedIndex; + var oldPos = { + x: this._getPositionValue(currentItem, "x"), + y: this._getPositionValue(currentItem, "y") + }; + var newPos = { + x: this._getPositionValue(nextItem, "x"), + y: this._getPositionValue(nextItem, "y") + }; + var previousCurrentItemZIndex = currentItem.zIndex; + currentItem.zIndex = previousCurrentItemZIndex + 1; + this._swapItemArrayPos(this.items, index, previousIndex); + currentItem.setSmooth("x", newPos.x); + currentItem.setSmooth("y", newPos.y); + nextItem.setSmooth("x", oldPos.x); + nextItem.setSmooth("y", oldPos.y); + _asyncToGenerator((function*() { + var _this10$Items$childre; + yield Promise.all([ _this10._waitForTransition(currentItem, "x"), _this10._waitForTransition(currentItem, "y"), _this10._waitForTransition(nextItem, "x"), _this10._waitForTransition(nextItem, "y") ]); + currentItem.zIndex = previousCurrentItemZIndex; + if (!_this10.Items.children.length || !((_this10$Items$childre = _this10.Items.children[index]) !== null && _this10$Items$childre !== void 0 && _this10$Items$childre.skipFocus)) { + _this10._selectedIndex = index; + _this10._render(_this10.selected, _this10.prevSelected); + _this10.signal("selectedChange", _this10.selected, _this10.prevSelected); + _this10._refocus(); + } + }))(); + } + _selectedChange(selected, prevSelected) { + if (this.isEditing) return; + this._render(selected, prevSelected); + this.signal("selectedChange", selected, prevSelected); + } + }; +} + +var rad = deg => deg * Math.PI / 180; + +var deg = rad => rad * 180 / Math.PI; + +var getBreakpoints = (width, height) => { + var a = height / 2; + var b = width / 2; + var c = Math.sqrt(Math.pow(a, 2) + Math.pow(b, 2)); + var C = 90; + var A = Math.ceil(deg(Math.asin(a * Math.sin(rad(C)) / c))); + var B = 180 - C - A; + return [ B, 90, 90 + A, 180, 180 + B, 270, 270 + A, 360 ]; +}; + +var points = (degrees, width, height) => { + var breakAngles = getBreakpoints(width, height); + var breakIndex = breakAngles.findIndex((angle => angle >= degrees)); + var b = height / 2; + var max = width / 2; + if ([ 1, 2, 5, 6 ].includes(breakIndex)) { + b = width / 2; + max = height / 2; + } + if ([ 2, 4, 6 ].includes(breakIndex)) { + degrees = degrees - breakAngles[breakIndex - 1]; + } else if (breakIndex > 0) { + degrees = breakAngles[breakIndex] - degrees; + } + var A = degrees; + var B = 90 - A; + var a = Math.ceil(Math.sin(rad(A)) * b / Math.sin(rad(B))); + if (a > max) { + a = max; + } + var x0 = 0; + var y0 = 0; + var x1 = 0; + var y1 = 0; + switch (breakIndex) { + case 0: + x0 = width / 2 + a; + break; + + case 1: + x0 = width; + y0 = height / 2 - a; + break; + + case 2: + x0 = width; + y0 = height / 2 + a; + break; + + case 3: + x0 = width / 2 + a; + y0 = height; + break; + + case 4: + x0 = width / 2 - a; + y0 = height; + break; + + case 5: + y0 = height / 2 + a; + break; + + case 6: + y0 = height / 2 - a; + break; + + case 7: + x0 = width / 2 - a; + break; + } + if (x0 == 0) { + x1 = width; + y1 = height - y0; + } + if (y0 == 0) { + y1 = height; + x1 = width - x0; + } + if (x0 == width) { + x1 = 0; + y1 = height - y0; + } + if (y0 == height) { + y1 = 0; + x1 = width - x0; + } + return { + x0: x0, + y0: y0, + x1: x1, + y1: y1 + }; +}; + +class LinearGradient extends _lightningjs_core__WEBPACK_IMPORTED_MODULE_0__.Texture { + constructor(stage) { + super(stage); + this._w = 0; + this._h = 0; + this._steps = []; + this._degrees = 0; + } + get w() { + return this._w; + } + set w(w) { + this._w = w; + this._changed(); + } + get h() { + return this._h; + } + set h(h) { + this._h = h; + this._changed(); + } + get steps() { + return this._steps; + } + set steps(steps) { + this._steps = steps; + this._changed(); + } + get degrees() { + return this._degrees; + } + set degrees(degrees) { + this._degrees = degrees; + this._changed(); + } + _getLookupId() { + return "__linearGradient_".concat(this._h, "_").concat(this._w, "_").concat(this._steps.count, "_").concat(this._degrees); + } + _getSourceLoader() { + var w = this._w; + var h = this._h; + var d = this._degrees; + var p = points(d, w, h); + var {x0: x0, y0: y0, x1: x1, y1: y1} = p; + var steps = this._steps; + var strokeWidth = this.strokeWidth; + var strokeRadius = this.strokeRadius ? Array.isArray(this.strokeRadius) && this.strokeRadius.length === 4 ? this.strokeRadius : Array(4).fill(this.strokeRadius) : Array(4).fill(0); + return function(cb) { + var canvas = this.stage.platform.getDrawingCanvas(); + canvas.width = w + strokeWidth + 2; + canvas.height = h + strokeWidth + 2; + var ctx = canvas.getContext("2d"); + var gradient = ctx.createLinearGradient(x0, y0, x1, y1); + steps.forEach((step => { + gradient.addColorStop(step.percent, step.color); + })); + if (strokeWidth) { + var x = .5 * strokeWidth + 1, y = .5 * strokeWidth + 1; + ctx.beginPath(); + ctx.moveTo(x + strokeRadius[0], y); + ctx.lineTo(x + w - strokeRadius[1], y); + ctx.arcTo(x + w, y, x + w, y + strokeRadius[1], strokeRadius[1]); + ctx.lineTo(x + w, y + h - strokeRadius[2]); + ctx.arcTo(x + w, y + h, x + w - strokeRadius[2], y + h, strokeRadius[2]); + ctx.lineTo(x + strokeRadius[3], y + h); + ctx.arcTo(x, y + h, x, y + h - strokeRadius[3], strokeRadius[3]); + ctx.lineTo(x, y + strokeRadius[0]); + ctx.arcTo(x, y, x + strokeRadius[0], y, strokeRadius[0]); + ctx.closePath(); + ctx.lineWidth = strokeWidth; + ctx.strokeStyle = gradient; + ctx.stroke(); + } else { + ctx.fillStyle = gradient; + ctx.fillRect(0, 0, w, h); + } + cb(null, { + source: canvas, + w: w, + h: h + }); + }; + } +} + +class Circle extends _lightningjs_core__WEBPACK_IMPORTED_MODULE_0__.Texture { + constructor(stage) { + super(stage); + this._color = "rgb(0,0,0)"; + this._fill = true; + this._radius = 100; + this._stroke = false; + this._strokeColor = "rgb(0,0,0)"; + this._strokeWidth = 1; + } + get fill() { + return this._fill; + } + set fill(fill) { + this._fill = fill; + this._changed(); + } + get radius() { + return this._radius; + } + set radius(radius) { + this._radius = radius; + this._changed(); + } + get color() { + return this._color; + } + set color(color) { + this._color = color; + this._changed(); + } + get stroke() { + return this._stroke; + } + set stroke(stroke) { + this._stroke = stroke; + this._changed(); + } + get strokeWidth() { + return this._strokeWidth; + } + set strokeWidth(strokeWidth) { + this._strokeWidth = strokeWidth; + this._changed(); + } + get strokeColor() { + return this._strokeColor; + } + set strokeColor(strokeColor) { + this._strokeColor = strokeColor; + this._changed(); + } + _getLookupId() { + return "__circle_".concat(this._radius); + } + _getSourceLoader() { + var color = this._color; + var fill = this._fill; + var radius = this._radius; + var stroke = this._stroke; + var strokeColor = this._strokeColor; + var strokeWidth = this._strokeWidth; + var canvas = this.stage.platform.getDrawingCanvas(); + var dimension = radius; + if (stroke) { + dimension = radius + strokeWidth * 2; + } + canvas.width = dimension * 2; + canvas.height = dimension * 2; + return function(cb) { + var ctx = canvas.getContext("2d"); + ctx.lineWidth = strokeWidth; + ctx.strokeStyle = strokeColor; + ctx.fillStyle = color; + ctx.beginPath(); + ctx.arc(dimension, dimension, radius, 0, 2 * Math.PI); + if (fill) { + ctx.fill(); + } + if (stroke) { + ctx.stroke(); + } + cb(null, { + source: canvas, + radius: radius + }); + }; + } +} + +class Arrow extends _lightningjs_core__WEBPACK_IMPORTED_MODULE_0__.Texture { + constructor(stage) { + super(stage); + this._color = "rgb(13, 13, 15)"; + this._w = 0; + this._h = 0; + this._direction = "right"; + } + get w() { + return this._w; + } + set w(l) { + this._w = l; + this._changed(); + } + get h() { + return this._h; + } + set h(l) { + this._h = l; + this._changed(); + } + get direction() { + return this._direction; + } + get color() { + return this._color; + } + set color(color) { + this._color = color; + this._changed(); + } + set direction(direction) { + this._direction = direction; + this._changed(); + } + _getLookupId() { + return "__triangle_".concat(this._direction, "_").concat(this._w, "x").concat(this._h); + } + _getSourceLoader() { + var color = this._color; + var w = this._w; + var h = this._h; + var direction = this._direction; + var canvas = this.stage.platform.getDrawingCanvas(); + return function(cb) { + var ctx = canvas.getContext("2d"); + canvas.width = w; + canvas.height = h; + ctx.fillStyle = color; + ctx.strokeStyle = ctx.fillStyle; + ctx.lineWidth = 2; + ctx.lineCap = "round"; + ctx.lineJoin = "round"; + var p = ctx.lineWidth / 2; + ctx.beginPath(); + if (direction === "right") { + ctx.moveTo(p, p); + ctx.lineTo(p, h - p); + ctx.lineTo(w - p, h / 2); + } else if (direction === "down") { + ctx.moveTo(p, p); + ctx.lineTo(w - p, p); + ctx.lineTo(w / 2, h - p); + } else { + ctx.moveTo(p, h / 2); + ctx.lineTo(w - p, p); + ctx.lineTo(w - p, h - p); + } + ctx.closePath(); + ctx.stroke(); + ctx.fill(); + cb(null, { + source: canvas, + w: w, + h: h, + direction: direction + }); + }; + } +} + +class Line extends _lightningjs_core__WEBPACK_IMPORTED_MODULE_0__.Texture { + constructor(stage) { + super(stage); + this._w = 0; + this._h = 0; + this._rounded = false; + } + get w() { + return this._w; + } + set w(l) { + this._w = l; + this._changed(); + } + get h() { + return this._h; + } + set h(l) { + this._h = l; + this._changed(); + } + get rounded() { + return this._rounded; + } + set rounded(rounded) { + this._rounded = rounded; + this._changed(); + } + _getLookupId() { + return "__line_".concat(this._w, "x").concat(this._h).concat(this._rounded ? "_rounded" : ""); + } + _getSourceLoader() { + var w = this._w; + var h = this._h; + var rounded = this._rounded; + var canvas = this.stage.platform.getDrawingCanvas(); + return function(cb) { + var ctx = canvas.getContext("2d"); + canvas.width = w; + canvas.height = h; + ctx.lineWidth = h; + if (rounded) { + ctx.lineCap = "round"; + } + ctx.strokeStyle = "white"; + ctx.beginPath(); + ctx.moveTo(rounded ? 2 : 0, h / 2); + ctx.lineTo(rounded ? w - 2 : w, h / 2); + ctx.stroke(); + cb(null, { + source: canvas, + w: w, + h: h, + rounded: rounded + }); + }; + } +} + +class SignalButton extends Button { + onEnter() { + this.signal(this.signalName); + } + set signalName(signalName) { + this._signalName = signalName; + } + get signalName() { + return this._signalName; + } +} + + +//# sourceMappingURL=lightning-ui-components.min.mjs.map + + +/***/ }), + +/***/ "./node_modules/@metrological/sdk/index.js": +/*!*************************************************!*\ + !*** ./node_modules/@metrological/sdk/index.js ***! + \*************************************************/ +/*! exports provided: Metadata, initMetadata, Metrics, initMetrics, Profile, initProfile, Purchase, initPurchase, TV, initTV, Pin, initPin, VideoPlayer, initVideoPlayer, mediaUrl, initLightningSdkPlugin */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var _src_Metadata__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./src/Metadata */ "./node_modules/@metrological/sdk/src/Metadata/index.js"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Metadata", function() { return _src_Metadata__WEBPACK_IMPORTED_MODULE_0__["default"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "initMetadata", function() { return _src_Metadata__WEBPACK_IMPORTED_MODULE_0__["initMetadata"]; }); + +/* harmony import */ var _src_Metrics__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./src/Metrics */ "./node_modules/@metrological/sdk/src/Metrics/index.js"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Metrics", function() { return _src_Metrics__WEBPACK_IMPORTED_MODULE_1__["default"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "initMetrics", function() { return _src_Metrics__WEBPACK_IMPORTED_MODULE_1__["initMetrics"]; }); + +/* harmony import */ var _src_Profile__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./src/Profile */ "./node_modules/@metrological/sdk/src/Profile/index.js"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Profile", function() { return _src_Profile__WEBPACK_IMPORTED_MODULE_2__["default"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "initProfile", function() { return _src_Profile__WEBPACK_IMPORTED_MODULE_2__["initProfile"]; }); + +/* harmony import */ var _src_Purchase__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./src/Purchase */ "./node_modules/@metrological/sdk/src/Purchase/index.js"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Purchase", function() { return _src_Purchase__WEBPACK_IMPORTED_MODULE_3__["default"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "initPurchase", function() { return _src_Purchase__WEBPACK_IMPORTED_MODULE_3__["initPurchase"]; }); + +/* harmony import */ var _src_TV__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./src/TV */ "./node_modules/@metrological/sdk/src/TV/index.js"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "TV", function() { return _src_TV__WEBPACK_IMPORTED_MODULE_4__["default"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "initTV", function() { return _src_TV__WEBPACK_IMPORTED_MODULE_4__["initTV"]; }); + +/* harmony import */ var _src_Pin__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./src/Pin */ "./node_modules/@metrological/sdk/src/Pin/index.js"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Pin", function() { return _src_Pin__WEBPACK_IMPORTED_MODULE_5__["default"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "initPin", function() { return _src_Pin__WEBPACK_IMPORTED_MODULE_5__["initPin"]; }); + +/* harmony import */ var _src_VideoPlayer__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./src/VideoPlayer */ "./node_modules/@metrological/sdk/src/VideoPlayer/index.js"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "VideoPlayer", function() { return _src_VideoPlayer__WEBPACK_IMPORTED_MODULE_6__["default"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "initVideoPlayer", function() { return _src_VideoPlayer__WEBPACK_IMPORTED_MODULE_6__["initVideoPlayer"]; }); + +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "mediaUrl", function() { return _src_VideoPlayer__WEBPACK_IMPORTED_MODULE_6__["mediaUrl"]; }); + +/* harmony import */ var _src_LightningSdkPlugins__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./src/LightningSdkPlugins */ "./node_modules/@metrological/sdk/src/LightningSdkPlugins/index.js"); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "initLightningSdkPlugin", function() { return _src_LightningSdkPlugins__WEBPACK_IMPORTED_MODULE_7__["initLightningSdkPlugin"]; }); + +/* + * If not stated otherwise in this file or this component's LICENSE file the + * following copyright and licenses apply: + * + * Copyright 2020 Metrological + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + + + + + + + + + +/***/ }), + +/***/ "./node_modules/@metrological/sdk/src/LightningSdkPlugins/index.js": +/*!*************************************************************************!*\ + !*** ./node_modules/@metrological/sdk/src/LightningSdkPlugins/index.js ***! + \*************************************************************************/ +/*! exports provided: Log, Settings, ApplicationInstance, Ads, Lightning, initLightningSdkPlugin */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Log", function() { return Log; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Settings", function() { return Settings; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ApplicationInstance", function() { return ApplicationInstance; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Ads", function() { return Ads; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Lightning", function() { return Lightning; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "initLightningSdkPlugin", function() { return initLightningSdkPlugin; }); +/* + * If not stated otherwise in this file or this component's LICENSE file the + * following copyright and licenses apply: + * + * Copyright 2020 Metrological + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +let Log +let Settings +let ApplicationInstance +let Ads +let Lightning + +const initLightningSdkPlugin = { + set log(v) { + Log = v + }, + set settings(v) { + Settings = v + }, + set ads(v) { + Ads = v + }, + set lightning(v) { + Lightning = v + }, + set appInstance(v) { + ApplicationInstance = v + } +} + + +/***/ }), + +/***/ "./node_modules/@metrological/sdk/src/Metadata/index.js": +/*!**************************************************************!*\ + !*** ./node_modules/@metrological/sdk/src/Metadata/index.js ***! + \**************************************************************/ +/*! exports provided: initMetadata, default */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "initMetadata", function() { return initMetadata; }); +/* + * If not stated otherwise in this file or this component's LICENSE file the + * following copyright and licenses apply: + * + * Copyright 2020 Metrological + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +let metadata = {} + +const initMetadata = metadataObj => { + metadata = metadataObj +} + +/* harmony default export */ __webpack_exports__["default"] = ({ + get(key, fallback = undefined) { + return key in metadata ? metadata[key] : fallback + }, + appId() { + return this.get('id') + }, + safeAppId() { + return this.get('id').replace(/[^0-9a-zA-Z_$]/g, '_') + }, + appName() { + return this.get('name') + }, + appVersion() { + return (this.get('version') || '').split('-').shift() + }, + appIcon() { + return this.get('icon') + }, + // Version from app store (with commit hash) + appFullVersion() { + return this.get('version') + }, +}); + + +/***/ }), + +/***/ "./node_modules/@metrological/sdk/src/Metrics/index.js": +/*!*************************************************************!*\ + !*** ./node_modules/@metrological/sdk/src/Metrics/index.js ***! + \*************************************************************/ +/*! exports provided: initMetrics, default */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "initMetrics", function() { return initMetrics; }); +/* harmony import */ var _LightningSdkPlugins__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../LightningSdkPlugins */ "./node_modules/@metrological/sdk/src/LightningSdkPlugins/index.js"); +/* + * If not stated otherwise in this file or this component's LICENSE file the + * following copyright and licenses apply: + * + * Copyright 2020 Metrological + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + +const initMetrics = config => { + sendMetric = config.sendMetric +} + +let sendMetric = (type, event, params) => { + _LightningSdkPlugins__WEBPACK_IMPORTED_MODULE_0__["Log"].info('Sending metric', type, event, params) +} + +// available metric per category +const metrics = { + app: ['launch', 'loaded', 'ready', 'close'], + page: ['view', 'leave'], + user: ['click', 'input'], + media: [ + 'abort', + 'canplay', + 'ended', + 'pause', + 'play', + // with some videos there occur almost constant suspend events ... should investigate + // 'suspend', + 'volumechange', + 'waiting', + 'seeking', + 'seeked', + ], +} + +// error metric function (added to each category) +const errorMetric = (type, message, code, visible, params = {}) => { + params = { params, ...{ message, code, visible } } + sendMetric(type, 'error', params) +} + +const Metric = (type, events, options = {}) => { + return events.reduce( + (obj, event) => { + obj[event] = (name, params = {}) => { + params = { ...options, ...(name ? { name } : {}), ...params } + sendMetric(type, event, params) + } + return obj + }, + { + error(message, code, params) { + errorMetric(type, message, code, params) + }, + event(name, params) { + sendMetric(type, name, params) + }, + } + ) +} + +const Metrics = types => { + return Object.keys(types).reduce( + (obj, type) => { + // media metric works a bit different! + // it's a function that accepts a url and returns an object with the available metrics + // url is automatically passed as a param in every metric + type === 'media' + ? (obj[type] = url => Metric(type, types[type], { url })) + : (obj[type] = Metric(type, types[type])) + return obj + }, + { error: errorMetric, event: sendMetric } + ) +} + +/* harmony default export */ __webpack_exports__["default"] = (Metrics(metrics)); + + +/***/ }), + +/***/ "./node_modules/@metrological/sdk/src/Pin/dialog.js": +/*!**********************************************************!*\ + !*** ./node_modules/@metrological/sdk/src/Pin/dialog.js ***! + \**********************************************************/ +/*! exports provided: default */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var _LightningSdkPlugins__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../LightningSdkPlugins */ "./node_modules/@metrological/sdk/src/LightningSdkPlugins/index.js"); +/* harmony import */ var _Pin__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Pin */ "./node_modules/@metrological/sdk/src/Pin/index.js"); +/* + * If not stated otherwise in this file or this component's LICENSE file the + * following copyright and licenses apply: + * + * Copyright 2020 Metrological + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + + +const PinInput = () => { + return class PinInput extends _LightningSdkPlugins__WEBPACK_IMPORTED_MODULE_0__["Lightning"].Component { + static _template() { + return { + w: 120, + h: 150, + rect: true, + color: 0xff949393, + alpha: 0.5, + shader: { type: _LightningSdkPlugins__WEBPACK_IMPORTED_MODULE_0__["Lightning"].shaders.RoundedRectangle, radius: 10 }, + Nr: { + w: w => w, + y: 24, + text: { + text: '', + textColor: 0xff333333, + fontSize: 80, + textAlign: 'center', + verticalAlign: 'middle', + }, + }, + } + } + + set index(v) { + this.x = v * (120 + 24) + } + + set nr(v) { + this._timeout && clearTimeout(this._timeout) + + if (v) { + this.setSmooth('alpha', 1) + } else { + this.setSmooth('alpha', 0.5) + } + + this.tag('Nr').patch({ + text: { + text: (v && v.toString()) || '', + fontSize: v === '*' ? 120 : 80, + }, + }) + + if (v && v !== '*') { + this._timeout = setTimeout(() => { + this._timeout = null + this.nr = '*' + }, 750) + } + } + } + +} + +/* harmony default export */ __webpack_exports__["default"] = (() => { + return class PinDialog extends _LightningSdkPlugins__WEBPACK_IMPORTED_MODULE_0__["Lightning"].Component { + static _template() { + return { + zIndex: 1, + w: w => w, + h: h => h, + rect: true, + color: 0xdd000000, + alpha: 0.000001, + Dialog: { + w: 648, + h: 320, + y: h => (h - 320) / 2, + x: w => (w - 648) / 2, + rect: true, + color: 0xdd333333, + shader: { type: _LightningSdkPlugins__WEBPACK_IMPORTED_MODULE_0__["Lightning"].shaders.RoundedRectangle, radius: 10 }, + Info: { + y: 24, + x: 48, + text: { text: 'Please enter your PIN', fontSize: 32 }, + }, + Msg: { + y: 260, + x: 48, + text: { text: '', fontSize: 28, textColor: 0xffffffff }, + }, + Code: { + x: 48, + y: 96, + }, + }, + } + } + + _init() { + const children = [] + for (let i = 0; i < 4; i++) { + children.push({ + type: PinInput(), + index: i, + }) + } + + this.tag('Code').children = children + } + + get pin() { + if (!this._pin) this._pin = '' + return this._pin + } + + set pin(v) { + if (v.length <= 4) { + const maskedPin = new Array(Math.max(v.length - 1, 0)).fill('*', 0, v.length - 1) + v.length && maskedPin.push(v.length > this._pin.length ? v.slice(-1) : '*') + for (let i = 0; i < 4; i++) { + this.tag('Code').children[i].nr = maskedPin[i] || '' + } + this._pin = v + } + } + + get msg() { + if (!this._msg) this._msg = '' + return this._msg + } + + set msg(v) { + this._timeout && clearTimeout(this._timeout) + + this._msg = v + if (this._msg) { + this.tag('Msg').text = this._msg + this.tag('Info').setSmooth('alpha', 0.5) + this.tag('Code').setSmooth('alpha', 0.5) + } else { + this.tag('Msg').text = '' + this.tag('Info').setSmooth('alpha', 1) + this.tag('Code').setSmooth('alpha', 1) + } + this._timeout = setTimeout(() => { + this.msg = '' + }, 2000) + } + + _firstActive() { + this.setSmooth('alpha', 1) + } + + _handleKey(event) { + if (this.msg) { + this.msg = false + } else { + const val = parseInt(event.key) + if (val > -1) { + this.pin += val + } + } + } + + _handleBack() { + if (this.msg) { + this.msg = false + } else { + if (this.pin.length) { + this.pin = this.pin.slice(0, this.pin.length - 1) + } else { + _Pin__WEBPACK_IMPORTED_MODULE_1__["default"].hide() + this.resolve(false) + } + } + } + + _handleEnter() { + if (this.msg) { + this.msg = false + } else { + _Pin__WEBPACK_IMPORTED_MODULE_1__["default"].submit(this.pin) + .then(val => { + this.msg = 'Unlocking ...' + setTimeout(() => { + _Pin__WEBPACK_IMPORTED_MODULE_1__["default"].hide() + }, 1000) + this.resolve(val) + }) + .catch(e => { + this.msg = e + this.reject(e) + }) + } + } + } +}); + + +/***/ }), + +/***/ "./node_modules/@metrological/sdk/src/Pin/index.js": +/*!*********************************************************!*\ + !*** ./node_modules/@metrological/sdk/src/Pin/index.js ***! + \*********************************************************/ +/*! exports provided: initPin, default */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "initPin", function() { return initPin; }); +/* harmony import */ var _LightningSdkPlugins__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../LightningSdkPlugins */ "./node_modules/@metrological/sdk/src/LightningSdkPlugins/index.js"); +/* harmony import */ var _dialog__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./dialog */ "./node_modules/@metrological/sdk/src/Pin/dialog.js"); +/* + * If not stated otherwise in this file or this component's LICENSE file the + * following copyright and licenses apply: + * + * Copyright 2020 Metrological + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + + +// only used during local development +let unlocked = false +const contextItems = ['purchase', 'parental'] + +let submit = (pin, context) => { + return new Promise((resolve, reject) => { + if (pin.toString() === _LightningSdkPlugins__WEBPACK_IMPORTED_MODULE_0__["Settings"].get('platform', 'pin', '0000').toString()) { + unlocked = true + resolve(unlocked) + } else { + reject('Incorrect pin') + } + }) +} + +let check = context => { + return new Promise(resolve => { + resolve(unlocked) + }) +} + +const initPin = config => { + if (config.submit && typeof config.submit === 'function') { + submit = config.submit + } + if (config.check && typeof config.check === 'function') { + check = config.check + } +} + +let pinDialog = null + +const contextCheck = context => { + if (context === undefined) { + _LightningSdkPlugins__WEBPACK_IMPORTED_MODULE_0__["Log"].info('Please provide context explicitly') + return contextItems[0] + } else if (!contextItems.includes(context)) { + _LightningSdkPlugins__WEBPACK_IMPORTED_MODULE_0__["Log"].warn('Incorrect context provided') + return false + } + return context +} + +// Public API +/* harmony default export */ __webpack_exports__["default"] = ({ + show() { + return new Promise((resolve, reject) => { + pinDialog = _LightningSdkPlugins__WEBPACK_IMPORTED_MODULE_0__["ApplicationInstance"].stage.c({ + ref: 'PinDialog', + type: Object(_dialog__WEBPACK_IMPORTED_MODULE_1__["default"])(), + resolve, + reject, + }) + _LightningSdkPlugins__WEBPACK_IMPORTED_MODULE_0__["ApplicationInstance"].childList.a(pinDialog) + _LightningSdkPlugins__WEBPACK_IMPORTED_MODULE_0__["ApplicationInstance"].focus = pinDialog + }) + }, + hide() { + _LightningSdkPlugins__WEBPACK_IMPORTED_MODULE_0__["ApplicationInstance"].focus = null + _LightningSdkPlugins__WEBPACK_IMPORTED_MODULE_0__["ApplicationInstance"].children = _LightningSdkPlugins__WEBPACK_IMPORTED_MODULE_0__["ApplicationInstance"].children.map(child => child !== pinDialog && child) + pinDialog = null + }, + submit(pin, context) { + return new Promise((resolve, reject) => { + try { + context = contextCheck(context) + if (context) { + submit(pin, context) + .then(resolve) + .catch(reject) + } else { + reject('Incorrect Context provided') + } + } catch (e) { + reject(e) + } + }) + }, + unlocked(context) { + return new Promise((resolve, reject) => { + try { + context = contextCheck(context) + if (context) { + check(context) + .then(resolve) + .catch(reject) + } else { + reject('Incorrect Context provided') + } + } catch (e) { + reject(e) + } + }) + }, + locked(context) { + return new Promise((resolve, reject) => { + try { + context = contextCheck(context) + if (context) { + check(context) + .then(unlocked => resolve(!!!unlocked)) + .catch(reject) + } else { + reject('Incorrect Context provided') + } + } catch (e) { + reject(e) + } + }) + }, +}); + + +/***/ }), + +/***/ "./node_modules/@metrological/sdk/src/Profile/defaults.js": +/*!****************************************************************!*\ + !*** ./node_modules/@metrological/sdk/src/Profile/defaults.js ***! + \****************************************************************/ +/*! exports provided: defaultProfile */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "defaultProfile", function() { return defaultProfile; }); +/* harmony import */ var _helpers__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./helpers */ "./node_modules/@metrological/sdk/src/Profile/helpers.js"); +/* + * If not stated otherwise in this file or this component's LICENSE file the + * following copyright and licenses apply: + * + * Copyright 2020 Metrological + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + +const defaultProfile = { + ageRating: 'adult', + city: 'New York', + zipCode: '27505', + countryCode: () => Object(_helpers__WEBPACK_IMPORTED_MODULE_0__["getCountryCode"])('US'), + ip: '127.0.0.1', + household: 'b2244e9d4c04826ccd5a7b2c2a50e7d4', + language: () => Object(_helpers__WEBPACK_IMPORTED_MODULE_0__["getLanguage"])('en'), + latlon: () => Object(_helpers__WEBPACK_IMPORTED_MODULE_0__["getLatLon"])([40.7128, 74.006]), + locale: () => Object(_helpers__WEBPACK_IMPORTED_MODULE_0__["getLocale"])('en-US'), + mac: '00:00:00:00:00:00', + operator: 'metrological', + platform: 'metrological', + packages: [], + uid: 'ee6723b8-7ab3-462c-8d93-dbf61227998e', + stbType: 'metrological', +} + + +/***/ }), + +/***/ "./node_modules/@metrological/sdk/src/Profile/helpers.js": +/*!***************************************************************!*\ + !*** ./node_modules/@metrological/sdk/src/Profile/helpers.js ***! + \***************************************************************/ +/*! exports provided: getLocale, getLanguage, getCountryCode, getLatLon */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getLocale", function() { return getLocale; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getLanguage", function() { return getLanguage; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getCountryCode", function() { return getCountryCode; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getLatLon", function() { return getLatLon; }); +/* harmony import */ var _LightningSdkPlugins__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../LightningSdkPlugins */ "./node_modules/@metrological/sdk/src/LightningSdkPlugins/index.js"); +/* + * If not stated otherwise in this file or this component's LICENSE file the + * following copyright and licenses apply: + * + * Copyright 2020 Metrological + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + +const formatLocale = locale => { + if (locale && locale.length === 2) { + return `${locale.toLowerCase()}-${locale.toUpperCase()}` + } else { + return locale + } +} + +const getLocale = defaultValue => { + if ('language' in navigator) { + const locale = formatLocale(navigator.language) + return Promise.resolve(locale) + } else { + return Promise.resolve(defaultValue) + } +} + +const getLanguage = defaultValue => { + if ('language' in navigator) { + const language = formatLocale(navigator.language).slice(0, 2) + return Promise.resolve(language) + } else { + return Promise.resolve(defaultValue) + } +} + +const getCountryCode = defaultValue => { + if ('language' in navigator) { + const countryCode = formatLocale(navigator.language).slice(3, 5) + return Promise.resolve(countryCode) + } else { + return Promise.resolve(defaultValue) + } +} + +const hasOrAskForGeoLocationPermission = () => { + return new Promise(resolve => { + // force to prompt for location permission + if (_LightningSdkPlugins__WEBPACK_IMPORTED_MODULE_0__["Settings"].get('platform', 'forceBrowserGeolocation') === true) resolve(true) + if ('permissions' in navigator && typeof navigator.permissions.query === 'function') { + navigator.permissions.query({ name: 'geolocation' }).then(status => { + resolve(status.state === 'granted' || status.status === 'granted') + }) + } else { + resolve(false) + } + }) +} + +const getLatLon = defaultValue => { + return new Promise(resolve => { + hasOrAskForGeoLocationPermission().then(granted => { + if (granted === true) { + if ('geolocation' in navigator) { + navigator.geolocation.getCurrentPosition( + // success + result => + result && result.coords && resolve([result.coords.latitude, result.coords.longitude]), + // error + () => resolve(defaultValue), + // options + { + enableHighAccuracy: true, + timeout: 5000, + maximumAge: 0, + } + ) + } else { + return queryForLatLon().then(result => resolve(result || defaultValue)) + } + } else { + return queryForLatLon().then(result => resolve(result || defaultValue)) + } + }) + }) +} + +const queryForLatLon = () => { + return new Promise(resolve => { + fetch('https://geolocation-db.com/json/') + .then(response => response.json()) + .then(({ latitude, longitude }) => + latitude && longitude ? resolve([latitude, longitude]) : resolve(false) + ) + .catch(() => resolve(false)) + }) +} + + +/***/ }), + +/***/ "./node_modules/@metrological/sdk/src/Profile/index.js": +/*!*************************************************************!*\ + !*** ./node_modules/@metrological/sdk/src/Profile/index.js ***! + \*************************************************************/ +/*! exports provided: initProfile, default */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "initProfile", function() { return initProfile; }); +/* harmony import */ var _LightningSdkPlugins__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../LightningSdkPlugins */ "./node_modules/@metrological/sdk/src/LightningSdkPlugins/index.js"); +/* harmony import */ var _defaults__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./defaults */ "./node_modules/@metrological/sdk/src/Profile/defaults.js"); +/* + * If not stated otherwise in this file or this component's LICENSE file the + * following copyright and licenses apply: + * + * Copyright 2020 Metrological + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + + +let getInfo = key => { + const profile = { ..._defaults__WEBPACK_IMPORTED_MODULE_1__["defaultProfile"], ..._LightningSdkPlugins__WEBPACK_IMPORTED_MODULE_0__["Settings"].get('platform', 'profile') } + return Promise.resolve(typeof profile[key] === 'function' ? profile[key]() : profile[key]) +} + +let setInfo = (key, params) => { + if (key in _defaults__WEBPACK_IMPORTED_MODULE_1__["defaultProfile"]) return (_defaults__WEBPACK_IMPORTED_MODULE_1__["defaultProfile"][key] = params) +} + +const initProfile = config => { + getInfo = config.getInfo ? config.getInfo : getInfo + setInfo = config.setInfo ? config.setInfo : setInfo +} + +const getOrSet = (key, params) => (params ? setInfo(key, params) : getInfo(key)) + +// public API +/* harmony default export */ __webpack_exports__["default"] = ({ + ageRating(params) { + return getOrSet('ageRating', params) + }, + city(params) { + return getOrSet('city', params) + }, + zipCode(params) { + return getOrSet('zipCode', params) + }, + countryCode(params) { + return getOrSet('countryCode', params) + }, + ip(params) { + return getOrSet('ip', params) + }, + household(params) { + return getOrSet('household', params) + }, + language(params) { + return getOrSet('language', params) + }, + latlon(params) { + return getOrSet('latlon', params) + }, + locale(params) { + return getOrSet('locale', params) + }, + mac(params) { + return getOrSet('mac', params) + }, + operator(params) { + return getOrSet('operator', params) + }, + platform(params) { + return getOrSet('platform', params) + }, + packages(params) { + return getOrSet('packages', params) + }, + uid(params) { + return getOrSet('uid', params) + }, + stbType(params) { + return getOrSet('stbType', params) + }, +}); + + +/***/ }), + +/***/ "./node_modules/@metrological/sdk/src/Purchase/index.js": +/*!**************************************************************!*\ + !*** ./node_modules/@metrological/sdk/src/Purchase/index.js ***! + \**************************************************************/ +/*! exports provided: initPurchase, default */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "initPurchase", function() { return initPurchase; }); +/* harmony import */ var _Profile__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Profile */ "./node_modules/@metrological/sdk/src/Profile/index.js"); +/* harmony import */ var _LightningSdkPlugins__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../LightningSdkPlugins */ "./node_modules/@metrological/sdk/src/LightningSdkPlugins/index.js"); +/* harmony import */ var _helpers_sequence__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../helpers/sequence */ "./node_modules/@metrological/sdk/src/helpers/sequence.js"); +/* + * If not stated otherwise in this file or this component's LICENSE file the + * following copyright and licenses apply: + * + * Copyright 2020 Metrological + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + + + +let cspUrl = 'http://payment-csp-example.metrological.com:8080/' +let billingUrl = 'https://payment-sdk.metrological.com/' + +let cspEndpoints = { + assets: { + uri: '/assets', + method: 'GET', + }, + asset: { + uri: '/assets/:id', + method: 'GET', + }, + signature: { + uri: '/assets/:id/signature', + method: 'POST', + }, + subscribe: { + uri: '/assets/:id/subscribe', + method: 'POST', + }, + unsubscribe: { + uri: '/assets/:id/unsubscribe', + method: 'POST', + }, +} + +const initPurchase = config => { + if (config.billingUrl) billingUrl = config.billingUrl +} + +const createUrl = (uri, baseUrl, params = {}) => { + return new URL( + // sprinkle in the params + Object.keys(params) + .reduce((res, key) => res.replace(new RegExp(':' + key, 'g'), params[key]), uri) + // remove any leading slash from uri + .replace(/^\//, ''), + // make sure baseUrl always has a trailing slash + /\/$/.test(baseUrl) ? baseUrl : baseUrl.replace(/$/, '/') + ) +} + +const request = (url, method = 'GET', data, headers = {}) => { + if (method === 'GET' && data) { + url.search = new URLSearchParams(data) + } + + return new Promise((resolve, reject) => { + fetch(url, { + headers: { + ...{ + Accept: 'application/json', + 'Content-Type': 'application/json', + }, + ...headers, + }, + method: method, + body: method !== 'GET' && data ? JSON.stringify(data) : null, + }) + .then(response => (response.ok ? resolve(response.json()) : reject(response.statusText))) + .catch(reject) + }) +} + +const cspRequest = (type, data = null, params = {}) => { + return new Promise((resolve, reject) => { + const endpoint = cspEndpoints[type] + + if (!endpoint) { + reject('No endpoint found for "' + type + '" call') + } else { + if (endpoint.callback && typeof endpoint.callback === 'function') { + endpoint + .callback(data, params) + .then(resolve) + .catch(reject) + } else { + request( + createUrl(endpoint.uri, cspUrl, params), + endpoint.method, + { + ...(endpoint.data || {}), + ...data, + }, + endpoint.headers || {} + ) + .then(resolve) + .catch(reject) + } + } + }) +} + +const billingRequest = (uri, data, method = 'POST') => { + return new Promise((resolve, reject) => { + request(createUrl(uri, billingUrl), method, data) + .then(resolve) + .catch(reject) + }) +} + +/* harmony default export */ __webpack_exports__["default"] = ({ + setup(config) { + if (config.cspUrl) cspUrl = config.cspUrl + if (config.endpoints) cspEndpoints = { cspEndpoints, ...config.endpoints } + }, + assets() { + return new Promise((resolve, reject) => { + _Profile__WEBPACK_IMPORTED_MODULE_0__["default"].household().then(household => { + cspRequest('assets', { household }) + .then(resolve) + .catch(reject) + }) + }) + }, + asset(id) { + return new Promise((resolve, reject) => { + _Profile__WEBPACK_IMPORTED_MODULE_0__["default"].household().then(household => { + cspRequest('asset', { household }, { id }) + .then(resolve) + .catch(reject) + }) + }) + }, + signature(id) { + return new Promise((resolve, reject) => { + Promise.all([_Profile__WEBPACK_IMPORTED_MODULE_0__["default"].household()]).then(([household]) => { + cspRequest('signature', { household }, { id }) + .then(resolve) + .catch(reject) + }) + }) + }, + subscribe(id, transaction) { + return new Promise((resolve, reject) => { + cspRequest('subscribe', { ...transaction }, { id }) + .then(resolve) + .catch(reject) + }) + }, + unsubscribe(id) { + return new Promise((resolve, reject) => { + _Profile__WEBPACK_IMPORTED_MODULE_0__["default"].household().then(household => { + cspRequest('unsubscribe', { household }, { id }) + .then(resolve) + .catch(reject) + }) + }) + }, + payment(signature = {}, type = 'in-app') { + return new Promise((resolve, reject) => { + Promise.all([ + _Profile__WEBPACK_IMPORTED_MODULE_0__["default"].household(), + _Profile__WEBPACK_IMPORTED_MODULE_0__["default"].countryCode(), + _Profile__WEBPACK_IMPORTED_MODULE_0__["default"].operator(), + _Profile__WEBPACK_IMPORTED_MODULE_0__["default"].mac(), + _Profile__WEBPACK_IMPORTED_MODULE_0__["default"].uid(), + ]) + .then(([household, country, operator, mac, uid]) => { + billingRequest('/', { + purchase: signature, + identifier: _LightningSdkPlugins__WEBPACK_IMPORTED_MODULE_1__["Settings"].get('app', 'id'), + name: _LightningSdkPlugins__WEBPACK_IMPORTED_MODULE_1__["Settings"].get('app', 'id'), + household, + country, + operator, + mac, + uid, + type, + }) + .then(resolve) + .catch(reject) + }) + .catch(reject) + }) + }, + confirm(transactionId) { + return new Promise((resolve, reject) => { + billingRequest('/confirm', { + transactionId, + }) + .then(resolve) + .catch(reject) + }) + }, + buy(assetId, type) { + return new Promise((resolve, reject) => { + let transactionId + Object(_helpers_sequence__WEBPACK_IMPORTED_MODULE_2__["default"])([ + () => this.signature(assetId), + signature => this.payment(signature, type), + transaction => { + transactionId = transaction.transactionId + return this.subscribe(assetId, transaction) + }, + () => this.confirm(transactionId), + ]) + .then(resolve) + .catch(reject) + }) + }, +}); + + +/***/ }), + +/***/ "./node_modules/@metrological/sdk/src/TV/defaults.js": +/*!***********************************************************!*\ + !*** ./node_modules/@metrological/sdk/src/TV/defaults.js ***! + \***********************************************************/ +/*! exports provided: channels, randomChannel */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "channels", function() { return channels; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "randomChannel", function() { return randomChannel; }); +/* harmony import */ var _LightningSdkPlugins__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../LightningSdkPlugins */ "./node_modules/@metrological/sdk/src/LightningSdkPlugins/index.js"); +/* + * If not stated otherwise in this file or this component's LICENSE file the + * following copyright and licenses apply: + * + * Copyright 2020 Metrological + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + +const defaultChannels = [ + { + number: 1, + name: 'Metro News 1', + description: 'New York Cable News Channel', + entitled: true, + program: { + title: 'The Morning Show', + description: "New York's best morning show", + startTime: new Date(new Date() - 60 * 5 * 1000).toUTCString(), // started 5 minutes ago + duration: 60 * 30, // 30 minutes + ageRating: 0, + }, + }, + { + number: 2, + name: 'MTV', + description: 'Music Television', + entitled: true, + program: { + title: 'Beavis and Butthead', + description: 'American adult animated sitcom created by Mike Judge', + startTime: new Date(new Date() - 60 * 20 * 1000).toUTCString(), // started 20 minutes ago + duration: 60 * 45, // 45 minutes + ageRating: 18, + }, + }, + { + number: 3, + name: 'NBC', + description: 'NBC TV Network', + entitled: false, + program: { + title: 'The Tonight Show Starring Jimmy Fallon', + description: 'Late-night talk show hosted by Jimmy Fallon on NBC', + startTime: new Date(new Date() - 60 * 10 * 1000).toUTCString(), // started 10 minutes ago + duration: 60 * 60, // 1 hour + ageRating: 10, + }, + }, +] + +const channels = () => _LightningSdkPlugins__WEBPACK_IMPORTED_MODULE_0__["Settings"].get('platform', 'tv', defaultChannels) + +const randomChannel = () => channels()[~~(channels.length * Math.random())] + + +/***/ }), + +/***/ "./node_modules/@metrological/sdk/src/TV/index.js": +/*!********************************************************!*\ + !*** ./node_modules/@metrological/sdk/src/TV/index.js ***! + \********************************************************/ +/*! exports provided: initTV, default */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "initTV", function() { return initTV; }); +/* harmony import */ var _LightningSdkPlugins__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../LightningSdkPlugins */ "./node_modules/@metrological/sdk/src/LightningSdkPlugins/index.js"); +/* harmony import */ var _defaults__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./defaults */ "./node_modules/@metrological/sdk/src/TV/defaults.js"); +/* + * If not stated otherwise in this file or this component's LICENSE file the + * following copyright and licenses apply: + * + * Copyright 2020 Metrological + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + + + +let currentChannel +const callbacks = {} + +const emit = (event, ...args) => { + callbacks[event] && + callbacks[event].forEach(cb => { + cb.apply(null, args) + }) +} + +// local mock methods +let methods = { + getChannel() { + if (!currentChannel) currentChannel = Object(_defaults__WEBPACK_IMPORTED_MODULE_1__["randomChannel"])() + return new Promise((resolve, reject) => { + if (currentChannel) { + const channel = { ...currentChannel } + delete channel.program + resolve(channel) + } else { + reject('No channel found') + } + }) + }, + getProgram() { + if (!currentChannel) currentChannel = Object(_defaults__WEBPACK_IMPORTED_MODULE_1__["randomChannel"])() + return new Promise((resolve, reject) => { + currentChannel.program ? resolve(currentChannel.program) : reject('No program found') + }) + }, + setChannel(number) { + return new Promise((resolve, reject) => { + if (number) { + const newChannel = Object(_defaults__WEBPACK_IMPORTED_MODULE_1__["channels"])().find(c => c.number === number) + if (newChannel) { + currentChannel = newChannel + const channel = { ...currentChannel } + delete channel.program + emit('channelChange', channel) + resolve(channel) + } else { + reject('Channel not found') + } + } else { + reject('No channel number supplied') + } + }) + }, +} + +const initTV = config => { + methods = {} + if (config.getChannel && typeof config.getChannel === 'function') { + methods.getChannel = config.getChannel + } + if (config.getProgram && typeof config.getProgram === 'function') { + methods.getProgram = config.getProgram + } + if (config.setChannel && typeof config.setChannel === 'function') { + methods.setChannel = config.setChannel + } + if (config.emit && typeof config.emit === 'function') { + config.emit(emit) + } +} + +// public API +/* harmony default export */ __webpack_exports__["default"] = ({ + channel(number = null) { + return new Promise((resolve, reject) => { + try { + // call setChannel when number argument is passed, otherwise getChannel + methods[number ? 'setChannel' : 'getChannel'](number) + .then(channel => { + // to do: ensure consistent formatting of channel info here? + resolve(channel) + }) + .catch(reject) + } catch (e) { + reject(e) + } + }) + }, + program() { + return new Promise((resolve, reject) => { + try { + methods + .getProgram() + .then(program => { + // to do: ensure consistent formatting of program info here? + resolve(program) + }) + .catch(reject) + } catch (e) { + reject(e) + } + }) + }, + entitled() { + return new Promise((resolve, reject) => { + try { + methods + .getChannel() + .then(channel => { + 'entitled' in channel ? resolve(!!channel.entitled) : reject() + }) + .catch(reject) + } catch (e) { + reject(e) + } + }) + }, + addEventListener(event, cb) { + if (typeof cb === 'function') { + callbacks[event] = callbacks[event] || [] + callbacks[event].push(cb) + } else { + _LightningSdkPlugins__WEBPACK_IMPORTED_MODULE_0__["Log"].error('Please provide a function as a callback') + } + }, + removeEventListener(event, cb = false) { + if (callbacks[event] && callbacks[event].length) { + callbacks[event] = cb ? callbacks[event].filter(_cb => _cb === cb) : [] + } + }, +}); + + +/***/ }), + +/***/ "./node_modules/@metrological/sdk/src/VideoPlayer/VideoTexture.js": +/*!************************************************************************!*\ + !*** ./node_modules/@metrological/sdk/src/VideoPlayer/VideoTexture.js ***! + \************************************************************************/ +/*! exports provided: default */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var _LightningSdkPlugins__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../LightningSdkPlugins */ "./node_modules/@metrological/sdk/src/LightningSdkPlugins/index.js"); +/* + * If not stated otherwise in this file or this component's LICENSE file the + * following copyright and licenses apply: + * + * Copyright 2020 Metrological + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + +/* harmony default export */ __webpack_exports__["default"] = (() => { + return class VideoTexture extends _LightningSdkPlugins__WEBPACK_IMPORTED_MODULE_0__["Lightning"].Component { + static _template() { + return { + Video: { + alpha: 1, + visible: false, + pivot: 0.5, + texture: { type: _LightningSdkPlugins__WEBPACK_IMPORTED_MODULE_0__["Lightning"].textures.StaticTexture, options: {} }, + }, + } + } + + set videoEl(v) { + this._videoEl = v + } + + get videoEl() { + return this._videoEl + } + + get videoView() { + return this.tag('Video') + } + + get videoTexture() { + return this.videoView.texture + } + + get isVisible() { + return this.videoView.alpha === 1 && this.videoView.visible === true + } + + _init() { + this._createVideoTexture() + } + + _createVideoTexture() { + const stage = this.stage + + const gl = stage.gl + const glTexture = gl.createTexture() + gl.bindTexture(gl.TEXTURE_2D, glTexture) + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR) + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR) + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE) + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE) + this.videoTexture.options = { + source: glTexture, + w: this.videoEl.width, + h: this.videoEl.height, + } + + this.videoView.w = this.videoEl.width / this.stage.getRenderPrecision() + this.videoView.h = this.videoEl.height / this.stage.getRenderPrecision() + } + + start() { + const stage = this.stage + this._lastTime = 0 + if (!this._updateVideoTexture) { + this._updateVideoTexture = () => { + if (this.videoTexture.options.source && this.videoEl.videoWidth && this.active) { + const gl = stage.gl + + const currentTime = new Date().getTime() + const getVideoPlaybackQuality = this.videoEl.getVideoPlaybackQuality() + + // When BR2_PACKAGE_GST1_PLUGINS_BAD_PLUGIN_DEBUGUTILS is not set in WPE, webkitDecodedFrameCount will not be available. + // We'll fallback to fixed 30fps in this case. + // As 'webkitDecodedFrameCount' is about to deprecate, check for the 'totalVideoFrames' + const frameCount = getVideoPlaybackQuality + ? getVideoPlaybackQuality.totalVideoFrames + : this.videoEl.webkitDecodedFrameCount + + const mustUpdate = frameCount + ? this._lastFrame !== frameCount + : this._lastTime < currentTime - 30 + + if (mustUpdate) { + this._lastTime = currentTime + this._lastFrame = frameCount + try { + gl.bindTexture(gl.TEXTURE_2D, this.videoTexture.options.source) + gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false) + gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, this.videoEl) + this._lastFrame = this.videoEl.webkitDecodedFrameCount + this.videoView.visible = true + + this.videoTexture.options.w = this.videoEl.width + this.videoTexture.options.h = this.videoEl.height + const expectedAspectRatio = this.videoView.w / this.videoView.h + const realAspectRatio = this.videoEl.width / this.videoEl.height + + if (expectedAspectRatio > realAspectRatio) { + this.videoView.scaleX = realAspectRatio / expectedAspectRatio + this.videoView.scaleY = 1 + } else { + this.videoView.scaleY = expectedAspectRatio / realAspectRatio + this.videoView.scaleX = 1 + } + } catch (e) { + _LightningSdkPlugins__WEBPACK_IMPORTED_MODULE_0__["Log"].error('texImage2d video', e) + this.stop() + } + this.videoTexture.source.forceRenderUpdate() + } + } + } + } + if (!this._updatingVideoTexture) { + stage.on('frameStart', this._updateVideoTexture) + this._updatingVideoTexture = true + } + } + + stop() { + const stage = this.stage + stage.removeListener('frameStart', this._updateVideoTexture) + this._updatingVideoTexture = false + this.videoView.visible = false + + if (this.videoTexture.options.source) { + const gl = stage.gl + gl.bindTexture(gl.TEXTURE_2D, this.videoTexture.options.source) + gl.clearColor(0, 0, 0, 1) + gl.clear(gl.COLOR_BUFFER_BIT) + } + } + + position(top, left) { + this.videoView.patch({ + x: left, + y: top, + }) + } + + size(width, height) { + this.videoView.patch({ + w: width, + h: height, + }) + } + + show() { + this.videoView.alpha = 1 + } + + hide() { + this.videoView.alpha = 0 + } + } +}); + + +/***/ }), + +/***/ "./node_modules/@metrological/sdk/src/VideoPlayer/events.js": +/*!******************************************************************!*\ + !*** ./node_modules/@metrological/sdk/src/VideoPlayer/events.js ***! + \******************************************************************/ +/*! exports provided: default */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* + * If not stated otherwise in this file or this component's LICENSE file the + * following copyright and licenses apply: + * + * Copyright 2020 Metrological + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* harmony default export */ __webpack_exports__["default"] = ({ + abort: 'Abort', + canplay: 'CanPlay', + canplaythrough: 'CanPlayThrough', + durationchange: 'DurationChange', + emptied: 'Emptied', + encrypted: 'Encrypted', + ended: 'Ended', + error: 'Error', + interruptbegin: 'InterruptBegin', + interruptend: 'InterruptEnd', + loadeddata: 'LoadedData', + loadedmetadata: 'LoadedMetadata', + loadstart: 'LoadStart', + pause: 'Pause', + play: 'Play', + playing: 'Playing', + progress: 'Progress', + ratechange: 'Ratechange', + seeked: 'Seeked', + seeking: 'Seeking', + stalled: 'Stalled', + // suspend: 'Suspend', // this one is called a looooot for some videos + timeupdate: 'TimeUpdate', + volumechange: 'VolumeChange', + waiting: 'Waiting', +}); + + +/***/ }), + +/***/ "./node_modules/@metrological/sdk/src/VideoPlayer/index.js": +/*!*****************************************************************!*\ + !*** ./node_modules/@metrological/sdk/src/VideoPlayer/index.js ***! + \*****************************************************************/ +/*! exports provided: mediaUrl, initVideoPlayer, setupVideoTag, setUpVideoTexture, default */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "mediaUrl", function() { return mediaUrl; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "initVideoPlayer", function() { return initVideoPlayer; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "setupVideoTag", function() { return setupVideoTag; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "setUpVideoTexture", function() { return setUpVideoTexture; }); +/* harmony import */ var _michieljs_execute_as_promise__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @michieljs/execute-as-promise */ "./node_modules/@michieljs/execute-as-promise/src/execute-as-promise.js"); +/* harmony import */ var _Metrics__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Metrics */ "./node_modules/@metrological/sdk/src/Metrics/index.js"); +/* harmony import */ var _LightningSdkPlugins__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../LightningSdkPlugins */ "./node_modules/@metrological/sdk/src/LightningSdkPlugins/index.js"); +/* harmony import */ var _events__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./events */ "./node_modules/@metrological/sdk/src/VideoPlayer/events.js"); +/* harmony import */ var _helpers_autoSetupMixin__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../helpers/autoSetupMixin */ "./node_modules/@metrological/sdk/src/helpers/autoSetupMixin.js"); +/* harmony import */ var _helpers_easeExecution__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../helpers/easeExecution */ "./node_modules/@metrological/sdk/src/helpers/easeExecution.js"); +/* harmony import */ var _VideoTexture__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./VideoTexture */ "./node_modules/@metrological/sdk/src/VideoPlayer/VideoTexture.js"); +/* + * If not stated otherwise in this file or this component's LICENSE file the + * following copyright and licenses apply: + * + * Copyright 2020 Metrological + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + + + + + + + + + + +let mediaUrl = url => url +let videoEl +let videoTexture +let metrics +let consumer +let precision = 1 +let textureMode = false + +const initVideoPlayer = config => { + if (config.mediaUrl) { + mediaUrl = config.mediaUrl + } +} +// todo: add this in a 'Registry' plugin +// to be able to always clean this up on app close +let eventHandlers = {} + +const state = { + adsEnabled: false, + playing: false, + _playingAds: false, + get playingAds() { + return this._playingAds + }, + set playingAds(val) { + if (this._playingAds !== val) { + this._playingAds = val + fireOnConsumer(val === true ? 'AdStart' : 'AdEnd') + } + }, + skipTime: false, + playAfterSeek: null, +} + +const hooks = { + play() { + state.playing = true + }, + pause() { + state.playing = false + }, + seeked() { + state.playAfterSeek === true && videoPlayerPlugin.play() + state.playAfterSeek = null + }, + abort() { + deregisterEventListeners() + }, +} + +const withPrecision = val => Math.round(precision * val) + 'px' + +const fireOnConsumer = (event, args) => { + if (consumer) { + consumer.fire('$videoPlayer' + event, args, videoEl.currentTime) + consumer.fire('$videoPlayerEvent', event, args, videoEl.currentTime) + } +} + +const fireHook = (event, args) => { + hooks[event] && typeof hooks[event] === 'function' && hooks[event].call(null, event, args) +} + +let customLoader = null +let customUnloader = null + +const loader = (url, videoEl, config) => { + return customLoader && typeof customLoader === 'function' + ? customLoader(url, videoEl, config) + : new Promise(resolve => { + url = mediaUrl(url) + videoEl.setAttribute('src', url) + videoEl.load() + resolve() + }) +} + +const unloader = videoEl => { + return customUnloader && typeof customUnloader === 'function' + ? customUnloader(videoEl) + : new Promise(resolve => { + videoEl.removeAttribute('src') + videoEl.load() + resolve() + }) +} + +const setupVideoTag = () => { + const videoEls = document.getElementsByTagName('video') + if (videoEls && videoEls.length) { + return videoEls[0] + } else { + const videoEl = document.createElement('video') + const platformSettingsWidth = _LightningSdkPlugins__WEBPACK_IMPORTED_MODULE_2__["Settings"].get('platform', 'width') + ? _LightningSdkPlugins__WEBPACK_IMPORTED_MODULE_2__["Settings"].get('platform', 'width') + : 1920 + const platformSettingsHeight = _LightningSdkPlugins__WEBPACK_IMPORTED_MODULE_2__["Settings"].get('platform', 'height') + ? _LightningSdkPlugins__WEBPACK_IMPORTED_MODULE_2__["Settings"].get('platform', 'height') + : 1080 + videoEl.setAttribute('id', 'video-player') + videoEl.setAttribute('width', withPrecision(platformSettingsWidth)) + videoEl.setAttribute('height', withPrecision(platformSettingsHeight)) + videoEl.style.position = 'absolute' + videoEl.style.zIndex = '1' + videoEl.style.display = 'none' + videoEl.style.visibility = 'hidden' + videoEl.style.top = withPrecision(0) + videoEl.style.left = withPrecision(0) + videoEl.style.width = withPrecision(platformSettingsWidth) + videoEl.style.height = withPrecision(platformSettingsHeight) + document.body.appendChild(videoEl) + return videoEl + } +} + +const setUpVideoTexture = () => { + if (!_LightningSdkPlugins__WEBPACK_IMPORTED_MODULE_2__["ApplicationInstance"].tag('VideoTexture')) { + const el = _LightningSdkPlugins__WEBPACK_IMPORTED_MODULE_2__["ApplicationInstance"].stage.c({ + type: Object(_VideoTexture__WEBPACK_IMPORTED_MODULE_6__["default"])(), + ref: 'VideoTexture', + zIndex: 0, + videoEl, + }) + _LightningSdkPlugins__WEBPACK_IMPORTED_MODULE_2__["ApplicationInstance"].childList.addAt(el, 0) + } + return _LightningSdkPlugins__WEBPACK_IMPORTED_MODULE_2__["ApplicationInstance"].tag('VideoTexture') +} + +const registerEventListeners = () => { + _LightningSdkPlugins__WEBPACK_IMPORTED_MODULE_2__["Log"].info('VideoPlayer', 'Registering event listeners') + Object.keys(_events__WEBPACK_IMPORTED_MODULE_3__["default"]).forEach(event => { + const handler = e => { + // Fire a metric for each event (if it exists on the metrics object) + if (metrics && metrics[event] && typeof metrics[event] === 'function') { + metrics[event]({ currentTime: videoEl.currentTime }) + } + // fire an internal hook + fireHook(event, { videoElement: videoEl, event: e }) + + // fire the event (with human friendly event name) to the consumer of the VideoPlayer + fireOnConsumer(_events__WEBPACK_IMPORTED_MODULE_3__["default"][event], { videoElement: videoEl, event: e }) + } + + eventHandlers[event] = handler + videoEl.addEventListener(event, handler) + }) +} + +const deregisterEventListeners = () => { + _LightningSdkPlugins__WEBPACK_IMPORTED_MODULE_2__["Log"].info('VideoPlayer', 'Deregistering event listeners') + Object.keys(eventHandlers).forEach(event => { + videoEl.removeEventListener(event, eventHandlers[event]) + }) + eventHandlers = {} +} + +const videoPlayerPlugin = { + consumer(component) { + consumer = component + }, + + loader(loaderFn) { + customLoader = loaderFn + }, + + unloader(unloaderFn) { + customUnloader = unloaderFn + }, + + position(top = 0, left = 0) { + videoEl.style.left = withPrecision(left) + videoEl.style.top = withPrecision(top) + if (textureMode === true) { + videoTexture.position(top, left) + } + }, + + size(width = 1920, height = 1080) { + videoEl.style.width = withPrecision(width) + videoEl.style.height = withPrecision(height) + videoEl.width = parseFloat(videoEl.style.width) + videoEl.height = parseFloat(videoEl.style.height) + if (textureMode === true) { + videoTexture.size(width, height) + } + }, + + area(top = 0, right = 1920, bottom = 1080, left = 0) { + this.position(top, left) + this.size(right - left, bottom - top) + }, + + open(url, config = {}) { + if (!this.canInteract) return + metrics = _Metrics__WEBPACK_IMPORTED_MODULE_1__["default"].media(url) + + this.hide() + deregisterEventListeners() + + if (this.src == url) { + this.clear().then(this.open(url, config)) + } else { + const adConfig = { enabled: state.adsEnabled, duration: 300 } + if (config.videoId) { + adConfig.caid = config.videoId + } + _LightningSdkPlugins__WEBPACK_IMPORTED_MODULE_2__["Ads"].get(adConfig, consumer).then(ads => { + state.playingAds = true + ads.prerolls().then(() => { + state.playingAds = false + loader(url, videoEl, config) + .then(() => { + registerEventListeners() + this.show() + this.play() + }) + .catch(e => { + fireOnConsumer('Error', { videoElement: videoEl, event: e }) + + // This is not API-compliant, as it results in firing "$videoPlayererror" rather than "$videoPlayerError". + // See docs here for API-compliant events -> https://github.com/Metrological/metrological-sdk/blob/master/docs/plugins/videoplayer.md#event-overview + // It has been kept for backwards compatability for library consumers who may have already written handler functions to match it. + fireOnConsumer('error', { videoElement: videoEl, event: e }) + }) + }) + }) + } + }, + + reload() { + if (!this.canInteract) return + const url = videoEl.getAttribute('src') + this.close() + this.open(url) + }, + + close() { + _LightningSdkPlugins__WEBPACK_IMPORTED_MODULE_2__["Ads"].cancel() + if (state.playingAds) { + state.playingAds = false + _LightningSdkPlugins__WEBPACK_IMPORTED_MODULE_2__["Ads"].stop() + // call self in next tick + setTimeout(() => { + this.close() + }) + } + if (!this.canInteract) return + this.clear() + this.hide() + deregisterEventListeners() + }, + + clear() { + if (!this.canInteract) return + // pause the video first to disable sound + this.pause() + if (textureMode === true) videoTexture.stop() + return unloader(videoEl).then(() => { + fireOnConsumer('Clear', { videoElement: videoEl }) + }) + }, + + play() { + if (!this.canInteract) return + if (textureMode === true) videoTexture.start() + Object(_michieljs_execute_as_promise__WEBPACK_IMPORTED_MODULE_0__["default"])(videoEl.play, null, videoEl).catch(e => { + fireOnConsumer('Error', { videoElement: videoEl, event: e }) + + // This is not API-compliant, as it results in firing "$videoPlayererror" rather than "$videoPlayerError". + // See docs here for API-compliant events -> https://github.com/Metrological/metrological-sdk/blob/master/docs/plugins/videoplayer.md#event-overview + // It has been kept for backwards compatability for library consumers who may have already written handler functions to match it. + fireOnConsumer('error', { videoElement: videoEl, event: e }) + }) + }, + + pause() { + if (!this.canInteract) return + videoEl.pause() + }, + + playPause() { + if (!this.canInteract) return + this.playing === true ? this.pause() : this.play() + }, + + mute(muted = true) { + if (!this.canInteract) return + videoEl.muted = muted + }, + + loop(looped = true) { + videoEl.loop = looped + }, + + seek(time) { + if (!this.canInteract) return + if (!this.src) return + // define whether should continue to play after seek is complete (in seeked hook) + if (state.playAfterSeek === null) { + state.playAfterSeek = !!state.playing + } + // pause before actually seeking + this.pause() + // currentTime always between 0 and the duration of the video (minus 0.1s to not set to the final frame and stall the video) + videoEl.currentTime = Math.max(0, Math.min(time, this.duration - 0.1)) + }, + + skip(seconds) { + if (!this.canInteract) return + if (!this.src) return + + state.skipTime = (state.skipTime || videoEl.currentTime) + seconds + Object(_helpers_easeExecution__WEBPACK_IMPORTED_MODULE_5__["default"])(() => { + this.seek(state.skipTime) + state.skipTime = false + }, 300) + }, + + show() { + if (!this.canInteract) return + if (textureMode === true) { + videoTexture.show() + } else { + videoEl.style.display = 'block' + videoEl.style.visibility = 'visible' + } + }, + + hide() { + if (!this.canInteract) return + if (textureMode === true) { + videoTexture.hide() + } else { + videoEl.style.display = 'none' + videoEl.style.visibility = 'hidden' + } + }, + + enableAds(enabled = true) { + state.adsEnabled = enabled + }, + + /* Public getters */ + get duration() { + return videoEl && (isNaN(videoEl.duration) ? Infinity : videoEl.duration) + }, + + get currentTime() { + return videoEl && videoEl.currentTime + }, + + get muted() { + return videoEl && videoEl.muted + }, + + get looped() { + return videoEl && videoEl.loop + }, + + get src() { + return videoEl && videoEl.getAttribute('src') + }, + + get playing() { + return state.playing + }, + + get playingAds() { + return state.playingAds + }, + + get canInteract() { + // todo: perhaps add an extra flag wether we allow interactions (i.e. pauze, mute, etc.) during ad playback + return state.playingAds === false + }, + + get top() { + return videoEl && parseFloat(videoEl.style.top) + }, + + get left() { + return videoEl && parseFloat(videoEl.style.left) + }, + + get bottom() { + return videoEl && parseFloat(videoEl.style.top - videoEl.style.height) + }, + + get right() { + return videoEl && parseFloat(videoEl.style.left - videoEl.style.width) + }, + + get width() { + return videoEl && parseFloat(videoEl.style.width) + }, + + get height() { + return videoEl && parseFloat(videoEl.style.height) + }, + + get visible() { + if (textureMode === true) { + return videoTexture.isVisible + } else { + return videoEl && videoEl.style.display === 'block' + } + }, + + get adsEnabled() { + return state.adsEnabled + }, + + // prefixed with underscore to indicate 'semi-private' + // because it's not recommended to interact directly with the video element + get _videoEl() { + return videoEl + }, + + get _consumer() { + return consumer + }, +} + +/* harmony default export */ __webpack_exports__["default"] = (Object(_helpers_autoSetupMixin__WEBPACK_IMPORTED_MODULE_4__["default"])(videoPlayerPlugin, () => { + precision = + (_LightningSdkPlugins__WEBPACK_IMPORTED_MODULE_2__["ApplicationInstance"] && _LightningSdkPlugins__WEBPACK_IMPORTED_MODULE_2__["ApplicationInstance"].stage && _LightningSdkPlugins__WEBPACK_IMPORTED_MODULE_2__["ApplicationInstance"].stage.getRenderPrecision()) || precision + + videoEl = setupVideoTag() + + textureMode = _LightningSdkPlugins__WEBPACK_IMPORTED_MODULE_2__["Settings"].get('platform', 'textureMode', false) + if (textureMode === true) { + videoEl.setAttribute('crossorigin', 'anonymous') + videoTexture = setUpVideoTexture() + } +})); + + +/***/ }), + +/***/ "./node_modules/@metrological/sdk/src/helpers/autoSetupMixin.js": +/*!**********************************************************************!*\ + !*** ./node_modules/@metrological/sdk/src/helpers/autoSetupMixin.js ***! + \**********************************************************************/ +/*! exports provided: default */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* + * If not stated otherwise in this file or this component's LICENSE file the + * following copyright and licenses apply: + * + * Copyright 2020 Metrological + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* harmony default export */ __webpack_exports__["default"] = ((sourceObject, setup = () => {}) => { + let ready = false + + const doSetup = () => { + if (ready === false) { + setup() + ready = true + } + } + + return Object.keys(sourceObject).reduce((obj, key) => { + if (typeof sourceObject[key] === 'function') { + obj[key] = function() { + doSetup() + return sourceObject[key].apply(sourceObject, arguments) + } + } else if (typeof Object.getOwnPropertyDescriptor(sourceObject, key).get === 'function') { + obj.__defineGetter__(key, function() { + doSetup() + return Object.getOwnPropertyDescriptor(sourceObject, key).get.apply(sourceObject) + }) + } else if (typeof Object.getOwnPropertyDescriptor(sourceObject, key).set === 'function') { + obj.__defineSetter__(key, function() { + doSetup() + return Object.getOwnPropertyDescriptor(sourceObject, key).set.sourceObject[key].apply( + sourceObject, + arguments + ) + }) + } else { + obj[key] = sourceObject[key] + } + return obj + }, {}) +}); + + +/***/ }), + +/***/ "./node_modules/@metrological/sdk/src/helpers/easeExecution.js": +/*!*********************************************************************!*\ + !*** ./node_modules/@metrological/sdk/src/helpers/easeExecution.js ***! + \*********************************************************************/ +/*! exports provided: default */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* + * If not stated otherwise in this file or this component's LICENSE file the + * following copyright and licenses apply: + * + * Copyright 2020 Metrological + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +let timeout = null + +/* harmony default export */ __webpack_exports__["default"] = ((cb, delay) => { + clearTimeout(timeout) + timeout = setTimeout(() => { + cb() + }, delay) +}); + + +/***/ }), + +/***/ "./node_modules/@metrological/sdk/src/helpers/sequence.js": +/*!****************************************************************!*\ + !*** ./node_modules/@metrological/sdk/src/helpers/sequence.js ***! + \****************************************************************/ +/*! exports provided: default */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* + * If not stated otherwise in this file or this component's LICENSE file the + * following copyright and licenses apply: + * + * Copyright 2020 Metrological + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* harmony default export */ __webpack_exports__["default"] = (steps => { + return steps.reduce((promise, method) => { + return promise + .then(function() { + return method(...arguments) + }) + .catch(e => Promise.reject(e)) + }, Promise.resolve(null)) +}); + + +/***/ }), + +/***/ "./node_modules/@michieljs/execute-as-promise/src/execute-as-promise.js": +/*!******************************************************************************!*\ + !*** ./node_modules/@michieljs/execute-as-promise/src/execute-as-promise.js ***! + \******************************************************************************/ +/*! exports provided: default */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony default export */ __webpack_exports__["default"] = ((method, args = null, context = null) => { + let result + if (method && typeof method === 'function') { + try { + result = method.apply(context, args) + } catch (e) { + result = e + } + } else { + result = method + } + + // if it looks like a duck .. ehm ... promise and talks like a promise, let's assume it's a promise + if ( + result !== null && + typeof result === 'object' && + result.then && + typeof result.then === 'function' + ) { + return result + } + // otherwise make it into a promise + else { + return new Promise((resolve, reject) => { + if (result instanceof Error) { + reject(result) + } else { + resolve(result) + } + }) + } +}); + + +/***/ }), + +/***/ "./node_modules/assert/assert.js": +/*!***************************************!*\ + !*** ./node_modules/assert/assert.js ***! + \***************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/* WEBPACK VAR INJECTION */(function(global) { + +var objectAssign = __webpack_require__(/*! object.assign/polyfill */ "./node_modules/object.assign/polyfill.js")(); + +// compare and isBuffer taken from https://github.com/feross/buffer/blob/680e9e5e488f22aac27599a57dc844a6315928dd/index.js +// original notice: + +/*! + * The buffer module from node.js, for the browser. + * + * @author Feross Aboukhadijeh + * @license MIT + */ +function compare(a, b) { + if (a === b) { + return 0; + } + + var x = a.length; + var y = b.length; + + for (var i = 0, len = Math.min(x, y); i < len; ++i) { + if (a[i] !== b[i]) { + x = a[i]; + y = b[i]; + break; + } + } + + if (x < y) { + return -1; + } + if (y < x) { + return 1; + } + return 0; +} +function isBuffer(b) { + if (global.Buffer && typeof global.Buffer.isBuffer === 'function') { + return global.Buffer.isBuffer(b); + } + return !!(b != null && b._isBuffer); +} + +// based on node assert, original notice: +// NB: The URL to the CommonJS spec is kept just for tradition. +// node-assert has evolved a lot since then, both in API and behavior. + +// http://wiki.commonjs.org/wiki/Unit_Testing/1.0 +// +// THIS IS NOT TESTED NOR LIKELY TO WORK OUTSIDE V8! +// +// Originally from narwhal.js (http://narwhaljs.org) +// Copyright (c) 2009 Thomas Robinson <280north.com> +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the 'Software'), to +// deal in the Software without restriction, including without limitation the +// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or +// sell copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN +// ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +var util = __webpack_require__(/*! util/ */ "./node_modules/util/util.js"); +var hasOwn = Object.prototype.hasOwnProperty; +var pSlice = Array.prototype.slice; +var functionsHaveNames = (function () { + return function foo() {}.name === 'foo'; +}()); +function pToString (obj) { + return Object.prototype.toString.call(obj); +} +function isView(arrbuf) { + if (isBuffer(arrbuf)) { + return false; + } + if (typeof global.ArrayBuffer !== 'function') { + return false; + } + if (typeof ArrayBuffer.isView === 'function') { + return ArrayBuffer.isView(arrbuf); + } + if (!arrbuf) { + return false; + } + if (arrbuf instanceof DataView) { + return true; + } + if (arrbuf.buffer && arrbuf.buffer instanceof ArrayBuffer) { + return true; + } + return false; +} +// 1. The assert module provides functions that throw +// AssertionError's when particular conditions are not met. The +// assert module must conform to the following interface. + +var assert = module.exports = ok; + +// 2. The AssertionError is defined in assert. +// new assert.AssertionError({ message: message, +// actual: actual, +// expected: expected }) + +var regex = /\s*function\s+([^\(\s]*)\s*/; +// based on https://github.com/ljharb/function.prototype.name/blob/adeeeec8bfcc6068b187d7d9fb3d5bb1d3a30899/implementation.js +function getName(func) { + if (!util.isFunction(func)) { + return; + } + if (functionsHaveNames) { + return func.name; + } + var str = func.toString(); + var match = str.match(regex); + return match && match[1]; +} +assert.AssertionError = function AssertionError(options) { + this.name = 'AssertionError'; + this.actual = options.actual; + this.expected = options.expected; + this.operator = options.operator; + if (options.message) { + this.message = options.message; + this.generatedMessage = false; + } else { + this.message = getMessage(this); + this.generatedMessage = true; + } + var stackStartFunction = options.stackStartFunction || fail; + if (Error.captureStackTrace) { + Error.captureStackTrace(this, stackStartFunction); + } else { + // non v8 browsers so we can have a stacktrace + var err = new Error(); + if (err.stack) { + var out = err.stack; + + // try to strip useless frames + var fn_name = getName(stackStartFunction); + var idx = out.indexOf('\n' + fn_name); + if (idx >= 0) { + // once we have located the function frame + // we need to strip out everything before it (and its line) + var next_line = out.indexOf('\n', idx + 1); + out = out.substring(next_line + 1); + } + + this.stack = out; + } + } +}; + +// assert.AssertionError instanceof Error +util.inherits(assert.AssertionError, Error); + +function truncate(s, n) { + if (typeof s === 'string') { + return s.length < n ? s : s.slice(0, n); + } else { + return s; + } +} +function inspect(something) { + if (functionsHaveNames || !util.isFunction(something)) { + return util.inspect(something); + } + var rawname = getName(something); + var name = rawname ? ': ' + rawname : ''; + return '[Function' + name + ']'; +} +function getMessage(self) { + return truncate(inspect(self.actual), 128) + ' ' + + self.operator + ' ' + + truncate(inspect(self.expected), 128); +} + +// At present only the three keys mentioned above are used and +// understood by the spec. Implementations or sub modules can pass +// other keys to the AssertionError's constructor - they will be +// ignored. + +// 3. All of the following functions must throw an AssertionError +// when a corresponding condition is not met, with a message that +// may be undefined if not provided. All assertion methods provide +// both the actual and expected values to the assertion error for +// display purposes. + +function fail(actual, expected, message, operator, stackStartFunction) { + throw new assert.AssertionError({ + message: message, + actual: actual, + expected: expected, + operator: operator, + stackStartFunction: stackStartFunction + }); +} + +// EXTENSION! allows for well behaved errors defined elsewhere. +assert.fail = fail; + +// 4. Pure assertion tests whether a value is truthy, as determined +// by !!guard. +// assert.ok(guard, message_opt); +// This statement is equivalent to assert.equal(true, !!guard, +// message_opt);. To test strictly for the value true, use +// assert.strictEqual(true, guard, message_opt);. + +function ok(value, message) { + if (!value) fail(value, true, message, '==', assert.ok); +} +assert.ok = ok; + +// 5. The equality assertion tests shallow, coercive equality with +// ==. +// assert.equal(actual, expected, message_opt); + +assert.equal = function equal(actual, expected, message) { + if (actual != expected) fail(actual, expected, message, '==', assert.equal); +}; + +// 6. The non-equality assertion tests for whether two objects are not equal +// with != assert.notEqual(actual, expected, message_opt); + +assert.notEqual = function notEqual(actual, expected, message) { + if (actual == expected) { + fail(actual, expected, message, '!=', assert.notEqual); + } +}; + +// 7. The equivalence assertion tests a deep equality relation. +// assert.deepEqual(actual, expected, message_opt); + +assert.deepEqual = function deepEqual(actual, expected, message) { + if (!_deepEqual(actual, expected, false)) { + fail(actual, expected, message, 'deepEqual', assert.deepEqual); + } +}; + +assert.deepStrictEqual = function deepStrictEqual(actual, expected, message) { + if (!_deepEqual(actual, expected, true)) { + fail(actual, expected, message, 'deepStrictEqual', assert.deepStrictEqual); + } +}; + +function _deepEqual(actual, expected, strict, memos) { + // 7.1. All identical values are equivalent, as determined by ===. + if (actual === expected) { + return true; + } else if (isBuffer(actual) && isBuffer(expected)) { + return compare(actual, expected) === 0; + + // 7.2. If the expected value is a Date object, the actual value is + // equivalent if it is also a Date object that refers to the same time. + } else if (util.isDate(actual) && util.isDate(expected)) { + return actual.getTime() === expected.getTime(); + + // 7.3 If the expected value is a RegExp object, the actual value is + // equivalent if it is also a RegExp object with the same source and + // properties (`global`, `multiline`, `lastIndex`, `ignoreCase`). + } else if (util.isRegExp(actual) && util.isRegExp(expected)) { + return actual.source === expected.source && + actual.global === expected.global && + actual.multiline === expected.multiline && + actual.lastIndex === expected.lastIndex && + actual.ignoreCase === expected.ignoreCase; + + // 7.4. Other pairs that do not both pass typeof value == 'object', + // equivalence is determined by ==. + } else if ((actual === null || typeof actual !== 'object') && + (expected === null || typeof expected !== 'object')) { + return strict ? actual === expected : actual == expected; + + // If both values are instances of typed arrays, wrap their underlying + // ArrayBuffers in a Buffer each to increase performance + // This optimization requires the arrays to have the same type as checked by + // Object.prototype.toString (aka pToString). Never perform binary + // comparisons for Float*Arrays, though, since e.g. +0 === -0 but their + // bit patterns are not identical. + } else if (isView(actual) && isView(expected) && + pToString(actual) === pToString(expected) && + !(actual instanceof Float32Array || + actual instanceof Float64Array)) { + return compare(new Uint8Array(actual.buffer), + new Uint8Array(expected.buffer)) === 0; + + // 7.5 For all other Object pairs, including Array objects, equivalence is + // determined by having the same number of owned properties (as verified + // with Object.prototype.hasOwnProperty.call), the same set of keys + // (although not necessarily the same order), equivalent values for every + // corresponding key, and an identical 'prototype' property. Note: this + // accounts for both named and indexed properties on Arrays. + } else if (isBuffer(actual) !== isBuffer(expected)) { + return false; + } else { + memos = memos || {actual: [], expected: []}; + + var actualIndex = memos.actual.indexOf(actual); + if (actualIndex !== -1) { + if (actualIndex === memos.expected.indexOf(expected)) { + return true; + } + } + + memos.actual.push(actual); + memos.expected.push(expected); + + return objEquiv(actual, expected, strict, memos); + } +} + +function isArguments(object) { + return Object.prototype.toString.call(object) == '[object Arguments]'; +} + +function objEquiv(a, b, strict, actualVisitedObjects) { + if (a === null || a === undefined || b === null || b === undefined) + return false; + // if one is a primitive, the other must be same + if (util.isPrimitive(a) || util.isPrimitive(b)) + return a === b; + if (strict && Object.getPrototypeOf(a) !== Object.getPrototypeOf(b)) + return false; + var aIsArgs = isArguments(a); + var bIsArgs = isArguments(b); + if ((aIsArgs && !bIsArgs) || (!aIsArgs && bIsArgs)) + return false; + if (aIsArgs) { + a = pSlice.call(a); + b = pSlice.call(b); + return _deepEqual(a, b, strict); + } + var ka = objectKeys(a); + var kb = objectKeys(b); + var key, i; + // having the same number of owned properties (keys incorporates + // hasOwnProperty) + if (ka.length !== kb.length) + return false; + //the same set of keys (although not necessarily the same order), + ka.sort(); + kb.sort(); + //~~~cheap key test + for (i = ka.length - 1; i >= 0; i--) { + if (ka[i] !== kb[i]) + return false; + } + //equivalent values for every corresponding key, and + //~~~possibly expensive deep test + for (i = ka.length - 1; i >= 0; i--) { + key = ka[i]; + if (!_deepEqual(a[key], b[key], strict, actualVisitedObjects)) + return false; + } + return true; +} + +// 8. The non-equivalence assertion tests for any deep inequality. +// assert.notDeepEqual(actual, expected, message_opt); + +assert.notDeepEqual = function notDeepEqual(actual, expected, message) { + if (_deepEqual(actual, expected, false)) { + fail(actual, expected, message, 'notDeepEqual', assert.notDeepEqual); + } +}; + +assert.notDeepStrictEqual = notDeepStrictEqual; +function notDeepStrictEqual(actual, expected, message) { + if (_deepEqual(actual, expected, true)) { + fail(actual, expected, message, 'notDeepStrictEqual', notDeepStrictEqual); + } +} + + +// 9. The strict equality assertion tests strict equality, as determined by ===. +// assert.strictEqual(actual, expected, message_opt); + +assert.strictEqual = function strictEqual(actual, expected, message) { + if (actual !== expected) { + fail(actual, expected, message, '===', assert.strictEqual); + } +}; + +// 10. The strict non-equality assertion tests for strict inequality, as +// determined by !==. assert.notStrictEqual(actual, expected, message_opt); + +assert.notStrictEqual = function notStrictEqual(actual, expected, message) { + if (actual === expected) { + fail(actual, expected, message, '!==', assert.notStrictEqual); + } +}; + +function expectedException(actual, expected) { + if (!actual || !expected) { + return false; + } + + if (Object.prototype.toString.call(expected) == '[object RegExp]') { + return expected.test(actual); + } + + try { + if (actual instanceof expected) { + return true; + } + } catch (e) { + // Ignore. The instanceof check doesn't work for arrow functions. + } + + if (Error.isPrototypeOf(expected)) { + return false; + } + + return expected.call({}, actual) === true; +} + +function _tryBlock(block) { + var error; + try { + block(); + } catch (e) { + error = e; + } + return error; +} + +function _throws(shouldThrow, block, expected, message) { + var actual; + + if (typeof block !== 'function') { + throw new TypeError('"block" argument must be a function'); + } + + if (typeof expected === 'string') { + message = expected; + expected = null; + } + + actual = _tryBlock(block); + + message = (expected && expected.name ? ' (' + expected.name + ').' : '.') + + (message ? ' ' + message : '.'); + + if (shouldThrow && !actual) { + fail(actual, expected, 'Missing expected exception' + message); + } + + var userProvidedMessage = typeof message === 'string'; + var isUnwantedException = !shouldThrow && util.isError(actual); + var isUnexpectedException = !shouldThrow && actual && !expected; + + if ((isUnwantedException && + userProvidedMessage && + expectedException(actual, expected)) || + isUnexpectedException) { + fail(actual, expected, 'Got unwanted exception' + message); + } + + if ((shouldThrow && actual && expected && + !expectedException(actual, expected)) || (!shouldThrow && actual)) { + throw actual; + } +} + +// 11. Expected to throw an error: +// assert.throws(block, Error_opt, message_opt); + +assert.throws = function(block, /*optional*/error, /*optional*/message) { + _throws(true, block, error, message); +}; + +// EXTENSION! This is annoying to write outside this module. +assert.doesNotThrow = function(block, /*optional*/error, /*optional*/message) { + _throws(false, block, error, message); +}; + +assert.ifError = function(err) { if (err) throw err; }; + +// Expose a strict only variant of assert +function strict(value, message) { + if (!value) fail(value, true, message, '==', strict); +} +assert.strict = objectAssign(strict, assert, { + equal: assert.strictEqual, + deepEqual: assert.deepStrictEqual, + notEqual: assert.notStrictEqual, + notDeepEqual: assert.notDeepStrictEqual +}); +assert.strict.strict = assert.strict; + +var objectKeys = Object.keys || function (obj) { + var keys = []; + for (var key in obj) { + if (hasOwn.call(obj, key)) keys.push(key); + } + return keys; +}; + +/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../webpack/buildin/global.js */ "./node_modules/webpack/buildin/global.js"))) + +/***/ }), + +/***/ "./node_modules/base64-js/index.js": +/*!*****************************************!*\ + !*** ./node_modules/base64-js/index.js ***! + \*****************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +exports.byteLength = byteLength +exports.toByteArray = toByteArray +exports.fromByteArray = fromByteArray + +var lookup = [] +var revLookup = [] +var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array + +var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/' +for (var i = 0, len = code.length; i < len; ++i) { + lookup[i] = code[i] + revLookup[code.charCodeAt(i)] = i +} + +// Support decoding URL-safe base64 strings, as Node.js does. +// See: https://en.wikipedia.org/wiki/Base64#URL_applications +revLookup['-'.charCodeAt(0)] = 62 +revLookup['_'.charCodeAt(0)] = 63 + +function getLens (b64) { + var len = b64.length + + if (len % 4 > 0) { + throw new Error('Invalid string. Length must be a multiple of 4') + } + + // Trim off extra bytes after placeholder bytes are found + // See: https://github.com/beatgammit/base64-js/issues/42 + var validLen = b64.indexOf('=') + if (validLen === -1) validLen = len + + var placeHoldersLen = validLen === len + ? 0 + : 4 - (validLen % 4) + + return [validLen, placeHoldersLen] +} + +// base64 is 4/3 + up to two characters of the original data +function byteLength (b64) { + var lens = getLens(b64) + var validLen = lens[0] + var placeHoldersLen = lens[1] + return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen +} + +function _byteLength (b64, validLen, placeHoldersLen) { + return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen +} + +function toByteArray (b64) { + var tmp + var lens = getLens(b64) + var validLen = lens[0] + var placeHoldersLen = lens[1] + + var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen)) + + var curByte = 0 + + // if there are placeholders, only get up to the last complete 4 chars + var len = placeHoldersLen > 0 + ? validLen - 4 + : validLen + + var i + for (i = 0; i < len; i += 4) { + tmp = + (revLookup[b64.charCodeAt(i)] << 18) | + (revLookup[b64.charCodeAt(i + 1)] << 12) | + (revLookup[b64.charCodeAt(i + 2)] << 6) | + revLookup[b64.charCodeAt(i + 3)] + arr[curByte++] = (tmp >> 16) & 0xFF + arr[curByte++] = (tmp >> 8) & 0xFF + arr[curByte++] = tmp & 0xFF + } + + if (placeHoldersLen === 2) { + tmp = + (revLookup[b64.charCodeAt(i)] << 2) | + (revLookup[b64.charCodeAt(i + 1)] >> 4) + arr[curByte++] = tmp & 0xFF + } + + if (placeHoldersLen === 1) { + tmp = + (revLookup[b64.charCodeAt(i)] << 10) | + (revLookup[b64.charCodeAt(i + 1)] << 4) | + (revLookup[b64.charCodeAt(i + 2)] >> 2) + arr[curByte++] = (tmp >> 8) & 0xFF + arr[curByte++] = tmp & 0xFF + } + + return arr +} + +function tripletToBase64 (num) { + return lookup[num >> 18 & 0x3F] + + lookup[num >> 12 & 0x3F] + + lookup[num >> 6 & 0x3F] + + lookup[num & 0x3F] +} + +function encodeChunk (uint8, start, end) { + var tmp + var output = [] + for (var i = start; i < end; i += 3) { + tmp = + ((uint8[i] << 16) & 0xFF0000) + + ((uint8[i + 1] << 8) & 0xFF00) + + (uint8[i + 2] & 0xFF) + output.push(tripletToBase64(tmp)) + } + return output.join('') +} + +function fromByteArray (uint8) { + var tmp + var len = uint8.length + var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes + var parts = [] + var maxChunkLength = 16383 // must be multiple of 3 + + // go through the array every three bytes, we'll deal with trailing stuff later + for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) { + parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength))) + } + + // pad the end with zeros, but make sure to not forget the extra bytes + if (extraBytes === 1) { + tmp = uint8[len - 1] + parts.push( + lookup[tmp >> 2] + + lookup[(tmp << 4) & 0x3F] + + '==' + ) + } else if (extraBytes === 2) { + tmp = (uint8[len - 2] << 8) + uint8[len - 1] + parts.push( + lookup[tmp >> 10] + + lookup[(tmp >> 4) & 0x3F] + + lookup[(tmp << 2) & 0x3F] + + '=' + ) + } + + return parts.join('') +} + + +/***/ }), + +/***/ "./node_modules/browserify-zlib/lib/binding.js": +/*!*****************************************************!*\ + !*** ./node_modules/browserify-zlib/lib/binding.js ***! + \*****************************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/* WEBPACK VAR INJECTION */(function(Buffer, process) { +/* eslint camelcase: "off" */ + +var assert = __webpack_require__(/*! assert */ "./node_modules/assert/assert.js"); + +var Zstream = __webpack_require__(/*! pako/lib/zlib/zstream */ "./node_modules/pako/lib/zlib/zstream.js"); +var zlib_deflate = __webpack_require__(/*! pako/lib/zlib/deflate.js */ "./node_modules/pako/lib/zlib/deflate.js"); +var zlib_inflate = __webpack_require__(/*! pako/lib/zlib/inflate.js */ "./node_modules/pako/lib/zlib/inflate.js"); +var constants = __webpack_require__(/*! pako/lib/zlib/constants */ "./node_modules/pako/lib/zlib/constants.js"); + +for (var key in constants) { + exports[key] = constants[key]; +} + +// zlib modes +exports.NONE = 0; +exports.DEFLATE = 1; +exports.INFLATE = 2; +exports.GZIP = 3; +exports.GUNZIP = 4; +exports.DEFLATERAW = 5; +exports.INFLATERAW = 6; +exports.UNZIP = 7; + +var GZIP_HEADER_ID1 = 0x1f; +var GZIP_HEADER_ID2 = 0x8b; + +/** + * Emulate Node's zlib C++ layer for use by the JS layer in index.js + */ +function Zlib(mode) { + if (typeof mode !== 'number' || mode < exports.DEFLATE || mode > exports.UNZIP) { + throw new TypeError('Bad argument'); + } + + this.dictionary = null; + this.err = 0; + this.flush = 0; + this.init_done = false; + this.level = 0; + this.memLevel = 0; + this.mode = mode; + this.strategy = 0; + this.windowBits = 0; + this.write_in_progress = false; + this.pending_close = false; + this.gzip_id_bytes_read = 0; +} + +Zlib.prototype.close = function () { + if (this.write_in_progress) { + this.pending_close = true; + return; + } + + this.pending_close = false; + + assert(this.init_done, 'close before init'); + assert(this.mode <= exports.UNZIP); + + if (this.mode === exports.DEFLATE || this.mode === exports.GZIP || this.mode === exports.DEFLATERAW) { + zlib_deflate.deflateEnd(this.strm); + } else if (this.mode === exports.INFLATE || this.mode === exports.GUNZIP || this.mode === exports.INFLATERAW || this.mode === exports.UNZIP) { + zlib_inflate.inflateEnd(this.strm); + } + + this.mode = exports.NONE; + + this.dictionary = null; +}; + +Zlib.prototype.write = function (flush, input, in_off, in_len, out, out_off, out_len) { + return this._write(true, flush, input, in_off, in_len, out, out_off, out_len); +}; + +Zlib.prototype.writeSync = function (flush, input, in_off, in_len, out, out_off, out_len) { + return this._write(false, flush, input, in_off, in_len, out, out_off, out_len); +}; + +Zlib.prototype._write = function (async, flush, input, in_off, in_len, out, out_off, out_len) { + assert.equal(arguments.length, 8); + + assert(this.init_done, 'write before init'); + assert(this.mode !== exports.NONE, 'already finalized'); + assert.equal(false, this.write_in_progress, 'write already in progress'); + assert.equal(false, this.pending_close, 'close is pending'); + + this.write_in_progress = true; + + assert.equal(false, flush === undefined, 'must provide flush value'); + + this.write_in_progress = true; + + if (flush !== exports.Z_NO_FLUSH && flush !== exports.Z_PARTIAL_FLUSH && flush !== exports.Z_SYNC_FLUSH && flush !== exports.Z_FULL_FLUSH && flush !== exports.Z_FINISH && flush !== exports.Z_BLOCK) { + throw new Error('Invalid flush value'); + } + + if (input == null) { + input = Buffer.alloc(0); + in_len = 0; + in_off = 0; + } + + this.strm.avail_in = in_len; + this.strm.input = input; + this.strm.next_in = in_off; + this.strm.avail_out = out_len; + this.strm.output = out; + this.strm.next_out = out_off; + this.flush = flush; + + if (!async) { + // sync version + this._process(); + + if (this._checkError()) { + return this._afterSync(); + } + return; + } + + // async version + var self = this; + process.nextTick(function () { + self._process(); + self._after(); + }); + + return this; +}; + +Zlib.prototype._afterSync = function () { + var avail_out = this.strm.avail_out; + var avail_in = this.strm.avail_in; + + this.write_in_progress = false; + + return [avail_in, avail_out]; +}; + +Zlib.prototype._process = function () { + var next_expected_header_byte = null; + + // If the avail_out is left at 0, then it means that it ran out + // of room. If there was avail_out left over, then it means + // that all of the input was consumed. + switch (this.mode) { + case exports.DEFLATE: + case exports.GZIP: + case exports.DEFLATERAW: + this.err = zlib_deflate.deflate(this.strm, this.flush); + break; + case exports.UNZIP: + if (this.strm.avail_in > 0) { + next_expected_header_byte = this.strm.next_in; + } + + switch (this.gzip_id_bytes_read) { + case 0: + if (next_expected_header_byte === null) { + break; + } + + if (this.strm.input[next_expected_header_byte] === GZIP_HEADER_ID1) { + this.gzip_id_bytes_read = 1; + next_expected_header_byte++; + + if (this.strm.avail_in === 1) { + // The only available byte was already read. + break; + } + } else { + this.mode = exports.INFLATE; + break; + } + + // fallthrough + case 1: + if (next_expected_header_byte === null) { + break; + } + + if (this.strm.input[next_expected_header_byte] === GZIP_HEADER_ID2) { + this.gzip_id_bytes_read = 2; + this.mode = exports.GUNZIP; + } else { + // There is no actual difference between INFLATE and INFLATERAW + // (after initialization). + this.mode = exports.INFLATE; + } + + break; + default: + throw new Error('invalid number of gzip magic number bytes read'); + } + + // fallthrough + case exports.INFLATE: + case exports.GUNZIP: + case exports.INFLATERAW: + this.err = zlib_inflate.inflate(this.strm, this.flush + + // If data was encoded with dictionary + );if (this.err === exports.Z_NEED_DICT && this.dictionary) { + // Load it + this.err = zlib_inflate.inflateSetDictionary(this.strm, this.dictionary); + if (this.err === exports.Z_OK) { + // And try to decode again + this.err = zlib_inflate.inflate(this.strm, this.flush); + } else if (this.err === exports.Z_DATA_ERROR) { + // Both inflateSetDictionary() and inflate() return Z_DATA_ERROR. + // Make it possible for After() to tell a bad dictionary from bad + // input. + this.err = exports.Z_NEED_DICT; + } + } + while (this.strm.avail_in > 0 && this.mode === exports.GUNZIP && this.err === exports.Z_STREAM_END && this.strm.next_in[0] !== 0x00) { + // Bytes remain in input buffer. Perhaps this is another compressed + // member in the same archive, or just trailing garbage. + // Trailing zero bytes are okay, though, since they are frequently + // used for padding. + + this.reset(); + this.err = zlib_inflate.inflate(this.strm, this.flush); + } + break; + default: + throw new Error('Unknown mode ' + this.mode); + } +}; + +Zlib.prototype._checkError = function () { + // Acceptable error states depend on the type of zlib stream. + switch (this.err) { + case exports.Z_OK: + case exports.Z_BUF_ERROR: + if (this.strm.avail_out !== 0 && this.flush === exports.Z_FINISH) { + this._error('unexpected end of file'); + return false; + } + break; + case exports.Z_STREAM_END: + // normal statuses, not fatal + break; + case exports.Z_NEED_DICT: + if (this.dictionary == null) { + this._error('Missing dictionary'); + } else { + this._error('Bad dictionary'); + } + return false; + default: + // something else. + this._error('Zlib error'); + return false; + } + + return true; +}; + +Zlib.prototype._after = function () { + if (!this._checkError()) { + return; + } + + var avail_out = this.strm.avail_out; + var avail_in = this.strm.avail_in; + + this.write_in_progress = false; + + // call the write() cb + this.callback(avail_in, avail_out); + + if (this.pending_close) { + this.close(); + } +}; + +Zlib.prototype._error = function (message) { + if (this.strm.msg) { + message = this.strm.msg; + } + this.onerror(message, this.err + + // no hope of rescue. + );this.write_in_progress = false; + if (this.pending_close) { + this.close(); + } +}; + +Zlib.prototype.init = function (windowBits, level, memLevel, strategy, dictionary) { + assert(arguments.length === 4 || arguments.length === 5, 'init(windowBits, level, memLevel, strategy, [dictionary])'); + + assert(windowBits >= 8 && windowBits <= 15, 'invalid windowBits'); + assert(level >= -1 && level <= 9, 'invalid compression level'); + + assert(memLevel >= 1 && memLevel <= 9, 'invalid memlevel'); + + assert(strategy === exports.Z_FILTERED || strategy === exports.Z_HUFFMAN_ONLY || strategy === exports.Z_RLE || strategy === exports.Z_FIXED || strategy === exports.Z_DEFAULT_STRATEGY, 'invalid strategy'); + + this._init(level, windowBits, memLevel, strategy, dictionary); + this._setDictionary(); +}; + +Zlib.prototype.params = function () { + throw new Error('deflateParams Not supported'); +}; + +Zlib.prototype.reset = function () { + this._reset(); + this._setDictionary(); +}; + +Zlib.prototype._init = function (level, windowBits, memLevel, strategy, dictionary) { + this.level = level; + this.windowBits = windowBits; + this.memLevel = memLevel; + this.strategy = strategy; + + this.flush = exports.Z_NO_FLUSH; + + this.err = exports.Z_OK; + + if (this.mode === exports.GZIP || this.mode === exports.GUNZIP) { + this.windowBits += 16; + } + + if (this.mode === exports.UNZIP) { + this.windowBits += 32; + } + + if (this.mode === exports.DEFLATERAW || this.mode === exports.INFLATERAW) { + this.windowBits = -1 * this.windowBits; + } + + this.strm = new Zstream(); + + switch (this.mode) { + case exports.DEFLATE: + case exports.GZIP: + case exports.DEFLATERAW: + this.err = zlib_deflate.deflateInit2(this.strm, this.level, exports.Z_DEFLATED, this.windowBits, this.memLevel, this.strategy); + break; + case exports.INFLATE: + case exports.GUNZIP: + case exports.INFLATERAW: + case exports.UNZIP: + this.err = zlib_inflate.inflateInit2(this.strm, this.windowBits); + break; + default: + throw new Error('Unknown mode ' + this.mode); + } + + if (this.err !== exports.Z_OK) { + this._error('Init error'); + } + + this.dictionary = dictionary; + + this.write_in_progress = false; + this.init_done = true; +}; + +Zlib.prototype._setDictionary = function () { + if (this.dictionary == null) { + return; + } + + this.err = exports.Z_OK; + + switch (this.mode) { + case exports.DEFLATE: + case exports.DEFLATERAW: + this.err = zlib_deflate.deflateSetDictionary(this.strm, this.dictionary); + break; + default: + break; + } + + if (this.err !== exports.Z_OK) { + this._error('Failed to set dictionary'); + } +}; + +Zlib.prototype._reset = function () { + this.err = exports.Z_OK; + + switch (this.mode) { + case exports.DEFLATE: + case exports.DEFLATERAW: + case exports.GZIP: + this.err = zlib_deflate.deflateReset(this.strm); + break; + case exports.INFLATE: + case exports.INFLATERAW: + case exports.GUNZIP: + this.err = zlib_inflate.inflateReset(this.strm); + break; + default: + break; + } + + if (this.err !== exports.Z_OK) { + this._error('Failed to reset stream'); + } +}; + +exports.Zlib = Zlib; +/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../../buffer/index.js */ "./node_modules/buffer/index.js").Buffer, __webpack_require__(/*! ./../../process/browser.js */ "./node_modules/process/browser.js"))) + +/***/ }), + +/***/ "./node_modules/browserify-zlib/lib/index.js": +/*!***************************************************!*\ + !*** ./node_modules/browserify-zlib/lib/index.js ***! + \***************************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/* WEBPACK VAR INJECTION */(function(process) { + +var Buffer = __webpack_require__(/*! buffer */ "./node_modules/buffer/index.js").Buffer; +var Transform = __webpack_require__(/*! stream */ "./node_modules/stream-browserify/index.js").Transform; +var binding = __webpack_require__(/*! ./binding */ "./node_modules/browserify-zlib/lib/binding.js"); +var util = __webpack_require__(/*! util */ "./node_modules/util/util.js"); +var assert = __webpack_require__(/*! assert */ "./node_modules/assert/assert.js").ok; +var kMaxLength = __webpack_require__(/*! buffer */ "./node_modules/buffer/index.js").kMaxLength; +var kRangeErrorMessage = 'Cannot create final Buffer. It would be larger ' + 'than 0x' + kMaxLength.toString(16) + ' bytes'; + +// zlib doesn't provide these, so kludge them in following the same +// const naming scheme zlib uses. +binding.Z_MIN_WINDOWBITS = 8; +binding.Z_MAX_WINDOWBITS = 15; +binding.Z_DEFAULT_WINDOWBITS = 15; + +// fewer than 64 bytes per chunk is stupid. +// technically it could work with as few as 8, but even 64 bytes +// is absurdly low. Usually a MB or more is best. +binding.Z_MIN_CHUNK = 64; +binding.Z_MAX_CHUNK = Infinity; +binding.Z_DEFAULT_CHUNK = 16 * 1024; + +binding.Z_MIN_MEMLEVEL = 1; +binding.Z_MAX_MEMLEVEL = 9; +binding.Z_DEFAULT_MEMLEVEL = 8; + +binding.Z_MIN_LEVEL = -1; +binding.Z_MAX_LEVEL = 9; +binding.Z_DEFAULT_LEVEL = binding.Z_DEFAULT_COMPRESSION; + +// expose all the zlib constants +var bkeys = Object.keys(binding); +for (var bk = 0; bk < bkeys.length; bk++) { + var bkey = bkeys[bk]; + if (bkey.match(/^Z/)) { + Object.defineProperty(exports, bkey, { + enumerable: true, value: binding[bkey], writable: false + }); + } +} + +// translation table for return codes. +var codes = { + Z_OK: binding.Z_OK, + Z_STREAM_END: binding.Z_STREAM_END, + Z_NEED_DICT: binding.Z_NEED_DICT, + Z_ERRNO: binding.Z_ERRNO, + Z_STREAM_ERROR: binding.Z_STREAM_ERROR, + Z_DATA_ERROR: binding.Z_DATA_ERROR, + Z_MEM_ERROR: binding.Z_MEM_ERROR, + Z_BUF_ERROR: binding.Z_BUF_ERROR, + Z_VERSION_ERROR: binding.Z_VERSION_ERROR +}; + +var ckeys = Object.keys(codes); +for (var ck = 0; ck < ckeys.length; ck++) { + var ckey = ckeys[ck]; + codes[codes[ckey]] = ckey; +} + +Object.defineProperty(exports, 'codes', { + enumerable: true, value: Object.freeze(codes), writable: false +}); + +exports.Deflate = Deflate; +exports.Inflate = Inflate; +exports.Gzip = Gzip; +exports.Gunzip = Gunzip; +exports.DeflateRaw = DeflateRaw; +exports.InflateRaw = InflateRaw; +exports.Unzip = Unzip; + +exports.createDeflate = function (o) { + return new Deflate(o); +}; + +exports.createInflate = function (o) { + return new Inflate(o); +}; + +exports.createDeflateRaw = function (o) { + return new DeflateRaw(o); +}; + +exports.createInflateRaw = function (o) { + return new InflateRaw(o); +}; + +exports.createGzip = function (o) { + return new Gzip(o); +}; + +exports.createGunzip = function (o) { + return new Gunzip(o); +}; + +exports.createUnzip = function (o) { + return new Unzip(o); +}; + +// Convenience methods. +// compress/decompress a string or buffer in one step. +exports.deflate = function (buffer, opts, callback) { + if (typeof opts === 'function') { + callback = opts; + opts = {}; + } + return zlibBuffer(new Deflate(opts), buffer, callback); +}; + +exports.deflateSync = function (buffer, opts) { + return zlibBufferSync(new Deflate(opts), buffer); +}; + +exports.gzip = function (buffer, opts, callback) { + if (typeof opts === 'function') { + callback = opts; + opts = {}; + } + return zlibBuffer(new Gzip(opts), buffer, callback); +}; + +exports.gzipSync = function (buffer, opts) { + return zlibBufferSync(new Gzip(opts), buffer); +}; + +exports.deflateRaw = function (buffer, opts, callback) { + if (typeof opts === 'function') { + callback = opts; + opts = {}; + } + return zlibBuffer(new DeflateRaw(opts), buffer, callback); +}; + +exports.deflateRawSync = function (buffer, opts) { + return zlibBufferSync(new DeflateRaw(opts), buffer); +}; + +exports.unzip = function (buffer, opts, callback) { + if (typeof opts === 'function') { + callback = opts; + opts = {}; + } + return zlibBuffer(new Unzip(opts), buffer, callback); +}; + +exports.unzipSync = function (buffer, opts) { + return zlibBufferSync(new Unzip(opts), buffer); +}; + +exports.inflate = function (buffer, opts, callback) { + if (typeof opts === 'function') { + callback = opts; + opts = {}; + } + return zlibBuffer(new Inflate(opts), buffer, callback); +}; + +exports.inflateSync = function (buffer, opts) { + return zlibBufferSync(new Inflate(opts), buffer); +}; + +exports.gunzip = function (buffer, opts, callback) { + if (typeof opts === 'function') { + callback = opts; + opts = {}; + } + return zlibBuffer(new Gunzip(opts), buffer, callback); +}; + +exports.gunzipSync = function (buffer, opts) { + return zlibBufferSync(new Gunzip(opts), buffer); +}; + +exports.inflateRaw = function (buffer, opts, callback) { + if (typeof opts === 'function') { + callback = opts; + opts = {}; + } + return zlibBuffer(new InflateRaw(opts), buffer, callback); +}; + +exports.inflateRawSync = function (buffer, opts) { + return zlibBufferSync(new InflateRaw(opts), buffer); +}; + +function zlibBuffer(engine, buffer, callback) { + var buffers = []; + var nread = 0; + + engine.on('error', onError); + engine.on('end', onEnd); + + engine.end(buffer); + flow(); + + function flow() { + var chunk; + while (null !== (chunk = engine.read())) { + buffers.push(chunk); + nread += chunk.length; + } + engine.once('readable', flow); + } + + function onError(err) { + engine.removeListener('end', onEnd); + engine.removeListener('readable', flow); + callback(err); + } + + function onEnd() { + var buf; + var err = null; + + if (nread >= kMaxLength) { + err = new RangeError(kRangeErrorMessage); + } else { + buf = Buffer.concat(buffers, nread); + } + + buffers = []; + engine.close(); + callback(err, buf); + } +} + +function zlibBufferSync(engine, buffer) { + if (typeof buffer === 'string') buffer = Buffer.from(buffer); + + if (!Buffer.isBuffer(buffer)) throw new TypeError('Not a string or buffer'); + + var flushFlag = engine._finishFlushFlag; + + return engine._processChunk(buffer, flushFlag); +} + +// generic zlib +// minimal 2-byte header +function Deflate(opts) { + if (!(this instanceof Deflate)) return new Deflate(opts); + Zlib.call(this, opts, binding.DEFLATE); +} + +function Inflate(opts) { + if (!(this instanceof Inflate)) return new Inflate(opts); + Zlib.call(this, opts, binding.INFLATE); +} + +// gzip - bigger header, same deflate compression +function Gzip(opts) { + if (!(this instanceof Gzip)) return new Gzip(opts); + Zlib.call(this, opts, binding.GZIP); +} + +function Gunzip(opts) { + if (!(this instanceof Gunzip)) return new Gunzip(opts); + Zlib.call(this, opts, binding.GUNZIP); +} + +// raw - no header +function DeflateRaw(opts) { + if (!(this instanceof DeflateRaw)) return new DeflateRaw(opts); + Zlib.call(this, opts, binding.DEFLATERAW); +} + +function InflateRaw(opts) { + if (!(this instanceof InflateRaw)) return new InflateRaw(opts); + Zlib.call(this, opts, binding.INFLATERAW); +} + +// auto-detect header. +function Unzip(opts) { + if (!(this instanceof Unzip)) return new Unzip(opts); + Zlib.call(this, opts, binding.UNZIP); +} + +function isValidFlushFlag(flag) { + return flag === binding.Z_NO_FLUSH || flag === binding.Z_PARTIAL_FLUSH || flag === binding.Z_SYNC_FLUSH || flag === binding.Z_FULL_FLUSH || flag === binding.Z_FINISH || flag === binding.Z_BLOCK; +} + +// the Zlib class they all inherit from +// This thing manages the queue of requests, and returns +// true or false if there is anything in the queue when +// you call the .write() method. + +function Zlib(opts, mode) { + var _this = this; + + this._opts = opts = opts || {}; + this._chunkSize = opts.chunkSize || exports.Z_DEFAULT_CHUNK; + + Transform.call(this, opts); + + if (opts.flush && !isValidFlushFlag(opts.flush)) { + throw new Error('Invalid flush flag: ' + opts.flush); + } + if (opts.finishFlush && !isValidFlushFlag(opts.finishFlush)) { + throw new Error('Invalid flush flag: ' + opts.finishFlush); + } + + this._flushFlag = opts.flush || binding.Z_NO_FLUSH; + this._finishFlushFlag = typeof opts.finishFlush !== 'undefined' ? opts.finishFlush : binding.Z_FINISH; + + if (opts.chunkSize) { + if (opts.chunkSize < exports.Z_MIN_CHUNK || opts.chunkSize > exports.Z_MAX_CHUNK) { + throw new Error('Invalid chunk size: ' + opts.chunkSize); + } + } + + if (opts.windowBits) { + if (opts.windowBits < exports.Z_MIN_WINDOWBITS || opts.windowBits > exports.Z_MAX_WINDOWBITS) { + throw new Error('Invalid windowBits: ' + opts.windowBits); + } + } + + if (opts.level) { + if (opts.level < exports.Z_MIN_LEVEL || opts.level > exports.Z_MAX_LEVEL) { + throw new Error('Invalid compression level: ' + opts.level); + } + } + + if (opts.memLevel) { + if (opts.memLevel < exports.Z_MIN_MEMLEVEL || opts.memLevel > exports.Z_MAX_MEMLEVEL) { + throw new Error('Invalid memLevel: ' + opts.memLevel); + } + } + + if (opts.strategy) { + if (opts.strategy != exports.Z_FILTERED && opts.strategy != exports.Z_HUFFMAN_ONLY && opts.strategy != exports.Z_RLE && opts.strategy != exports.Z_FIXED && opts.strategy != exports.Z_DEFAULT_STRATEGY) { + throw new Error('Invalid strategy: ' + opts.strategy); + } + } + + if (opts.dictionary) { + if (!Buffer.isBuffer(opts.dictionary)) { + throw new Error('Invalid dictionary: it should be a Buffer instance'); + } + } + + this._handle = new binding.Zlib(mode); + + var self = this; + this._hadError = false; + this._handle.onerror = function (message, errno) { + // there is no way to cleanly recover. + // continuing only obscures problems. + _close(self); + self._hadError = true; + + var error = new Error(message); + error.errno = errno; + error.code = exports.codes[errno]; + self.emit('error', error); + }; + + var level = exports.Z_DEFAULT_COMPRESSION; + if (typeof opts.level === 'number') level = opts.level; + + var strategy = exports.Z_DEFAULT_STRATEGY; + if (typeof opts.strategy === 'number') strategy = opts.strategy; + + this._handle.init(opts.windowBits || exports.Z_DEFAULT_WINDOWBITS, level, opts.memLevel || exports.Z_DEFAULT_MEMLEVEL, strategy, opts.dictionary); + + this._buffer = Buffer.allocUnsafe(this._chunkSize); + this._offset = 0; + this._level = level; + this._strategy = strategy; + + this.once('end', this.close); + + Object.defineProperty(this, '_closed', { + get: function () { + return !_this._handle; + }, + configurable: true, + enumerable: true + }); +} + +util.inherits(Zlib, Transform); + +Zlib.prototype.params = function (level, strategy, callback) { + if (level < exports.Z_MIN_LEVEL || level > exports.Z_MAX_LEVEL) { + throw new RangeError('Invalid compression level: ' + level); + } + if (strategy != exports.Z_FILTERED && strategy != exports.Z_HUFFMAN_ONLY && strategy != exports.Z_RLE && strategy != exports.Z_FIXED && strategy != exports.Z_DEFAULT_STRATEGY) { + throw new TypeError('Invalid strategy: ' + strategy); + } + + if (this._level !== level || this._strategy !== strategy) { + var self = this; + this.flush(binding.Z_SYNC_FLUSH, function () { + assert(self._handle, 'zlib binding closed'); + self._handle.params(level, strategy); + if (!self._hadError) { + self._level = level; + self._strategy = strategy; + if (callback) callback(); + } + }); + } else { + process.nextTick(callback); + } +}; + +Zlib.prototype.reset = function () { + assert(this._handle, 'zlib binding closed'); + return this._handle.reset(); +}; + +// This is the _flush function called by the transform class, +// internally, when the last chunk has been written. +Zlib.prototype._flush = function (callback) { + this._transform(Buffer.alloc(0), '', callback); +}; + +Zlib.prototype.flush = function (kind, callback) { + var _this2 = this; + + var ws = this._writableState; + + if (typeof kind === 'function' || kind === undefined && !callback) { + callback = kind; + kind = binding.Z_FULL_FLUSH; + } + + if (ws.ended) { + if (callback) process.nextTick(callback); + } else if (ws.ending) { + if (callback) this.once('end', callback); + } else if (ws.needDrain) { + if (callback) { + this.once('drain', function () { + return _this2.flush(kind, callback); + }); + } + } else { + this._flushFlag = kind; + this.write(Buffer.alloc(0), '', callback); + } +}; + +Zlib.prototype.close = function (callback) { + _close(this, callback); + process.nextTick(emitCloseNT, this); +}; + +function _close(engine, callback) { + if (callback) process.nextTick(callback); + + // Caller may invoke .close after a zlib error (which will null _handle). + if (!engine._handle) return; + + engine._handle.close(); + engine._handle = null; +} + +function emitCloseNT(self) { + self.emit('close'); +} + +Zlib.prototype._transform = function (chunk, encoding, cb) { + var flushFlag; + var ws = this._writableState; + var ending = ws.ending || ws.ended; + var last = ending && (!chunk || ws.length === chunk.length); + + if (chunk !== null && !Buffer.isBuffer(chunk)) return cb(new Error('invalid input')); + + if (!this._handle) return cb(new Error('zlib binding closed')); + + // If it's the last chunk, or a final flush, we use the Z_FINISH flush flag + // (or whatever flag was provided using opts.finishFlush). + // If it's explicitly flushing at some other time, then we use + // Z_FULL_FLUSH. Otherwise, use Z_NO_FLUSH for maximum compression + // goodness. + if (last) flushFlag = this._finishFlushFlag;else { + flushFlag = this._flushFlag; + // once we've flushed the last of the queue, stop flushing and + // go back to the normal behavior. + if (chunk.length >= ws.length) { + this._flushFlag = this._opts.flush || binding.Z_NO_FLUSH; + } + } + + this._processChunk(chunk, flushFlag, cb); +}; + +Zlib.prototype._processChunk = function (chunk, flushFlag, cb) { + var availInBefore = chunk && chunk.length; + var availOutBefore = this._chunkSize - this._offset; + var inOff = 0; + + var self = this; + + var async = typeof cb === 'function'; + + if (!async) { + var buffers = []; + var nread = 0; + + var error; + this.on('error', function (er) { + error = er; + }); + + assert(this._handle, 'zlib binding closed'); + do { + var res = this._handle.writeSync(flushFlag, chunk, // in + inOff, // in_off + availInBefore, // in_len + this._buffer, // out + this._offset, //out_off + availOutBefore); // out_len + } while (!this._hadError && callback(res[0], res[1])); + + if (this._hadError) { + throw error; + } + + if (nread >= kMaxLength) { + _close(this); + throw new RangeError(kRangeErrorMessage); + } + + var buf = Buffer.concat(buffers, nread); + _close(this); + + return buf; + } + + assert(this._handle, 'zlib binding closed'); + var req = this._handle.write(flushFlag, chunk, // in + inOff, // in_off + availInBefore, // in_len + this._buffer, // out + this._offset, //out_off + availOutBefore); // out_len + + req.buffer = chunk; + req.callback = callback; + + function callback(availInAfter, availOutAfter) { + // When the callback is used in an async write, the callback's + // context is the `req` object that was created. The req object + // is === this._handle, and that's why it's important to null + // out the values after they are done being used. `this._handle` + // can stay in memory longer than the callback and buffer are needed. + if (this) { + this.buffer = null; + this.callback = null; + } + + if (self._hadError) return; + + var have = availOutBefore - availOutAfter; + assert(have >= 0, 'have should not go down'); + + if (have > 0) { + var out = self._buffer.slice(self._offset, self._offset + have); + self._offset += have; + // serve some output to the consumer. + if (async) { + self.push(out); + } else { + buffers.push(out); + nread += out.length; + } + } + + // exhausted the output buffer, or used all the input create a new one. + if (availOutAfter === 0 || self._offset >= self._chunkSize) { + availOutBefore = self._chunkSize; + self._offset = 0; + self._buffer = Buffer.allocUnsafe(self._chunkSize); + } + + if (availOutAfter === 0) { + // Not actually done. Need to reprocess. + // Also, update the availInBefore to the availInAfter value, + // so that if we have to hit it a third (fourth, etc.) time, + // it'll have the correct byte counts. + inOff += availInBefore - availInAfter; + availInBefore = availInAfter; + + if (!async) return true; + + var newReq = self._handle.write(flushFlag, chunk, inOff, availInBefore, self._buffer, self._offset, self._chunkSize); + newReq.callback = callback; // this same function + newReq.buffer = chunk; + return; + } + + if (!async) return false; + + // finished with the chunk. + cb(); + } +}; + +util.inherits(Deflate, Zlib); +util.inherits(Inflate, Zlib); +util.inherits(Gzip, Zlib); +util.inherits(Gunzip, Zlib); +util.inherits(DeflateRaw, Zlib); +util.inherits(InflateRaw, Zlib); +util.inherits(Unzip, Zlib); +/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../../process/browser.js */ "./node_modules/process/browser.js"))) + +/***/ }), + +/***/ "./node_modules/buffer/index.js": +/*!**************************************!*\ + !*** ./node_modules/buffer/index.js ***! + \**************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/* WEBPACK VAR INJECTION */(function(global) {/*! + * The buffer module from node.js, for the browser. + * + * @author Feross Aboukhadijeh + * @license MIT + */ +/* eslint-disable no-proto */ + + + +var base64 = __webpack_require__(/*! base64-js */ "./node_modules/base64-js/index.js") +var ieee754 = __webpack_require__(/*! ieee754 */ "./node_modules/ieee754/index.js") +var isArray = __webpack_require__(/*! isarray */ "./node_modules/isarray/index.js") + +exports.Buffer = Buffer +exports.SlowBuffer = SlowBuffer +exports.INSPECT_MAX_BYTES = 50 + +/** + * If `Buffer.TYPED_ARRAY_SUPPORT`: + * === true Use Uint8Array implementation (fastest) + * === false Use Object implementation (most compatible, even IE6) + * + * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+, + * Opera 11.6+, iOS 4.2+. + * + * Due to various browser bugs, sometimes the Object implementation will be used even + * when the browser supports typed arrays. + * + * Note: + * + * - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances, + * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438. + * + * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function. + * + * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of + * incorrect length in some situations. + + * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they + * get the Object implementation, which is slower but behaves correctly. + */ +Buffer.TYPED_ARRAY_SUPPORT = global.TYPED_ARRAY_SUPPORT !== undefined + ? global.TYPED_ARRAY_SUPPORT + : typedArraySupport() + +/* + * Export kMaxLength after typed array support is determined. + */ +exports.kMaxLength = kMaxLength() + +function typedArraySupport () { + try { + var arr = new Uint8Array(1) + arr.__proto__ = {__proto__: Uint8Array.prototype, foo: function () { return 42 }} + return arr.foo() === 42 && // typed array instances can be augmented + typeof arr.subarray === 'function' && // chrome 9-10 lack `subarray` + arr.subarray(1, 1).byteLength === 0 // ie10 has broken `subarray` + } catch (e) { + return false + } +} + +function kMaxLength () { + return Buffer.TYPED_ARRAY_SUPPORT + ? 0x7fffffff + : 0x3fffffff +} + +function createBuffer (that, length) { + if (kMaxLength() < length) { + throw new RangeError('Invalid typed array length') + } + if (Buffer.TYPED_ARRAY_SUPPORT) { + // Return an augmented `Uint8Array` instance, for best performance + that = new Uint8Array(length) + that.__proto__ = Buffer.prototype + } else { + // Fallback: Return an object instance of the Buffer class + if (that === null) { + that = new Buffer(length) + } + that.length = length + } + + return that +} + +/** + * The Buffer constructor returns instances of `Uint8Array` that have their + * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of + * `Uint8Array`, so the returned instances will have all the node `Buffer` methods + * and the `Uint8Array` methods. Square bracket notation works as expected -- it + * returns a single octet. + * + * The `Uint8Array` prototype remains unmodified. + */ + +function Buffer (arg, encodingOrOffset, length) { + if (!Buffer.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer)) { + return new Buffer(arg, encodingOrOffset, length) + } + + // Common case. + if (typeof arg === 'number') { + if (typeof encodingOrOffset === 'string') { + throw new Error( + 'If encoding is specified then the first argument must be a string' + ) + } + return allocUnsafe(this, arg) + } + return from(this, arg, encodingOrOffset, length) +} + +Buffer.poolSize = 8192 // not used by this implementation + +// TODO: Legacy, not needed anymore. Remove in next major version. +Buffer._augment = function (arr) { + arr.__proto__ = Buffer.prototype + return arr +} + +function from (that, value, encodingOrOffset, length) { + if (typeof value === 'number') { + throw new TypeError('"value" argument must not be a number') + } + + if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) { + return fromArrayBuffer(that, value, encodingOrOffset, length) + } + + if (typeof value === 'string') { + return fromString(that, value, encodingOrOffset) + } + + return fromObject(that, value) +} + +/** + * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError + * if value is a number. + * Buffer.from(str[, encoding]) + * Buffer.from(array) + * Buffer.from(buffer) + * Buffer.from(arrayBuffer[, byteOffset[, length]]) + **/ +Buffer.from = function (value, encodingOrOffset, length) { + return from(null, value, encodingOrOffset, length) +} + +if (Buffer.TYPED_ARRAY_SUPPORT) { + Buffer.prototype.__proto__ = Uint8Array.prototype + Buffer.__proto__ = Uint8Array + if (typeof Symbol !== 'undefined' && Symbol.species && + Buffer[Symbol.species] === Buffer) { + // Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97 + Object.defineProperty(Buffer, Symbol.species, { + value: null, + configurable: true + }) + } +} + +function assertSize (size) { + if (typeof size !== 'number') { + throw new TypeError('"size" argument must be a number') + } else if (size < 0) { + throw new RangeError('"size" argument must not be negative') + } +} + +function alloc (that, size, fill, encoding) { + assertSize(size) + if (size <= 0) { + return createBuffer(that, size) + } + if (fill !== undefined) { + // Only pay attention to encoding if it's a string. This + // prevents accidentally sending in a number that would + // be interpretted as a start offset. + return typeof encoding === 'string' + ? createBuffer(that, size).fill(fill, encoding) + : createBuffer(that, size).fill(fill) + } + return createBuffer(that, size) +} + +/** + * Creates a new filled Buffer instance. + * alloc(size[, fill[, encoding]]) + **/ +Buffer.alloc = function (size, fill, encoding) { + return alloc(null, size, fill, encoding) +} + +function allocUnsafe (that, size) { + assertSize(size) + that = createBuffer(that, size < 0 ? 0 : checked(size) | 0) + if (!Buffer.TYPED_ARRAY_SUPPORT) { + for (var i = 0; i < size; ++i) { + that[i] = 0 + } + } + return that +} + +/** + * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance. + * */ +Buffer.allocUnsafe = function (size) { + return allocUnsafe(null, size) +} +/** + * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance. + */ +Buffer.allocUnsafeSlow = function (size) { + return allocUnsafe(null, size) +} + +function fromString (that, string, encoding) { + if (typeof encoding !== 'string' || encoding === '') { + encoding = 'utf8' + } + + if (!Buffer.isEncoding(encoding)) { + throw new TypeError('"encoding" must be a valid string encoding') + } + + var length = byteLength(string, encoding) | 0 + that = createBuffer(that, length) + + var actual = that.write(string, encoding) + + if (actual !== length) { + // Writing a hex string, for example, that contains invalid characters will + // cause everything after the first invalid character to be ignored. (e.g. + // 'abxxcd' will be treated as 'ab') + that = that.slice(0, actual) + } + + return that +} + +function fromArrayLike (that, array) { + var length = array.length < 0 ? 0 : checked(array.length) | 0 + that = createBuffer(that, length) + for (var i = 0; i < length; i += 1) { + that[i] = array[i] & 255 + } + return that +} + +function fromArrayBuffer (that, array, byteOffset, length) { + array.byteLength // this throws if `array` is not a valid ArrayBuffer + + if (byteOffset < 0 || array.byteLength < byteOffset) { + throw new RangeError('\'offset\' is out of bounds') + } + + if (array.byteLength < byteOffset + (length || 0)) { + throw new RangeError('\'length\' is out of bounds') + } + + if (byteOffset === undefined && length === undefined) { + array = new Uint8Array(array) + } else if (length === undefined) { + array = new Uint8Array(array, byteOffset) + } else { + array = new Uint8Array(array, byteOffset, length) + } + + if (Buffer.TYPED_ARRAY_SUPPORT) { + // Return an augmented `Uint8Array` instance, for best performance + that = array + that.__proto__ = Buffer.prototype + } else { + // Fallback: Return an object instance of the Buffer class + that = fromArrayLike(that, array) + } + return that +} + +function fromObject (that, obj) { + if (Buffer.isBuffer(obj)) { + var len = checked(obj.length) | 0 + that = createBuffer(that, len) + + if (that.length === 0) { + return that + } + + obj.copy(that, 0, 0, len) + return that + } + + if (obj) { + if ((typeof ArrayBuffer !== 'undefined' && + obj.buffer instanceof ArrayBuffer) || 'length' in obj) { + if (typeof obj.length !== 'number' || isnan(obj.length)) { + return createBuffer(that, 0) + } + return fromArrayLike(that, obj) + } + + if (obj.type === 'Buffer' && isArray(obj.data)) { + return fromArrayLike(that, obj.data) + } + } + + throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.') +} + +function checked (length) { + // Note: cannot use `length < kMaxLength()` here because that fails when + // length is NaN (which is otherwise coerced to zero.) + if (length >= kMaxLength()) { + throw new RangeError('Attempt to allocate Buffer larger than maximum ' + + 'size: 0x' + kMaxLength().toString(16) + ' bytes') + } + return length | 0 +} + +function SlowBuffer (length) { + if (+length != length) { // eslint-disable-line eqeqeq + length = 0 + } + return Buffer.alloc(+length) +} + +Buffer.isBuffer = function isBuffer (b) { + return !!(b != null && b._isBuffer) +} + +Buffer.compare = function compare (a, b) { + if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) { + throw new TypeError('Arguments must be Buffers') + } + + if (a === b) return 0 + + var x = a.length + var y = b.length + + for (var i = 0, len = Math.min(x, y); i < len; ++i) { + if (a[i] !== b[i]) { + x = a[i] + y = b[i] + break + } + } + + if (x < y) return -1 + if (y < x) return 1 + return 0 +} + +Buffer.isEncoding = function isEncoding (encoding) { + switch (String(encoding).toLowerCase()) { + case 'hex': + case 'utf8': + case 'utf-8': + case 'ascii': + case 'latin1': + case 'binary': + case 'base64': + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return true + default: + return false + } +} + +Buffer.concat = function concat (list, length) { + if (!isArray(list)) { + throw new TypeError('"list" argument must be an Array of Buffers') + } + + if (list.length === 0) { + return Buffer.alloc(0) + } + + var i + if (length === undefined) { + length = 0 + for (i = 0; i < list.length; ++i) { + length += list[i].length + } + } + + var buffer = Buffer.allocUnsafe(length) + var pos = 0 + for (i = 0; i < list.length; ++i) { + var buf = list[i] + if (!Buffer.isBuffer(buf)) { + throw new TypeError('"list" argument must be an Array of Buffers') + } + buf.copy(buffer, pos) + pos += buf.length + } + return buffer +} + +function byteLength (string, encoding) { + if (Buffer.isBuffer(string)) { + return string.length + } + if (typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'function' && + (ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) { + return string.byteLength + } + if (typeof string !== 'string') { + string = '' + string + } + + var len = string.length + if (len === 0) return 0 + + // Use a for loop to avoid recursion + var loweredCase = false + for (;;) { + switch (encoding) { + case 'ascii': + case 'latin1': + case 'binary': + return len + case 'utf8': + case 'utf-8': + case undefined: + return utf8ToBytes(string).length + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return len * 2 + case 'hex': + return len >>> 1 + case 'base64': + return base64ToBytes(string).length + default: + if (loweredCase) return utf8ToBytes(string).length // assume utf8 + encoding = ('' + encoding).toLowerCase() + loweredCase = true + } + } +} +Buffer.byteLength = byteLength + +function slowToString (encoding, start, end) { + var loweredCase = false + + // No need to verify that "this.length <= MAX_UINT32" since it's a read-only + // property of a typed array. + + // This behaves neither like String nor Uint8Array in that we set start/end + // to their upper/lower bounds if the value passed is out of range. + // undefined is handled specially as per ECMA-262 6th Edition, + // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization. + if (start === undefined || start < 0) { + start = 0 + } + // Return early if start > this.length. Done here to prevent potential uint32 + // coercion fail below. + if (start > this.length) { + return '' + } + + if (end === undefined || end > this.length) { + end = this.length + } + + if (end <= 0) { + return '' + } + + // Force coersion to uint32. This will also coerce falsey/NaN values to 0. + end >>>= 0 + start >>>= 0 + + if (end <= start) { + return '' + } + + if (!encoding) encoding = 'utf8' + + while (true) { + switch (encoding) { + case 'hex': + return hexSlice(this, start, end) + + case 'utf8': + case 'utf-8': + return utf8Slice(this, start, end) + + case 'ascii': + return asciiSlice(this, start, end) + + case 'latin1': + case 'binary': + return latin1Slice(this, start, end) + + case 'base64': + return base64Slice(this, start, end) + + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return utf16leSlice(this, start, end) + + default: + if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) + encoding = (encoding + '').toLowerCase() + loweredCase = true + } + } +} + +// The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect +// Buffer instances. +Buffer.prototype._isBuffer = true + +function swap (b, n, m) { + var i = b[n] + b[n] = b[m] + b[m] = i +} + +Buffer.prototype.swap16 = function swap16 () { + var len = this.length + if (len % 2 !== 0) { + throw new RangeError('Buffer size must be a multiple of 16-bits') + } + for (var i = 0; i < len; i += 2) { + swap(this, i, i + 1) + } + return this +} + +Buffer.prototype.swap32 = function swap32 () { + var len = this.length + if (len % 4 !== 0) { + throw new RangeError('Buffer size must be a multiple of 32-bits') + } + for (var i = 0; i < len; i += 4) { + swap(this, i, i + 3) + swap(this, i + 1, i + 2) + } + return this +} + +Buffer.prototype.swap64 = function swap64 () { + var len = this.length + if (len % 8 !== 0) { + throw new RangeError('Buffer size must be a multiple of 64-bits') + } + for (var i = 0; i < len; i += 8) { + swap(this, i, i + 7) + swap(this, i + 1, i + 6) + swap(this, i + 2, i + 5) + swap(this, i + 3, i + 4) + } + return this +} + +Buffer.prototype.toString = function toString () { + var length = this.length | 0 + if (length === 0) return '' + if (arguments.length === 0) return utf8Slice(this, 0, length) + return slowToString.apply(this, arguments) +} + +Buffer.prototype.equals = function equals (b) { + if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer') + if (this === b) return true + return Buffer.compare(this, b) === 0 +} + +Buffer.prototype.inspect = function inspect () { + var str = '' + var max = exports.INSPECT_MAX_BYTES + if (this.length > 0) { + str = this.toString('hex', 0, max).match(/.{2}/g).join(' ') + if (this.length > max) str += ' ... ' + } + return '' +} + +Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) { + if (!Buffer.isBuffer(target)) { + throw new TypeError('Argument must be a Buffer') + } + + if (start === undefined) { + start = 0 + } + if (end === undefined) { + end = target ? target.length : 0 + } + if (thisStart === undefined) { + thisStart = 0 + } + if (thisEnd === undefined) { + thisEnd = this.length + } + + if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) { + throw new RangeError('out of range index') + } + + if (thisStart >= thisEnd && start >= end) { + return 0 + } + if (thisStart >= thisEnd) { + return -1 + } + if (start >= end) { + return 1 + } + + start >>>= 0 + end >>>= 0 + thisStart >>>= 0 + thisEnd >>>= 0 + + if (this === target) return 0 + + var x = thisEnd - thisStart + var y = end - start + var len = Math.min(x, y) + + var thisCopy = this.slice(thisStart, thisEnd) + var targetCopy = target.slice(start, end) + + for (var i = 0; i < len; ++i) { + if (thisCopy[i] !== targetCopy[i]) { + x = thisCopy[i] + y = targetCopy[i] + break + } + } + + if (x < y) return -1 + if (y < x) return 1 + return 0 +} + +// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`, +// OR the last index of `val` in `buffer` at offset <= `byteOffset`. +// +// Arguments: +// - buffer - a Buffer to search +// - val - a string, Buffer, or number +// - byteOffset - an index into `buffer`; will be clamped to an int32 +// - encoding - an optional encoding, relevant is val is a string +// - dir - true for indexOf, false for lastIndexOf +function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) { + // Empty buffer means no match + if (buffer.length === 0) return -1 + + // Normalize byteOffset + if (typeof byteOffset === 'string') { + encoding = byteOffset + byteOffset = 0 + } else if (byteOffset > 0x7fffffff) { + byteOffset = 0x7fffffff + } else if (byteOffset < -0x80000000) { + byteOffset = -0x80000000 + } + byteOffset = +byteOffset // Coerce to Number. + if (isNaN(byteOffset)) { + // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer + byteOffset = dir ? 0 : (buffer.length - 1) + } + + // Normalize byteOffset: negative offsets start from the end of the buffer + if (byteOffset < 0) byteOffset = buffer.length + byteOffset + if (byteOffset >= buffer.length) { + if (dir) return -1 + else byteOffset = buffer.length - 1 + } else if (byteOffset < 0) { + if (dir) byteOffset = 0 + else return -1 + } + + // Normalize val + if (typeof val === 'string') { + val = Buffer.from(val, encoding) + } + + // Finally, search either indexOf (if dir is true) or lastIndexOf + if (Buffer.isBuffer(val)) { + // Special case: looking for empty string/buffer always fails + if (val.length === 0) { + return -1 + } + return arrayIndexOf(buffer, val, byteOffset, encoding, dir) + } else if (typeof val === 'number') { + val = val & 0xFF // Search for a byte value [0-255] + if (Buffer.TYPED_ARRAY_SUPPORT && + typeof Uint8Array.prototype.indexOf === 'function') { + if (dir) { + return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset) + } else { + return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset) + } + } + return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir) + } + + throw new TypeError('val must be string, number or Buffer') +} + +function arrayIndexOf (arr, val, byteOffset, encoding, dir) { + var indexSize = 1 + var arrLength = arr.length + var valLength = val.length + + if (encoding !== undefined) { + encoding = String(encoding).toLowerCase() + if (encoding === 'ucs2' || encoding === 'ucs-2' || + encoding === 'utf16le' || encoding === 'utf-16le') { + if (arr.length < 2 || val.length < 2) { + return -1 + } + indexSize = 2 + arrLength /= 2 + valLength /= 2 + byteOffset /= 2 + } + } + + function read (buf, i) { + if (indexSize === 1) { + return buf[i] + } else { + return buf.readUInt16BE(i * indexSize) + } + } + + var i + if (dir) { + var foundIndex = -1 + for (i = byteOffset; i < arrLength; i++) { + if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) { + if (foundIndex === -1) foundIndex = i + if (i - foundIndex + 1 === valLength) return foundIndex * indexSize + } else { + if (foundIndex !== -1) i -= i - foundIndex + foundIndex = -1 + } + } + } else { + if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength + for (i = byteOffset; i >= 0; i--) { + var found = true + for (var j = 0; j < valLength; j++) { + if (read(arr, i + j) !== read(val, j)) { + found = false + break + } + } + if (found) return i + } + } + + return -1 +} + +Buffer.prototype.includes = function includes (val, byteOffset, encoding) { + return this.indexOf(val, byteOffset, encoding) !== -1 +} + +Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, true) +} + +Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, false) +} + +function hexWrite (buf, string, offset, length) { + offset = Number(offset) || 0 + var remaining = buf.length - offset + if (!length) { + length = remaining + } else { + length = Number(length) + if (length > remaining) { + length = remaining + } + } + + // must be an even number of digits + var strLen = string.length + if (strLen % 2 !== 0) throw new TypeError('Invalid hex string') + + if (length > strLen / 2) { + length = strLen / 2 + } + for (var i = 0; i < length; ++i) { + var parsed = parseInt(string.substr(i * 2, 2), 16) + if (isNaN(parsed)) return i + buf[offset + i] = parsed + } + return i +} + +function utf8Write (buf, string, offset, length) { + return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length) +} + +function asciiWrite (buf, string, offset, length) { + return blitBuffer(asciiToBytes(string), buf, offset, length) +} + +function latin1Write (buf, string, offset, length) { + return asciiWrite(buf, string, offset, length) +} + +function base64Write (buf, string, offset, length) { + return blitBuffer(base64ToBytes(string), buf, offset, length) +} + +function ucs2Write (buf, string, offset, length) { + return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length) +} + +Buffer.prototype.write = function write (string, offset, length, encoding) { + // Buffer#write(string) + if (offset === undefined) { + encoding = 'utf8' + length = this.length + offset = 0 + // Buffer#write(string, encoding) + } else if (length === undefined && typeof offset === 'string') { + encoding = offset + length = this.length + offset = 0 + // Buffer#write(string, offset[, length][, encoding]) + } else if (isFinite(offset)) { + offset = offset | 0 + if (isFinite(length)) { + length = length | 0 + if (encoding === undefined) encoding = 'utf8' + } else { + encoding = length + length = undefined + } + // legacy write(string, encoding, offset, length) - remove in v0.13 + } else { + throw new Error( + 'Buffer.write(string, encoding, offset[, length]) is no longer supported' + ) + } + + var remaining = this.length - offset + if (length === undefined || length > remaining) length = remaining + + if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) { + throw new RangeError('Attempt to write outside buffer bounds') + } + + if (!encoding) encoding = 'utf8' + + var loweredCase = false + for (;;) { + switch (encoding) { + case 'hex': + return hexWrite(this, string, offset, length) + + case 'utf8': + case 'utf-8': + return utf8Write(this, string, offset, length) + + case 'ascii': + return asciiWrite(this, string, offset, length) + + case 'latin1': + case 'binary': + return latin1Write(this, string, offset, length) + + case 'base64': + // Warning: maxLength not taken into account in base64Write + return base64Write(this, string, offset, length) + + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return ucs2Write(this, string, offset, length) + + default: + if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) + encoding = ('' + encoding).toLowerCase() + loweredCase = true + } + } +} + +Buffer.prototype.toJSON = function toJSON () { + return { + type: 'Buffer', + data: Array.prototype.slice.call(this._arr || this, 0) + } +} + +function base64Slice (buf, start, end) { + if (start === 0 && end === buf.length) { + return base64.fromByteArray(buf) + } else { + return base64.fromByteArray(buf.slice(start, end)) + } +} + +function utf8Slice (buf, start, end) { + end = Math.min(buf.length, end) + var res = [] + + var i = start + while (i < end) { + var firstByte = buf[i] + var codePoint = null + var bytesPerSequence = (firstByte > 0xEF) ? 4 + : (firstByte > 0xDF) ? 3 + : (firstByte > 0xBF) ? 2 + : 1 + + if (i + bytesPerSequence <= end) { + var secondByte, thirdByte, fourthByte, tempCodePoint + + switch (bytesPerSequence) { + case 1: + if (firstByte < 0x80) { + codePoint = firstByte + } + break + case 2: + secondByte = buf[i + 1] + if ((secondByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F) + if (tempCodePoint > 0x7F) { + codePoint = tempCodePoint + } + } + break + case 3: + secondByte = buf[i + 1] + thirdByte = buf[i + 2] + if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F) + if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) { + codePoint = tempCodePoint + } + } + break + case 4: + secondByte = buf[i + 1] + thirdByte = buf[i + 2] + fourthByte = buf[i + 3] + if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F) + if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) { + codePoint = tempCodePoint + } + } + } + } + + if (codePoint === null) { + // we did not generate a valid codePoint so insert a + // replacement char (U+FFFD) and advance only 1 byte + codePoint = 0xFFFD + bytesPerSequence = 1 + } else if (codePoint > 0xFFFF) { + // encode to utf16 (surrogate pair dance) + codePoint -= 0x10000 + res.push(codePoint >>> 10 & 0x3FF | 0xD800) + codePoint = 0xDC00 | codePoint & 0x3FF + } + + res.push(codePoint) + i += bytesPerSequence + } + + return decodeCodePointsArray(res) +} + +// Based on http://stackoverflow.com/a/22747272/680742, the browser with +// the lowest limit is Chrome, with 0x10000 args. +// We go 1 magnitude less, for safety +var MAX_ARGUMENTS_LENGTH = 0x1000 + +function decodeCodePointsArray (codePoints) { + var len = codePoints.length + if (len <= MAX_ARGUMENTS_LENGTH) { + return String.fromCharCode.apply(String, codePoints) // avoid extra slice() + } + + // Decode in chunks to avoid "call stack size exceeded". + var res = '' + var i = 0 + while (i < len) { + res += String.fromCharCode.apply( + String, + codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH) + ) + } + return res +} + +function asciiSlice (buf, start, end) { + var ret = '' + end = Math.min(buf.length, end) + + for (var i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i] & 0x7F) + } + return ret +} + +function latin1Slice (buf, start, end) { + var ret = '' + end = Math.min(buf.length, end) + + for (var i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i]) + } + return ret +} + +function hexSlice (buf, start, end) { + var len = buf.length + + if (!start || start < 0) start = 0 + if (!end || end < 0 || end > len) end = len + + var out = '' + for (var i = start; i < end; ++i) { + out += toHex(buf[i]) + } + return out +} + +function utf16leSlice (buf, start, end) { + var bytes = buf.slice(start, end) + var res = '' + for (var i = 0; i < bytes.length; i += 2) { + res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256) + } + return res +} + +Buffer.prototype.slice = function slice (start, end) { + var len = this.length + start = ~~start + end = end === undefined ? len : ~~end + + if (start < 0) { + start += len + if (start < 0) start = 0 + } else if (start > len) { + start = len + } + + if (end < 0) { + end += len + if (end < 0) end = 0 + } else if (end > len) { + end = len + } + + if (end < start) end = start + + var newBuf + if (Buffer.TYPED_ARRAY_SUPPORT) { + newBuf = this.subarray(start, end) + newBuf.__proto__ = Buffer.prototype + } else { + var sliceLen = end - start + newBuf = new Buffer(sliceLen, undefined) + for (var i = 0; i < sliceLen; ++i) { + newBuf[i] = this[i + start] + } + } + + return newBuf +} + +/* + * Need to make sure that buffer isn't trying to write out of bounds. + */ +function checkOffset (offset, ext, length) { + if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint') + if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length') +} + +Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) { + offset = offset | 0 + byteLength = byteLength | 0 + if (!noAssert) checkOffset(offset, byteLength, this.length) + + var val = this[offset] + var mul = 1 + var i = 0 + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul + } + + return val +} + +Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) { + offset = offset | 0 + byteLength = byteLength | 0 + if (!noAssert) { + checkOffset(offset, byteLength, this.length) + } + + var val = this[offset + --byteLength] + var mul = 1 + while (byteLength > 0 && (mul *= 0x100)) { + val += this[offset + --byteLength] * mul + } + + return val +} + +Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) { + if (!noAssert) checkOffset(offset, 1, this.length) + return this[offset] +} + +Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length) + return this[offset] | (this[offset + 1] << 8) +} + +Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length) + return (this[offset] << 8) | this[offset + 1] +} + +Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length) + + return ((this[offset]) | + (this[offset + 1] << 8) | + (this[offset + 2] << 16)) + + (this[offset + 3] * 0x1000000) +} + +Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length) + + return (this[offset] * 0x1000000) + + ((this[offset + 1] << 16) | + (this[offset + 2] << 8) | + this[offset + 3]) +} + +Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) { + offset = offset | 0 + byteLength = byteLength | 0 + if (!noAssert) checkOffset(offset, byteLength, this.length) + + var val = this[offset] + var mul = 1 + var i = 0 + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul + } + mul *= 0x80 + + if (val >= mul) val -= Math.pow(2, 8 * byteLength) + + return val +} + +Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) { + offset = offset | 0 + byteLength = byteLength | 0 + if (!noAssert) checkOffset(offset, byteLength, this.length) + + var i = byteLength + var mul = 1 + var val = this[offset + --i] + while (i > 0 && (mul *= 0x100)) { + val += this[offset + --i] * mul + } + mul *= 0x80 + + if (val >= mul) val -= Math.pow(2, 8 * byteLength) + + return val +} + +Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) { + if (!noAssert) checkOffset(offset, 1, this.length) + if (!(this[offset] & 0x80)) return (this[offset]) + return ((0xff - this[offset] + 1) * -1) +} + +Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length) + var val = this[offset] | (this[offset + 1] << 8) + return (val & 0x8000) ? val | 0xFFFF0000 : val +} + +Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length) + var val = this[offset + 1] | (this[offset] << 8) + return (val & 0x8000) ? val | 0xFFFF0000 : val +} + +Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length) + + return (this[offset]) | + (this[offset + 1] << 8) | + (this[offset + 2] << 16) | + (this[offset + 3] << 24) +} + +Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length) + + return (this[offset] << 24) | + (this[offset + 1] << 16) | + (this[offset + 2] << 8) | + (this[offset + 3]) +} + +Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length) + return ieee754.read(this, offset, true, 23, 4) +} + +Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length) + return ieee754.read(this, offset, false, 23, 4) +} + +Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 8, this.length) + return ieee754.read(this, offset, true, 52, 8) +} + +Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 8, this.length) + return ieee754.read(this, offset, false, 52, 8) +} + +function checkInt (buf, value, offset, ext, max, min) { + if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance') + if (value > max || value < min) throw new RangeError('"value" argument is out of bounds') + if (offset + ext > buf.length) throw new RangeError('Index out of range') +} + +Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) { + value = +value + offset = offset | 0 + byteLength = byteLength | 0 + if (!noAssert) { + var maxBytes = Math.pow(2, 8 * byteLength) - 1 + checkInt(this, value, offset, byteLength, maxBytes, 0) + } + + var mul = 1 + var i = 0 + this[offset] = value & 0xFF + while (++i < byteLength && (mul *= 0x100)) { + this[offset + i] = (value / mul) & 0xFF + } + + return offset + byteLength +} + +Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) { + value = +value + offset = offset | 0 + byteLength = byteLength | 0 + if (!noAssert) { + var maxBytes = Math.pow(2, 8 * byteLength) - 1 + checkInt(this, value, offset, byteLength, maxBytes, 0) + } + + var i = byteLength - 1 + var mul = 1 + this[offset + i] = value & 0xFF + while (--i >= 0 && (mul *= 0x100)) { + this[offset + i] = (value / mul) & 0xFF + } + + return offset + byteLength +} + +Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0) + if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value) + this[offset] = (value & 0xff) + return offset + 1 +} + +function objectWriteUInt16 (buf, value, offset, littleEndian) { + if (value < 0) value = 0xffff + value + 1 + for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; ++i) { + buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>> + (littleEndian ? i : 1 - i) * 8 + } +} + +Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value & 0xff) + this[offset + 1] = (value >>> 8) + } else { + objectWriteUInt16(this, value, offset, true) + } + return offset + 2 +} + +Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 8) + this[offset + 1] = (value & 0xff) + } else { + objectWriteUInt16(this, value, offset, false) + } + return offset + 2 +} + +function objectWriteUInt32 (buf, value, offset, littleEndian) { + if (value < 0) value = 0xffffffff + value + 1 + for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; ++i) { + buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff + } +} + +Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset + 3] = (value >>> 24) + this[offset + 2] = (value >>> 16) + this[offset + 1] = (value >>> 8) + this[offset] = (value & 0xff) + } else { + objectWriteUInt32(this, value, offset, true) + } + return offset + 4 +} + +Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 24) + this[offset + 1] = (value >>> 16) + this[offset + 2] = (value >>> 8) + this[offset + 3] = (value & 0xff) + } else { + objectWriteUInt32(this, value, offset, false) + } + return offset + 4 +} + +Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) { + var limit = Math.pow(2, 8 * byteLength - 1) + + checkInt(this, value, offset, byteLength, limit - 1, -limit) + } + + var i = 0 + var mul = 1 + var sub = 0 + this[offset] = value & 0xFF + while (++i < byteLength && (mul *= 0x100)) { + if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) { + sub = 1 + } + this[offset + i] = ((value / mul) >> 0) - sub & 0xFF + } + + return offset + byteLength +} + +Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) { + var limit = Math.pow(2, 8 * byteLength - 1) + + checkInt(this, value, offset, byteLength, limit - 1, -limit) + } + + var i = byteLength - 1 + var mul = 1 + var sub = 0 + this[offset + i] = value & 0xFF + while (--i >= 0 && (mul *= 0x100)) { + if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) { + sub = 1 + } + this[offset + i] = ((value / mul) >> 0) - sub & 0xFF + } + + return offset + byteLength +} + +Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80) + if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value) + if (value < 0) value = 0xff + value + 1 + this[offset] = (value & 0xff) + return offset + 1 +} + +Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value & 0xff) + this[offset + 1] = (value >>> 8) + } else { + objectWriteUInt16(this, value, offset, true) + } + return offset + 2 +} + +Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 8) + this[offset + 1] = (value & 0xff) + } else { + objectWriteUInt16(this, value, offset, false) + } + return offset + 2 +} + +Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value & 0xff) + this[offset + 1] = (value >>> 8) + this[offset + 2] = (value >>> 16) + this[offset + 3] = (value >>> 24) + } else { + objectWriteUInt32(this, value, offset, true) + } + return offset + 4 +} + +Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) + if (value < 0) value = 0xffffffff + value + 1 + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 24) + this[offset + 1] = (value >>> 16) + this[offset + 2] = (value >>> 8) + this[offset + 3] = (value & 0xff) + } else { + objectWriteUInt32(this, value, offset, false) + } + return offset + 4 +} + +function checkIEEE754 (buf, value, offset, ext, max, min) { + if (offset + ext > buf.length) throw new RangeError('Index out of range') + if (offset < 0) throw new RangeError('Index out of range') +} + +function writeFloat (buf, value, offset, littleEndian, noAssert) { + if (!noAssert) { + checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38) + } + ieee754.write(buf, value, offset, littleEndian, 23, 4) + return offset + 4 +} + +Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) { + return writeFloat(this, value, offset, true, noAssert) +} + +Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) { + return writeFloat(this, value, offset, false, noAssert) +} + +function writeDouble (buf, value, offset, littleEndian, noAssert) { + if (!noAssert) { + checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308) + } + ieee754.write(buf, value, offset, littleEndian, 52, 8) + return offset + 8 +} + +Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) { + return writeDouble(this, value, offset, true, noAssert) +} + +Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) { + return writeDouble(this, value, offset, false, noAssert) +} + +// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) +Buffer.prototype.copy = function copy (target, targetStart, start, end) { + if (!start) start = 0 + if (!end && end !== 0) end = this.length + if (targetStart >= target.length) targetStart = target.length + if (!targetStart) targetStart = 0 + if (end > 0 && end < start) end = start + + // Copy 0 bytes; we're done + if (end === start) return 0 + if (target.length === 0 || this.length === 0) return 0 + + // Fatal error conditions + if (targetStart < 0) { + throw new RangeError('targetStart out of bounds') + } + if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds') + if (end < 0) throw new RangeError('sourceEnd out of bounds') + + // Are we oob? + if (end > this.length) end = this.length + if (target.length - targetStart < end - start) { + end = target.length - targetStart + start + } + + var len = end - start + var i + + if (this === target && start < targetStart && targetStart < end) { + // descending copy from end + for (i = len - 1; i >= 0; --i) { + target[i + targetStart] = this[i + start] + } + } else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) { + // ascending copy from start + for (i = 0; i < len; ++i) { + target[i + targetStart] = this[i + start] + } + } else { + Uint8Array.prototype.set.call( + target, + this.subarray(start, start + len), + targetStart + ) + } + + return len +} + +// Usage: +// buffer.fill(number[, offset[, end]]) +// buffer.fill(buffer[, offset[, end]]) +// buffer.fill(string[, offset[, end]][, encoding]) +Buffer.prototype.fill = function fill (val, start, end, encoding) { + // Handle string cases: + if (typeof val === 'string') { + if (typeof start === 'string') { + encoding = start + start = 0 + end = this.length + } else if (typeof end === 'string') { + encoding = end + end = this.length + } + if (val.length === 1) { + var code = val.charCodeAt(0) + if (code < 256) { + val = code + } + } + if (encoding !== undefined && typeof encoding !== 'string') { + throw new TypeError('encoding must be a string') + } + if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) { + throw new TypeError('Unknown encoding: ' + encoding) + } + } else if (typeof val === 'number') { + val = val & 255 + } + + // Invalid ranges are not set to a default, so can range check early. + if (start < 0 || this.length < start || this.length < end) { + throw new RangeError('Out of range index') + } + + if (end <= start) { + return this + } + + start = start >>> 0 + end = end === undefined ? this.length : end >>> 0 + + if (!val) val = 0 + + var i + if (typeof val === 'number') { + for (i = start; i < end; ++i) { + this[i] = val + } + } else { + var bytes = Buffer.isBuffer(val) + ? val + : utf8ToBytes(new Buffer(val, encoding).toString()) + var len = bytes.length + for (i = 0; i < end - start; ++i) { + this[i + start] = bytes[i % len] + } + } + + return this +} + +// HELPER FUNCTIONS +// ================ + +var INVALID_BASE64_RE = /[^+\/0-9A-Za-z-_]/g + +function base64clean (str) { + // Node strips out invalid characters like \n and \t from the string, base64-js does not + str = stringtrim(str).replace(INVALID_BASE64_RE, '') + // Node converts strings with length < 2 to '' + if (str.length < 2) return '' + // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not + while (str.length % 4 !== 0) { + str = str + '=' + } + return str +} + +function stringtrim (str) { + if (str.trim) return str.trim() + return str.replace(/^\s+|\s+$/g, '') +} + +function toHex (n) { + if (n < 16) return '0' + n.toString(16) + return n.toString(16) +} + +function utf8ToBytes (string, units) { + units = units || Infinity + var codePoint + var length = string.length + var leadSurrogate = null + var bytes = [] + + for (var i = 0; i < length; ++i) { + codePoint = string.charCodeAt(i) + + // is surrogate component + if (codePoint > 0xD7FF && codePoint < 0xE000) { + // last char was a lead + if (!leadSurrogate) { + // no lead yet + if (codePoint > 0xDBFF) { + // unexpected trail + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) + continue + } else if (i + 1 === length) { + // unpaired lead + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) + continue + } + + // valid lead + leadSurrogate = codePoint + + continue + } + + // 2 leads in a row + if (codePoint < 0xDC00) { + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) + leadSurrogate = codePoint + continue + } + + // valid surrogate pair + codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000 + } else if (leadSurrogate) { + // valid bmp char, but last char was a lead + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) + } + + leadSurrogate = null + + // encode utf8 + if (codePoint < 0x80) { + if ((units -= 1) < 0) break + bytes.push(codePoint) + } else if (codePoint < 0x800) { + if ((units -= 2) < 0) break + bytes.push( + codePoint >> 0x6 | 0xC0, + codePoint & 0x3F | 0x80 + ) + } else if (codePoint < 0x10000) { + if ((units -= 3) < 0) break + bytes.push( + codePoint >> 0xC | 0xE0, + codePoint >> 0x6 & 0x3F | 0x80, + codePoint & 0x3F | 0x80 + ) + } else if (codePoint < 0x110000) { + if ((units -= 4) < 0) break + bytes.push( + codePoint >> 0x12 | 0xF0, + codePoint >> 0xC & 0x3F | 0x80, + codePoint >> 0x6 & 0x3F | 0x80, + codePoint & 0x3F | 0x80 + ) + } else { + throw new Error('Invalid code point') + } + } + + return bytes +} + +function asciiToBytes (str) { + var byteArray = [] + for (var i = 0; i < str.length; ++i) { + // Node's code seems to be doing this and not & 0x7F.. + byteArray.push(str.charCodeAt(i) & 0xFF) + } + return byteArray +} + +function utf16leToBytes (str, units) { + var c, hi, lo + var byteArray = [] + for (var i = 0; i < str.length; ++i) { + if ((units -= 2) < 0) break + + c = str.charCodeAt(i) + hi = c >> 8 + lo = c % 256 + byteArray.push(lo) + byteArray.push(hi) + } + + return byteArray +} + +function base64ToBytes (str) { + return base64.toByteArray(base64clean(str)) +} + +function blitBuffer (src, dst, offset, length) { + for (var i = 0; i < length; ++i) { + if ((i + offset >= dst.length) || (i >= src.length)) break + dst[i + offset] = src[i] + } + return i +} + +function isnan (val) { + return val !== val // eslint-disable-line no-self-compare +} + +/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../webpack/buildin/global.js */ "./node_modules/webpack/buildin/global.js"))) + +/***/ }), + +/***/ "./node_modules/builtin-status-codes/index.js": +/*!****************************************************!*\ + !*** ./node_modules/builtin-status-codes/index.js ***! + \****************************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +module.exports = __webpack_require__(/*! http */ "./node_modules/stream-http/index.js").STATUS_CODES + + +/***/ }), + +/***/ "./node_modules/call-bind/callBound.js": +/*!*********************************************!*\ + !*** ./node_modules/call-bind/callBound.js ***! + \*********************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +var GetIntrinsic = __webpack_require__(/*! get-intrinsic */ "./node_modules/get-intrinsic/index.js"); + +var callBind = __webpack_require__(/*! ./ */ "./node_modules/call-bind/index.js"); + +var $indexOf = callBind(GetIntrinsic('String.prototype.indexOf')); + +module.exports = function callBoundIntrinsic(name, allowMissing) { + var intrinsic = GetIntrinsic(name, !!allowMissing); + if (typeof intrinsic === 'function' && $indexOf(name, '.prototype.') > -1) { + return callBind(intrinsic); + } + return intrinsic; +}; + + +/***/ }), + +/***/ "./node_modules/call-bind/index.js": +/*!*****************************************!*\ + !*** ./node_modules/call-bind/index.js ***! + \*****************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +var bind = __webpack_require__(/*! function-bind */ "./node_modules/function-bind/index.js"); +var GetIntrinsic = __webpack_require__(/*! get-intrinsic */ "./node_modules/get-intrinsic/index.js"); +var setFunctionLength = __webpack_require__(/*! set-function-length */ "./node_modules/set-function-length/index.js"); + +var $TypeError = __webpack_require__(/*! es-errors/type */ "./node_modules/es-errors/type.js"); +var $apply = GetIntrinsic('%Function.prototype.apply%'); +var $call = GetIntrinsic('%Function.prototype.call%'); +var $reflectApply = GetIntrinsic('%Reflect.apply%', true) || bind.call($call, $apply); + +var $defineProperty = __webpack_require__(/*! es-define-property */ "./node_modules/es-define-property/index.js"); +var $max = GetIntrinsic('%Math.max%'); + +module.exports = function callBind(originalFunction) { + if (typeof originalFunction !== 'function') { + throw new $TypeError('a function is required'); + } + var func = $reflectApply(bind, $call, arguments); + return setFunctionLength( + func, + 1 + $max(0, originalFunction.length - (arguments.length - 1)), + true + ); +}; + +var applyBind = function applyBind() { + return $reflectApply(bind, $apply, arguments); +}; + +if ($defineProperty) { + $defineProperty(module.exports, 'apply', { value: applyBind }); +} else { + module.exports.apply = applyBind; +} + + +/***/ }), + +/***/ "./node_modules/call-me-maybe/src/maybe.js": +/*!*************************************************!*\ + !*** ./node_modules/call-me-maybe/src/maybe.js ***! + \*************************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +var next = __webpack_require__(/*! ./next.js */ "./node_modules/call-me-maybe/src/next.js") + +module.exports = function maybe (cb, promise) { + if (cb) { + promise + .then(function (result) { + next(function () { cb(null, result) }) + }, function (err) { + next(function () { cb(err) }) + }) + return undefined + } + else { + return promise + } +} + + +/***/ }), + +/***/ "./node_modules/call-me-maybe/src/next.js": +/*!************************************************!*\ + !*** ./node_modules/call-me-maybe/src/next.js ***! + \************************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/* WEBPACK VAR INJECTION */(function(process, setImmediate) { + +function makeNext () { + if (typeof process === 'object' && typeof process.nextTick === 'function') { + return process.nextTick + } else if (typeof setImmediate === 'function') { + return setImmediate + } else { + return function next (f) { + setTimeout(f, 0) + } + } +} + +module.exports = makeNext() + +/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../../process/browser.js */ "./node_modules/process/browser.js"), __webpack_require__(/*! ./../../timers-browserify/main.js */ "./node_modules/timers-browserify/main.js").setImmediate)) + +/***/ }), + +/***/ "./node_modules/color-name/index.js": +/*!******************************************!*\ + !*** ./node_modules/color-name/index.js ***! + \******************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +module.exports = { + "aliceblue": [240, 248, 255], + "antiquewhite": [250, 235, 215], + "aqua": [0, 255, 255], + "aquamarine": [127, 255, 212], + "azure": [240, 255, 255], + "beige": [245, 245, 220], + "bisque": [255, 228, 196], + "black": [0, 0, 0], + "blanchedalmond": [255, 235, 205], + "blue": [0, 0, 255], + "blueviolet": [138, 43, 226], + "brown": [165, 42, 42], + "burlywood": [222, 184, 135], + "cadetblue": [95, 158, 160], + "chartreuse": [127, 255, 0], + "chocolate": [210, 105, 30], + "coral": [255, 127, 80], + "cornflowerblue": [100, 149, 237], + "cornsilk": [255, 248, 220], + "crimson": [220, 20, 60], + "cyan": [0, 255, 255], + "darkblue": [0, 0, 139], + "darkcyan": [0, 139, 139], + "darkgoldenrod": [184, 134, 11], + "darkgray": [169, 169, 169], + "darkgreen": [0, 100, 0], + "darkgrey": [169, 169, 169], + "darkkhaki": [189, 183, 107], + "darkmagenta": [139, 0, 139], + "darkolivegreen": [85, 107, 47], + "darkorange": [255, 140, 0], + "darkorchid": [153, 50, 204], + "darkred": [139, 0, 0], + "darksalmon": [233, 150, 122], + "darkseagreen": [143, 188, 143], + "darkslateblue": [72, 61, 139], + "darkslategray": [47, 79, 79], + "darkslategrey": [47, 79, 79], + "darkturquoise": [0, 206, 209], + "darkviolet": [148, 0, 211], + "deeppink": [255, 20, 147], + "deepskyblue": [0, 191, 255], + "dimgray": [105, 105, 105], + "dimgrey": [105, 105, 105], + "dodgerblue": [30, 144, 255], + "firebrick": [178, 34, 34], + "floralwhite": [255, 250, 240], + "forestgreen": [34, 139, 34], + "fuchsia": [255, 0, 255], + "gainsboro": [220, 220, 220], + "ghostwhite": [248, 248, 255], + "gold": [255, 215, 0], + "goldenrod": [218, 165, 32], + "gray": [128, 128, 128], + "green": [0, 128, 0], + "greenyellow": [173, 255, 47], + "grey": [128, 128, 128], + "honeydew": [240, 255, 240], + "hotpink": [255, 105, 180], + "indianred": [205, 92, 92], + "indigo": [75, 0, 130], + "ivory": [255, 255, 240], + "khaki": [240, 230, 140], + "lavender": [230, 230, 250], + "lavenderblush": [255, 240, 245], + "lawngreen": [124, 252, 0], + "lemonchiffon": [255, 250, 205], + "lightblue": [173, 216, 230], + "lightcoral": [240, 128, 128], + "lightcyan": [224, 255, 255], + "lightgoldenrodyellow": [250, 250, 210], + "lightgray": [211, 211, 211], + "lightgreen": [144, 238, 144], + "lightgrey": [211, 211, 211], + "lightpink": [255, 182, 193], + "lightsalmon": [255, 160, 122], + "lightseagreen": [32, 178, 170], + "lightskyblue": [135, 206, 250], + "lightslategray": [119, 136, 153], + "lightslategrey": [119, 136, 153], + "lightsteelblue": [176, 196, 222], + "lightyellow": [255, 255, 224], + "lime": [0, 255, 0], + "limegreen": [50, 205, 50], + "linen": [250, 240, 230], + "magenta": [255, 0, 255], + "maroon": [128, 0, 0], + "mediumaquamarine": [102, 205, 170], + "mediumblue": [0, 0, 205], + "mediumorchid": [186, 85, 211], + "mediumpurple": [147, 112, 219], + "mediumseagreen": [60, 179, 113], + "mediumslateblue": [123, 104, 238], + "mediumspringgreen": [0, 250, 154], + "mediumturquoise": [72, 209, 204], + "mediumvioletred": [199, 21, 133], + "midnightblue": [25, 25, 112], + "mintcream": [245, 255, 250], + "mistyrose": [255, 228, 225], + "moccasin": [255, 228, 181], + "navajowhite": [255, 222, 173], + "navy": [0, 0, 128], + "oldlace": [253, 245, 230], + "olive": [128, 128, 0], + "olivedrab": [107, 142, 35], + "orange": [255, 165, 0], + "orangered": [255, 69, 0], + "orchid": [218, 112, 214], + "palegoldenrod": [238, 232, 170], + "palegreen": [152, 251, 152], + "paleturquoise": [175, 238, 238], + "palevioletred": [219, 112, 147], + "papayawhip": [255, 239, 213], + "peachpuff": [255, 218, 185], + "peru": [205, 133, 63], + "pink": [255, 192, 203], + "plum": [221, 160, 221], + "powderblue": [176, 224, 230], + "purple": [128, 0, 128], + "rebeccapurple": [102, 51, 153], + "red": [255, 0, 0], + "rosybrown": [188, 143, 143], + "royalblue": [65, 105, 225], + "saddlebrown": [139, 69, 19], + "salmon": [250, 128, 114], + "sandybrown": [244, 164, 96], + "seagreen": [46, 139, 87], + "seashell": [255, 245, 238], + "sienna": [160, 82, 45], + "silver": [192, 192, 192], + "skyblue": [135, 206, 235], + "slateblue": [106, 90, 205], + "slategray": [112, 128, 144], + "slategrey": [112, 128, 144], + "snow": [255, 250, 250], + "springgreen": [0, 255, 127], + "steelblue": [70, 130, 180], + "tan": [210, 180, 140], + "teal": [0, 128, 128], + "thistle": [216, 191, 216], + "tomato": [255, 99, 71], + "turquoise": [64, 224, 208], + "violet": [238, 130, 238], + "wheat": [245, 222, 179], + "white": [255, 255, 255], + "whitesmoke": [245, 245, 245], + "yellow": [255, 255, 0], + "yellowgreen": [154, 205, 50] +}; + + +/***/ }), + +/***/ "./node_modules/color-string/index.js": +/*!********************************************!*\ + !*** ./node_modules/color-string/index.js ***! + \********************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +/* MIT license */ +var colorNames = __webpack_require__(/*! color-name */ "./node_modules/color-name/index.js"); +var swizzle = __webpack_require__(/*! simple-swizzle */ "./node_modules/simple-swizzle/index.js"); +var hasOwnProperty = Object.hasOwnProperty; + +var reverseNames = Object.create(null); + +// create a list of reverse color names +for (var name in colorNames) { + if (hasOwnProperty.call(colorNames, name)) { + reverseNames[colorNames[name]] = name; + } +} + +var cs = module.exports = { + to: {}, + get: {} +}; + +cs.get = function (string) { + var prefix = string.substring(0, 3).toLowerCase(); + var val; + var model; + switch (prefix) { + case 'hsl': + val = cs.get.hsl(string); + model = 'hsl'; + break; + case 'hwb': + val = cs.get.hwb(string); + model = 'hwb'; + break; + default: + val = cs.get.rgb(string); + model = 'rgb'; + break; + } + + if (!val) { + return null; + } + + return {model: model, value: val}; +}; + +cs.get.rgb = function (string) { + if (!string) { + return null; + } + + var abbr = /^#([a-f0-9]{3,4})$/i; + var hex = /^#([a-f0-9]{6})([a-f0-9]{2})?$/i; + var rgba = /^rgba?\(\s*([+-]?\d+)(?=[\s,])\s*(?:,\s*)?([+-]?\d+)(?=[\s,])\s*(?:,\s*)?([+-]?\d+)\s*(?:[,|\/]\s*([+-]?[\d\.]+)(%?)\s*)?\)$/; + var per = /^rgba?\(\s*([+-]?[\d\.]+)\%\s*,?\s*([+-]?[\d\.]+)\%\s*,?\s*([+-]?[\d\.]+)\%\s*(?:[,|\/]\s*([+-]?[\d\.]+)(%?)\s*)?\)$/; + var keyword = /^(\w+)$/; + + var rgb = [0, 0, 0, 1]; + var match; + var i; + var hexAlpha; + + if (match = string.match(hex)) { + hexAlpha = match[2]; + match = match[1]; + + for (i = 0; i < 3; i++) { + // https://jsperf.com/slice-vs-substr-vs-substring-methods-long-string/19 + var i2 = i * 2; + rgb[i] = parseInt(match.slice(i2, i2 + 2), 16); + } + + if (hexAlpha) { + rgb[3] = parseInt(hexAlpha, 16) / 255; + } + } else if (match = string.match(abbr)) { + match = match[1]; + hexAlpha = match[3]; + + for (i = 0; i < 3; i++) { + rgb[i] = parseInt(match[i] + match[i], 16); + } + + if (hexAlpha) { + rgb[3] = parseInt(hexAlpha + hexAlpha, 16) / 255; + } + } else if (match = string.match(rgba)) { + for (i = 0; i < 3; i++) { + rgb[i] = parseInt(match[i + 1], 0); + } + + if (match[4]) { + if (match[5]) { + rgb[3] = parseFloat(match[4]) * 0.01; + } else { + rgb[3] = parseFloat(match[4]); + } + } + } else if (match = string.match(per)) { + for (i = 0; i < 3; i++) { + rgb[i] = Math.round(parseFloat(match[i + 1]) * 2.55); + } + + if (match[4]) { + if (match[5]) { + rgb[3] = parseFloat(match[4]) * 0.01; + } else { + rgb[3] = parseFloat(match[4]); + } + } + } else if (match = string.match(keyword)) { + if (match[1] === 'transparent') { + return [0, 0, 0, 0]; + } + + if (!hasOwnProperty.call(colorNames, match[1])) { + return null; + } + + rgb = colorNames[match[1]]; + rgb[3] = 1; + + return rgb; + } else { + return null; + } + + for (i = 0; i < 3; i++) { + rgb[i] = clamp(rgb[i], 0, 255); + } + rgb[3] = clamp(rgb[3], 0, 1); + + return rgb; +}; + +cs.get.hsl = function (string) { + if (!string) { + return null; + } + + var hsl = /^hsla?\(\s*([+-]?(?:\d{0,3}\.)?\d+)(?:deg)?\s*,?\s*([+-]?[\d\.]+)%\s*,?\s*([+-]?[\d\.]+)%\s*(?:[,|\/]\s*([+-]?(?=\.\d|\d)(?:0|[1-9]\d*)?(?:\.\d*)?(?:[eE][+-]?\d+)?)\s*)?\)$/; + var match = string.match(hsl); + + if (match) { + var alpha = parseFloat(match[4]); + var h = ((parseFloat(match[1]) % 360) + 360) % 360; + var s = clamp(parseFloat(match[2]), 0, 100); + var l = clamp(parseFloat(match[3]), 0, 100); + var a = clamp(isNaN(alpha) ? 1 : alpha, 0, 1); + + return [h, s, l, a]; + } + + return null; +}; + +cs.get.hwb = function (string) { + if (!string) { + return null; + } + + var hwb = /^hwb\(\s*([+-]?\d{0,3}(?:\.\d+)?)(?:deg)?\s*,\s*([+-]?[\d\.]+)%\s*,\s*([+-]?[\d\.]+)%\s*(?:,\s*([+-]?(?=\.\d|\d)(?:0|[1-9]\d*)?(?:\.\d*)?(?:[eE][+-]?\d+)?)\s*)?\)$/; + var match = string.match(hwb); + + if (match) { + var alpha = parseFloat(match[4]); + var h = ((parseFloat(match[1]) % 360) + 360) % 360; + var w = clamp(parseFloat(match[2]), 0, 100); + var b = clamp(parseFloat(match[3]), 0, 100); + var a = clamp(isNaN(alpha) ? 1 : alpha, 0, 1); + return [h, w, b, a]; + } + + return null; +}; + +cs.to.hex = function () { + var rgba = swizzle(arguments); + + return ( + '#' + + hexDouble(rgba[0]) + + hexDouble(rgba[1]) + + hexDouble(rgba[2]) + + (rgba[3] < 1 + ? (hexDouble(Math.round(rgba[3] * 255))) + : '') + ); +}; + +cs.to.rgb = function () { + var rgba = swizzle(arguments); + + return rgba.length < 4 || rgba[3] === 1 + ? 'rgb(' + Math.round(rgba[0]) + ', ' + Math.round(rgba[1]) + ', ' + Math.round(rgba[2]) + ')' + : 'rgba(' + Math.round(rgba[0]) + ', ' + Math.round(rgba[1]) + ', ' + Math.round(rgba[2]) + ', ' + rgba[3] + ')'; +}; + +cs.to.rgb.percent = function () { + var rgba = swizzle(arguments); + + var r = Math.round(rgba[0] / 255 * 100); + var g = Math.round(rgba[1] / 255 * 100); + var b = Math.round(rgba[2] / 255 * 100); + + return rgba.length < 4 || rgba[3] === 1 + ? 'rgb(' + r + '%, ' + g + '%, ' + b + '%)' + : 'rgba(' + r + '%, ' + g + '%, ' + b + '%, ' + rgba[3] + ')'; +}; + +cs.to.hsl = function () { + var hsla = swizzle(arguments); + return hsla.length < 4 || hsla[3] === 1 + ? 'hsl(' + hsla[0] + ', ' + hsla[1] + '%, ' + hsla[2] + '%)' + : 'hsla(' + hsla[0] + ', ' + hsla[1] + '%, ' + hsla[2] + '%, ' + hsla[3] + ')'; +}; + +// hwb is a bit different than rgb(a) & hsl(a) since there is no alpha specific syntax +// (hwb have alpha optional & 1 is default value) +cs.to.hwb = function () { + var hwba = swizzle(arguments); + + var a = ''; + if (hwba.length >= 4 && hwba[3] !== 1) { + a = ', ' + hwba[3]; + } + + return 'hwb(' + hwba[0] + ', ' + hwba[1] + '%, ' + hwba[2] + '%' + a + ')'; +}; + +cs.to.keyword = function (rgb) { + return reverseNames[rgb.slice(0, 3)]; +}; + +// helpers +function clamp(num, min, max) { + return Math.min(Math.max(min, num), max); +} + +function hexDouble(num) { + var str = Math.round(num).toString(16).toUpperCase(); + return (str.length < 2) ? '0' + str : str; +} + + +/***/ }), + +/***/ "./node_modules/color/index.js": +/*!*************************************!*\ + !*** ./node_modules/color/index.js ***! + \*************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +var colorString = __webpack_require__(/*! color-string */ "./node_modules/color-string/index.js"); +var convert = __webpack_require__(/*! color-convert */ "./node_modules/color/node_modules/color-convert/index.js"); + +var _slice = [].slice; + +var skippedModels = [ + // to be honest, I don't really feel like keyword belongs in color convert, but eh. + 'keyword', + + // gray conflicts with some method names, and has its own method defined. + 'gray', + + // shouldn't really be in color-convert either... + 'hex' +]; + +var hashedModelKeys = {}; +Object.keys(convert).forEach(function (model) { + hashedModelKeys[_slice.call(convert[model].labels).sort().join('')] = model; +}); + +var limiters = {}; + +function Color(obj, model) { + if (!(this instanceof Color)) { + return new Color(obj, model); + } + + if (model && model in skippedModels) { + model = null; + } + + if (model && !(model in convert)) { + throw new Error('Unknown model: ' + model); + } + + var i; + var channels; + + if (obj == null) { // eslint-disable-line no-eq-null,eqeqeq + this.model = 'rgb'; + this.color = [0, 0, 0]; + this.valpha = 1; + } else if (obj instanceof Color) { + this.model = obj.model; + this.color = obj.color.slice(); + this.valpha = obj.valpha; + } else if (typeof obj === 'string') { + var result = colorString.get(obj); + if (result === null) { + throw new Error('Unable to parse color from string: ' + obj); + } + + this.model = result.model; + channels = convert[this.model].channels; + this.color = result.value.slice(0, channels); + this.valpha = typeof result.value[channels] === 'number' ? result.value[channels] : 1; + } else if (obj.length) { + this.model = model || 'rgb'; + channels = convert[this.model].channels; + var newArr = _slice.call(obj, 0, channels); + this.color = zeroArray(newArr, channels); + this.valpha = typeof obj[channels] === 'number' ? obj[channels] : 1; + } else if (typeof obj === 'number') { + // this is always RGB - can be converted later on. + obj &= 0xFFFFFF; + this.model = 'rgb'; + this.color = [ + (obj >> 16) & 0xFF, + (obj >> 8) & 0xFF, + obj & 0xFF + ]; + this.valpha = 1; + } else { + this.valpha = 1; + + var keys = Object.keys(obj); + if ('alpha' in obj) { + keys.splice(keys.indexOf('alpha'), 1); + this.valpha = typeof obj.alpha === 'number' ? obj.alpha : 0; + } + + var hashedKeys = keys.sort().join(''); + if (!(hashedKeys in hashedModelKeys)) { + throw new Error('Unable to parse color from object: ' + JSON.stringify(obj)); + } + + this.model = hashedModelKeys[hashedKeys]; + + var labels = convert[this.model].labels; + var color = []; + for (i = 0; i < labels.length; i++) { + color.push(obj[labels[i]]); + } + + this.color = zeroArray(color); + } + + // perform limitations (clamping, etc.) + if (limiters[this.model]) { + channels = convert[this.model].channels; + for (i = 0; i < channels; i++) { + var limit = limiters[this.model][i]; + if (limit) { + this.color[i] = limit(this.color[i]); + } + } + } + + this.valpha = Math.max(0, Math.min(1, this.valpha)); + + if (Object.freeze) { + Object.freeze(this); + } +} + +Color.prototype = { + toString: function () { + return this.string(); + }, + + toJSON: function () { + return this[this.model](); + }, + + string: function (places) { + var self = this.model in colorString.to ? this : this.rgb(); + self = self.round(typeof places === 'number' ? places : 1); + var args = self.valpha === 1 ? self.color : self.color.concat(this.valpha); + return colorString.to[self.model](args); + }, + + percentString: function (places) { + var self = this.rgb().round(typeof places === 'number' ? places : 1); + var args = self.valpha === 1 ? self.color : self.color.concat(this.valpha); + return colorString.to.rgb.percent(args); + }, + + array: function () { + return this.valpha === 1 ? this.color.slice() : this.color.concat(this.valpha); + }, + + object: function () { + var result = {}; + var channels = convert[this.model].channels; + var labels = convert[this.model].labels; + + for (var i = 0; i < channels; i++) { + result[labels[i]] = this.color[i]; + } + + if (this.valpha !== 1) { + result.alpha = this.valpha; + } + + return result; + }, + + unitArray: function () { + var rgb = this.rgb().color; + rgb[0] /= 255; + rgb[1] /= 255; + rgb[2] /= 255; + + if (this.valpha !== 1) { + rgb.push(this.valpha); + } + + return rgb; + }, + + unitObject: function () { + var rgb = this.rgb().object(); + rgb.r /= 255; + rgb.g /= 255; + rgb.b /= 255; + + if (this.valpha !== 1) { + rgb.alpha = this.valpha; + } + + return rgb; + }, + + round: function (places) { + places = Math.max(places || 0, 0); + return new Color(this.color.map(roundToPlace(places)).concat(this.valpha), this.model); + }, + + alpha: function (val) { + if (arguments.length) { + return new Color(this.color.concat(Math.max(0, Math.min(1, val))), this.model); + } + + return this.valpha; + }, + + // rgb + red: getset('rgb', 0, maxfn(255)), + green: getset('rgb', 1, maxfn(255)), + blue: getset('rgb', 2, maxfn(255)), + + hue: getset(['hsl', 'hsv', 'hsl', 'hwb', 'hcg'], 0, function (val) { return ((val % 360) + 360) % 360; }), // eslint-disable-line brace-style + + saturationl: getset('hsl', 1, maxfn(100)), + lightness: getset('hsl', 2, maxfn(100)), + + saturationv: getset('hsv', 1, maxfn(100)), + value: getset('hsv', 2, maxfn(100)), + + chroma: getset('hcg', 1, maxfn(100)), + gray: getset('hcg', 2, maxfn(100)), + + white: getset('hwb', 1, maxfn(100)), + wblack: getset('hwb', 2, maxfn(100)), + + cyan: getset('cmyk', 0, maxfn(100)), + magenta: getset('cmyk', 1, maxfn(100)), + yellow: getset('cmyk', 2, maxfn(100)), + black: getset('cmyk', 3, maxfn(100)), + + x: getset('xyz', 0, maxfn(100)), + y: getset('xyz', 1, maxfn(100)), + z: getset('xyz', 2, maxfn(100)), + + l: getset('lab', 0, maxfn(100)), + a: getset('lab', 1), + b: getset('lab', 2), + + keyword: function (val) { + if (arguments.length) { + return new Color(val); + } + + return convert[this.model].keyword(this.color); + }, + + hex: function (val) { + if (arguments.length) { + return new Color(val); + } + + return colorString.to.hex(this.rgb().round().color); + }, + + rgbNumber: function () { + var rgb = this.rgb().color; + return ((rgb[0] & 0xFF) << 16) | ((rgb[1] & 0xFF) << 8) | (rgb[2] & 0xFF); + }, + + luminosity: function () { + // http://www.w3.org/TR/WCAG20/#relativeluminancedef + var rgb = this.rgb().color; + + var lum = []; + for (var i = 0; i < rgb.length; i++) { + var chan = rgb[i] / 255; + lum[i] = (chan <= 0.03928) ? chan / 12.92 : Math.pow(((chan + 0.055) / 1.055), 2.4); + } + + return 0.2126 * lum[0] + 0.7152 * lum[1] + 0.0722 * lum[2]; + }, + + contrast: function (color2) { + // http://www.w3.org/TR/WCAG20/#contrast-ratiodef + var lum1 = this.luminosity(); + var lum2 = color2.luminosity(); + + if (lum1 > lum2) { + return (lum1 + 0.05) / (lum2 + 0.05); + } + + return (lum2 + 0.05) / (lum1 + 0.05); + }, + + level: function (color2) { + var contrastRatio = this.contrast(color2); + if (contrastRatio >= 7.1) { + return 'AAA'; + } + + return (contrastRatio >= 4.5) ? 'AA' : ''; + }, + + isDark: function () { + // YIQ equation from http://24ways.org/2010/calculating-color-contrast + var rgb = this.rgb().color; + var yiq = (rgb[0] * 299 + rgb[1] * 587 + rgb[2] * 114) / 1000; + return yiq < 128; + }, + + isLight: function () { + return !this.isDark(); + }, + + negate: function () { + var rgb = this.rgb(); + for (var i = 0; i < 3; i++) { + rgb.color[i] = 255 - rgb.color[i]; + } + return rgb; + }, + + lighten: function (ratio) { + var hsl = this.hsl(); + hsl.color[2] += hsl.color[2] * ratio; + return hsl; + }, + + darken: function (ratio) { + var hsl = this.hsl(); + hsl.color[2] -= hsl.color[2] * ratio; + return hsl; + }, + + saturate: function (ratio) { + var hsl = this.hsl(); + hsl.color[1] += hsl.color[1] * ratio; + return hsl; + }, + + desaturate: function (ratio) { + var hsl = this.hsl(); + hsl.color[1] -= hsl.color[1] * ratio; + return hsl; + }, + + whiten: function (ratio) { + var hwb = this.hwb(); + hwb.color[1] += hwb.color[1] * ratio; + return hwb; + }, + + blacken: function (ratio) { + var hwb = this.hwb(); + hwb.color[2] += hwb.color[2] * ratio; + return hwb; + }, + + grayscale: function () { + // http://en.wikipedia.org/wiki/Grayscale#Converting_color_to_grayscale + var rgb = this.rgb().color; + var val = rgb[0] * 0.3 + rgb[1] * 0.59 + rgb[2] * 0.11; + return Color.rgb(val, val, val); + }, + + fade: function (ratio) { + return this.alpha(this.valpha - (this.valpha * ratio)); + }, + + opaquer: function (ratio) { + return this.alpha(this.valpha + (this.valpha * ratio)); + }, + + rotate: function (degrees) { + var hsl = this.hsl(); + var hue = hsl.color[0]; + hue = (hue + degrees) % 360; + hue = hue < 0 ? 360 + hue : hue; + hsl.color[0] = hue; + return hsl; + }, + + mix: function (mixinColor, weight) { + // ported from sass implementation in C + // https://github.com/sass/libsass/blob/0e6b4a2850092356aa3ece07c6b249f0221caced/functions.cpp#L209 + if (!mixinColor || !mixinColor.rgb) { + throw new Error('Argument to "mix" was not a Color instance, but rather an instance of ' + typeof mixinColor); + } + var color1 = mixinColor.rgb(); + var color2 = this.rgb(); + var p = weight === undefined ? 0.5 : weight; + + var w = 2 * p - 1; + var a = color1.alpha() - color2.alpha(); + + var w1 = (((w * a === -1) ? w : (w + a) / (1 + w * a)) + 1) / 2.0; + var w2 = 1 - w1; + + return Color.rgb( + w1 * color1.red() + w2 * color2.red(), + w1 * color1.green() + w2 * color2.green(), + w1 * color1.blue() + w2 * color2.blue(), + color1.alpha() * p + color2.alpha() * (1 - p)); + } +}; + +// model conversion methods and static constructors +Object.keys(convert).forEach(function (model) { + if (skippedModels.indexOf(model) !== -1) { + return; + } + + var channels = convert[model].channels; + + // conversion methods + Color.prototype[model] = function () { + if (this.model === model) { + return new Color(this); + } + + if (arguments.length) { + return new Color(arguments, model); + } + + var newAlpha = typeof arguments[channels] === 'number' ? channels : this.valpha; + return new Color(assertArray(convert[this.model][model].raw(this.color)).concat(newAlpha), model); + }; + + // 'static' construction methods + Color[model] = function (color) { + if (typeof color === 'number') { + color = zeroArray(_slice.call(arguments), channels); + } + return new Color(color, model); + }; +}); + +function roundTo(num, places) { + return Number(num.toFixed(places)); +} + +function roundToPlace(places) { + return function (num) { + return roundTo(num, places); + }; +} + +function getset(model, channel, modifier) { + model = Array.isArray(model) ? model : [model]; + + model.forEach(function (m) { + (limiters[m] || (limiters[m] = []))[channel] = modifier; + }); + + model = model[0]; + + return function (val) { + var result; + + if (arguments.length) { + if (modifier) { + val = modifier(val); + } + + result = this[model](); + result.color[channel] = val; + return result; + } + + result = this[model]().color[channel]; + if (modifier) { + result = modifier(result); + } + + return result; + }; +} + +function maxfn(max) { + return function (v) { + return Math.max(0, Math.min(max, v)); + }; +} + +function assertArray(val) { + return Array.isArray(val) ? val : [val]; +} + +function zeroArray(arr, length) { + for (var i = 0; i < length; i++) { + if (typeof arr[i] !== 'number') { + arr[i] = 0; + } + } + + return arr; +} + +module.exports = Color; + + +/***/ }), + +/***/ "./node_modules/color/node_modules/color-convert/conversions.js": +/*!**********************************************************************!*\ + !*** ./node_modules/color/node_modules/color-convert/conversions.js ***! + \**********************************************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +/* MIT license */ +var cssKeywords = __webpack_require__(/*! color-name */ "./node_modules/color/node_modules/color-name/index.js"); + +// NOTE: conversions should only return primitive values (i.e. arrays, or +// values that give correct `typeof` results). +// do not use box values types (i.e. Number(), String(), etc.) + +var reverseKeywords = {}; +for (var key in cssKeywords) { + if (cssKeywords.hasOwnProperty(key)) { + reverseKeywords[cssKeywords[key]] = key; + } +} + +var convert = module.exports = { + rgb: {channels: 3, labels: 'rgb'}, + hsl: {channels: 3, labels: 'hsl'}, + hsv: {channels: 3, labels: 'hsv'}, + hwb: {channels: 3, labels: 'hwb'}, + cmyk: {channels: 4, labels: 'cmyk'}, + xyz: {channels: 3, labels: 'xyz'}, + lab: {channels: 3, labels: 'lab'}, + lch: {channels: 3, labels: 'lch'}, + hex: {channels: 1, labels: ['hex']}, + keyword: {channels: 1, labels: ['keyword']}, + ansi16: {channels: 1, labels: ['ansi16']}, + ansi256: {channels: 1, labels: ['ansi256']}, + hcg: {channels: 3, labels: ['h', 'c', 'g']}, + apple: {channels: 3, labels: ['r16', 'g16', 'b16']}, + gray: {channels: 1, labels: ['gray']} +}; + +// hide .channels and .labels properties +for (var model in convert) { + if (convert.hasOwnProperty(model)) { + if (!('channels' in convert[model])) { + throw new Error('missing channels property: ' + model); + } + + if (!('labels' in convert[model])) { + throw new Error('missing channel labels property: ' + model); + } + + if (convert[model].labels.length !== convert[model].channels) { + throw new Error('channel and label counts mismatch: ' + model); + } + + var channels = convert[model].channels; + var labels = convert[model].labels; + delete convert[model].channels; + delete convert[model].labels; + Object.defineProperty(convert[model], 'channels', {value: channels}); + Object.defineProperty(convert[model], 'labels', {value: labels}); + } +} + +convert.rgb.hsl = function (rgb) { + var r = rgb[0] / 255; + var g = rgb[1] / 255; + var b = rgb[2] / 255; + var min = Math.min(r, g, b); + var max = Math.max(r, g, b); + var delta = max - min; + var h; + var s; + var l; + + if (max === min) { + h = 0; + } else if (r === max) { + h = (g - b) / delta; + } else if (g === max) { + h = 2 + (b - r) / delta; + } else if (b === max) { + h = 4 + (r - g) / delta; + } + + h = Math.min(h * 60, 360); + + if (h < 0) { + h += 360; + } + + l = (min + max) / 2; + + if (max === min) { + s = 0; + } else if (l <= 0.5) { + s = delta / (max + min); + } else { + s = delta / (2 - max - min); + } + + return [h, s * 100, l * 100]; +}; + +convert.rgb.hsv = function (rgb) { + var rdif; + var gdif; + var bdif; + var h; + var s; + + var r = rgb[0] / 255; + var g = rgb[1] / 255; + var b = rgb[2] / 255; + var v = Math.max(r, g, b); + var diff = v - Math.min(r, g, b); + var diffc = function (c) { + return (v - c) / 6 / diff + 1 / 2; + }; + + if (diff === 0) { + h = s = 0; + } else { + s = diff / v; + rdif = diffc(r); + gdif = diffc(g); + bdif = diffc(b); + + if (r === v) { + h = bdif - gdif; + } else if (g === v) { + h = (1 / 3) + rdif - bdif; + } else if (b === v) { + h = (2 / 3) + gdif - rdif; + } + if (h < 0) { + h += 1; + } else if (h > 1) { + h -= 1; + } + } + + return [ + h * 360, + s * 100, + v * 100 + ]; +}; + +convert.rgb.hwb = function (rgb) { + var r = rgb[0]; + var g = rgb[1]; + var b = rgb[2]; + var h = convert.rgb.hsl(rgb)[0]; + var w = 1 / 255 * Math.min(r, Math.min(g, b)); + + b = 1 - 1 / 255 * Math.max(r, Math.max(g, b)); + + return [h, w * 100, b * 100]; +}; + +convert.rgb.cmyk = function (rgb) { + var r = rgb[0] / 255; + var g = rgb[1] / 255; + var b = rgb[2] / 255; + var c; + var m; + var y; + var k; + + k = Math.min(1 - r, 1 - g, 1 - b); + c = (1 - r - k) / (1 - k) || 0; + m = (1 - g - k) / (1 - k) || 0; + y = (1 - b - k) / (1 - k) || 0; + + return [c * 100, m * 100, y * 100, k * 100]; +}; + +/** + * See https://en.m.wikipedia.org/wiki/Euclidean_distance#Squared_Euclidean_distance + * */ +function comparativeDistance(x, y) { + return ( + Math.pow(x[0] - y[0], 2) + + Math.pow(x[1] - y[1], 2) + + Math.pow(x[2] - y[2], 2) + ); +} + +convert.rgb.keyword = function (rgb) { + var reversed = reverseKeywords[rgb]; + if (reversed) { + return reversed; + } + + var currentClosestDistance = Infinity; + var currentClosestKeyword; + + for (var keyword in cssKeywords) { + if (cssKeywords.hasOwnProperty(keyword)) { + var value = cssKeywords[keyword]; + + // Compute comparative distance + var distance = comparativeDistance(rgb, value); + + // Check if its less, if so set as closest + if (distance < currentClosestDistance) { + currentClosestDistance = distance; + currentClosestKeyword = keyword; + } + } + } + + return currentClosestKeyword; +}; + +convert.keyword.rgb = function (keyword) { + return cssKeywords[keyword]; +}; + +convert.rgb.xyz = function (rgb) { + var r = rgb[0] / 255; + var g = rgb[1] / 255; + var b = rgb[2] / 255; + + // assume sRGB + r = r > 0.04045 ? Math.pow(((r + 0.055) / 1.055), 2.4) : (r / 12.92); + g = g > 0.04045 ? Math.pow(((g + 0.055) / 1.055), 2.4) : (g / 12.92); + b = b > 0.04045 ? Math.pow(((b + 0.055) / 1.055), 2.4) : (b / 12.92); + + var x = (r * 0.4124) + (g * 0.3576) + (b * 0.1805); + var y = (r * 0.2126) + (g * 0.7152) + (b * 0.0722); + var z = (r * 0.0193) + (g * 0.1192) + (b * 0.9505); + + return [x * 100, y * 100, z * 100]; +}; + +convert.rgb.lab = function (rgb) { + var xyz = convert.rgb.xyz(rgb); + var x = xyz[0]; + var y = xyz[1]; + var z = xyz[2]; + var l; + var a; + var b; + + x /= 95.047; + y /= 100; + z /= 108.883; + + x = x > 0.008856 ? Math.pow(x, 1 / 3) : (7.787 * x) + (16 / 116); + y = y > 0.008856 ? Math.pow(y, 1 / 3) : (7.787 * y) + (16 / 116); + z = z > 0.008856 ? Math.pow(z, 1 / 3) : (7.787 * z) + (16 / 116); + + l = (116 * y) - 16; + a = 500 * (x - y); + b = 200 * (y - z); + + return [l, a, b]; +}; + +convert.hsl.rgb = function (hsl) { + var h = hsl[0] / 360; + var s = hsl[1] / 100; + var l = hsl[2] / 100; + var t1; + var t2; + var t3; + var rgb; + var val; + + if (s === 0) { + val = l * 255; + return [val, val, val]; + } + + if (l < 0.5) { + t2 = l * (1 + s); + } else { + t2 = l + s - l * s; + } + + t1 = 2 * l - t2; + + rgb = [0, 0, 0]; + for (var i = 0; i < 3; i++) { + t3 = h + 1 / 3 * -(i - 1); + if (t3 < 0) { + t3++; + } + if (t3 > 1) { + t3--; + } + + if (6 * t3 < 1) { + val = t1 + (t2 - t1) * 6 * t3; + } else if (2 * t3 < 1) { + val = t2; + } else if (3 * t3 < 2) { + val = t1 + (t2 - t1) * (2 / 3 - t3) * 6; + } else { + val = t1; + } + + rgb[i] = val * 255; + } + + return rgb; +}; + +convert.hsl.hsv = function (hsl) { + var h = hsl[0]; + var s = hsl[1] / 100; + var l = hsl[2] / 100; + var smin = s; + var lmin = Math.max(l, 0.01); + var sv; + var v; + + l *= 2; + s *= (l <= 1) ? l : 2 - l; + smin *= lmin <= 1 ? lmin : 2 - lmin; + v = (l + s) / 2; + sv = l === 0 ? (2 * smin) / (lmin + smin) : (2 * s) / (l + s); + + return [h, sv * 100, v * 100]; +}; + +convert.hsv.rgb = function (hsv) { + var h = hsv[0] / 60; + var s = hsv[1] / 100; + var v = hsv[2] / 100; + var hi = Math.floor(h) % 6; + + var f = h - Math.floor(h); + var p = 255 * v * (1 - s); + var q = 255 * v * (1 - (s * f)); + var t = 255 * v * (1 - (s * (1 - f))); + v *= 255; + + switch (hi) { + case 0: + return [v, t, p]; + case 1: + return [q, v, p]; + case 2: + return [p, v, t]; + case 3: + return [p, q, v]; + case 4: + return [t, p, v]; + case 5: + return [v, p, q]; + } +}; + +convert.hsv.hsl = function (hsv) { + var h = hsv[0]; + var s = hsv[1] / 100; + var v = hsv[2] / 100; + var vmin = Math.max(v, 0.01); + var lmin; + var sl; + var l; + + l = (2 - s) * v; + lmin = (2 - s) * vmin; + sl = s * vmin; + sl /= (lmin <= 1) ? lmin : 2 - lmin; + sl = sl || 0; + l /= 2; + + return [h, sl * 100, l * 100]; +}; + +// http://dev.w3.org/csswg/css-color/#hwb-to-rgb +convert.hwb.rgb = function (hwb) { + var h = hwb[0] / 360; + var wh = hwb[1] / 100; + var bl = hwb[2] / 100; + var ratio = wh + bl; + var i; + var v; + var f; + var n; + + // wh + bl cant be > 1 + if (ratio > 1) { + wh /= ratio; + bl /= ratio; + } + + i = Math.floor(6 * h); + v = 1 - bl; + f = 6 * h - i; + + if ((i & 0x01) !== 0) { + f = 1 - f; + } + + n = wh + f * (v - wh); // linear interpolation + + var r; + var g; + var b; + switch (i) { + default: + case 6: + case 0: r = v; g = n; b = wh; break; + case 1: r = n; g = v; b = wh; break; + case 2: r = wh; g = v; b = n; break; + case 3: r = wh; g = n; b = v; break; + case 4: r = n; g = wh; b = v; break; + case 5: r = v; g = wh; b = n; break; + } + + return [r * 255, g * 255, b * 255]; +}; + +convert.cmyk.rgb = function (cmyk) { + var c = cmyk[0] / 100; + var m = cmyk[1] / 100; + var y = cmyk[2] / 100; + var k = cmyk[3] / 100; + var r; + var g; + var b; + + r = 1 - Math.min(1, c * (1 - k) + k); + g = 1 - Math.min(1, m * (1 - k) + k); + b = 1 - Math.min(1, y * (1 - k) + k); + + return [r * 255, g * 255, b * 255]; +}; + +convert.xyz.rgb = function (xyz) { + var x = xyz[0] / 100; + var y = xyz[1] / 100; + var z = xyz[2] / 100; + var r; + var g; + var b; + + r = (x * 3.2406) + (y * -1.5372) + (z * -0.4986); + g = (x * -0.9689) + (y * 1.8758) + (z * 0.0415); + b = (x * 0.0557) + (y * -0.2040) + (z * 1.0570); + + // assume sRGB + r = r > 0.0031308 + ? ((1.055 * Math.pow(r, 1.0 / 2.4)) - 0.055) + : r * 12.92; + + g = g > 0.0031308 + ? ((1.055 * Math.pow(g, 1.0 / 2.4)) - 0.055) + : g * 12.92; + + b = b > 0.0031308 + ? ((1.055 * Math.pow(b, 1.0 / 2.4)) - 0.055) + : b * 12.92; + + r = Math.min(Math.max(0, r), 1); + g = Math.min(Math.max(0, g), 1); + b = Math.min(Math.max(0, b), 1); + + return [r * 255, g * 255, b * 255]; +}; + +convert.xyz.lab = function (xyz) { + var x = xyz[0]; + var y = xyz[1]; + var z = xyz[2]; + var l; + var a; + var b; + + x /= 95.047; + y /= 100; + z /= 108.883; + + x = x > 0.008856 ? Math.pow(x, 1 / 3) : (7.787 * x) + (16 / 116); + y = y > 0.008856 ? Math.pow(y, 1 / 3) : (7.787 * y) + (16 / 116); + z = z > 0.008856 ? Math.pow(z, 1 / 3) : (7.787 * z) + (16 / 116); + + l = (116 * y) - 16; + a = 500 * (x - y); + b = 200 * (y - z); + + return [l, a, b]; +}; + +convert.lab.xyz = function (lab) { + var l = lab[0]; + var a = lab[1]; + var b = lab[2]; + var x; + var y; + var z; + + y = (l + 16) / 116; + x = a / 500 + y; + z = y - b / 200; + + var y2 = Math.pow(y, 3); + var x2 = Math.pow(x, 3); + var z2 = Math.pow(z, 3); + y = y2 > 0.008856 ? y2 : (y - 16 / 116) / 7.787; + x = x2 > 0.008856 ? x2 : (x - 16 / 116) / 7.787; + z = z2 > 0.008856 ? z2 : (z - 16 / 116) / 7.787; + + x *= 95.047; + y *= 100; + z *= 108.883; + + return [x, y, z]; +}; + +convert.lab.lch = function (lab) { + var l = lab[0]; + var a = lab[1]; + var b = lab[2]; + var hr; + var h; + var c; + + hr = Math.atan2(b, a); + h = hr * 360 / 2 / Math.PI; + + if (h < 0) { + h += 360; + } + + c = Math.sqrt(a * a + b * b); + + return [l, c, h]; +}; + +convert.lch.lab = function (lch) { + var l = lch[0]; + var c = lch[1]; + var h = lch[2]; + var a; + var b; + var hr; + + hr = h / 360 * 2 * Math.PI; + a = c * Math.cos(hr); + b = c * Math.sin(hr); + + return [l, a, b]; +}; + +convert.rgb.ansi16 = function (args) { + var r = args[0]; + var g = args[1]; + var b = args[2]; + var value = 1 in arguments ? arguments[1] : convert.rgb.hsv(args)[2]; // hsv -> ansi16 optimization + + value = Math.round(value / 50); + + if (value === 0) { + return 30; + } + + var ansi = 30 + + ((Math.round(b / 255) << 2) + | (Math.round(g / 255) << 1) + | Math.round(r / 255)); + + if (value === 2) { + ansi += 60; + } + + return ansi; +}; + +convert.hsv.ansi16 = function (args) { + // optimization here; we already know the value and don't need to get + // it converted for us. + return convert.rgb.ansi16(convert.hsv.rgb(args), args[2]); +}; + +convert.rgb.ansi256 = function (args) { + var r = args[0]; + var g = args[1]; + var b = args[2]; + + // we use the extended greyscale palette here, with the exception of + // black and white. normal palette only has 4 greyscale shades. + if (r === g && g === b) { + if (r < 8) { + return 16; + } + + if (r > 248) { + return 231; + } + + return Math.round(((r - 8) / 247) * 24) + 232; + } + + var ansi = 16 + + (36 * Math.round(r / 255 * 5)) + + (6 * Math.round(g / 255 * 5)) + + Math.round(b / 255 * 5); + + return ansi; +}; + +convert.ansi16.rgb = function (args) { + var color = args % 10; + + // handle greyscale + if (color === 0 || color === 7) { + if (args > 50) { + color += 3.5; + } + + color = color / 10.5 * 255; + + return [color, color, color]; + } + + var mult = (~~(args > 50) + 1) * 0.5; + var r = ((color & 1) * mult) * 255; + var g = (((color >> 1) & 1) * mult) * 255; + var b = (((color >> 2) & 1) * mult) * 255; + + return [r, g, b]; +}; + +convert.ansi256.rgb = function (args) { + // handle greyscale + if (args >= 232) { + var c = (args - 232) * 10 + 8; + return [c, c, c]; + } + + args -= 16; + + var rem; + var r = Math.floor(args / 36) / 5 * 255; + var g = Math.floor((rem = args % 36) / 6) / 5 * 255; + var b = (rem % 6) / 5 * 255; + + return [r, g, b]; +}; + +convert.rgb.hex = function (args) { + var integer = ((Math.round(args[0]) & 0xFF) << 16) + + ((Math.round(args[1]) & 0xFF) << 8) + + (Math.round(args[2]) & 0xFF); + + var string = integer.toString(16).toUpperCase(); + return '000000'.substring(string.length) + string; +}; + +convert.hex.rgb = function (args) { + var match = args.toString(16).match(/[a-f0-9]{6}|[a-f0-9]{3}/i); + if (!match) { + return [0, 0, 0]; + } + + var colorString = match[0]; + + if (match[0].length === 3) { + colorString = colorString.split('').map(function (char) { + return char + char; + }).join(''); + } + + var integer = parseInt(colorString, 16); + var r = (integer >> 16) & 0xFF; + var g = (integer >> 8) & 0xFF; + var b = integer & 0xFF; + + return [r, g, b]; +}; + +convert.rgb.hcg = function (rgb) { + var r = rgb[0] / 255; + var g = rgb[1] / 255; + var b = rgb[2] / 255; + var max = Math.max(Math.max(r, g), b); + var min = Math.min(Math.min(r, g), b); + var chroma = (max - min); + var grayscale; + var hue; + + if (chroma < 1) { + grayscale = min / (1 - chroma); + } else { + grayscale = 0; + } + + if (chroma <= 0) { + hue = 0; + } else + if (max === r) { + hue = ((g - b) / chroma) % 6; + } else + if (max === g) { + hue = 2 + (b - r) / chroma; + } else { + hue = 4 + (r - g) / chroma + 4; + } + + hue /= 6; + hue %= 1; + + return [hue * 360, chroma * 100, grayscale * 100]; +}; + +convert.hsl.hcg = function (hsl) { + var s = hsl[1] / 100; + var l = hsl[2] / 100; + var c = 1; + var f = 0; + + if (l < 0.5) { + c = 2.0 * s * l; + } else { + c = 2.0 * s * (1.0 - l); + } + + if (c < 1.0) { + f = (l - 0.5 * c) / (1.0 - c); + } + + return [hsl[0], c * 100, f * 100]; +}; + +convert.hsv.hcg = function (hsv) { + var s = hsv[1] / 100; + var v = hsv[2] / 100; + + var c = s * v; + var f = 0; + + if (c < 1.0) { + f = (v - c) / (1 - c); + } + + return [hsv[0], c * 100, f * 100]; +}; + +convert.hcg.rgb = function (hcg) { + var h = hcg[0] / 360; + var c = hcg[1] / 100; + var g = hcg[2] / 100; + + if (c === 0.0) { + return [g * 255, g * 255, g * 255]; + } + + var pure = [0, 0, 0]; + var hi = (h % 1) * 6; + var v = hi % 1; + var w = 1 - v; + var mg = 0; + + switch (Math.floor(hi)) { + case 0: + pure[0] = 1; pure[1] = v; pure[2] = 0; break; + case 1: + pure[0] = w; pure[1] = 1; pure[2] = 0; break; + case 2: + pure[0] = 0; pure[1] = 1; pure[2] = v; break; + case 3: + pure[0] = 0; pure[1] = w; pure[2] = 1; break; + case 4: + pure[0] = v; pure[1] = 0; pure[2] = 1; break; + default: + pure[0] = 1; pure[1] = 0; pure[2] = w; + } + + mg = (1.0 - c) * g; + + return [ + (c * pure[0] + mg) * 255, + (c * pure[1] + mg) * 255, + (c * pure[2] + mg) * 255 + ]; +}; + +convert.hcg.hsv = function (hcg) { + var c = hcg[1] / 100; + var g = hcg[2] / 100; + + var v = c + g * (1.0 - c); + var f = 0; + + if (v > 0.0) { + f = c / v; + } + + return [hcg[0], f * 100, v * 100]; +}; + +convert.hcg.hsl = function (hcg) { + var c = hcg[1] / 100; + var g = hcg[2] / 100; + + var l = g * (1.0 - c) + 0.5 * c; + var s = 0; + + if (l > 0.0 && l < 0.5) { + s = c / (2 * l); + } else + if (l >= 0.5 && l < 1.0) { + s = c / (2 * (1 - l)); + } + + return [hcg[0], s * 100, l * 100]; +}; + +convert.hcg.hwb = function (hcg) { + var c = hcg[1] / 100; + var g = hcg[2] / 100; + var v = c + g * (1.0 - c); + return [hcg[0], (v - c) * 100, (1 - v) * 100]; +}; + +convert.hwb.hcg = function (hwb) { + var w = hwb[1] / 100; + var b = hwb[2] / 100; + var v = 1 - b; + var c = v - w; + var g = 0; + + if (c < 1) { + g = (v - c) / (1 - c); + } + + return [hwb[0], c * 100, g * 100]; +}; + +convert.apple.rgb = function (apple) { + return [(apple[0] / 65535) * 255, (apple[1] / 65535) * 255, (apple[2] / 65535) * 255]; +}; + +convert.rgb.apple = function (rgb) { + return [(rgb[0] / 255) * 65535, (rgb[1] / 255) * 65535, (rgb[2] / 255) * 65535]; +}; + +convert.gray.rgb = function (args) { + return [args[0] / 100 * 255, args[0] / 100 * 255, args[0] / 100 * 255]; +}; + +convert.gray.hsl = convert.gray.hsv = function (args) { + return [0, 0, args[0]]; +}; + +convert.gray.hwb = function (gray) { + return [0, 100, gray[0]]; +}; + +convert.gray.cmyk = function (gray) { + return [0, 0, 0, gray[0]]; +}; + +convert.gray.lab = function (gray) { + return [gray[0], 0, 0]; +}; + +convert.gray.hex = function (gray) { + var val = Math.round(gray[0] / 100 * 255) & 0xFF; + var integer = (val << 16) + (val << 8) + val; + + var string = integer.toString(16).toUpperCase(); + return '000000'.substring(string.length) + string; +}; + +convert.rgb.gray = function (rgb) { + var val = (rgb[0] + rgb[1] + rgb[2]) / 3; + return [val / 255 * 100]; +}; + + +/***/ }), + +/***/ "./node_modules/color/node_modules/color-convert/index.js": +/*!****************************************************************!*\ + !*** ./node_modules/color/node_modules/color-convert/index.js ***! + \****************************************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +var conversions = __webpack_require__(/*! ./conversions */ "./node_modules/color/node_modules/color-convert/conversions.js"); +var route = __webpack_require__(/*! ./route */ "./node_modules/color/node_modules/color-convert/route.js"); + +var convert = {}; + +var models = Object.keys(conversions); + +function wrapRaw(fn) { + var wrappedFn = function (args) { + if (args === undefined || args === null) { + return args; + } + + if (arguments.length > 1) { + args = Array.prototype.slice.call(arguments); + } + + return fn(args); + }; + + // preserve .conversion property if there is one + if ('conversion' in fn) { + wrappedFn.conversion = fn.conversion; + } + + return wrappedFn; +} + +function wrapRounded(fn) { + var wrappedFn = function (args) { + if (args === undefined || args === null) { + return args; + } + + if (arguments.length > 1) { + args = Array.prototype.slice.call(arguments); + } + + var result = fn(args); + + // we're assuming the result is an array here. + // see notice in conversions.js; don't use box types + // in conversion functions. + if (typeof result === 'object') { + for (var len = result.length, i = 0; i < len; i++) { + result[i] = Math.round(result[i]); + } + } + + return result; + }; + + // preserve .conversion property if there is one + if ('conversion' in fn) { + wrappedFn.conversion = fn.conversion; + } + + return wrappedFn; +} + +models.forEach(function (fromModel) { + convert[fromModel] = {}; + + Object.defineProperty(convert[fromModel], 'channels', {value: conversions[fromModel].channels}); + Object.defineProperty(convert[fromModel], 'labels', {value: conversions[fromModel].labels}); + + var routes = route(fromModel); + var routeModels = Object.keys(routes); + + routeModels.forEach(function (toModel) { + var fn = routes[toModel]; + + convert[fromModel][toModel] = wrapRounded(fn); + convert[fromModel][toModel].raw = wrapRaw(fn); + }); +}); + +module.exports = convert; + + +/***/ }), + +/***/ "./node_modules/color/node_modules/color-convert/route.js": +/*!****************************************************************!*\ + !*** ./node_modules/color/node_modules/color-convert/route.js ***! + \****************************************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +var conversions = __webpack_require__(/*! ./conversions */ "./node_modules/color/node_modules/color-convert/conversions.js"); + +/* + this function routes a model to all other models. + + all functions that are routed have a property `.conversion` attached + to the returned synthetic function. This property is an array + of strings, each with the steps in between the 'from' and 'to' + color models (inclusive). + + conversions that are not possible simply are not included. +*/ + +function buildGraph() { + var graph = {}; + // https://jsperf.com/object-keys-vs-for-in-with-closure/3 + var models = Object.keys(conversions); + + for (var len = models.length, i = 0; i < len; i++) { + graph[models[i]] = { + // http://jsperf.com/1-vs-infinity + // micro-opt, but this is simple. + distance: -1, + parent: null + }; + } + + return graph; +} + +// https://en.wikipedia.org/wiki/Breadth-first_search +function deriveBFS(fromModel) { + var graph = buildGraph(); + var queue = [fromModel]; // unshift -> queue -> pop + + graph[fromModel].distance = 0; + + while (queue.length) { + var current = queue.pop(); + var adjacents = Object.keys(conversions[current]); + + for (var len = adjacents.length, i = 0; i < len; i++) { + var adjacent = adjacents[i]; + var node = graph[adjacent]; + + if (node.distance === -1) { + node.distance = graph[current].distance + 1; + node.parent = current; + queue.unshift(adjacent); + } + } + } + + return graph; +} + +function link(from, to) { + return function (args) { + return to(from(args)); + }; +} + +function wrapConversion(toModel, graph) { + var path = [graph[toModel].parent, toModel]; + var fn = conversions[graph[toModel].parent][toModel]; + + var cur = graph[toModel].parent; + while (graph[cur].parent) { + path.unshift(graph[cur].parent); + fn = link(conversions[graph[cur].parent][cur], fn); + cur = graph[cur].parent; + } + + fn.conversion = path; + return fn; +} + +module.exports = function (fromModel) { + var graph = deriveBFS(fromModel); + var conversion = {}; + + var models = Object.keys(graph); + for (var len = models.length, i = 0; i < len; i++) { + var toModel = models[i]; + var node = graph[toModel]; + + if (node.parent === null) { + // no possible conversion, or this node is the source model. + continue; + } + + conversion[toModel] = wrapConversion(toModel, graph); + } + + return conversion; +}; + + + +/***/ }), + +/***/ "./node_modules/color/node_modules/color-name/index.js": +/*!*************************************************************!*\ + !*** ./node_modules/color/node_modules/color-name/index.js ***! + \*************************************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +module.exports = { + "aliceblue": [240, 248, 255], + "antiquewhite": [250, 235, 215], + "aqua": [0, 255, 255], + "aquamarine": [127, 255, 212], + "azure": [240, 255, 255], + "beige": [245, 245, 220], + "bisque": [255, 228, 196], + "black": [0, 0, 0], + "blanchedalmond": [255, 235, 205], + "blue": [0, 0, 255], + "blueviolet": [138, 43, 226], + "brown": [165, 42, 42], + "burlywood": [222, 184, 135], + "cadetblue": [95, 158, 160], + "chartreuse": [127, 255, 0], + "chocolate": [210, 105, 30], + "coral": [255, 127, 80], + "cornflowerblue": [100, 149, 237], + "cornsilk": [255, 248, 220], + "crimson": [220, 20, 60], + "cyan": [0, 255, 255], + "darkblue": [0, 0, 139], + "darkcyan": [0, 139, 139], + "darkgoldenrod": [184, 134, 11], + "darkgray": [169, 169, 169], + "darkgreen": [0, 100, 0], + "darkgrey": [169, 169, 169], + "darkkhaki": [189, 183, 107], + "darkmagenta": [139, 0, 139], + "darkolivegreen": [85, 107, 47], + "darkorange": [255, 140, 0], + "darkorchid": [153, 50, 204], + "darkred": [139, 0, 0], + "darksalmon": [233, 150, 122], + "darkseagreen": [143, 188, 143], + "darkslateblue": [72, 61, 139], + "darkslategray": [47, 79, 79], + "darkslategrey": [47, 79, 79], + "darkturquoise": [0, 206, 209], + "darkviolet": [148, 0, 211], + "deeppink": [255, 20, 147], + "deepskyblue": [0, 191, 255], + "dimgray": [105, 105, 105], + "dimgrey": [105, 105, 105], + "dodgerblue": [30, 144, 255], + "firebrick": [178, 34, 34], + "floralwhite": [255, 250, 240], + "forestgreen": [34, 139, 34], + "fuchsia": [255, 0, 255], + "gainsboro": [220, 220, 220], + "ghostwhite": [248, 248, 255], + "gold": [255, 215, 0], + "goldenrod": [218, 165, 32], + "gray": [128, 128, 128], + "green": [0, 128, 0], + "greenyellow": [173, 255, 47], + "grey": [128, 128, 128], + "honeydew": [240, 255, 240], + "hotpink": [255, 105, 180], + "indianred": [205, 92, 92], + "indigo": [75, 0, 130], + "ivory": [255, 255, 240], + "khaki": [240, 230, 140], + "lavender": [230, 230, 250], + "lavenderblush": [255, 240, 245], + "lawngreen": [124, 252, 0], + "lemonchiffon": [255, 250, 205], + "lightblue": [173, 216, 230], + "lightcoral": [240, 128, 128], + "lightcyan": [224, 255, 255], + "lightgoldenrodyellow": [250, 250, 210], + "lightgray": [211, 211, 211], + "lightgreen": [144, 238, 144], + "lightgrey": [211, 211, 211], + "lightpink": [255, 182, 193], + "lightsalmon": [255, 160, 122], + "lightseagreen": [32, 178, 170], + "lightskyblue": [135, 206, 250], + "lightslategray": [119, 136, 153], + "lightslategrey": [119, 136, 153], + "lightsteelblue": [176, 196, 222], + "lightyellow": [255, 255, 224], + "lime": [0, 255, 0], + "limegreen": [50, 205, 50], + "linen": [250, 240, 230], + "magenta": [255, 0, 255], + "maroon": [128, 0, 0], + "mediumaquamarine": [102, 205, 170], + "mediumblue": [0, 0, 205], + "mediumorchid": [186, 85, 211], + "mediumpurple": [147, 112, 219], + "mediumseagreen": [60, 179, 113], + "mediumslateblue": [123, 104, 238], + "mediumspringgreen": [0, 250, 154], + "mediumturquoise": [72, 209, 204], + "mediumvioletred": [199, 21, 133], + "midnightblue": [25, 25, 112], + "mintcream": [245, 255, 250], + "mistyrose": [255, 228, 225], + "moccasin": [255, 228, 181], + "navajowhite": [255, 222, 173], + "navy": [0, 0, 128], + "oldlace": [253, 245, 230], + "olive": [128, 128, 0], + "olivedrab": [107, 142, 35], + "orange": [255, 165, 0], + "orangered": [255, 69, 0], + "orchid": [218, 112, 214], + "palegoldenrod": [238, 232, 170], + "palegreen": [152, 251, 152], + "paleturquoise": [175, 238, 238], + "palevioletred": [219, 112, 147], + "papayawhip": [255, 239, 213], + "peachpuff": [255, 218, 185], + "peru": [205, 133, 63], + "pink": [255, 192, 203], + "plum": [221, 160, 221], + "powderblue": [176, 224, 230], + "purple": [128, 0, 128], + "rebeccapurple": [102, 51, 153], + "red": [255, 0, 0], + "rosybrown": [188, 143, 143], + "royalblue": [65, 105, 225], + "saddlebrown": [139, 69, 19], + "salmon": [250, 128, 114], + "sandybrown": [244, 164, 96], + "seagreen": [46, 139, 87], + "seashell": [255, 245, 238], + "sienna": [160, 82, 45], + "silver": [192, 192, 192], + "skyblue": [135, 206, 235], + "slateblue": [106, 90, 205], + "slategray": [112, 128, 144], + "slategrey": [112, 128, 144], + "snow": [255, 250, 250], + "springgreen": [0, 255, 127], + "steelblue": [70, 130, 180], + "tan": [210, 180, 140], + "teal": [0, 128, 128], + "thistle": [216, 191, 216], + "tomato": [255, 99, 71], + "turquoise": [64, 224, 208], + "violet": [238, 130, 238], + "wheat": [245, 222, 179], + "white": [255, 255, 255], + "whitesmoke": [245, 245, 245], + "yellow": [255, 255, 0], + "yellowgreen": [154, 205, 50] +}; + + +/***/ }), + +/***/ "./node_modules/colorspace/index.js": +/*!******************************************!*\ + !*** ./node_modules/colorspace/index.js ***! + \******************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +var color = __webpack_require__(/*! color */ "./node_modules/color/index.js") + , hex = __webpack_require__(/*! text-hex */ "./node_modules/text-hex/index.js"); + +/** + * Generate a color for a given name. But be reasonably smart about it by + * understanding name spaces and coloring each namespace a bit lighter so they + * still have the same base color as the root. + * + * @param {string} namespace The namespace + * @param {string} [delimiter] The delimiter + * @returns {string} color + */ +module.exports = function colorspace(namespace, delimiter) { + var split = namespace.split(delimiter || ':'); + var base = hex(split[0]); + + if (!split.length) return base; + + for (var i = 0, l = split.length - 1; i < l; i++) { + base = color(base) + .mix(color(hex(split[i + 1]))) + .saturate(1) + .hex(); + } + + return base; +}; + + +/***/ }), + +/***/ "./node_modules/core-util-is/lib/util.js": +/*!***********************************************!*\ + !*** ./node_modules/core-util-is/lib/util.js ***! + \***********************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// NOTE: These type checking functions intentionally don't use `instanceof` +// because it is fragile and can be easily faked with `Object.create()`. + +function isArray(arg) { + if (Array.isArray) { + return Array.isArray(arg); + } + return objectToString(arg) === '[object Array]'; +} +exports.isArray = isArray; + +function isBoolean(arg) { + return typeof arg === 'boolean'; +} +exports.isBoolean = isBoolean; + +function isNull(arg) { + return arg === null; +} +exports.isNull = isNull; + +function isNullOrUndefined(arg) { + return arg == null; +} +exports.isNullOrUndefined = isNullOrUndefined; + +function isNumber(arg) { + return typeof arg === 'number'; +} +exports.isNumber = isNumber; + +function isString(arg) { + return typeof arg === 'string'; +} +exports.isString = isString; + +function isSymbol(arg) { + return typeof arg === 'symbol'; +} +exports.isSymbol = isSymbol; + +function isUndefined(arg) { + return arg === void 0; +} +exports.isUndefined = isUndefined; + +function isRegExp(re) { + return objectToString(re) === '[object RegExp]'; +} +exports.isRegExp = isRegExp; + +function isObject(arg) { + return typeof arg === 'object' && arg !== null; +} +exports.isObject = isObject; + +function isDate(d) { + return objectToString(d) === '[object Date]'; +} +exports.isDate = isDate; + +function isError(e) { + return (objectToString(e) === '[object Error]' || e instanceof Error); +} +exports.isError = isError; + +function isFunction(arg) { + return typeof arg === 'function'; +} +exports.isFunction = isFunction; + +function isPrimitive(arg) { + return arg === null || + typeof arg === 'boolean' || + typeof arg === 'number' || + typeof arg === 'string' || + typeof arg === 'symbol' || // ES6 symbol + typeof arg === 'undefined'; +} +exports.isPrimitive = isPrimitive; + +exports.isBuffer = __webpack_require__(/*! buffer */ "./node_modules/buffer/index.js").Buffer.isBuffer; + +function objectToString(o) { + return Object.prototype.toString.call(o); +} + + +/***/ }), + +/***/ "./node_modules/deepmerge/dist/cjs.js": +/*!********************************************!*\ + !*** ./node_modules/deepmerge/dist/cjs.js ***! + \********************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +var isMergeableObject = function isMergeableObject(value) { + return isNonNullObject(value) + && !isSpecial(value) +}; + +function isNonNullObject(value) { + return !!value && typeof value === 'object' +} + +function isSpecial(value) { + var stringValue = Object.prototype.toString.call(value); + + return stringValue === '[object RegExp]' + || stringValue === '[object Date]' + || isReactElement(value) +} + +// see https://github.com/facebook/react/blob/b5ac963fb791d1298e7f396236383bc955f916c1/src/isomorphic/classic/element/ReactElement.js#L21-L25 +var canUseSymbol = typeof Symbol === 'function' && Symbol.for; +var REACT_ELEMENT_TYPE = canUseSymbol ? Symbol.for('react.element') : 0xeac7; + +function isReactElement(value) { + return value.$$typeof === REACT_ELEMENT_TYPE +} + +function emptyTarget(val) { + return Array.isArray(val) ? [] : {} +} + +function cloneUnlessOtherwiseSpecified(value, options) { + return (options.clone !== false && options.isMergeableObject(value)) + ? deepmerge(emptyTarget(value), value, options) + : value +} + +function defaultArrayMerge(target, source, options) { + return target.concat(source).map(function(element) { + return cloneUnlessOtherwiseSpecified(element, options) + }) +} + +function getMergeFunction(key, options) { + if (!options.customMerge) { + return deepmerge + } + var customMerge = options.customMerge(key); + return typeof customMerge === 'function' ? customMerge : deepmerge +} + +function getEnumerableOwnPropertySymbols(target) { + return Object.getOwnPropertySymbols + ? Object.getOwnPropertySymbols(target).filter(function(symbol) { + return Object.propertyIsEnumerable.call(target, symbol) + }) + : [] +} + +function getKeys(target) { + return Object.keys(target).concat(getEnumerableOwnPropertySymbols(target)) +} + +function propertyIsOnObject(object, property) { + try { + return property in object + } catch(_) { + return false + } +} + +// Protects from prototype poisoning and unexpected merging up the prototype chain. +function propertyIsUnsafe(target, key) { + return propertyIsOnObject(target, key) // Properties are safe to merge if they don't exist in the target yet, + && !(Object.hasOwnProperty.call(target, key) // unsafe if they exist up the prototype chain, + && Object.propertyIsEnumerable.call(target, key)) // and also unsafe if they're nonenumerable. +} + +function mergeObject(target, source, options) { + var destination = {}; + if (options.isMergeableObject(target)) { + getKeys(target).forEach(function(key) { + destination[key] = cloneUnlessOtherwiseSpecified(target[key], options); + }); + } + getKeys(source).forEach(function(key) { + if (propertyIsUnsafe(target, key)) { + return + } + + if (propertyIsOnObject(target, key) && options.isMergeableObject(source[key])) { + destination[key] = getMergeFunction(key, options)(target[key], source[key], options); + } else { + destination[key] = cloneUnlessOtherwiseSpecified(source[key], options); + } + }); + return destination +} + +function deepmerge(target, source, options) { + options = options || {}; + options.arrayMerge = options.arrayMerge || defaultArrayMerge; + options.isMergeableObject = options.isMergeableObject || isMergeableObject; + // cloneUnlessOtherwiseSpecified is added to `options` so that custom arrayMerge() + // implementations can use it. The caller may not replace it. + options.cloneUnlessOtherwiseSpecified = cloneUnlessOtherwiseSpecified; + + var sourceIsArray = Array.isArray(source); + var targetIsArray = Array.isArray(target); + var sourceAndTargetTypesMatch = sourceIsArray === targetIsArray; + + if (!sourceAndTargetTypesMatch) { + return cloneUnlessOtherwiseSpecified(source, options) + } else if (sourceIsArray) { + return options.arrayMerge(target, source, options) + } else { + return mergeObject(target, source, options) + } +} + +deepmerge.all = function deepmergeAll(array, options) { + if (!Array.isArray(array)) { + throw new Error('first argument should be an array') + } + + return array.reduce(function(prev, next) { + return deepmerge(prev, next, options) + }, {}) +}; + +var deepmerge_1 = deepmerge; + +module.exports = deepmerge_1; + + +/***/ }), + +/***/ "./node_modules/define-data-property/index.js": +/*!****************************************************!*\ + !*** ./node_modules/define-data-property/index.js ***! + \****************************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +var $defineProperty = __webpack_require__(/*! es-define-property */ "./node_modules/es-define-property/index.js"); + +var $SyntaxError = __webpack_require__(/*! es-errors/syntax */ "./node_modules/es-errors/syntax.js"); +var $TypeError = __webpack_require__(/*! es-errors/type */ "./node_modules/es-errors/type.js"); + +var gopd = __webpack_require__(/*! gopd */ "./node_modules/gopd/index.js"); + +/** @type {import('.')} */ +module.exports = function defineDataProperty( + obj, + property, + value +) { + if (!obj || (typeof obj !== 'object' && typeof obj !== 'function')) { + throw new $TypeError('`obj` must be an object or a function`'); + } + if (typeof property !== 'string' && typeof property !== 'symbol') { + throw new $TypeError('`property` must be a string or a symbol`'); + } + if (arguments.length > 3 && typeof arguments[3] !== 'boolean' && arguments[3] !== null) { + throw new $TypeError('`nonEnumerable`, if provided, must be a boolean or null'); + } + if (arguments.length > 4 && typeof arguments[4] !== 'boolean' && arguments[4] !== null) { + throw new $TypeError('`nonWritable`, if provided, must be a boolean or null'); + } + if (arguments.length > 5 && typeof arguments[5] !== 'boolean' && arguments[5] !== null) { + throw new $TypeError('`nonConfigurable`, if provided, must be a boolean or null'); + } + if (arguments.length > 6 && typeof arguments[6] !== 'boolean') { + throw new $TypeError('`loose`, if provided, must be a boolean'); + } + + var nonEnumerable = arguments.length > 3 ? arguments[3] : null; + var nonWritable = arguments.length > 4 ? arguments[4] : null; + var nonConfigurable = arguments.length > 5 ? arguments[5] : null; + var loose = arguments.length > 6 ? arguments[6] : false; + + /* @type {false | TypedPropertyDescriptor} */ + var desc = !!gopd && gopd(obj, property); + + if ($defineProperty) { + $defineProperty(obj, property, { + configurable: nonConfigurable === null && desc ? desc.configurable : !nonConfigurable, + enumerable: nonEnumerable === null && desc ? desc.enumerable : !nonEnumerable, + value: value, + writable: nonWritable === null && desc ? desc.writable : !nonWritable + }); + } else if (loose || (!nonEnumerable && !nonWritable && !nonConfigurable)) { + // must fall back to [[Set]], and was not explicitly asked to make non-enumerable, non-writable, or non-configurable + obj[property] = value; // eslint-disable-line no-param-reassign + } else { + throw new $SyntaxError('This environment does not support defining a property as non-configurable, non-writable, or non-enumerable.'); + } +}; + + +/***/ }), + +/***/ "./node_modules/dotenv/lib/main.js": +/*!*****************************************!*\ + !*** ./node_modules/dotenv/lib/main.js ***! + \*****************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +/* WEBPACK VAR INJECTION */(function(process) {const fs = __webpack_require__(/*! fs */ "./node_modules/node-libs-browser/mock/empty.js") +const path = __webpack_require__(/*! path */ "./node_modules/path-browserify/index.js") +const os = __webpack_require__(/*! os */ "./node_modules/os-browserify/browser.js") + +function log (message) { + console.log(`[dotenv][DEBUG] ${message}`) +} + +const NEWLINE = '\n' +const RE_INI_KEY_VAL = /^\s*([\w.-]+)\s*=\s*("[^"]*"|'[^']*'|.*?)(\s+#.*)?$/ +const RE_NEWLINES = /\\n/g +const NEWLINES_MATCH = /\r\n|\n|\r/ + +// Parses src into an Object +function parse (src, options) { + const debug = Boolean(options && options.debug) + const multiline = Boolean(options && options.multiline) + const obj = {} + + // convert Buffers before splitting into lines and processing + const lines = src.toString().split(NEWLINES_MATCH) + + for (let idx = 0; idx < lines.length; idx++) { + let line = lines[idx] + + // matching "KEY' and 'VAL' in 'KEY=VAL' + const keyValueArr = line.match(RE_INI_KEY_VAL) + // matched? + if (keyValueArr != null) { + const key = keyValueArr[1] + // default undefined or missing values to empty string + let val = (keyValueArr[2] || '') + let end = val.length - 1 + const isDoubleQuoted = val[0] === '"' && val[end] === '"' + const isSingleQuoted = val[0] === "'" && val[end] === "'" + + const isMultilineDoubleQuoted = val[0] === '"' && val[end] !== '"' + const isMultilineSingleQuoted = val[0] === "'" && val[end] !== "'" + + // if parsing line breaks and the value starts with a quote + if (multiline && (isMultilineDoubleQuoted || isMultilineSingleQuoted)) { + const quoteChar = isMultilineDoubleQuoted ? '"' : "'" + + val = val.substring(1) + + while (idx++ < lines.length - 1) { + line = lines[idx] + end = line.length - 1 + if (line[end] === quoteChar) { + val += NEWLINE + line.substring(0, end) + break + } + val += NEWLINE + line + } + // if single or double quoted, remove quotes + } else if (isSingleQuoted || isDoubleQuoted) { + val = val.substring(1, end) + + // if double quoted, expand newlines + if (isDoubleQuoted) { + val = val.replace(RE_NEWLINES, NEWLINE) + } + } else { + // remove surrounding whitespace + val = val.trim() + } + + obj[key] = val + } else if (debug) { + const trimmedLine = line.trim() + + // ignore empty and commented lines + if (trimmedLine.length && trimmedLine[0] !== '#') { + log(`Failed to match key and value when parsing line ${idx + 1}: ${line}`) + } + } + } + + return obj +} + +function resolveHome (envPath) { + return envPath[0] === '~' ? path.join(os.homedir(), envPath.slice(1)) : envPath +} + +// Populates process.env from .env file +function config (options) { + let dotenvPath = path.resolve(process.cwd(), '.env') + let encoding = 'utf8' + const debug = Boolean(options && options.debug) + const override = Boolean(options && options.override) + const multiline = Boolean(options && options.multiline) + + if (options) { + if (options.path != null) { + dotenvPath = resolveHome(options.path) + } + if (options.encoding != null) { + encoding = options.encoding + } + } + + try { + // specifying an encoding returns a string instead of a buffer + const parsed = DotenvModule.parse(fs.readFileSync(dotenvPath, { encoding }), { debug, multiline }) + + Object.keys(parsed).forEach(function (key) { + if (!Object.prototype.hasOwnProperty.call(process.env, key)) { + process.env[key] = parsed[key] + } else { + if (override === true) { + process.env[key] = parsed[key] + } + + if (debug) { + if (override === true) { + log(`"${key}" is already defined in \`process.env\` and WAS overwritten`) + } else { + log(`"${key}" is already defined in \`process.env\` and was NOT overwritten`) + } + } + } + }) + + return { parsed } + } catch (e) { + if (debug) { + log(`Failed to load ${dotenvPath} ${e.message}`) + } + + return { error: e } + } +} + +const DotenvModule = { + config, + parse +} + +module.exports.config = DotenvModule.config +module.exports.parse = DotenvModule.parse +module.exports = DotenvModule + +/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../../process/browser.js */ "./node_modules/process/browser.js"))) + +/***/ }), + +/***/ "./node_modules/enabled/index.js": +/*!***************************************!*\ + !*** ./node_modules/enabled/index.js ***! + \***************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +/** + * Checks if a given namespace is allowed by the given variable. + * + * @param {String} name namespace that should be included. + * @param {String} variable Value that needs to be tested. + * @returns {Boolean} Indication if namespace is enabled. + * @public + */ +module.exports = function enabled(name, variable) { + if (!variable) return false; + + var variables = variable.split(/[\s,]+/) + , i = 0; + + for (; i < variables.length; i++) { + variable = variables[i].replace('*', '.*?'); + + if ('-' === variable.charAt(0)) { + if ((new RegExp('^'+ variable.substr(1) +'$')).test(name)) { + return false; + } + + continue; + } + + if ((new RegExp('^'+ variable +'$')).test(name)) { + return true; + } + } + + return false; +}; + + +/***/ }), + +/***/ "./node_modules/es-define-property/index.js": +/*!**************************************************!*\ + !*** ./node_modules/es-define-property/index.js ***! + \**************************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +var GetIntrinsic = __webpack_require__(/*! get-intrinsic */ "./node_modules/get-intrinsic/index.js"); + +/** @type {import('.')} */ +var $defineProperty = GetIntrinsic('%Object.defineProperty%', true) || false; +if ($defineProperty) { + try { + $defineProperty({}, 'a', { value: 1 }); + } catch (e) { + // IE 8 has a broken defineProperty + $defineProperty = false; + } +} + +module.exports = $defineProperty; + + +/***/ }), + +/***/ "./node_modules/es-errors/eval.js": +/*!****************************************!*\ + !*** ./node_modules/es-errors/eval.js ***! + \****************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +/** @type {import('./eval')} */ +module.exports = EvalError; + + +/***/ }), + +/***/ "./node_modules/es-errors/index.js": +/*!*****************************************!*\ + !*** ./node_modules/es-errors/index.js ***! + \*****************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +/** @type {import('.')} */ +module.exports = Error; + + +/***/ }), + +/***/ "./node_modules/es-errors/range.js": +/*!*****************************************!*\ + !*** ./node_modules/es-errors/range.js ***! + \*****************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +/** @type {import('./range')} */ +module.exports = RangeError; + + +/***/ }), + +/***/ "./node_modules/es-errors/ref.js": +/*!***************************************!*\ + !*** ./node_modules/es-errors/ref.js ***! + \***************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +/** @type {import('./ref')} */ +module.exports = ReferenceError; + + +/***/ }), + +/***/ "./node_modules/es-errors/syntax.js": +/*!******************************************!*\ + !*** ./node_modules/es-errors/syntax.js ***! + \******************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +/** @type {import('./syntax')} */ +module.exports = SyntaxError; + + +/***/ }), + +/***/ "./node_modules/es-errors/type.js": +/*!****************************************!*\ + !*** ./node_modules/es-errors/type.js ***! + \****************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +/** @type {import('./type')} */ +module.exports = TypeError; + + +/***/ }), + +/***/ "./node_modules/es-errors/uri.js": +/*!***************************************!*\ + !*** ./node_modules/es-errors/uri.js ***! + \***************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +/** @type {import('./uri')} */ +module.exports = URIError; + + +/***/ }), + +/***/ "./node_modules/eventemitter3/index.js": +/*!*********************************************!*\ + !*** ./node_modules/eventemitter3/index.js ***! + \*********************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +var has = Object.prototype.hasOwnProperty + , prefix = '~'; + +/** + * Constructor to create a storage for our `EE` objects. + * An `Events` instance is a plain object whose properties are event names. + * + * @constructor + * @private + */ +function Events() {} + +// +// We try to not inherit from `Object.prototype`. In some engines creating an +// instance in this way is faster than calling `Object.create(null)` directly. +// If `Object.create(null)` is not supported we prefix the event names with a +// character to make sure that the built-in object properties are not +// overridden or used as an attack vector. +// +if (Object.create) { + Events.prototype = Object.create(null); + + // + // This hack is needed because the `__proto__` property is still inherited in + // some old browsers like Android 4, iPhone 5.1, Opera 11 and Safari 5. + // + if (!new Events().__proto__) prefix = false; +} + +/** + * Representation of a single event listener. + * + * @param {Function} fn The listener function. + * @param {*} context The context to invoke the listener with. + * @param {Boolean} [once=false] Specify if the listener is a one-time listener. + * @constructor + * @private + */ +function EE(fn, context, once) { + this.fn = fn; + this.context = context; + this.once = once || false; +} + +/** + * Add a listener for a given event. + * + * @param {EventEmitter} emitter Reference to the `EventEmitter` instance. + * @param {(String|Symbol)} event The event name. + * @param {Function} fn The listener function. + * @param {*} context The context to invoke the listener with. + * @param {Boolean} once Specify if the listener is a one-time listener. + * @returns {EventEmitter} + * @private + */ +function addListener(emitter, event, fn, context, once) { + if (typeof fn !== 'function') { + throw new TypeError('The listener must be a function'); + } + + var listener = new EE(fn, context || emitter, once) + , evt = prefix ? prefix + event : event; + + if (!emitter._events[evt]) emitter._events[evt] = listener, emitter._eventsCount++; + else if (!emitter._events[evt].fn) emitter._events[evt].push(listener); + else emitter._events[evt] = [emitter._events[evt], listener]; + + return emitter; +} + +/** + * Clear event by name. + * + * @param {EventEmitter} emitter Reference to the `EventEmitter` instance. + * @param {(String|Symbol)} evt The Event name. + * @private + */ +function clearEvent(emitter, evt) { + if (--emitter._eventsCount === 0) emitter._events = new Events(); + else delete emitter._events[evt]; +} + +/** + * Minimal `EventEmitter` interface that is molded against the Node.js + * `EventEmitter` interface. + * + * @constructor + * @public + */ +function EventEmitter() { + this._events = new Events(); + this._eventsCount = 0; +} + +/** + * Return an array listing the events for which the emitter has registered + * listeners. + * + * @returns {Array} + * @public + */ +EventEmitter.prototype.eventNames = function eventNames() { + var names = [] + , events + , name; + + if (this._eventsCount === 0) return names; + + for (name in (events = this._events)) { + if (has.call(events, name)) names.push(prefix ? name.slice(1) : name); + } + + if (Object.getOwnPropertySymbols) { + return names.concat(Object.getOwnPropertySymbols(events)); + } + + return names; +}; + +/** + * Return the listeners registered for a given event. + * + * @param {(String|Symbol)} event The event name. + * @returns {Array} The registered listeners. + * @public + */ +EventEmitter.prototype.listeners = function listeners(event) { + var evt = prefix ? prefix + event : event + , handlers = this._events[evt]; + + if (!handlers) return []; + if (handlers.fn) return [handlers.fn]; + + for (var i = 0, l = handlers.length, ee = new Array(l); i < l; i++) { + ee[i] = handlers[i].fn; + } + + return ee; +}; + +/** + * Return the number of listeners listening to a given event. + * + * @param {(String|Symbol)} event The event name. + * @returns {Number} The number of listeners. + * @public + */ +EventEmitter.prototype.listenerCount = function listenerCount(event) { + var evt = prefix ? prefix + event : event + , listeners = this._events[evt]; + + if (!listeners) return 0; + if (listeners.fn) return 1; + return listeners.length; +}; + +/** + * Calls each of the listeners registered for a given event. + * + * @param {(String|Symbol)} event The event name. + * @returns {Boolean} `true` if the event had listeners, else `false`. + * @public + */ +EventEmitter.prototype.emit = function emit(event, a1, a2, a3, a4, a5) { + var evt = prefix ? prefix + event : event; + + if (!this._events[evt]) return false; + + var listeners = this._events[evt] + , len = arguments.length + , args + , i; + + if (listeners.fn) { + if (listeners.once) this.removeListener(event, listeners.fn, undefined, true); + + switch (len) { + case 1: return listeners.fn.call(listeners.context), true; + case 2: return listeners.fn.call(listeners.context, a1), true; + case 3: return listeners.fn.call(listeners.context, a1, a2), true; + case 4: return listeners.fn.call(listeners.context, a1, a2, a3), true; + case 5: return listeners.fn.call(listeners.context, a1, a2, a3, a4), true; + case 6: return listeners.fn.call(listeners.context, a1, a2, a3, a4, a5), true; + } + + for (i = 1, args = new Array(len -1); i < len; i++) { + args[i - 1] = arguments[i]; + } + + listeners.fn.apply(listeners.context, args); + } else { + var length = listeners.length + , j; + + for (i = 0; i < length; i++) { + if (listeners[i].once) this.removeListener(event, listeners[i].fn, undefined, true); + + switch (len) { + case 1: listeners[i].fn.call(listeners[i].context); break; + case 2: listeners[i].fn.call(listeners[i].context, a1); break; + case 3: listeners[i].fn.call(listeners[i].context, a1, a2); break; + case 4: listeners[i].fn.call(listeners[i].context, a1, a2, a3); break; + default: + if (!args) for (j = 1, args = new Array(len -1); j < len; j++) { + args[j - 1] = arguments[j]; + } + + listeners[i].fn.apply(listeners[i].context, args); + } + } + } + + return true; +}; + +/** + * Add a listener for a given event. + * + * @param {(String|Symbol)} event The event name. + * @param {Function} fn The listener function. + * @param {*} [context=this] The context to invoke the listener with. + * @returns {EventEmitter} `this`. + * @public + */ +EventEmitter.prototype.on = function on(event, fn, context) { + return addListener(this, event, fn, context, false); +}; + +/** + * Add a one-time listener for a given event. + * + * @param {(String|Symbol)} event The event name. + * @param {Function} fn The listener function. + * @param {*} [context=this] The context to invoke the listener with. + * @returns {EventEmitter} `this`. + * @public + */ +EventEmitter.prototype.once = function once(event, fn, context) { + return addListener(this, event, fn, context, true); +}; + +/** + * Remove the listeners of a given event. + * + * @param {(String|Symbol)} event The event name. + * @param {Function} fn Only remove the listeners that match this function. + * @param {*} context Only remove the listeners that have this context. + * @param {Boolean} once Only remove one-time listeners. + * @returns {EventEmitter} `this`. + * @public + */ +EventEmitter.prototype.removeListener = function removeListener(event, fn, context, once) { + var evt = prefix ? prefix + event : event; + + if (!this._events[evt]) return this; + if (!fn) { + clearEvent(this, evt); + return this; + } + + var listeners = this._events[evt]; + + if (listeners.fn) { + if ( + listeners.fn === fn && + (!once || listeners.once) && + (!context || listeners.context === context) + ) { + clearEvent(this, evt); + } + } else { + for (var i = 0, events = [], length = listeners.length; i < length; i++) { + if ( + listeners[i].fn !== fn || + (once && !listeners[i].once) || + (context && listeners[i].context !== context) + ) { + events.push(listeners[i]); + } + } + + // + // Reset the array, or remove it completely if we have no more listeners. + // + if (events.length) this._events[evt] = events.length === 1 ? events[0] : events; + else clearEvent(this, evt); + } + + return this; +}; + +/** + * Remove all listeners, or those of the specified event. + * + * @param {(String|Symbol)} [event] The event name. + * @returns {EventEmitter} `this`. + * @public + */ +EventEmitter.prototype.removeAllListeners = function removeAllListeners(event) { + var evt; + + if (event) { + evt = prefix ? prefix + event : event; + if (this._events[evt]) clearEvent(this, evt); + } else { + this._events = new Events(); + this._eventsCount = 0; + } + + return this; +}; + +// +// Alias methods names because people roll like that. +// +EventEmitter.prototype.off = EventEmitter.prototype.removeListener; +EventEmitter.prototype.addListener = EventEmitter.prototype.on; + +// +// Expose the prefix. +// +EventEmitter.prefixed = prefix; + +// +// Allow `EventEmitter` to be imported as module namespace. +// +EventEmitter.EventEmitter = EventEmitter; + +// +// Expose the module. +// +if (true) { + module.exports = EventEmitter; +} + + +/***/ }), + +/***/ "./node_modules/events/events.js": +/*!***************************************!*\ + !*** ./node_modules/events/events.js ***! + \***************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + + +var R = typeof Reflect === 'object' ? Reflect : null +var ReflectApply = R && typeof R.apply === 'function' + ? R.apply + : function ReflectApply(target, receiver, args) { + return Function.prototype.apply.call(target, receiver, args); + } + +var ReflectOwnKeys +if (R && typeof R.ownKeys === 'function') { + ReflectOwnKeys = R.ownKeys +} else if (Object.getOwnPropertySymbols) { + ReflectOwnKeys = function ReflectOwnKeys(target) { + return Object.getOwnPropertyNames(target) + .concat(Object.getOwnPropertySymbols(target)); + }; +} else { + ReflectOwnKeys = function ReflectOwnKeys(target) { + return Object.getOwnPropertyNames(target); + }; +} + +function ProcessEmitWarning(warning) { + if (console && console.warn) console.warn(warning); +} + +var NumberIsNaN = Number.isNaN || function NumberIsNaN(value) { + return value !== value; +} + +function EventEmitter() { + EventEmitter.init.call(this); +} +module.exports = EventEmitter; +module.exports.once = once; + +// Backwards-compat with node 0.10.x +EventEmitter.EventEmitter = EventEmitter; + +EventEmitter.prototype._events = undefined; +EventEmitter.prototype._eventsCount = 0; +EventEmitter.prototype._maxListeners = undefined; + +// By default EventEmitters will print a warning if more than 10 listeners are +// added to it. This is a useful default which helps finding memory leaks. +var defaultMaxListeners = 10; + +function checkListener(listener) { + if (typeof listener !== 'function') { + throw new TypeError('The "listener" argument must be of type Function. Received type ' + typeof listener); + } +} + +Object.defineProperty(EventEmitter, 'defaultMaxListeners', { + enumerable: true, + get: function() { + return defaultMaxListeners; + }, + set: function(arg) { + if (typeof arg !== 'number' || arg < 0 || NumberIsNaN(arg)) { + throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received ' + arg + '.'); + } + defaultMaxListeners = arg; + } +}); + +EventEmitter.init = function() { + + if (this._events === undefined || + this._events === Object.getPrototypeOf(this)._events) { + this._events = Object.create(null); + this._eventsCount = 0; + } + + this._maxListeners = this._maxListeners || undefined; +}; + +// Obviously not all Emitters should be limited to 10. This function allows +// that to be increased. Set to zero for unlimited. +EventEmitter.prototype.setMaxListeners = function setMaxListeners(n) { + if (typeof n !== 'number' || n < 0 || NumberIsNaN(n)) { + throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received ' + n + '.'); + } + this._maxListeners = n; + return this; +}; + +function _getMaxListeners(that) { + if (that._maxListeners === undefined) + return EventEmitter.defaultMaxListeners; + return that._maxListeners; +} + +EventEmitter.prototype.getMaxListeners = function getMaxListeners() { + return _getMaxListeners(this); +}; + +EventEmitter.prototype.emit = function emit(type) { + var args = []; + for (var i = 1; i < arguments.length; i++) args.push(arguments[i]); + var doError = (type === 'error'); + + var events = this._events; + if (events !== undefined) + doError = (doError && events.error === undefined); + else if (!doError) + return false; + + // If there is no 'error' event listener then throw. + if (doError) { + var er; + if (args.length > 0) + er = args[0]; + if (er instanceof Error) { + // Note: The comments on the `throw` lines are intentional, they show + // up in Node's output if this results in an unhandled exception. + throw er; // Unhandled 'error' event + } + // At least give some kind of context to the user + var err = new Error('Unhandled error.' + (er ? ' (' + er.message + ')' : '')); + err.context = er; + throw err; // Unhandled 'error' event + } + + var handler = events[type]; + + if (handler === undefined) + return false; + + if (typeof handler === 'function') { + ReflectApply(handler, this, args); + } else { + var len = handler.length; + var listeners = arrayClone(handler, len); + for (var i = 0; i < len; ++i) + ReflectApply(listeners[i], this, args); + } + + return true; +}; + +function _addListener(target, type, listener, prepend) { + var m; + var events; + var existing; + + checkListener(listener); + + events = target._events; + if (events === undefined) { + events = target._events = Object.create(null); + target._eventsCount = 0; + } else { + // To avoid recursion in the case that type === "newListener"! Before + // adding it to the listeners, first emit "newListener". + if (events.newListener !== undefined) { + target.emit('newListener', type, + listener.listener ? listener.listener : listener); + + // Re-assign `events` because a newListener handler could have caused the + // this._events to be assigned to a new object + events = target._events; + } + existing = events[type]; + } + + if (existing === undefined) { + // Optimize the case of one listener. Don't need the extra array object. + existing = events[type] = listener; + ++target._eventsCount; + } else { + if (typeof existing === 'function') { + // Adding the second element, need to change to array. + existing = events[type] = + prepend ? [listener, existing] : [existing, listener]; + // If we've already got an array, just append. + } else if (prepend) { + existing.unshift(listener); + } else { + existing.push(listener); + } + + // Check for listener leak + m = _getMaxListeners(target); + if (m > 0 && existing.length > m && !existing.warned) { + existing.warned = true; + // No error code for this since it is a Warning + // eslint-disable-next-line no-restricted-syntax + var w = new Error('Possible EventEmitter memory leak detected. ' + + existing.length + ' ' + String(type) + ' listeners ' + + 'added. Use emitter.setMaxListeners() to ' + + 'increase limit'); + w.name = 'MaxListenersExceededWarning'; + w.emitter = target; + w.type = type; + w.count = existing.length; + ProcessEmitWarning(w); + } + } + + return target; +} + +EventEmitter.prototype.addListener = function addListener(type, listener) { + return _addListener(this, type, listener, false); +}; + +EventEmitter.prototype.on = EventEmitter.prototype.addListener; + +EventEmitter.prototype.prependListener = + function prependListener(type, listener) { + return _addListener(this, type, listener, true); + }; + +function onceWrapper() { + if (!this.fired) { + this.target.removeListener(this.type, this.wrapFn); + this.fired = true; + if (arguments.length === 0) + return this.listener.call(this.target); + return this.listener.apply(this.target, arguments); + } +} + +function _onceWrap(target, type, listener) { + var state = { fired: false, wrapFn: undefined, target: target, type: type, listener: listener }; + var wrapped = onceWrapper.bind(state); + wrapped.listener = listener; + state.wrapFn = wrapped; + return wrapped; +} + +EventEmitter.prototype.once = function once(type, listener) { + checkListener(listener); + this.on(type, _onceWrap(this, type, listener)); + return this; +}; + +EventEmitter.prototype.prependOnceListener = + function prependOnceListener(type, listener) { + checkListener(listener); + this.prependListener(type, _onceWrap(this, type, listener)); + return this; + }; + +// Emits a 'removeListener' event if and only if the listener was removed. +EventEmitter.prototype.removeListener = + function removeListener(type, listener) { + var list, events, position, i, originalListener; + + checkListener(listener); + + events = this._events; + if (events === undefined) + return this; + + list = events[type]; + if (list === undefined) + return this; + + if (list === listener || list.listener === listener) { + if (--this._eventsCount === 0) + this._events = Object.create(null); + else { + delete events[type]; + if (events.removeListener) + this.emit('removeListener', type, list.listener || listener); + } + } else if (typeof list !== 'function') { + position = -1; + + for (i = list.length - 1; i >= 0; i--) { + if (list[i] === listener || list[i].listener === listener) { + originalListener = list[i].listener; + position = i; + break; + } + } + + if (position < 0) + return this; + + if (position === 0) + list.shift(); + else { + spliceOne(list, position); + } + + if (list.length === 1) + events[type] = list[0]; + + if (events.removeListener !== undefined) + this.emit('removeListener', type, originalListener || listener); + } + + return this; + }; + +EventEmitter.prototype.off = EventEmitter.prototype.removeListener; + +EventEmitter.prototype.removeAllListeners = + function removeAllListeners(type) { + var listeners, events, i; + + events = this._events; + if (events === undefined) + return this; + + // not listening for removeListener, no need to emit + if (events.removeListener === undefined) { + if (arguments.length === 0) { + this._events = Object.create(null); + this._eventsCount = 0; + } else if (events[type] !== undefined) { + if (--this._eventsCount === 0) + this._events = Object.create(null); + else + delete events[type]; + } + return this; + } + + // emit removeListener for all listeners on all events + if (arguments.length === 0) { + var keys = Object.keys(events); + var key; + for (i = 0; i < keys.length; ++i) { + key = keys[i]; + if (key === 'removeListener') continue; + this.removeAllListeners(key); + } + this.removeAllListeners('removeListener'); + this._events = Object.create(null); + this._eventsCount = 0; + return this; + } + + listeners = events[type]; + + if (typeof listeners === 'function') { + this.removeListener(type, listeners); + } else if (listeners !== undefined) { + // LIFO order + for (i = listeners.length - 1; i >= 0; i--) { + this.removeListener(type, listeners[i]); + } + } + + return this; + }; + +function _listeners(target, type, unwrap) { + var events = target._events; + + if (events === undefined) + return []; + + var evlistener = events[type]; + if (evlistener === undefined) + return []; + + if (typeof evlistener === 'function') + return unwrap ? [evlistener.listener || evlistener] : [evlistener]; + + return unwrap ? + unwrapListeners(evlistener) : arrayClone(evlistener, evlistener.length); +} + +EventEmitter.prototype.listeners = function listeners(type) { + return _listeners(this, type, true); +}; + +EventEmitter.prototype.rawListeners = function rawListeners(type) { + return _listeners(this, type, false); +}; + +EventEmitter.listenerCount = function(emitter, type) { + if (typeof emitter.listenerCount === 'function') { + return emitter.listenerCount(type); + } else { + return listenerCount.call(emitter, type); + } +}; + +EventEmitter.prototype.listenerCount = listenerCount; +function listenerCount(type) { + var events = this._events; + + if (events !== undefined) { + var evlistener = events[type]; + + if (typeof evlistener === 'function') { + return 1; + } else if (evlistener !== undefined) { + return evlistener.length; + } + } + + return 0; +} + +EventEmitter.prototype.eventNames = function eventNames() { + return this._eventsCount > 0 ? ReflectOwnKeys(this._events) : []; +}; + +function arrayClone(arr, n) { + var copy = new Array(n); + for (var i = 0; i < n; ++i) + copy[i] = arr[i]; + return copy; +} + +function spliceOne(list, index) { + for (; index + 1 < list.length; index++) + list[index] = list[index + 1]; + list.pop(); +} + +function unwrapListeners(arr) { + var ret = new Array(arr.length); + for (var i = 0; i < ret.length; ++i) { + ret[i] = arr[i].listener || arr[i]; + } + return ret; +} + +function once(emitter, name) { + return new Promise(function (resolve, reject) { + function errorListener(err) { + emitter.removeListener(name, resolver); + reject(err); + } + + function resolver() { + if (typeof emitter.removeListener === 'function') { + emitter.removeListener('error', errorListener); + } + resolve([].slice.call(arguments)); + }; + + eventTargetAgnosticAddListener(emitter, name, resolver, { once: true }); + if (name !== 'error') { + addErrorHandlerIfEventEmitter(emitter, errorListener, { once: true }); + } + }); +} + +function addErrorHandlerIfEventEmitter(emitter, handler, flags) { + if (typeof emitter.on === 'function') { + eventTargetAgnosticAddListener(emitter, 'error', handler, flags); + } +} + +function eventTargetAgnosticAddListener(emitter, name, listener, flags) { + if (typeof emitter.on === 'function') { + if (flags.once) { + emitter.once(name, listener); + } else { + emitter.on(name, listener); + } + } else if (typeof emitter.addEventListener === 'function') { + // EventTarget does not have `error` event semantics like Node + // EventEmitters, we do not listen for `error` events here. + emitter.addEventListener(name, function wrapListener(arg) { + // IE does not have builtin `{ once: true }` support so we + // have to do it manually. + if (flags.once) { + emitter.removeEventListener(name, wrapListener); + } + listener(arg); + }); + } else { + throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type ' + typeof emitter); + } +} + + +/***/ }), + +/***/ "./node_modules/fecha/lib/fecha.js": +/*!*****************************************!*\ + !*** ./node_modules/fecha/lib/fecha.js ***! + \*****************************************/ +/*! exports provided: default, assign, format, parse, defaultI18n, setGlobalDateI18n, setGlobalDateMasks */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "assign", function() { return assign; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "format", function() { return format; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "parse", function() { return parse; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "defaultI18n", function() { return defaultI18n; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "setGlobalDateI18n", function() { return setGlobalDateI18n; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "setGlobalDateMasks", function() { return setGlobalDateMasks; }); +var token = /d{1,4}|M{1,4}|YY(?:YY)?|S{1,3}|Do|ZZ|Z|([HhMsDm])\1?|[aA]|"[^"]*"|'[^']*'/g; +var twoDigitsOptional = "\\d\\d?"; +var twoDigits = "\\d\\d"; +var threeDigits = "\\d{3}"; +var fourDigits = "\\d{4}"; +var word = "[^\\s]+"; +var literal = /\[([^]*?)\]/gm; +function shorten(arr, sLen) { + var newArr = []; + for (var i = 0, len = arr.length; i < len; i++) { + newArr.push(arr[i].substr(0, sLen)); + } + return newArr; +} +var monthUpdate = function (arrName) { return function (v, i18n) { + var lowerCaseArr = i18n[arrName].map(function (v) { return v.toLowerCase(); }); + var index = lowerCaseArr.indexOf(v.toLowerCase()); + if (index > -1) { + return index; + } + return null; +}; }; +function assign(origObj) { + var args = []; + for (var _i = 1; _i < arguments.length; _i++) { + args[_i - 1] = arguments[_i]; + } + for (var _a = 0, args_1 = args; _a < args_1.length; _a++) { + var obj = args_1[_a]; + for (var key in obj) { + // @ts-ignore ex + origObj[key] = obj[key]; + } + } + return origObj; +} +var dayNames = [ + "Sunday", + "Monday", + "Tuesday", + "Wednesday", + "Thursday", + "Friday", + "Saturday" +]; +var monthNames = [ + "January", + "February", + "March", + "April", + "May", + "June", + "July", + "August", + "September", + "October", + "November", + "December" +]; +var monthNamesShort = shorten(monthNames, 3); +var dayNamesShort = shorten(dayNames, 3); +var defaultI18n = { + dayNamesShort: dayNamesShort, + dayNames: dayNames, + monthNamesShort: monthNamesShort, + monthNames: monthNames, + amPm: ["am", "pm"], + DoFn: function (dayOfMonth) { + return (dayOfMonth + + ["th", "st", "nd", "rd"][dayOfMonth % 10 > 3 + ? 0 + : ((dayOfMonth - (dayOfMonth % 10) !== 10 ? 1 : 0) * dayOfMonth) % 10]); + } +}; +var globalI18n = assign({}, defaultI18n); +var setGlobalDateI18n = function (i18n) { + return (globalI18n = assign(globalI18n, i18n)); +}; +var regexEscape = function (str) { + return str.replace(/[|\\{()[^$+*?.-]/g, "\\$&"); +}; +var pad = function (val, len) { + if (len === void 0) { len = 2; } + val = String(val); + while (val.length < len) { + val = "0" + val; + } + return val; +}; +var formatFlags = { + D: function (dateObj) { return String(dateObj.getDate()); }, + DD: function (dateObj) { return pad(dateObj.getDate()); }, + Do: function (dateObj, i18n) { + return i18n.DoFn(dateObj.getDate()); + }, + d: function (dateObj) { return String(dateObj.getDay()); }, + dd: function (dateObj) { return pad(dateObj.getDay()); }, + ddd: function (dateObj, i18n) { + return i18n.dayNamesShort[dateObj.getDay()]; + }, + dddd: function (dateObj, i18n) { + return i18n.dayNames[dateObj.getDay()]; + }, + M: function (dateObj) { return String(dateObj.getMonth() + 1); }, + MM: function (dateObj) { return pad(dateObj.getMonth() + 1); }, + MMM: function (dateObj, i18n) { + return i18n.monthNamesShort[dateObj.getMonth()]; + }, + MMMM: function (dateObj, i18n) { + return i18n.monthNames[dateObj.getMonth()]; + }, + YY: function (dateObj) { + return pad(String(dateObj.getFullYear()), 4).substr(2); + }, + YYYY: function (dateObj) { return pad(dateObj.getFullYear(), 4); }, + h: function (dateObj) { return String(dateObj.getHours() % 12 || 12); }, + hh: function (dateObj) { return pad(dateObj.getHours() % 12 || 12); }, + H: function (dateObj) { return String(dateObj.getHours()); }, + HH: function (dateObj) { return pad(dateObj.getHours()); }, + m: function (dateObj) { return String(dateObj.getMinutes()); }, + mm: function (dateObj) { return pad(dateObj.getMinutes()); }, + s: function (dateObj) { return String(dateObj.getSeconds()); }, + ss: function (dateObj) { return pad(dateObj.getSeconds()); }, + S: function (dateObj) { + return String(Math.round(dateObj.getMilliseconds() / 100)); + }, + SS: function (dateObj) { + return pad(Math.round(dateObj.getMilliseconds() / 10), 2); + }, + SSS: function (dateObj) { return pad(dateObj.getMilliseconds(), 3); }, + a: function (dateObj, i18n) { + return dateObj.getHours() < 12 ? i18n.amPm[0] : i18n.amPm[1]; + }, + A: function (dateObj, i18n) { + return dateObj.getHours() < 12 + ? i18n.amPm[0].toUpperCase() + : i18n.amPm[1].toUpperCase(); + }, + ZZ: function (dateObj) { + var offset = dateObj.getTimezoneOffset(); + return ((offset > 0 ? "-" : "+") + + pad(Math.floor(Math.abs(offset) / 60) * 100 + (Math.abs(offset) % 60), 4)); + }, + Z: function (dateObj) { + var offset = dateObj.getTimezoneOffset(); + return ((offset > 0 ? "-" : "+") + + pad(Math.floor(Math.abs(offset) / 60), 2) + + ":" + + pad(Math.abs(offset) % 60, 2)); + } +}; +var monthParse = function (v) { return +v - 1; }; +var emptyDigits = [null, twoDigitsOptional]; +var emptyWord = [null, word]; +var amPm = [ + "isPm", + word, + function (v, i18n) { + var val = v.toLowerCase(); + if (val === i18n.amPm[0]) { + return 0; + } + else if (val === i18n.amPm[1]) { + return 1; + } + return null; + } +]; +var timezoneOffset = [ + "timezoneOffset", + "[^\\s]*?[\\+\\-]\\d\\d:?\\d\\d|[^\\s]*?Z?", + function (v) { + var parts = (v + "").match(/([+-]|\d\d)/gi); + if (parts) { + var minutes = +parts[1] * 60 + parseInt(parts[2], 10); + return parts[0] === "+" ? minutes : -minutes; + } + return 0; + } +]; +var parseFlags = { + D: ["day", twoDigitsOptional], + DD: ["day", twoDigits], + Do: ["day", twoDigitsOptional + word, function (v) { return parseInt(v, 10); }], + M: ["month", twoDigitsOptional, monthParse], + MM: ["month", twoDigits, monthParse], + YY: [ + "year", + twoDigits, + function (v) { + var now = new Date(); + var cent = +("" + now.getFullYear()).substr(0, 2); + return +("" + (+v > 68 ? cent - 1 : cent) + v); + } + ], + h: ["hour", twoDigitsOptional, undefined, "isPm"], + hh: ["hour", twoDigits, undefined, "isPm"], + H: ["hour", twoDigitsOptional], + HH: ["hour", twoDigits], + m: ["minute", twoDigitsOptional], + mm: ["minute", twoDigits], + s: ["second", twoDigitsOptional], + ss: ["second", twoDigits], + YYYY: ["year", fourDigits], + S: ["millisecond", "\\d", function (v) { return +v * 100; }], + SS: ["millisecond", twoDigits, function (v) { return +v * 10; }], + SSS: ["millisecond", threeDigits], + d: emptyDigits, + dd: emptyDigits, + ddd: emptyWord, + dddd: emptyWord, + MMM: ["month", word, monthUpdate("monthNamesShort")], + MMMM: ["month", word, monthUpdate("monthNames")], + a: amPm, + A: amPm, + ZZ: timezoneOffset, + Z: timezoneOffset +}; +// Some common format strings +var globalMasks = { + default: "ddd MMM DD YYYY HH:mm:ss", + shortDate: "M/D/YY", + mediumDate: "MMM D, YYYY", + longDate: "MMMM D, YYYY", + fullDate: "dddd, MMMM D, YYYY", + isoDate: "YYYY-MM-DD", + isoDateTime: "YYYY-MM-DDTHH:mm:ssZ", + shortTime: "HH:mm", + mediumTime: "HH:mm:ss", + longTime: "HH:mm:ss.SSS" +}; +var setGlobalDateMasks = function (masks) { return assign(globalMasks, masks); }; +/*** + * Format a date + * @method format + * @param {Date|number} dateObj + * @param {string} mask Format of the date, i.e. 'mm-dd-yy' or 'shortDate' + * @returns {string} Formatted date string + */ +var format = function (dateObj, mask, i18n) { + if (mask === void 0) { mask = globalMasks["default"]; } + if (i18n === void 0) { i18n = {}; } + if (typeof dateObj === "number") { + dateObj = new Date(dateObj); + } + if (Object.prototype.toString.call(dateObj) !== "[object Date]" || + isNaN(dateObj.getTime())) { + throw new Error("Invalid Date pass to format"); + } + mask = globalMasks[mask] || mask; + var literals = []; + // Make literals inactive by replacing them with @@@ + mask = mask.replace(literal, function ($0, $1) { + literals.push($1); + return "@@@"; + }); + var combinedI18nSettings = assign(assign({}, globalI18n), i18n); + // Apply formatting rules + mask = mask.replace(token, function ($0) { + return formatFlags[$0](dateObj, combinedI18nSettings); + }); + // Inline literal values back into the formatted value + return mask.replace(/@@@/g, function () { return literals.shift(); }); +}; +/** + * Parse a date string into a Javascript Date object / + * @method parse + * @param {string} dateStr Date string + * @param {string} format Date parse format + * @param {i18n} I18nSettingsOptional Full or subset of I18N settings + * @returns {Date|null} Returns Date object. Returns null what date string is invalid or doesn't match format + */ +function parse(dateStr, format, i18n) { + if (i18n === void 0) { i18n = {}; } + if (typeof format !== "string") { + throw new Error("Invalid format in fecha parse"); + } + // Check to see if the format is actually a mask + format = globalMasks[format] || format; + // Avoid regular expression denial of service, fail early for really long strings + // https://www.owasp.org/index.php/Regular_expression_Denial_of_Service_-_ReDoS + if (dateStr.length > 1000) { + return null; + } + // Default to the beginning of the year. + var today = new Date(); + var dateInfo = { + year: today.getFullYear(), + month: 0, + day: 1, + hour: 0, + minute: 0, + second: 0, + millisecond: 0, + isPm: null, + timezoneOffset: null + }; + var parseInfo = []; + var literals = []; + // Replace all the literals with @@@. Hopefully a string that won't exist in the format + var newFormat = format.replace(literal, function ($0, $1) { + literals.push(regexEscape($1)); + return "@@@"; + }); + var specifiedFields = {}; + var requiredFields = {}; + // Change every token that we find into the correct regex + newFormat = regexEscape(newFormat).replace(token, function ($0) { + var info = parseFlags[$0]; + var field = info[0], regex = info[1], requiredField = info[3]; + // Check if the person has specified the same field twice. This will lead to confusing results. + if (specifiedFields[field]) { + throw new Error("Invalid format. " + field + " specified twice in format"); + } + specifiedFields[field] = true; + // Check if there are any required fields. For instance, 12 hour time requires AM/PM specified + if (requiredField) { + requiredFields[requiredField] = true; + } + parseInfo.push(info); + return "(" + regex + ")"; + }); + // Check all the required fields are present + Object.keys(requiredFields).forEach(function (field) { + if (!specifiedFields[field]) { + throw new Error("Invalid format. " + field + " is required in specified format"); + } + }); + // Add back all the literals after + newFormat = newFormat.replace(/@@@/g, function () { return literals.shift(); }); + // Check if the date string matches the format. If it doesn't return null + var matches = dateStr.match(new RegExp(newFormat, "i")); + if (!matches) { + return null; + } + var combinedI18nSettings = assign(assign({}, globalI18n), i18n); + // For each match, call the parser function for that date part + for (var i = 1; i < matches.length; i++) { + var _a = parseInfo[i - 1], field = _a[0], parser = _a[2]; + var value = parser + ? parser(matches[i], combinedI18nSettings) + : +matches[i]; + // If the parser can't make sense of the value, return null + if (value == null) { + return null; + } + dateInfo[field] = value; + } + if (dateInfo.isPm === 1 && dateInfo.hour != null && +dateInfo.hour !== 12) { + dateInfo.hour = +dateInfo.hour + 12; + } + else if (dateInfo.isPm === 0 && +dateInfo.hour === 12) { + dateInfo.hour = 0; + } + var dateTZ; + if (dateInfo.timezoneOffset == null) { + dateTZ = new Date(dateInfo.year, dateInfo.month, dateInfo.day, dateInfo.hour, dateInfo.minute, dateInfo.second, dateInfo.millisecond); + var validateFields = [ + ["month", "getMonth"], + ["day", "getDate"], + ["hour", "getHours"], + ["minute", "getMinutes"], + ["second", "getSeconds"] + ]; + for (var i = 0, len = validateFields.length; i < len; i++) { + // Check to make sure the date field is within the allowed range. Javascript dates allows values + // outside the allowed range. If the values don't match the value was invalid + if (specifiedFields[validateFields[i][0]] && + dateInfo[validateFields[i][0]] !== dateTZ[validateFields[i][1]]()) { + return null; + } + } + } + else { + dateTZ = new Date(Date.UTC(dateInfo.year, dateInfo.month, dateInfo.day, dateInfo.hour, dateInfo.minute - dateInfo.timezoneOffset, dateInfo.second, dateInfo.millisecond)); + // We can't validate dates in another timezone unfortunately. Do a basic check instead + if (dateInfo.month > 11 || + dateInfo.month < 0 || + dateInfo.day > 31 || + dateInfo.day < 1 || + dateInfo.hour > 23 || + dateInfo.hour < 0 || + dateInfo.minute > 59 || + dateInfo.minute < 0 || + dateInfo.second > 59 || + dateInfo.second < 0) { + return null; + } + } + // Don't allow invalid dates + return dateTZ; +} +var fecha = { + format: format, + parse: parse, + defaultI18n: defaultI18n, + setGlobalDateI18n: setGlobalDateI18n, + setGlobalDateMasks: setGlobalDateMasks +}; + +/* harmony default export */ __webpack_exports__["default"] = (fecha); + +//# sourceMappingURL=fecha.js.map + + +/***/ }), + +/***/ "./node_modules/fn.name/index.js": +/*!***************************************!*\ + !*** ./node_modules/fn.name/index.js ***! + \***************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +var toString = Object.prototype.toString; + +/** + * Extract names from functions. + * + * @param {Function} fn The function who's name we need to extract. + * @returns {String} The name of the function. + * @public + */ +module.exports = function name(fn) { + if ('string' === typeof fn.displayName && fn.constructor.name) { + return fn.displayName; + } else if ('string' === typeof fn.name && fn.name) { + return fn.name; + } + + // + // Check to see if the constructor has a name. + // + if ( + 'object' === typeof fn + && fn.constructor + && 'string' === typeof fn.constructor.name + ) return fn.constructor.name; + + // + // toString the given function and attempt to parse it out of it, or determine + // the class. + // + var named = fn.toString() + , type = toString.call(fn).slice(8, -1); + + if ('Function' === type) { + named = named.substring(named.indexOf('(') + 1, named.indexOf(')')); + } else { + named = type; + } + + return named || 'anonymous'; +}; + + +/***/ }), + +/***/ "./node_modules/function-bind/implementation.js": +/*!******************************************************!*\ + !*** ./node_modules/function-bind/implementation.js ***! + \******************************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +/* eslint no-invalid-this: 1 */ + +var ERROR_MESSAGE = 'Function.prototype.bind called on incompatible '; +var toStr = Object.prototype.toString; +var max = Math.max; +var funcType = '[object Function]'; + +var concatty = function concatty(a, b) { + var arr = []; + + for (var i = 0; i < a.length; i += 1) { + arr[i] = a[i]; + } + for (var j = 0; j < b.length; j += 1) { + arr[j + a.length] = b[j]; + } + + return arr; +}; + +var slicy = function slicy(arrLike, offset) { + var arr = []; + for (var i = offset || 0, j = 0; i < arrLike.length; i += 1, j += 1) { + arr[j] = arrLike[i]; + } + return arr; +}; + +var joiny = function (arr, joiner) { + var str = ''; + for (var i = 0; i < arr.length; i += 1) { + str += arr[i]; + if (i + 1 < arr.length) { + str += joiner; + } + } + return str; +}; + +module.exports = function bind(that) { + var target = this; + if (typeof target !== 'function' || toStr.apply(target) !== funcType) { + throw new TypeError(ERROR_MESSAGE + target); + } + var args = slicy(arguments, 1); + + var bound; + var binder = function () { + if (this instanceof bound) { + var result = target.apply( + this, + concatty(args, arguments) + ); + if (Object(result) === result) { + return result; + } + return this; + } + return target.apply( + that, + concatty(args, arguments) + ); + + }; + + var boundLength = max(0, target.length - args.length); + var boundArgs = []; + for (var i = 0; i < boundLength; i++) { + boundArgs[i] = '$' + i; + } + + bound = Function('binder', 'return function (' + joiny(boundArgs, ',') + '){ return binder.apply(this,arguments); }')(binder); + + if (target.prototype) { + var Empty = function Empty() {}; + Empty.prototype = target.prototype; + bound.prototype = new Empty(); + Empty.prototype = null; + } + + return bound; +}; + + +/***/ }), + +/***/ "./node_modules/function-bind/index.js": +/*!*********************************************!*\ + !*** ./node_modules/function-bind/index.js ***! + \*********************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +var implementation = __webpack_require__(/*! ./implementation */ "./node_modules/function-bind/implementation.js"); + +module.exports = Function.prototype.bind || implementation; + + +/***/ }), + +/***/ "./node_modules/get-intrinsic/index.js": +/*!*********************************************!*\ + !*** ./node_modules/get-intrinsic/index.js ***! + \*********************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +var undefined; + +var $Error = __webpack_require__(/*! es-errors */ "./node_modules/es-errors/index.js"); +var $EvalError = __webpack_require__(/*! es-errors/eval */ "./node_modules/es-errors/eval.js"); +var $RangeError = __webpack_require__(/*! es-errors/range */ "./node_modules/es-errors/range.js"); +var $ReferenceError = __webpack_require__(/*! es-errors/ref */ "./node_modules/es-errors/ref.js"); +var $SyntaxError = __webpack_require__(/*! es-errors/syntax */ "./node_modules/es-errors/syntax.js"); +var $TypeError = __webpack_require__(/*! es-errors/type */ "./node_modules/es-errors/type.js"); +var $URIError = __webpack_require__(/*! es-errors/uri */ "./node_modules/es-errors/uri.js"); + +var $Function = Function; + +// eslint-disable-next-line consistent-return +var getEvalledConstructor = function (expressionSyntax) { + try { + return $Function('"use strict"; return (' + expressionSyntax + ').constructor;')(); + } catch (e) {} +}; + +var $gOPD = Object.getOwnPropertyDescriptor; +if ($gOPD) { + try { + $gOPD({}, ''); + } catch (e) { + $gOPD = null; // this is IE 8, which has a broken gOPD + } +} + +var throwTypeError = function () { + throw new $TypeError(); +}; +var ThrowTypeError = $gOPD + ? (function () { + try { + // eslint-disable-next-line no-unused-expressions, no-caller, no-restricted-properties + arguments.callee; // IE 8 does not throw here + return throwTypeError; + } catch (calleeThrows) { + try { + // IE 8 throws on Object.getOwnPropertyDescriptor(arguments, '') + return $gOPD(arguments, 'callee').get; + } catch (gOPDthrows) { + return throwTypeError; + } + } + }()) + : throwTypeError; + +var hasSymbols = __webpack_require__(/*! has-symbols */ "./node_modules/has-symbols/index.js")(); +var hasProto = __webpack_require__(/*! has-proto */ "./node_modules/has-proto/index.js")(); + +var getProto = Object.getPrototypeOf || ( + hasProto + ? function (x) { return x.__proto__; } // eslint-disable-line no-proto + : null +); + +var needsEval = {}; + +var TypedArray = typeof Uint8Array === 'undefined' || !getProto ? undefined : getProto(Uint8Array); + +var INTRINSICS = { + __proto__: null, + '%AggregateError%': typeof AggregateError === 'undefined' ? undefined : AggregateError, + '%Array%': Array, + '%ArrayBuffer%': typeof ArrayBuffer === 'undefined' ? undefined : ArrayBuffer, + '%ArrayIteratorPrototype%': hasSymbols && getProto ? getProto([][Symbol.iterator]()) : undefined, + '%AsyncFromSyncIteratorPrototype%': undefined, + '%AsyncFunction%': needsEval, + '%AsyncGenerator%': needsEval, + '%AsyncGeneratorFunction%': needsEval, + '%AsyncIteratorPrototype%': needsEval, + '%Atomics%': typeof Atomics === 'undefined' ? undefined : Atomics, + '%BigInt%': typeof BigInt === 'undefined' ? undefined : BigInt, + '%BigInt64Array%': typeof BigInt64Array === 'undefined' ? undefined : BigInt64Array, + '%BigUint64Array%': typeof BigUint64Array === 'undefined' ? undefined : BigUint64Array, + '%Boolean%': Boolean, + '%DataView%': typeof DataView === 'undefined' ? undefined : DataView, + '%Date%': Date, + '%decodeURI%': decodeURI, + '%decodeURIComponent%': decodeURIComponent, + '%encodeURI%': encodeURI, + '%encodeURIComponent%': encodeURIComponent, + '%Error%': $Error, + '%eval%': eval, // eslint-disable-line no-eval + '%EvalError%': $EvalError, + '%Float32Array%': typeof Float32Array === 'undefined' ? undefined : Float32Array, + '%Float64Array%': typeof Float64Array === 'undefined' ? undefined : Float64Array, + '%FinalizationRegistry%': typeof FinalizationRegistry === 'undefined' ? undefined : FinalizationRegistry, + '%Function%': $Function, + '%GeneratorFunction%': needsEval, + '%Int8Array%': typeof Int8Array === 'undefined' ? undefined : Int8Array, + '%Int16Array%': typeof Int16Array === 'undefined' ? undefined : Int16Array, + '%Int32Array%': typeof Int32Array === 'undefined' ? undefined : Int32Array, + '%isFinite%': isFinite, + '%isNaN%': isNaN, + '%IteratorPrototype%': hasSymbols && getProto ? getProto(getProto([][Symbol.iterator]())) : undefined, + '%JSON%': typeof JSON === 'object' ? JSON : undefined, + '%Map%': typeof Map === 'undefined' ? undefined : Map, + '%MapIteratorPrototype%': typeof Map === 'undefined' || !hasSymbols || !getProto ? undefined : getProto(new Map()[Symbol.iterator]()), + '%Math%': Math, + '%Number%': Number, + '%Object%': Object, + '%parseFloat%': parseFloat, + '%parseInt%': parseInt, + '%Promise%': typeof Promise === 'undefined' ? undefined : Promise, + '%Proxy%': typeof Proxy === 'undefined' ? undefined : Proxy, + '%RangeError%': $RangeError, + '%ReferenceError%': $ReferenceError, + '%Reflect%': typeof Reflect === 'undefined' ? undefined : Reflect, + '%RegExp%': RegExp, + '%Set%': typeof Set === 'undefined' ? undefined : Set, + '%SetIteratorPrototype%': typeof Set === 'undefined' || !hasSymbols || !getProto ? undefined : getProto(new Set()[Symbol.iterator]()), + '%SharedArrayBuffer%': typeof SharedArrayBuffer === 'undefined' ? undefined : SharedArrayBuffer, + '%String%': String, + '%StringIteratorPrototype%': hasSymbols && getProto ? getProto(''[Symbol.iterator]()) : undefined, + '%Symbol%': hasSymbols ? Symbol : undefined, + '%SyntaxError%': $SyntaxError, + '%ThrowTypeError%': ThrowTypeError, + '%TypedArray%': TypedArray, + '%TypeError%': $TypeError, + '%Uint8Array%': typeof Uint8Array === 'undefined' ? undefined : Uint8Array, + '%Uint8ClampedArray%': typeof Uint8ClampedArray === 'undefined' ? undefined : Uint8ClampedArray, + '%Uint16Array%': typeof Uint16Array === 'undefined' ? undefined : Uint16Array, + '%Uint32Array%': typeof Uint32Array === 'undefined' ? undefined : Uint32Array, + '%URIError%': $URIError, + '%WeakMap%': typeof WeakMap === 'undefined' ? undefined : WeakMap, + '%WeakRef%': typeof WeakRef === 'undefined' ? undefined : WeakRef, + '%WeakSet%': typeof WeakSet === 'undefined' ? undefined : WeakSet +}; + +if (getProto) { + try { + null.error; // eslint-disable-line no-unused-expressions + } catch (e) { + // https://github.com/tc39/proposal-shadowrealm/pull/384#issuecomment-1364264229 + var errorProto = getProto(getProto(e)); + INTRINSICS['%Error.prototype%'] = errorProto; + } +} + +var doEval = function doEval(name) { + var value; + if (name === '%AsyncFunction%') { + value = getEvalledConstructor('async function () {}'); + } else if (name === '%GeneratorFunction%') { + value = getEvalledConstructor('function* () {}'); + } else if (name === '%AsyncGeneratorFunction%') { + value = getEvalledConstructor('async function* () {}'); + } else if (name === '%AsyncGenerator%') { + var fn = doEval('%AsyncGeneratorFunction%'); + if (fn) { + value = fn.prototype; + } + } else if (name === '%AsyncIteratorPrototype%') { + var gen = doEval('%AsyncGenerator%'); + if (gen && getProto) { + value = getProto(gen.prototype); + } + } + + INTRINSICS[name] = value; + + return value; +}; + +var LEGACY_ALIASES = { + __proto__: null, + '%ArrayBufferPrototype%': ['ArrayBuffer', 'prototype'], + '%ArrayPrototype%': ['Array', 'prototype'], + '%ArrayProto_entries%': ['Array', 'prototype', 'entries'], + '%ArrayProto_forEach%': ['Array', 'prototype', 'forEach'], + '%ArrayProto_keys%': ['Array', 'prototype', 'keys'], + '%ArrayProto_values%': ['Array', 'prototype', 'values'], + '%AsyncFunctionPrototype%': ['AsyncFunction', 'prototype'], + '%AsyncGenerator%': ['AsyncGeneratorFunction', 'prototype'], + '%AsyncGeneratorPrototype%': ['AsyncGeneratorFunction', 'prototype', 'prototype'], + '%BooleanPrototype%': ['Boolean', 'prototype'], + '%DataViewPrototype%': ['DataView', 'prototype'], + '%DatePrototype%': ['Date', 'prototype'], + '%ErrorPrototype%': ['Error', 'prototype'], + '%EvalErrorPrototype%': ['EvalError', 'prototype'], + '%Float32ArrayPrototype%': ['Float32Array', 'prototype'], + '%Float64ArrayPrototype%': ['Float64Array', 'prototype'], + '%FunctionPrototype%': ['Function', 'prototype'], + '%Generator%': ['GeneratorFunction', 'prototype'], + '%GeneratorPrototype%': ['GeneratorFunction', 'prototype', 'prototype'], + '%Int8ArrayPrototype%': ['Int8Array', 'prototype'], + '%Int16ArrayPrototype%': ['Int16Array', 'prototype'], + '%Int32ArrayPrototype%': ['Int32Array', 'prototype'], + '%JSONParse%': ['JSON', 'parse'], + '%JSONStringify%': ['JSON', 'stringify'], + '%MapPrototype%': ['Map', 'prototype'], + '%NumberPrototype%': ['Number', 'prototype'], + '%ObjectPrototype%': ['Object', 'prototype'], + '%ObjProto_toString%': ['Object', 'prototype', 'toString'], + '%ObjProto_valueOf%': ['Object', 'prototype', 'valueOf'], + '%PromisePrototype%': ['Promise', 'prototype'], + '%PromiseProto_then%': ['Promise', 'prototype', 'then'], + '%Promise_all%': ['Promise', 'all'], + '%Promise_reject%': ['Promise', 'reject'], + '%Promise_resolve%': ['Promise', 'resolve'], + '%RangeErrorPrototype%': ['RangeError', 'prototype'], + '%ReferenceErrorPrototype%': ['ReferenceError', 'prototype'], + '%RegExpPrototype%': ['RegExp', 'prototype'], + '%SetPrototype%': ['Set', 'prototype'], + '%SharedArrayBufferPrototype%': ['SharedArrayBuffer', 'prototype'], + '%StringPrototype%': ['String', 'prototype'], + '%SymbolPrototype%': ['Symbol', 'prototype'], + '%SyntaxErrorPrototype%': ['SyntaxError', 'prototype'], + '%TypedArrayPrototype%': ['TypedArray', 'prototype'], + '%TypeErrorPrototype%': ['TypeError', 'prototype'], + '%Uint8ArrayPrototype%': ['Uint8Array', 'prototype'], + '%Uint8ClampedArrayPrototype%': ['Uint8ClampedArray', 'prototype'], + '%Uint16ArrayPrototype%': ['Uint16Array', 'prototype'], + '%Uint32ArrayPrototype%': ['Uint32Array', 'prototype'], + '%URIErrorPrototype%': ['URIError', 'prototype'], + '%WeakMapPrototype%': ['WeakMap', 'prototype'], + '%WeakSetPrototype%': ['WeakSet', 'prototype'] +}; + +var bind = __webpack_require__(/*! function-bind */ "./node_modules/function-bind/index.js"); +var hasOwn = __webpack_require__(/*! hasown */ "./node_modules/hasown/index.js"); +var $concat = bind.call(Function.call, Array.prototype.concat); +var $spliceApply = bind.call(Function.apply, Array.prototype.splice); +var $replace = bind.call(Function.call, String.prototype.replace); +var $strSlice = bind.call(Function.call, String.prototype.slice); +var $exec = bind.call(Function.call, RegExp.prototype.exec); + +/* adapted from https://github.com/lodash/lodash/blob/4.17.15/dist/lodash.js#L6735-L6744 */ +var rePropName = /[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g; +var reEscapeChar = /\\(\\)?/g; /** Used to match backslashes in property paths. */ +var stringToPath = function stringToPath(string) { + var first = $strSlice(string, 0, 1); + var last = $strSlice(string, -1); + if (first === '%' && last !== '%') { + throw new $SyntaxError('invalid intrinsic syntax, expected closing `%`'); + } else if (last === '%' && first !== '%') { + throw new $SyntaxError('invalid intrinsic syntax, expected opening `%`'); + } + var result = []; + $replace(string, rePropName, function (match, number, quote, subString) { + result[result.length] = quote ? $replace(subString, reEscapeChar, '$1') : number || match; + }); + return result; +}; +/* end adaptation */ + +var getBaseIntrinsic = function getBaseIntrinsic(name, allowMissing) { + var intrinsicName = name; + var alias; + if (hasOwn(LEGACY_ALIASES, intrinsicName)) { + alias = LEGACY_ALIASES[intrinsicName]; + intrinsicName = '%' + alias[0] + '%'; + } + + if (hasOwn(INTRINSICS, intrinsicName)) { + var value = INTRINSICS[intrinsicName]; + if (value === needsEval) { + value = doEval(intrinsicName); + } + if (typeof value === 'undefined' && !allowMissing) { + throw new $TypeError('intrinsic ' + name + ' exists, but is not available. Please file an issue!'); + } + + return { + alias: alias, + name: intrinsicName, + value: value + }; + } + + throw new $SyntaxError('intrinsic ' + name + ' does not exist!'); +}; + +module.exports = function GetIntrinsic(name, allowMissing) { + if (typeof name !== 'string' || name.length === 0) { + throw new $TypeError('intrinsic name must be a non-empty string'); + } + if (arguments.length > 1 && typeof allowMissing !== 'boolean') { + throw new $TypeError('"allowMissing" argument must be a boolean'); + } + + if ($exec(/^%?[^%]*%?$/, name) === null) { + throw new $SyntaxError('`%` may not be present anywhere but at the beginning and end of the intrinsic name'); + } + var parts = stringToPath(name); + var intrinsicBaseName = parts.length > 0 ? parts[0] : ''; + + var intrinsic = getBaseIntrinsic('%' + intrinsicBaseName + '%', allowMissing); + var intrinsicRealName = intrinsic.name; + var value = intrinsic.value; + var skipFurtherCaching = false; + + var alias = intrinsic.alias; + if (alias) { + intrinsicBaseName = alias[0]; + $spliceApply(parts, $concat([0, 1], alias)); + } + + for (var i = 1, isOwn = true; i < parts.length; i += 1) { + var part = parts[i]; + var first = $strSlice(part, 0, 1); + var last = $strSlice(part, -1); + if ( + ( + (first === '"' || first === "'" || first === '`') + || (last === '"' || last === "'" || last === '`') + ) + && first !== last + ) { + throw new $SyntaxError('property names with quotes must have matching quotes'); + } + if (part === 'constructor' || !isOwn) { + skipFurtherCaching = true; + } + + intrinsicBaseName += '.' + part; + intrinsicRealName = '%' + intrinsicBaseName + '%'; + + if (hasOwn(INTRINSICS, intrinsicRealName)) { + value = INTRINSICS[intrinsicRealName]; + } else if (value != null) { + if (!(part in value)) { + if (!allowMissing) { + throw new $TypeError('base intrinsic for ' + name + ' exists, but the property is not available.'); + } + return void undefined; + } + if ($gOPD && (i + 1) >= parts.length) { + var desc = $gOPD(value, part); + isOwn = !!desc; + + // By convention, when a data property is converted to an accessor + // property to emulate a data property that does not suffer from + // the override mistake, that accessor's getter is marked with + // an `originalValue` property. Here, when we detect this, we + // uphold the illusion by pretending to see that original data + // property, i.e., returning the value rather than the getter + // itself. + if (isOwn && 'get' in desc && !('originalValue' in desc.get)) { + value = desc.get; + } else { + value = value[part]; + } + } else { + isOwn = hasOwn(value, part); + value = value[part]; + } + + if (isOwn && !skipFurtherCaching) { + INTRINSICS[intrinsicRealName] = value; + } + } + } + return value; +}; + + +/***/ }), + +/***/ "./node_modules/gopd/index.js": +/*!************************************!*\ + !*** ./node_modules/gopd/index.js ***! + \************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +var GetIntrinsic = __webpack_require__(/*! get-intrinsic */ "./node_modules/get-intrinsic/index.js"); + +var $gOPD = GetIntrinsic('%Object.getOwnPropertyDescriptor%', true); + +if ($gOPD) { + try { + $gOPD([], 'length'); + } catch (e) { + // IE 8 has a broken gOPD + $gOPD = null; + } +} + +module.exports = $gOPD; + + +/***/ }), + +/***/ "./node_modules/has-property-descriptors/index.js": +/*!********************************************************!*\ + !*** ./node_modules/has-property-descriptors/index.js ***! + \********************************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +var $defineProperty = __webpack_require__(/*! es-define-property */ "./node_modules/es-define-property/index.js"); + +var hasPropertyDescriptors = function hasPropertyDescriptors() { + return !!$defineProperty; +}; + +hasPropertyDescriptors.hasArrayLengthDefineBug = function hasArrayLengthDefineBug() { + // node v0.6 has a bug where array lengths can be Set but not Defined + if (!$defineProperty) { + return null; + } + try { + return $defineProperty([], 'length', { value: 1 }).length !== 1; + } catch (e) { + // In Firefox 4-22, defining length on an array throws an exception. + return true; + } +}; + +module.exports = hasPropertyDescriptors; + + +/***/ }), + +/***/ "./node_modules/has-proto/index.js": +/*!*****************************************!*\ + !*** ./node_modules/has-proto/index.js ***! + \*****************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +var test = { + __proto__: null, + foo: {} +}; + +var $Object = Object; + +/** @type {import('.')} */ +module.exports = function hasProto() { + // @ts-expect-error: TS errors on an inherited property for some reason + return { __proto__: test }.foo === test.foo + && !(test instanceof $Object); +}; + + +/***/ }), + +/***/ "./node_modules/has-symbols/index.js": +/*!*******************************************!*\ + !*** ./node_modules/has-symbols/index.js ***! + \*******************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +var origSymbol = typeof Symbol !== 'undefined' && Symbol; +var hasSymbolSham = __webpack_require__(/*! ./shams */ "./node_modules/has-symbols/shams.js"); + +module.exports = function hasNativeSymbols() { + if (typeof origSymbol !== 'function') { return false; } + if (typeof Symbol !== 'function') { return false; } + if (typeof origSymbol('foo') !== 'symbol') { return false; } + if (typeof Symbol('bar') !== 'symbol') { return false; } + + return hasSymbolSham(); +}; + + +/***/ }), + +/***/ "./node_modules/has-symbols/shams.js": +/*!*******************************************!*\ + !*** ./node_modules/has-symbols/shams.js ***! + \*******************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +/* eslint complexity: [2, 18], max-statements: [2, 33] */ +module.exports = function hasSymbols() { + if (typeof Symbol !== 'function' || typeof Object.getOwnPropertySymbols !== 'function') { return false; } + if (typeof Symbol.iterator === 'symbol') { return true; } + + var obj = {}; + var sym = Symbol('test'); + var symObj = Object(sym); + if (typeof sym === 'string') { return false; } + + if (Object.prototype.toString.call(sym) !== '[object Symbol]') { return false; } + if (Object.prototype.toString.call(symObj) !== '[object Symbol]') { return false; } + + // temp disabled per https://github.com/ljharb/object.assign/issues/17 + // if (sym instanceof Symbol) { return false; } + // temp disabled per https://github.com/WebReflection/get-own-property-symbols/issues/4 + // if (!(symObj instanceof Symbol)) { return false; } + + // if (typeof Symbol.prototype.toString !== 'function') { return false; } + // if (String(sym) !== Symbol.prototype.toString.call(sym)) { return false; } + + var symVal = 42; + obj[sym] = symVal; + for (sym in obj) { return false; } // eslint-disable-line no-restricted-syntax, no-unreachable-loop + if (typeof Object.keys === 'function' && Object.keys(obj).length !== 0) { return false; } + + if (typeof Object.getOwnPropertyNames === 'function' && Object.getOwnPropertyNames(obj).length !== 0) { return false; } + + var syms = Object.getOwnPropertySymbols(obj); + if (syms.length !== 1 || syms[0] !== sym) { return false; } + + if (!Object.prototype.propertyIsEnumerable.call(obj, sym)) { return false; } + + if (typeof Object.getOwnPropertyDescriptor === 'function') { + var descriptor = Object.getOwnPropertyDescriptor(obj, sym); + if (descriptor.value !== symVal || descriptor.enumerable !== true) { return false; } + } + + return true; +}; + + +/***/ }), + +/***/ "./node_modules/hasown/index.js": +/*!**************************************!*\ + !*** ./node_modules/hasown/index.js ***! + \**************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +var call = Function.prototype.call; +var $hasOwn = Object.prototype.hasOwnProperty; +var bind = __webpack_require__(/*! function-bind */ "./node_modules/function-bind/index.js"); + +/** @type {import('.')} */ +module.exports = bind.call(call, $hasOwn); + + +/***/ }), + +/***/ "./node_modules/https-browserify/index.js": +/*!************************************************!*\ + !*** ./node_modules/https-browserify/index.js ***! + \************************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +var http = __webpack_require__(/*! http */ "./node_modules/stream-http/index.js") +var url = __webpack_require__(/*! url */ "./node_modules/url/url.js") + +var https = module.exports + +for (var key in http) { + if (http.hasOwnProperty(key)) https[key] = http[key] +} + +https.request = function (params, cb) { + params = validateParams(params) + return http.request.call(this, params, cb) +} + +https.get = function (params, cb) { + params = validateParams(params) + return http.get.call(this, params, cb) +} + +function validateParams (params) { + if (typeof params === 'string') { + params = url.parse(params) + } + if (!params.protocol) { + params.protocol = 'https:' + } + if (params.protocol !== 'https:') { + throw new Error('Protocol "' + params.protocol + '" not supported. Expected "https:"') + } + return params +} + + +/***/ }), + +/***/ "./node_modules/ieee754/index.js": +/*!***************************************!*\ + !*** ./node_modules/ieee754/index.js ***! + \***************************************/ +/*! no static exports found */ +/***/ (function(module, exports) { + +/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh */ +exports.read = function (buffer, offset, isLE, mLen, nBytes) { + var e, m + var eLen = (nBytes * 8) - mLen - 1 + var eMax = (1 << eLen) - 1 + var eBias = eMax >> 1 + var nBits = -7 + var i = isLE ? (nBytes - 1) : 0 + var d = isLE ? -1 : 1 + var s = buffer[offset + i] + + i += d + + e = s & ((1 << (-nBits)) - 1) + s >>= (-nBits) + nBits += eLen + for (; nBits > 0; e = (e * 256) + buffer[offset + i], i += d, nBits -= 8) {} + + m = e & ((1 << (-nBits)) - 1) + e >>= (-nBits) + nBits += mLen + for (; nBits > 0; m = (m * 256) + buffer[offset + i], i += d, nBits -= 8) {} + + if (e === 0) { + e = 1 - eBias + } else if (e === eMax) { + return m ? NaN : ((s ? -1 : 1) * Infinity) + } else { + m = m + Math.pow(2, mLen) + e = e - eBias + } + return (s ? -1 : 1) * m * Math.pow(2, e - mLen) +} + +exports.write = function (buffer, value, offset, isLE, mLen, nBytes) { + var e, m, c + var eLen = (nBytes * 8) - mLen - 1 + var eMax = (1 << eLen) - 1 + var eBias = eMax >> 1 + var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0) + var i = isLE ? 0 : (nBytes - 1) + var d = isLE ? 1 : -1 + var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0 + + value = Math.abs(value) + + if (isNaN(value) || value === Infinity) { + m = isNaN(value) ? 1 : 0 + e = eMax + } else { + e = Math.floor(Math.log(value) / Math.LN2) + if (value * (c = Math.pow(2, -e)) < 1) { + e-- + c *= 2 + } + if (e + eBias >= 1) { + value += rt / c + } else { + value += rt * Math.pow(2, 1 - eBias) + } + if (value * c >= 2) { + e++ + c /= 2 + } + + if (e + eBias >= eMax) { + m = 0 + e = eMax + } else if (e + eBias >= 1) { + m = ((value * c) - 1) * Math.pow(2, mLen) + e = e + eBias + } else { + m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen) + e = 0 + } + } + + for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {} + + e = (e << mLen) | m + eLen += mLen + for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {} + + buffer[offset + i - d] |= s * 128 +} + + +/***/ }), + +/***/ "./node_modules/inherits/inherits.js": +/*!*******************************************!*\ + !*** ./node_modules/inherits/inherits.js ***! + \*******************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +try { + var util = __webpack_require__(/*! util */ "./node_modules/util/util.js"); + /* istanbul ignore next */ + if (typeof util.inherits !== 'function') throw ''; + module.exports = util.inherits; +} catch (e) { + /* istanbul ignore next */ + module.exports = __webpack_require__(/*! ./inherits_browser.js */ "./node_modules/inherits/inherits_browser.js"); +} + + +/***/ }), + +/***/ "./node_modules/inherits/inherits_browser.js": +/*!***************************************************!*\ + !*** ./node_modules/inherits/inherits_browser.js ***! + \***************************************************/ +/*! no static exports found */ +/***/ (function(module, exports) { + +if (typeof Object.create === 'function') { + // implementation from standard node.js 'util' module + module.exports = function inherits(ctor, superCtor) { + if (superCtor) { + ctor.super_ = superCtor + ctor.prototype = Object.create(superCtor.prototype, { + constructor: { + value: ctor, + enumerable: false, + writable: true, + configurable: true + } + }) + } + }; +} else { + // old school shim for old browsers + module.exports = function inherits(ctor, superCtor) { + if (superCtor) { + ctor.super_ = superCtor + var TempCtor = function () {} + TempCtor.prototype = superCtor.prototype + ctor.prototype = new TempCtor() + ctor.prototype.constructor = ctor + } + } +} + + +/***/ }), + +/***/ "./node_modules/is-plain-object/dist/is-plain-object.mjs": +/*!***************************************************************!*\ + !*** ./node_modules/is-plain-object/dist/is-plain-object.mjs ***! + \***************************************************************/ +/*! exports provided: isPlainObject */ +/***/ (function(__webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isPlainObject", function() { return isPlainObject; }); +/*! + * is-plain-object + * + * Copyright (c) 2014-2017, Jon Schlinkert. + * Released under the MIT License. + */ + +function isObject(o) { + return Object.prototype.toString.call(o) === '[object Object]'; +} + +function isPlainObject(o) { + var ctor,prot; + + if (isObject(o) === false) return false; + + // If has modified constructor + ctor = o.constructor; + if (ctor === undefined) return true; + + // If has modified prototype + prot = ctor.prototype; + if (isObject(prot) === false) return false; + + // If constructor does not have an Object-specific method + if (prot.hasOwnProperty('isPrototypeOf') === false) { + return false; + } + + // Most likely a plain Object + return true; +} + + + + +/***/ }), + +/***/ "./node_modules/is-stream/index.js": +/*!*****************************************!*\ + !*** ./node_modules/is-stream/index.js ***! + \*****************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +const isStream = stream => + stream !== null && + typeof stream === 'object' && + typeof stream.pipe === 'function'; + +isStream.writable = stream => + isStream(stream) && + stream.writable !== false && + typeof stream._write === 'function' && + typeof stream._writableState === 'object'; + +isStream.readable = stream => + isStream(stream) && + stream.readable !== false && + typeof stream._read === 'function' && + typeof stream._readableState === 'object'; + +isStream.duplex = stream => + isStream.writable(stream) && + isStream.readable(stream); + +isStream.transform = stream => + isStream.duplex(stream) && + typeof stream._transform === 'function'; + +module.exports = isStream; + + +/***/ }), + +/***/ "./node_modules/isarray/index.js": +/*!***************************************!*\ + !*** ./node_modules/isarray/index.js ***! + \***************************************/ +/*! no static exports found */ +/***/ (function(module, exports) { + +var toString = {}.toString; + +module.exports = Array.isArray || function (arr) { + return toString.call(arr) == '[object Array]'; +}; + + +/***/ }), + +/***/ "./node_modules/js-yaml/dist/js-yaml.mjs": +/*!***********************************************!*\ + !*** ./node_modules/js-yaml/dist/js-yaml.mjs ***! + \***********************************************/ +/*! exports provided: default, CORE_SCHEMA, DEFAULT_SCHEMA, FAILSAFE_SCHEMA, JSON_SCHEMA, Schema, Type, YAMLException, dump, load, loadAll, safeDump, safeLoad, safeLoadAll, types */ +/***/ (function(__webpack_module__, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CORE_SCHEMA", function() { return CORE_SCHEMA; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DEFAULT_SCHEMA", function() { return DEFAULT_SCHEMA; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "FAILSAFE_SCHEMA", function() { return FAILSAFE_SCHEMA; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "JSON_SCHEMA", function() { return JSON_SCHEMA; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Schema", function() { return Schema; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Type", function() { return Type; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "YAMLException", function() { return YAMLException; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "dump", function() { return dump; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "load", function() { return load; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "loadAll", function() { return loadAll; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "safeDump", function() { return safeDump; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "safeLoad", function() { return safeLoad; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "safeLoadAll", function() { return safeLoadAll; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "types", function() { return types; }); + +/*! js-yaml 4.1.0 https://github.com/nodeca/js-yaml @license MIT */ +function isNothing(subject) { + return (typeof subject === 'undefined') || (subject === null); +} + + +function isObject(subject) { + return (typeof subject === 'object') && (subject !== null); +} + + +function toArray(sequence) { + if (Array.isArray(sequence)) return sequence; + else if (isNothing(sequence)) return []; + + return [ sequence ]; +} + + +function extend(target, source) { + var index, length, key, sourceKeys; + + if (source) { + sourceKeys = Object.keys(source); + + for (index = 0, length = sourceKeys.length; index < length; index += 1) { + key = sourceKeys[index]; + target[key] = source[key]; + } + } + + return target; +} + + +function repeat(string, count) { + var result = '', cycle; + + for (cycle = 0; cycle < count; cycle += 1) { + result += string; + } + + return result; +} + + +function isNegativeZero(number) { + return (number === 0) && (Number.NEGATIVE_INFINITY === 1 / number); +} + + +var isNothing_1 = isNothing; +var isObject_1 = isObject; +var toArray_1 = toArray; +var repeat_1 = repeat; +var isNegativeZero_1 = isNegativeZero; +var extend_1 = extend; + +var common = { + isNothing: isNothing_1, + isObject: isObject_1, + toArray: toArray_1, + repeat: repeat_1, + isNegativeZero: isNegativeZero_1, + extend: extend_1 +}; + +// YAML error class. http://stackoverflow.com/questions/8458984 + + +function formatError(exception, compact) { + var where = '', message = exception.reason || '(unknown reason)'; + + if (!exception.mark) return message; + + if (exception.mark.name) { + where += 'in "' + exception.mark.name + '" '; + } + + where += '(' + (exception.mark.line + 1) + ':' + (exception.mark.column + 1) + ')'; + + if (!compact && exception.mark.snippet) { + where += '\n\n' + exception.mark.snippet; + } + + return message + ' ' + where; +} + + +function YAMLException$1(reason, mark) { + // Super constructor + Error.call(this); + + this.name = 'YAMLException'; + this.reason = reason; + this.mark = mark; + this.message = formatError(this, false); + + // Include stack trace in error object + if (Error.captureStackTrace) { + // Chrome and NodeJS + Error.captureStackTrace(this, this.constructor); + } else { + // FF, IE 10+ and Safari 6+. Fallback for others + this.stack = (new Error()).stack || ''; + } +} + + +// Inherit from Error +YAMLException$1.prototype = Object.create(Error.prototype); +YAMLException$1.prototype.constructor = YAMLException$1; + + +YAMLException$1.prototype.toString = function toString(compact) { + return this.name + ': ' + formatError(this, compact); +}; + + +var exception = YAMLException$1; + +// get snippet for a single line, respecting maxLength +function getLine(buffer, lineStart, lineEnd, position, maxLineLength) { + var head = ''; + var tail = ''; + var maxHalfLength = Math.floor(maxLineLength / 2) - 1; + + if (position - lineStart > maxHalfLength) { + head = ' ... '; + lineStart = position - maxHalfLength + head.length; + } + + if (lineEnd - position > maxHalfLength) { + tail = ' ...'; + lineEnd = position + maxHalfLength - tail.length; + } + + return { + str: head + buffer.slice(lineStart, lineEnd).replace(/\t/g, '→') + tail, + pos: position - lineStart + head.length // relative position + }; +} + + +function padStart(string, max) { + return common.repeat(' ', max - string.length) + string; +} + + +function makeSnippet(mark, options) { + options = Object.create(options || null); + + if (!mark.buffer) return null; + + if (!options.maxLength) options.maxLength = 79; + if (typeof options.indent !== 'number') options.indent = 1; + if (typeof options.linesBefore !== 'number') options.linesBefore = 3; + if (typeof options.linesAfter !== 'number') options.linesAfter = 2; + + var re = /\r?\n|\r|\0/g; + var lineStarts = [ 0 ]; + var lineEnds = []; + var match; + var foundLineNo = -1; + + while ((match = re.exec(mark.buffer))) { + lineEnds.push(match.index); + lineStarts.push(match.index + match[0].length); + + if (mark.position <= match.index && foundLineNo < 0) { + foundLineNo = lineStarts.length - 2; + } + } + + if (foundLineNo < 0) foundLineNo = lineStarts.length - 1; + + var result = '', i, line; + var lineNoLength = Math.min(mark.line + options.linesAfter, lineEnds.length).toString().length; + var maxLineLength = options.maxLength - (options.indent + lineNoLength + 3); + + for (i = 1; i <= options.linesBefore; i++) { + if (foundLineNo - i < 0) break; + line = getLine( + mark.buffer, + lineStarts[foundLineNo - i], + lineEnds[foundLineNo - i], + mark.position - (lineStarts[foundLineNo] - lineStarts[foundLineNo - i]), + maxLineLength + ); + result = common.repeat(' ', options.indent) + padStart((mark.line - i + 1).toString(), lineNoLength) + + ' | ' + line.str + '\n' + result; + } + + line = getLine(mark.buffer, lineStarts[foundLineNo], lineEnds[foundLineNo], mark.position, maxLineLength); + result += common.repeat(' ', options.indent) + padStart((mark.line + 1).toString(), lineNoLength) + + ' | ' + line.str + '\n'; + result += common.repeat('-', options.indent + lineNoLength + 3 + line.pos) + '^' + '\n'; + + for (i = 1; i <= options.linesAfter; i++) { + if (foundLineNo + i >= lineEnds.length) break; + line = getLine( + mark.buffer, + lineStarts[foundLineNo + i], + lineEnds[foundLineNo + i], + mark.position - (lineStarts[foundLineNo] - lineStarts[foundLineNo + i]), + maxLineLength + ); + result += common.repeat(' ', options.indent) + padStart((mark.line + i + 1).toString(), lineNoLength) + + ' | ' + line.str + '\n'; + } + + return result.replace(/\n$/, ''); +} + + +var snippet = makeSnippet; + +var TYPE_CONSTRUCTOR_OPTIONS = [ + 'kind', + 'multi', + 'resolve', + 'construct', + 'instanceOf', + 'predicate', + 'represent', + 'representName', + 'defaultStyle', + 'styleAliases' +]; + +var YAML_NODE_KINDS = [ + 'scalar', + 'sequence', + 'mapping' +]; + +function compileStyleAliases(map) { + var result = {}; + + if (map !== null) { + Object.keys(map).forEach(function (style) { + map[style].forEach(function (alias) { + result[String(alias)] = style; + }); + }); + } + + return result; +} + +function Type$1(tag, options) { + options = options || {}; + + Object.keys(options).forEach(function (name) { + if (TYPE_CONSTRUCTOR_OPTIONS.indexOf(name) === -1) { + throw new exception('Unknown option "' + name + '" is met in definition of "' + tag + '" YAML type.'); + } + }); + + // TODO: Add tag format check. + this.options = options; // keep original options in case user wants to extend this type later + this.tag = tag; + this.kind = options['kind'] || null; + this.resolve = options['resolve'] || function () { return true; }; + this.construct = options['construct'] || function (data) { return data; }; + this.instanceOf = options['instanceOf'] || null; + this.predicate = options['predicate'] || null; + this.represent = options['represent'] || null; + this.representName = options['representName'] || null; + this.defaultStyle = options['defaultStyle'] || null; + this.multi = options['multi'] || false; + this.styleAliases = compileStyleAliases(options['styleAliases'] || null); + + if (YAML_NODE_KINDS.indexOf(this.kind) === -1) { + throw new exception('Unknown kind "' + this.kind + '" is specified for "' + tag + '" YAML type.'); + } +} + +var type = Type$1; + +/*eslint-disable max-len*/ + + + + + +function compileList(schema, name) { + var result = []; + + schema[name].forEach(function (currentType) { + var newIndex = result.length; + + result.forEach(function (previousType, previousIndex) { + if (previousType.tag === currentType.tag && + previousType.kind === currentType.kind && + previousType.multi === currentType.multi) { + + newIndex = previousIndex; + } + }); + + result[newIndex] = currentType; + }); + + return result; +} + + +function compileMap(/* lists... */) { + var result = { + scalar: {}, + sequence: {}, + mapping: {}, + fallback: {}, + multi: { + scalar: [], + sequence: [], + mapping: [], + fallback: [] + } + }, index, length; + + function collectType(type) { + if (type.multi) { + result.multi[type.kind].push(type); + result.multi['fallback'].push(type); + } else { + result[type.kind][type.tag] = result['fallback'][type.tag] = type; + } + } + + for (index = 0, length = arguments.length; index < length; index += 1) { + arguments[index].forEach(collectType); + } + return result; +} + + +function Schema$1(definition) { + return this.extend(definition); +} + + +Schema$1.prototype.extend = function extend(definition) { + var implicit = []; + var explicit = []; + + if (definition instanceof type) { + // Schema.extend(type) + explicit.push(definition); + + } else if (Array.isArray(definition)) { + // Schema.extend([ type1, type2, ... ]) + explicit = explicit.concat(definition); + + } else if (definition && (Array.isArray(definition.implicit) || Array.isArray(definition.explicit))) { + // Schema.extend({ explicit: [ type1, type2, ... ], implicit: [ type1, type2, ... ] }) + if (definition.implicit) implicit = implicit.concat(definition.implicit); + if (definition.explicit) explicit = explicit.concat(definition.explicit); + + } else { + throw new exception('Schema.extend argument should be a Type, [ Type ], ' + + 'or a schema definition ({ implicit: [...], explicit: [...] })'); + } + + implicit.forEach(function (type$1) { + if (!(type$1 instanceof type)) { + throw new exception('Specified list of YAML types (or a single Type object) contains a non-Type object.'); + } + + if (type$1.loadKind && type$1.loadKind !== 'scalar') { + throw new exception('There is a non-scalar type in the implicit list of a schema. Implicit resolving of such types is not supported.'); + } + + if (type$1.multi) { + throw new exception('There is a multi type in the implicit list of a schema. Multi tags can only be listed as explicit.'); + } + }); + + explicit.forEach(function (type$1) { + if (!(type$1 instanceof type)) { + throw new exception('Specified list of YAML types (or a single Type object) contains a non-Type object.'); + } + }); + + var result = Object.create(Schema$1.prototype); + + result.implicit = (this.implicit || []).concat(implicit); + result.explicit = (this.explicit || []).concat(explicit); + + result.compiledImplicit = compileList(result, 'implicit'); + result.compiledExplicit = compileList(result, 'explicit'); + result.compiledTypeMap = compileMap(result.compiledImplicit, result.compiledExplicit); + + return result; +}; + + +var schema = Schema$1; + +var str = new type('tag:yaml.org,2002:str', { + kind: 'scalar', + construct: function (data) { return data !== null ? data : ''; } +}); + +var seq = new type('tag:yaml.org,2002:seq', { + kind: 'sequence', + construct: function (data) { return data !== null ? data : []; } +}); + +var map = new type('tag:yaml.org,2002:map', { + kind: 'mapping', + construct: function (data) { return data !== null ? data : {}; } +}); + +var failsafe = new schema({ + explicit: [ + str, + seq, + map + ] +}); + +function resolveYamlNull(data) { + if (data === null) return true; + + var max = data.length; + + return (max === 1 && data === '~') || + (max === 4 && (data === 'null' || data === 'Null' || data === 'NULL')); +} + +function constructYamlNull() { + return null; +} + +function isNull(object) { + return object === null; +} + +var _null = new type('tag:yaml.org,2002:null', { + kind: 'scalar', + resolve: resolveYamlNull, + construct: constructYamlNull, + predicate: isNull, + represent: { + canonical: function () { return '~'; }, + lowercase: function () { return 'null'; }, + uppercase: function () { return 'NULL'; }, + camelcase: function () { return 'Null'; }, + empty: function () { return ''; } + }, + defaultStyle: 'lowercase' +}); + +function resolveYamlBoolean(data) { + if (data === null) return false; + + var max = data.length; + + return (max === 4 && (data === 'true' || data === 'True' || data === 'TRUE')) || + (max === 5 && (data === 'false' || data === 'False' || data === 'FALSE')); +} + +function constructYamlBoolean(data) { + return data === 'true' || + data === 'True' || + data === 'TRUE'; +} + +function isBoolean(object) { + return Object.prototype.toString.call(object) === '[object Boolean]'; +} + +var bool = new type('tag:yaml.org,2002:bool', { + kind: 'scalar', + resolve: resolveYamlBoolean, + construct: constructYamlBoolean, + predicate: isBoolean, + represent: { + lowercase: function (object) { return object ? 'true' : 'false'; }, + uppercase: function (object) { return object ? 'TRUE' : 'FALSE'; }, + camelcase: function (object) { return object ? 'True' : 'False'; } + }, + defaultStyle: 'lowercase' +}); + +function isHexCode(c) { + return ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)) || + ((0x41/* A */ <= c) && (c <= 0x46/* F */)) || + ((0x61/* a */ <= c) && (c <= 0x66/* f */)); +} + +function isOctCode(c) { + return ((0x30/* 0 */ <= c) && (c <= 0x37/* 7 */)); +} + +function isDecCode(c) { + return ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)); +} + +function resolveYamlInteger(data) { + if (data === null) return false; + + var max = data.length, + index = 0, + hasDigits = false, + ch; + + if (!max) return false; + + ch = data[index]; + + // sign + if (ch === '-' || ch === '+') { + ch = data[++index]; + } + + if (ch === '0') { + // 0 + if (index + 1 === max) return true; + ch = data[++index]; + + // base 2, base 8, base 16 + + if (ch === 'b') { + // base 2 + index++; + + for (; index < max; index++) { + ch = data[index]; + if (ch === '_') continue; + if (ch !== '0' && ch !== '1') return false; + hasDigits = true; + } + return hasDigits && ch !== '_'; + } + + + if (ch === 'x') { + // base 16 + index++; + + for (; index < max; index++) { + ch = data[index]; + if (ch === '_') continue; + if (!isHexCode(data.charCodeAt(index))) return false; + hasDigits = true; + } + return hasDigits && ch !== '_'; + } + + + if (ch === 'o') { + // base 8 + index++; + + for (; index < max; index++) { + ch = data[index]; + if (ch === '_') continue; + if (!isOctCode(data.charCodeAt(index))) return false; + hasDigits = true; + } + return hasDigits && ch !== '_'; + } + } + + // base 10 (except 0) + + // value should not start with `_`; + if (ch === '_') return false; + + for (; index < max; index++) { + ch = data[index]; + if (ch === '_') continue; + if (!isDecCode(data.charCodeAt(index))) { + return false; + } + hasDigits = true; + } + + // Should have digits and should not end with `_` + if (!hasDigits || ch === '_') return false; + + return true; +} + +function constructYamlInteger(data) { + var value = data, sign = 1, ch; + + if (value.indexOf('_') !== -1) { + value = value.replace(/_/g, ''); + } + + ch = value[0]; + + if (ch === '-' || ch === '+') { + if (ch === '-') sign = -1; + value = value.slice(1); + ch = value[0]; + } + + if (value === '0') return 0; + + if (ch === '0') { + if (value[1] === 'b') return sign * parseInt(value.slice(2), 2); + if (value[1] === 'x') return sign * parseInt(value.slice(2), 16); + if (value[1] === 'o') return sign * parseInt(value.slice(2), 8); + } + + return sign * parseInt(value, 10); +} + +function isInteger(object) { + return (Object.prototype.toString.call(object)) === '[object Number]' && + (object % 1 === 0 && !common.isNegativeZero(object)); +} + +var int = new type('tag:yaml.org,2002:int', { + kind: 'scalar', + resolve: resolveYamlInteger, + construct: constructYamlInteger, + predicate: isInteger, + represent: { + binary: function (obj) { return obj >= 0 ? '0b' + obj.toString(2) : '-0b' + obj.toString(2).slice(1); }, + octal: function (obj) { return obj >= 0 ? '0o' + obj.toString(8) : '-0o' + obj.toString(8).slice(1); }, + decimal: function (obj) { return obj.toString(10); }, + /* eslint-disable max-len */ + hexadecimal: function (obj) { return obj >= 0 ? '0x' + obj.toString(16).toUpperCase() : '-0x' + obj.toString(16).toUpperCase().slice(1); } + }, + defaultStyle: 'decimal', + styleAliases: { + binary: [ 2, 'bin' ], + octal: [ 8, 'oct' ], + decimal: [ 10, 'dec' ], + hexadecimal: [ 16, 'hex' ] + } +}); + +var YAML_FLOAT_PATTERN = new RegExp( + // 2.5e4, 2.5 and integers + '^(?:[-+]?(?:[0-9][0-9_]*)(?:\\.[0-9_]*)?(?:[eE][-+]?[0-9]+)?' + + // .2e4, .2 + // special case, seems not from spec + '|\\.[0-9_]+(?:[eE][-+]?[0-9]+)?' + + // .inf + '|[-+]?\\.(?:inf|Inf|INF)' + + // .nan + '|\\.(?:nan|NaN|NAN))$'); + +function resolveYamlFloat(data) { + if (data === null) return false; + + if (!YAML_FLOAT_PATTERN.test(data) || + // Quick hack to not allow integers end with `_` + // Probably should update regexp & check speed + data[data.length - 1] === '_') { + return false; + } + + return true; +} + +function constructYamlFloat(data) { + var value, sign; + + value = data.replace(/_/g, '').toLowerCase(); + sign = value[0] === '-' ? -1 : 1; + + if ('+-'.indexOf(value[0]) >= 0) { + value = value.slice(1); + } + + if (value === '.inf') { + return (sign === 1) ? Number.POSITIVE_INFINITY : Number.NEGATIVE_INFINITY; + + } else if (value === '.nan') { + return NaN; + } + return sign * parseFloat(value, 10); +} + + +var SCIENTIFIC_WITHOUT_DOT = /^[-+]?[0-9]+e/; + +function representYamlFloat(object, style) { + var res; + + if (isNaN(object)) { + switch (style) { + case 'lowercase': return '.nan'; + case 'uppercase': return '.NAN'; + case 'camelcase': return '.NaN'; + } + } else if (Number.POSITIVE_INFINITY === object) { + switch (style) { + case 'lowercase': return '.inf'; + case 'uppercase': return '.INF'; + case 'camelcase': return '.Inf'; + } + } else if (Number.NEGATIVE_INFINITY === object) { + switch (style) { + case 'lowercase': return '-.inf'; + case 'uppercase': return '-.INF'; + case 'camelcase': return '-.Inf'; + } + } else if (common.isNegativeZero(object)) { + return '-0.0'; + } + + res = object.toString(10); + + // JS stringifier can build scientific format without dots: 5e-100, + // while YAML requres dot: 5.e-100. Fix it with simple hack + + return SCIENTIFIC_WITHOUT_DOT.test(res) ? res.replace('e', '.e') : res; +} + +function isFloat(object) { + return (Object.prototype.toString.call(object) === '[object Number]') && + (object % 1 !== 0 || common.isNegativeZero(object)); +} + +var float = new type('tag:yaml.org,2002:float', { + kind: 'scalar', + resolve: resolveYamlFloat, + construct: constructYamlFloat, + predicate: isFloat, + represent: representYamlFloat, + defaultStyle: 'lowercase' +}); + +var json = failsafe.extend({ + implicit: [ + _null, + bool, + int, + float + ] +}); + +var core = json; + +var YAML_DATE_REGEXP = new RegExp( + '^([0-9][0-9][0-9][0-9])' + // [1] year + '-([0-9][0-9])' + // [2] month + '-([0-9][0-9])$'); // [3] day + +var YAML_TIMESTAMP_REGEXP = new RegExp( + '^([0-9][0-9][0-9][0-9])' + // [1] year + '-([0-9][0-9]?)' + // [2] month + '-([0-9][0-9]?)' + // [3] day + '(?:[Tt]|[ \\t]+)' + // ... + '([0-9][0-9]?)' + // [4] hour + ':([0-9][0-9])' + // [5] minute + ':([0-9][0-9])' + // [6] second + '(?:\\.([0-9]*))?' + // [7] fraction + '(?:[ \\t]*(Z|([-+])([0-9][0-9]?)' + // [8] tz [9] tz_sign [10] tz_hour + '(?::([0-9][0-9]))?))?$'); // [11] tz_minute + +function resolveYamlTimestamp(data) { + if (data === null) return false; + if (YAML_DATE_REGEXP.exec(data) !== null) return true; + if (YAML_TIMESTAMP_REGEXP.exec(data) !== null) return true; + return false; +} + +function constructYamlTimestamp(data) { + var match, year, month, day, hour, minute, second, fraction = 0, + delta = null, tz_hour, tz_minute, date; + + match = YAML_DATE_REGEXP.exec(data); + if (match === null) match = YAML_TIMESTAMP_REGEXP.exec(data); + + if (match === null) throw new Error('Date resolve error'); + + // match: [1] year [2] month [3] day + + year = +(match[1]); + month = +(match[2]) - 1; // JS month starts with 0 + day = +(match[3]); + + if (!match[4]) { // no hour + return new Date(Date.UTC(year, month, day)); + } + + // match: [4] hour [5] minute [6] second [7] fraction + + hour = +(match[4]); + minute = +(match[5]); + second = +(match[6]); + + if (match[7]) { + fraction = match[7].slice(0, 3); + while (fraction.length < 3) { // milli-seconds + fraction += '0'; + } + fraction = +fraction; + } + + // match: [8] tz [9] tz_sign [10] tz_hour [11] tz_minute + + if (match[9]) { + tz_hour = +(match[10]); + tz_minute = +(match[11] || 0); + delta = (tz_hour * 60 + tz_minute) * 60000; // delta in mili-seconds + if (match[9] === '-') delta = -delta; + } + + date = new Date(Date.UTC(year, month, day, hour, minute, second, fraction)); + + if (delta) date.setTime(date.getTime() - delta); + + return date; +} + +function representYamlTimestamp(object /*, style*/) { + return object.toISOString(); +} + +var timestamp = new type('tag:yaml.org,2002:timestamp', { + kind: 'scalar', + resolve: resolveYamlTimestamp, + construct: constructYamlTimestamp, + instanceOf: Date, + represent: representYamlTimestamp +}); + +function resolveYamlMerge(data) { + return data === '<<' || data === null; +} + +var merge = new type('tag:yaml.org,2002:merge', { + kind: 'scalar', + resolve: resolveYamlMerge +}); + +/*eslint-disable no-bitwise*/ + + + + + +// [ 64, 65, 66 ] -> [ padding, CR, LF ] +var BASE64_MAP = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=\n\r'; + + +function resolveYamlBinary(data) { + if (data === null) return false; + + var code, idx, bitlen = 0, max = data.length, map = BASE64_MAP; + + // Convert one by one. + for (idx = 0; idx < max; idx++) { + code = map.indexOf(data.charAt(idx)); + + // Skip CR/LF + if (code > 64) continue; + + // Fail on illegal characters + if (code < 0) return false; + + bitlen += 6; + } + + // If there are any bits left, source was corrupted + return (bitlen % 8) === 0; +} + +function constructYamlBinary(data) { + var idx, tailbits, + input = data.replace(/[\r\n=]/g, ''), // remove CR/LF & padding to simplify scan + max = input.length, + map = BASE64_MAP, + bits = 0, + result = []; + + // Collect by 6*4 bits (3 bytes) + + for (idx = 0; idx < max; idx++) { + if ((idx % 4 === 0) && idx) { + result.push((bits >> 16) & 0xFF); + result.push((bits >> 8) & 0xFF); + result.push(bits & 0xFF); + } + + bits = (bits << 6) | map.indexOf(input.charAt(idx)); + } + + // Dump tail + + tailbits = (max % 4) * 6; + + if (tailbits === 0) { + result.push((bits >> 16) & 0xFF); + result.push((bits >> 8) & 0xFF); + result.push(bits & 0xFF); + } else if (tailbits === 18) { + result.push((bits >> 10) & 0xFF); + result.push((bits >> 2) & 0xFF); + } else if (tailbits === 12) { + result.push((bits >> 4) & 0xFF); + } + + return new Uint8Array(result); +} + +function representYamlBinary(object /*, style*/) { + var result = '', bits = 0, idx, tail, + max = object.length, + map = BASE64_MAP; + + // Convert every three bytes to 4 ASCII characters. + + for (idx = 0; idx < max; idx++) { + if ((idx % 3 === 0) && idx) { + result += map[(bits >> 18) & 0x3F]; + result += map[(bits >> 12) & 0x3F]; + result += map[(bits >> 6) & 0x3F]; + result += map[bits & 0x3F]; + } + + bits = (bits << 8) + object[idx]; + } + + // Dump tail + + tail = max % 3; + + if (tail === 0) { + result += map[(bits >> 18) & 0x3F]; + result += map[(bits >> 12) & 0x3F]; + result += map[(bits >> 6) & 0x3F]; + result += map[bits & 0x3F]; + } else if (tail === 2) { + result += map[(bits >> 10) & 0x3F]; + result += map[(bits >> 4) & 0x3F]; + result += map[(bits << 2) & 0x3F]; + result += map[64]; + } else if (tail === 1) { + result += map[(bits >> 2) & 0x3F]; + result += map[(bits << 4) & 0x3F]; + result += map[64]; + result += map[64]; + } + + return result; +} + +function isBinary(obj) { + return Object.prototype.toString.call(obj) === '[object Uint8Array]'; +} + +var binary = new type('tag:yaml.org,2002:binary', { + kind: 'scalar', + resolve: resolveYamlBinary, + construct: constructYamlBinary, + predicate: isBinary, + represent: representYamlBinary +}); + +var _hasOwnProperty$3 = Object.prototype.hasOwnProperty; +var _toString$2 = Object.prototype.toString; + +function resolveYamlOmap(data) { + if (data === null) return true; + + var objectKeys = [], index, length, pair, pairKey, pairHasKey, + object = data; + + for (index = 0, length = object.length; index < length; index += 1) { + pair = object[index]; + pairHasKey = false; + + if (_toString$2.call(pair) !== '[object Object]') return false; + + for (pairKey in pair) { + if (_hasOwnProperty$3.call(pair, pairKey)) { + if (!pairHasKey) pairHasKey = true; + else return false; + } + } + + if (!pairHasKey) return false; + + if (objectKeys.indexOf(pairKey) === -1) objectKeys.push(pairKey); + else return false; + } + + return true; +} + +function constructYamlOmap(data) { + return data !== null ? data : []; +} + +var omap = new type('tag:yaml.org,2002:omap', { + kind: 'sequence', + resolve: resolveYamlOmap, + construct: constructYamlOmap +}); + +var _toString$1 = Object.prototype.toString; + +function resolveYamlPairs(data) { + if (data === null) return true; + + var index, length, pair, keys, result, + object = data; + + result = new Array(object.length); + + for (index = 0, length = object.length; index < length; index += 1) { + pair = object[index]; + + if (_toString$1.call(pair) !== '[object Object]') return false; + + keys = Object.keys(pair); + + if (keys.length !== 1) return false; + + result[index] = [ keys[0], pair[keys[0]] ]; + } + + return true; +} + +function constructYamlPairs(data) { + if (data === null) return []; + + var index, length, pair, keys, result, + object = data; + + result = new Array(object.length); + + for (index = 0, length = object.length; index < length; index += 1) { + pair = object[index]; + + keys = Object.keys(pair); + + result[index] = [ keys[0], pair[keys[0]] ]; + } + + return result; +} + +var pairs = new type('tag:yaml.org,2002:pairs', { + kind: 'sequence', + resolve: resolveYamlPairs, + construct: constructYamlPairs +}); + +var _hasOwnProperty$2 = Object.prototype.hasOwnProperty; + +function resolveYamlSet(data) { + if (data === null) return true; + + var key, object = data; + + for (key in object) { + if (_hasOwnProperty$2.call(object, key)) { + if (object[key] !== null) return false; + } + } + + return true; +} + +function constructYamlSet(data) { + return data !== null ? data : {}; +} + +var set = new type('tag:yaml.org,2002:set', { + kind: 'mapping', + resolve: resolveYamlSet, + construct: constructYamlSet +}); + +var _default = core.extend({ + implicit: [ + timestamp, + merge + ], + explicit: [ + binary, + omap, + pairs, + set + ] +}); + +/*eslint-disable max-len,no-use-before-define*/ + + + + + + + +var _hasOwnProperty$1 = Object.prototype.hasOwnProperty; + + +var CONTEXT_FLOW_IN = 1; +var CONTEXT_FLOW_OUT = 2; +var CONTEXT_BLOCK_IN = 3; +var CONTEXT_BLOCK_OUT = 4; + + +var CHOMPING_CLIP = 1; +var CHOMPING_STRIP = 2; +var CHOMPING_KEEP = 3; + + +var PATTERN_NON_PRINTABLE = /[\x00-\x08\x0B\x0C\x0E-\x1F\x7F-\x84\x86-\x9F\uFFFE\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/; +var PATTERN_NON_ASCII_LINE_BREAKS = /[\x85\u2028\u2029]/; +var PATTERN_FLOW_INDICATORS = /[,\[\]\{\}]/; +var PATTERN_TAG_HANDLE = /^(?:!|!!|![a-z\-]+!)$/i; +var PATTERN_TAG_URI = /^(?:!|[^,\[\]\{\}])(?:%[0-9a-f]{2}|[0-9a-z\-#;\/\?:@&=\+\$,_\.!~\*'\(\)\[\]])*$/i; + + +function _class(obj) { return Object.prototype.toString.call(obj); } + +function is_EOL(c) { + return (c === 0x0A/* LF */) || (c === 0x0D/* CR */); +} + +function is_WHITE_SPACE(c) { + return (c === 0x09/* Tab */) || (c === 0x20/* Space */); +} + +function is_WS_OR_EOL(c) { + return (c === 0x09/* Tab */) || + (c === 0x20/* Space */) || + (c === 0x0A/* LF */) || + (c === 0x0D/* CR */); +} + +function is_FLOW_INDICATOR(c) { + return c === 0x2C/* , */ || + c === 0x5B/* [ */ || + c === 0x5D/* ] */ || + c === 0x7B/* { */ || + c === 0x7D/* } */; +} + +function fromHexCode(c) { + var lc; + + if ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)) { + return c - 0x30; + } + + /*eslint-disable no-bitwise*/ + lc = c | 0x20; + + if ((0x61/* a */ <= lc) && (lc <= 0x66/* f */)) { + return lc - 0x61 + 10; + } + + return -1; +} + +function escapedHexLen(c) { + if (c === 0x78/* x */) { return 2; } + if (c === 0x75/* u */) { return 4; } + if (c === 0x55/* U */) { return 8; } + return 0; +} + +function fromDecimalCode(c) { + if ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)) { + return c - 0x30; + } + + return -1; +} + +function simpleEscapeSequence(c) { + /* eslint-disable indent */ + return (c === 0x30/* 0 */) ? '\x00' : + (c === 0x61/* a */) ? '\x07' : + (c === 0x62/* b */) ? '\x08' : + (c === 0x74/* t */) ? '\x09' : + (c === 0x09/* Tab */) ? '\x09' : + (c === 0x6E/* n */) ? '\x0A' : + (c === 0x76/* v */) ? '\x0B' : + (c === 0x66/* f */) ? '\x0C' : + (c === 0x72/* r */) ? '\x0D' : + (c === 0x65/* e */) ? '\x1B' : + (c === 0x20/* Space */) ? ' ' : + (c === 0x22/* " */) ? '\x22' : + (c === 0x2F/* / */) ? '/' : + (c === 0x5C/* \ */) ? '\x5C' : + (c === 0x4E/* N */) ? '\x85' : + (c === 0x5F/* _ */) ? '\xA0' : + (c === 0x4C/* L */) ? '\u2028' : + (c === 0x50/* P */) ? '\u2029' : ''; +} + +function charFromCodepoint(c) { + if (c <= 0xFFFF) { + return String.fromCharCode(c); + } + // Encode UTF-16 surrogate pair + // https://en.wikipedia.org/wiki/UTF-16#Code_points_U.2B010000_to_U.2B10FFFF + return String.fromCharCode( + ((c - 0x010000) >> 10) + 0xD800, + ((c - 0x010000) & 0x03FF) + 0xDC00 + ); +} + +var simpleEscapeCheck = new Array(256); // integer, for fast access +var simpleEscapeMap = new Array(256); +for (var i = 0; i < 256; i++) { + simpleEscapeCheck[i] = simpleEscapeSequence(i) ? 1 : 0; + simpleEscapeMap[i] = simpleEscapeSequence(i); +} + + +function State$1(input, options) { + this.input = input; + + this.filename = options['filename'] || null; + this.schema = options['schema'] || _default; + this.onWarning = options['onWarning'] || null; + // (Hidden) Remove? makes the loader to expect YAML 1.1 documents + // if such documents have no explicit %YAML directive + this.legacy = options['legacy'] || false; + + this.json = options['json'] || false; + this.listener = options['listener'] || null; + + this.implicitTypes = this.schema.compiledImplicit; + this.typeMap = this.schema.compiledTypeMap; + + this.length = input.length; + this.position = 0; + this.line = 0; + this.lineStart = 0; + this.lineIndent = 0; + + // position of first leading tab in the current line, + // used to make sure there are no tabs in the indentation + this.firstTabInLine = -1; + + this.documents = []; + + /* + this.version; + this.checkLineBreaks; + this.tagMap; + this.anchorMap; + this.tag; + this.anchor; + this.kind; + this.result;*/ + +} + + +function generateError(state, message) { + var mark = { + name: state.filename, + buffer: state.input.slice(0, -1), // omit trailing \0 + position: state.position, + line: state.line, + column: state.position - state.lineStart + }; + + mark.snippet = snippet(mark); + + return new exception(message, mark); +} + +function throwError(state, message) { + throw generateError(state, message); +} + +function throwWarning(state, message) { + if (state.onWarning) { + state.onWarning.call(null, generateError(state, message)); + } +} + + +var directiveHandlers = { + + YAML: function handleYamlDirective(state, name, args) { + + var match, major, minor; + + if (state.version !== null) { + throwError(state, 'duplication of %YAML directive'); + } + + if (args.length !== 1) { + throwError(state, 'YAML directive accepts exactly one argument'); + } + + match = /^([0-9]+)\.([0-9]+)$/.exec(args[0]); + + if (match === null) { + throwError(state, 'ill-formed argument of the YAML directive'); + } + + major = parseInt(match[1], 10); + minor = parseInt(match[2], 10); + + if (major !== 1) { + throwError(state, 'unacceptable YAML version of the document'); + } + + state.version = args[0]; + state.checkLineBreaks = (minor < 2); + + if (minor !== 1 && minor !== 2) { + throwWarning(state, 'unsupported YAML version of the document'); + } + }, + + TAG: function handleTagDirective(state, name, args) { + + var handle, prefix; + + if (args.length !== 2) { + throwError(state, 'TAG directive accepts exactly two arguments'); + } + + handle = args[0]; + prefix = args[1]; + + if (!PATTERN_TAG_HANDLE.test(handle)) { + throwError(state, 'ill-formed tag handle (first argument) of the TAG directive'); + } + + if (_hasOwnProperty$1.call(state.tagMap, handle)) { + throwError(state, 'there is a previously declared suffix for "' + handle + '" tag handle'); + } + + if (!PATTERN_TAG_URI.test(prefix)) { + throwError(state, 'ill-formed tag prefix (second argument) of the TAG directive'); + } + + try { + prefix = decodeURIComponent(prefix); + } catch (err) { + throwError(state, 'tag prefix is malformed: ' + prefix); + } + + state.tagMap[handle] = prefix; + } +}; + + +function captureSegment(state, start, end, checkJson) { + var _position, _length, _character, _result; + + if (start < end) { + _result = state.input.slice(start, end); + + if (checkJson) { + for (_position = 0, _length = _result.length; _position < _length; _position += 1) { + _character = _result.charCodeAt(_position); + if (!(_character === 0x09 || + (0x20 <= _character && _character <= 0x10FFFF))) { + throwError(state, 'expected valid JSON character'); + } + } + } else if (PATTERN_NON_PRINTABLE.test(_result)) { + throwError(state, 'the stream contains non-printable characters'); + } + + state.result += _result; + } +} + +function mergeMappings(state, destination, source, overridableKeys) { + var sourceKeys, key, index, quantity; + + if (!common.isObject(source)) { + throwError(state, 'cannot merge mappings; the provided source object is unacceptable'); + } + + sourceKeys = Object.keys(source); + + for (index = 0, quantity = sourceKeys.length; index < quantity; index += 1) { + key = sourceKeys[index]; + + if (!_hasOwnProperty$1.call(destination, key)) { + destination[key] = source[key]; + overridableKeys[key] = true; + } + } +} + +function storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode, + startLine, startLineStart, startPos) { + + var index, quantity; + + // The output is a plain object here, so keys can only be strings. + // We need to convert keyNode to a string, but doing so can hang the process + // (deeply nested arrays that explode exponentially using aliases). + if (Array.isArray(keyNode)) { + keyNode = Array.prototype.slice.call(keyNode); + + for (index = 0, quantity = keyNode.length; index < quantity; index += 1) { + if (Array.isArray(keyNode[index])) { + throwError(state, 'nested arrays are not supported inside keys'); + } + + if (typeof keyNode === 'object' && _class(keyNode[index]) === '[object Object]') { + keyNode[index] = '[object Object]'; + } + } + } + + // Avoid code execution in load() via toString property + // (still use its own toString for arrays, timestamps, + // and whatever user schema extensions happen to have @@toStringTag) + if (typeof keyNode === 'object' && _class(keyNode) === '[object Object]') { + keyNode = '[object Object]'; + } + + + keyNode = String(keyNode); + + if (_result === null) { + _result = {}; + } + + if (keyTag === 'tag:yaml.org,2002:merge') { + if (Array.isArray(valueNode)) { + for (index = 0, quantity = valueNode.length; index < quantity; index += 1) { + mergeMappings(state, _result, valueNode[index], overridableKeys); + } + } else { + mergeMappings(state, _result, valueNode, overridableKeys); + } + } else { + if (!state.json && + !_hasOwnProperty$1.call(overridableKeys, keyNode) && + _hasOwnProperty$1.call(_result, keyNode)) { + state.line = startLine || state.line; + state.lineStart = startLineStart || state.lineStart; + state.position = startPos || state.position; + throwError(state, 'duplicated mapping key'); + } + + // used for this specific key only because Object.defineProperty is slow + if (keyNode === '__proto__') { + Object.defineProperty(_result, keyNode, { + configurable: true, + enumerable: true, + writable: true, + value: valueNode + }); + } else { + _result[keyNode] = valueNode; + } + delete overridableKeys[keyNode]; + } + + return _result; +} + +function readLineBreak(state) { + var ch; + + ch = state.input.charCodeAt(state.position); + + if (ch === 0x0A/* LF */) { + state.position++; + } else if (ch === 0x0D/* CR */) { + state.position++; + if (state.input.charCodeAt(state.position) === 0x0A/* LF */) { + state.position++; + } + } else { + throwError(state, 'a line break is expected'); + } + + state.line += 1; + state.lineStart = state.position; + state.firstTabInLine = -1; +} + +function skipSeparationSpace(state, allowComments, checkIndent) { + var lineBreaks = 0, + ch = state.input.charCodeAt(state.position); + + while (ch !== 0) { + while (is_WHITE_SPACE(ch)) { + if (ch === 0x09/* Tab */ && state.firstTabInLine === -1) { + state.firstTabInLine = state.position; + } + ch = state.input.charCodeAt(++state.position); + } + + if (allowComments && ch === 0x23/* # */) { + do { + ch = state.input.charCodeAt(++state.position); + } while (ch !== 0x0A/* LF */ && ch !== 0x0D/* CR */ && ch !== 0); + } + + if (is_EOL(ch)) { + readLineBreak(state); + + ch = state.input.charCodeAt(state.position); + lineBreaks++; + state.lineIndent = 0; + + while (ch === 0x20/* Space */) { + state.lineIndent++; + ch = state.input.charCodeAt(++state.position); + } + } else { + break; + } + } + + if (checkIndent !== -1 && lineBreaks !== 0 && state.lineIndent < checkIndent) { + throwWarning(state, 'deficient indentation'); + } + + return lineBreaks; +} + +function testDocumentSeparator(state) { + var _position = state.position, + ch; + + ch = state.input.charCodeAt(_position); + + // Condition state.position === state.lineStart is tested + // in parent on each call, for efficiency. No needs to test here again. + if ((ch === 0x2D/* - */ || ch === 0x2E/* . */) && + ch === state.input.charCodeAt(_position + 1) && + ch === state.input.charCodeAt(_position + 2)) { + + _position += 3; + + ch = state.input.charCodeAt(_position); + + if (ch === 0 || is_WS_OR_EOL(ch)) { + return true; + } + } + + return false; +} + +function writeFoldedLines(state, count) { + if (count === 1) { + state.result += ' '; + } else if (count > 1) { + state.result += common.repeat('\n', count - 1); + } +} + + +function readPlainScalar(state, nodeIndent, withinFlowCollection) { + var preceding, + following, + captureStart, + captureEnd, + hasPendingContent, + _line, + _lineStart, + _lineIndent, + _kind = state.kind, + _result = state.result, + ch; + + ch = state.input.charCodeAt(state.position); + + if (is_WS_OR_EOL(ch) || + is_FLOW_INDICATOR(ch) || + ch === 0x23/* # */ || + ch === 0x26/* & */ || + ch === 0x2A/* * */ || + ch === 0x21/* ! */ || + ch === 0x7C/* | */ || + ch === 0x3E/* > */ || + ch === 0x27/* ' */ || + ch === 0x22/* " */ || + ch === 0x25/* % */ || + ch === 0x40/* @ */ || + ch === 0x60/* ` */) { + return false; + } + + if (ch === 0x3F/* ? */ || ch === 0x2D/* - */) { + following = state.input.charCodeAt(state.position + 1); + + if (is_WS_OR_EOL(following) || + withinFlowCollection && is_FLOW_INDICATOR(following)) { + return false; + } + } + + state.kind = 'scalar'; + state.result = ''; + captureStart = captureEnd = state.position; + hasPendingContent = false; + + while (ch !== 0) { + if (ch === 0x3A/* : */) { + following = state.input.charCodeAt(state.position + 1); + + if (is_WS_OR_EOL(following) || + withinFlowCollection && is_FLOW_INDICATOR(following)) { + break; + } + + } else if (ch === 0x23/* # */) { + preceding = state.input.charCodeAt(state.position - 1); + + if (is_WS_OR_EOL(preceding)) { + break; + } + + } else if ((state.position === state.lineStart && testDocumentSeparator(state)) || + withinFlowCollection && is_FLOW_INDICATOR(ch)) { + break; + + } else if (is_EOL(ch)) { + _line = state.line; + _lineStart = state.lineStart; + _lineIndent = state.lineIndent; + skipSeparationSpace(state, false, -1); + + if (state.lineIndent >= nodeIndent) { + hasPendingContent = true; + ch = state.input.charCodeAt(state.position); + continue; + } else { + state.position = captureEnd; + state.line = _line; + state.lineStart = _lineStart; + state.lineIndent = _lineIndent; + break; + } + } + + if (hasPendingContent) { + captureSegment(state, captureStart, captureEnd, false); + writeFoldedLines(state, state.line - _line); + captureStart = captureEnd = state.position; + hasPendingContent = false; + } + + if (!is_WHITE_SPACE(ch)) { + captureEnd = state.position + 1; + } + + ch = state.input.charCodeAt(++state.position); + } + + captureSegment(state, captureStart, captureEnd, false); + + if (state.result) { + return true; + } + + state.kind = _kind; + state.result = _result; + return false; +} + +function readSingleQuotedScalar(state, nodeIndent) { + var ch, + captureStart, captureEnd; + + ch = state.input.charCodeAt(state.position); + + if (ch !== 0x27/* ' */) { + return false; + } + + state.kind = 'scalar'; + state.result = ''; + state.position++; + captureStart = captureEnd = state.position; + + while ((ch = state.input.charCodeAt(state.position)) !== 0) { + if (ch === 0x27/* ' */) { + captureSegment(state, captureStart, state.position, true); + ch = state.input.charCodeAt(++state.position); + + if (ch === 0x27/* ' */) { + captureStart = state.position; + state.position++; + captureEnd = state.position; + } else { + return true; + } + + } else if (is_EOL(ch)) { + captureSegment(state, captureStart, captureEnd, true); + writeFoldedLines(state, skipSeparationSpace(state, false, nodeIndent)); + captureStart = captureEnd = state.position; + + } else if (state.position === state.lineStart && testDocumentSeparator(state)) { + throwError(state, 'unexpected end of the document within a single quoted scalar'); + + } else { + state.position++; + captureEnd = state.position; + } + } + + throwError(state, 'unexpected end of the stream within a single quoted scalar'); +} + +function readDoubleQuotedScalar(state, nodeIndent) { + var captureStart, + captureEnd, + hexLength, + hexResult, + tmp, + ch; + + ch = state.input.charCodeAt(state.position); + + if (ch !== 0x22/* " */) { + return false; + } + + state.kind = 'scalar'; + state.result = ''; + state.position++; + captureStart = captureEnd = state.position; + + while ((ch = state.input.charCodeAt(state.position)) !== 0) { + if (ch === 0x22/* " */) { + captureSegment(state, captureStart, state.position, true); + state.position++; + return true; + + } else if (ch === 0x5C/* \ */) { + captureSegment(state, captureStart, state.position, true); + ch = state.input.charCodeAt(++state.position); + + if (is_EOL(ch)) { + skipSeparationSpace(state, false, nodeIndent); + + // TODO: rework to inline fn with no type cast? + } else if (ch < 256 && simpleEscapeCheck[ch]) { + state.result += simpleEscapeMap[ch]; + state.position++; + + } else if ((tmp = escapedHexLen(ch)) > 0) { + hexLength = tmp; + hexResult = 0; + + for (; hexLength > 0; hexLength--) { + ch = state.input.charCodeAt(++state.position); + + if ((tmp = fromHexCode(ch)) >= 0) { + hexResult = (hexResult << 4) + tmp; + + } else { + throwError(state, 'expected hexadecimal character'); + } + } + + state.result += charFromCodepoint(hexResult); + + state.position++; + + } else { + throwError(state, 'unknown escape sequence'); + } + + captureStart = captureEnd = state.position; + + } else if (is_EOL(ch)) { + captureSegment(state, captureStart, captureEnd, true); + writeFoldedLines(state, skipSeparationSpace(state, false, nodeIndent)); + captureStart = captureEnd = state.position; + + } else if (state.position === state.lineStart && testDocumentSeparator(state)) { + throwError(state, 'unexpected end of the document within a double quoted scalar'); + + } else { + state.position++; + captureEnd = state.position; + } + } + + throwError(state, 'unexpected end of the stream within a double quoted scalar'); +} + +function readFlowCollection(state, nodeIndent) { + var readNext = true, + _line, + _lineStart, + _pos, + _tag = state.tag, + _result, + _anchor = state.anchor, + following, + terminator, + isPair, + isExplicitPair, + isMapping, + overridableKeys = Object.create(null), + keyNode, + keyTag, + valueNode, + ch; + + ch = state.input.charCodeAt(state.position); + + if (ch === 0x5B/* [ */) { + terminator = 0x5D;/* ] */ + isMapping = false; + _result = []; + } else if (ch === 0x7B/* { */) { + terminator = 0x7D;/* } */ + isMapping = true; + _result = {}; + } else { + return false; + } + + if (state.anchor !== null) { + state.anchorMap[state.anchor] = _result; + } + + ch = state.input.charCodeAt(++state.position); + + while (ch !== 0) { + skipSeparationSpace(state, true, nodeIndent); + + ch = state.input.charCodeAt(state.position); + + if (ch === terminator) { + state.position++; + state.tag = _tag; + state.anchor = _anchor; + state.kind = isMapping ? 'mapping' : 'sequence'; + state.result = _result; + return true; + } else if (!readNext) { + throwError(state, 'missed comma between flow collection entries'); + } else if (ch === 0x2C/* , */) { + // "flow collection entries can never be completely empty", as per YAML 1.2, section 7.4 + throwError(state, "expected the node content, but found ','"); + } + + keyTag = keyNode = valueNode = null; + isPair = isExplicitPair = false; + + if (ch === 0x3F/* ? */) { + following = state.input.charCodeAt(state.position + 1); + + if (is_WS_OR_EOL(following)) { + isPair = isExplicitPair = true; + state.position++; + skipSeparationSpace(state, true, nodeIndent); + } + } + + _line = state.line; // Save the current line. + _lineStart = state.lineStart; + _pos = state.position; + composeNode(state, nodeIndent, CONTEXT_FLOW_IN, false, true); + keyTag = state.tag; + keyNode = state.result; + skipSeparationSpace(state, true, nodeIndent); + + ch = state.input.charCodeAt(state.position); + + if ((isExplicitPair || state.line === _line) && ch === 0x3A/* : */) { + isPair = true; + ch = state.input.charCodeAt(++state.position); + skipSeparationSpace(state, true, nodeIndent); + composeNode(state, nodeIndent, CONTEXT_FLOW_IN, false, true); + valueNode = state.result; + } + + if (isMapping) { + storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode, _line, _lineStart, _pos); + } else if (isPair) { + _result.push(storeMappingPair(state, null, overridableKeys, keyTag, keyNode, valueNode, _line, _lineStart, _pos)); + } else { + _result.push(keyNode); + } + + skipSeparationSpace(state, true, nodeIndent); + + ch = state.input.charCodeAt(state.position); + + if (ch === 0x2C/* , */) { + readNext = true; + ch = state.input.charCodeAt(++state.position); + } else { + readNext = false; + } + } + + throwError(state, 'unexpected end of the stream within a flow collection'); +} + +function readBlockScalar(state, nodeIndent) { + var captureStart, + folding, + chomping = CHOMPING_CLIP, + didReadContent = false, + detectedIndent = false, + textIndent = nodeIndent, + emptyLines = 0, + atMoreIndented = false, + tmp, + ch; + + ch = state.input.charCodeAt(state.position); + + if (ch === 0x7C/* | */) { + folding = false; + } else if (ch === 0x3E/* > */) { + folding = true; + } else { + return false; + } + + state.kind = 'scalar'; + state.result = ''; + + while (ch !== 0) { + ch = state.input.charCodeAt(++state.position); + + if (ch === 0x2B/* + */ || ch === 0x2D/* - */) { + if (CHOMPING_CLIP === chomping) { + chomping = (ch === 0x2B/* + */) ? CHOMPING_KEEP : CHOMPING_STRIP; + } else { + throwError(state, 'repeat of a chomping mode identifier'); + } + + } else if ((tmp = fromDecimalCode(ch)) >= 0) { + if (tmp === 0) { + throwError(state, 'bad explicit indentation width of a block scalar; it cannot be less than one'); + } else if (!detectedIndent) { + textIndent = nodeIndent + tmp - 1; + detectedIndent = true; + } else { + throwError(state, 'repeat of an indentation width identifier'); + } + + } else { + break; + } + } + + if (is_WHITE_SPACE(ch)) { + do { ch = state.input.charCodeAt(++state.position); } + while (is_WHITE_SPACE(ch)); + + if (ch === 0x23/* # */) { + do { ch = state.input.charCodeAt(++state.position); } + while (!is_EOL(ch) && (ch !== 0)); + } + } + + while (ch !== 0) { + readLineBreak(state); + state.lineIndent = 0; + + ch = state.input.charCodeAt(state.position); + + while ((!detectedIndent || state.lineIndent < textIndent) && + (ch === 0x20/* Space */)) { + state.lineIndent++; + ch = state.input.charCodeAt(++state.position); + } + + if (!detectedIndent && state.lineIndent > textIndent) { + textIndent = state.lineIndent; + } + + if (is_EOL(ch)) { + emptyLines++; + continue; + } + + // End of the scalar. + if (state.lineIndent < textIndent) { + + // Perform the chomping. + if (chomping === CHOMPING_KEEP) { + state.result += common.repeat('\n', didReadContent ? 1 + emptyLines : emptyLines); + } else if (chomping === CHOMPING_CLIP) { + if (didReadContent) { // i.e. only if the scalar is not empty. + state.result += '\n'; + } + } + + // Break this `while` cycle and go to the funciton's epilogue. + break; + } + + // Folded style: use fancy rules to handle line breaks. + if (folding) { + + // Lines starting with white space characters (more-indented lines) are not folded. + if (is_WHITE_SPACE(ch)) { + atMoreIndented = true; + // except for the first content line (cf. Example 8.1) + state.result += common.repeat('\n', didReadContent ? 1 + emptyLines : emptyLines); + + // End of more-indented block. + } else if (atMoreIndented) { + atMoreIndented = false; + state.result += common.repeat('\n', emptyLines + 1); + + // Just one line break - perceive as the same line. + } else if (emptyLines === 0) { + if (didReadContent) { // i.e. only if we have already read some scalar content. + state.result += ' '; + } + + // Several line breaks - perceive as different lines. + } else { + state.result += common.repeat('\n', emptyLines); + } + + // Literal style: just add exact number of line breaks between content lines. + } else { + // Keep all line breaks except the header line break. + state.result += common.repeat('\n', didReadContent ? 1 + emptyLines : emptyLines); + } + + didReadContent = true; + detectedIndent = true; + emptyLines = 0; + captureStart = state.position; + + while (!is_EOL(ch) && (ch !== 0)) { + ch = state.input.charCodeAt(++state.position); + } + + captureSegment(state, captureStart, state.position, false); + } + + return true; +} + +function readBlockSequence(state, nodeIndent) { + var _line, + _tag = state.tag, + _anchor = state.anchor, + _result = [], + following, + detected = false, + ch; + + // there is a leading tab before this token, so it can't be a block sequence/mapping; + // it can still be flow sequence/mapping or a scalar + if (state.firstTabInLine !== -1) return false; + + if (state.anchor !== null) { + state.anchorMap[state.anchor] = _result; + } + + ch = state.input.charCodeAt(state.position); + + while (ch !== 0) { + if (state.firstTabInLine !== -1) { + state.position = state.firstTabInLine; + throwError(state, 'tab characters must not be used in indentation'); + } + + if (ch !== 0x2D/* - */) { + break; + } + + following = state.input.charCodeAt(state.position + 1); + + if (!is_WS_OR_EOL(following)) { + break; + } + + detected = true; + state.position++; + + if (skipSeparationSpace(state, true, -1)) { + if (state.lineIndent <= nodeIndent) { + _result.push(null); + ch = state.input.charCodeAt(state.position); + continue; + } + } + + _line = state.line; + composeNode(state, nodeIndent, CONTEXT_BLOCK_IN, false, true); + _result.push(state.result); + skipSeparationSpace(state, true, -1); + + ch = state.input.charCodeAt(state.position); + + if ((state.line === _line || state.lineIndent > nodeIndent) && (ch !== 0)) { + throwError(state, 'bad indentation of a sequence entry'); + } else if (state.lineIndent < nodeIndent) { + break; + } + } + + if (detected) { + state.tag = _tag; + state.anchor = _anchor; + state.kind = 'sequence'; + state.result = _result; + return true; + } + return false; +} + +function readBlockMapping(state, nodeIndent, flowIndent) { + var following, + allowCompact, + _line, + _keyLine, + _keyLineStart, + _keyPos, + _tag = state.tag, + _anchor = state.anchor, + _result = {}, + overridableKeys = Object.create(null), + keyTag = null, + keyNode = null, + valueNode = null, + atExplicitKey = false, + detected = false, + ch; + + // there is a leading tab before this token, so it can't be a block sequence/mapping; + // it can still be flow sequence/mapping or a scalar + if (state.firstTabInLine !== -1) return false; + + if (state.anchor !== null) { + state.anchorMap[state.anchor] = _result; + } + + ch = state.input.charCodeAt(state.position); + + while (ch !== 0) { + if (!atExplicitKey && state.firstTabInLine !== -1) { + state.position = state.firstTabInLine; + throwError(state, 'tab characters must not be used in indentation'); + } + + following = state.input.charCodeAt(state.position + 1); + _line = state.line; // Save the current line. + + // + // Explicit notation case. There are two separate blocks: + // first for the key (denoted by "?") and second for the value (denoted by ":") + // + if ((ch === 0x3F/* ? */ || ch === 0x3A/* : */) && is_WS_OR_EOL(following)) { + + if (ch === 0x3F/* ? */) { + if (atExplicitKey) { + storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null, _keyLine, _keyLineStart, _keyPos); + keyTag = keyNode = valueNode = null; + } + + detected = true; + atExplicitKey = true; + allowCompact = true; + + } else if (atExplicitKey) { + // i.e. 0x3A/* : */ === character after the explicit key. + atExplicitKey = false; + allowCompact = true; + + } else { + throwError(state, 'incomplete explicit mapping pair; a key node is missed; or followed by a non-tabulated empty line'); + } + + state.position += 1; + ch = following; + + // + // Implicit notation case. Flow-style node as the key first, then ":", and the value. + // + } else { + _keyLine = state.line; + _keyLineStart = state.lineStart; + _keyPos = state.position; + + if (!composeNode(state, flowIndent, CONTEXT_FLOW_OUT, false, true)) { + // Neither implicit nor explicit notation. + // Reading is done. Go to the epilogue. + break; + } + + if (state.line === _line) { + ch = state.input.charCodeAt(state.position); + + while (is_WHITE_SPACE(ch)) { + ch = state.input.charCodeAt(++state.position); + } + + if (ch === 0x3A/* : */) { + ch = state.input.charCodeAt(++state.position); + + if (!is_WS_OR_EOL(ch)) { + throwError(state, 'a whitespace character is expected after the key-value separator within a block mapping'); + } + + if (atExplicitKey) { + storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null, _keyLine, _keyLineStart, _keyPos); + keyTag = keyNode = valueNode = null; + } + + detected = true; + atExplicitKey = false; + allowCompact = false; + keyTag = state.tag; + keyNode = state.result; + + } else if (detected) { + throwError(state, 'can not read an implicit mapping pair; a colon is missed'); + + } else { + state.tag = _tag; + state.anchor = _anchor; + return true; // Keep the result of `composeNode`. + } + + } else if (detected) { + throwError(state, 'can not read a block mapping entry; a multiline key may not be an implicit key'); + + } else { + state.tag = _tag; + state.anchor = _anchor; + return true; // Keep the result of `composeNode`. + } + } + + // + // Common reading code for both explicit and implicit notations. + // + if (state.line === _line || state.lineIndent > nodeIndent) { + if (atExplicitKey) { + _keyLine = state.line; + _keyLineStart = state.lineStart; + _keyPos = state.position; + } + + if (composeNode(state, nodeIndent, CONTEXT_BLOCK_OUT, true, allowCompact)) { + if (atExplicitKey) { + keyNode = state.result; + } else { + valueNode = state.result; + } + } + + if (!atExplicitKey) { + storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode, _keyLine, _keyLineStart, _keyPos); + keyTag = keyNode = valueNode = null; + } + + skipSeparationSpace(state, true, -1); + ch = state.input.charCodeAt(state.position); + } + + if ((state.line === _line || state.lineIndent > nodeIndent) && (ch !== 0)) { + throwError(state, 'bad indentation of a mapping entry'); + } else if (state.lineIndent < nodeIndent) { + break; + } + } + + // + // Epilogue. + // + + // Special case: last mapping's node contains only the key in explicit notation. + if (atExplicitKey) { + storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null, _keyLine, _keyLineStart, _keyPos); + } + + // Expose the resulting mapping. + if (detected) { + state.tag = _tag; + state.anchor = _anchor; + state.kind = 'mapping'; + state.result = _result; + } + + return detected; +} + +function readTagProperty(state) { + var _position, + isVerbatim = false, + isNamed = false, + tagHandle, + tagName, + ch; + + ch = state.input.charCodeAt(state.position); + + if (ch !== 0x21/* ! */) return false; + + if (state.tag !== null) { + throwError(state, 'duplication of a tag property'); + } + + ch = state.input.charCodeAt(++state.position); + + if (ch === 0x3C/* < */) { + isVerbatim = true; + ch = state.input.charCodeAt(++state.position); + + } else if (ch === 0x21/* ! */) { + isNamed = true; + tagHandle = '!!'; + ch = state.input.charCodeAt(++state.position); + + } else { + tagHandle = '!'; + } + + _position = state.position; + + if (isVerbatim) { + do { ch = state.input.charCodeAt(++state.position); } + while (ch !== 0 && ch !== 0x3E/* > */); + + if (state.position < state.length) { + tagName = state.input.slice(_position, state.position); + ch = state.input.charCodeAt(++state.position); + } else { + throwError(state, 'unexpected end of the stream within a verbatim tag'); + } + } else { + while (ch !== 0 && !is_WS_OR_EOL(ch)) { + + if (ch === 0x21/* ! */) { + if (!isNamed) { + tagHandle = state.input.slice(_position - 1, state.position + 1); + + if (!PATTERN_TAG_HANDLE.test(tagHandle)) { + throwError(state, 'named tag handle cannot contain such characters'); + } + + isNamed = true; + _position = state.position + 1; + } else { + throwError(state, 'tag suffix cannot contain exclamation marks'); + } + } + + ch = state.input.charCodeAt(++state.position); + } + + tagName = state.input.slice(_position, state.position); + + if (PATTERN_FLOW_INDICATORS.test(tagName)) { + throwError(state, 'tag suffix cannot contain flow indicator characters'); + } + } + + if (tagName && !PATTERN_TAG_URI.test(tagName)) { + throwError(state, 'tag name cannot contain such characters: ' + tagName); + } + + try { + tagName = decodeURIComponent(tagName); + } catch (err) { + throwError(state, 'tag name is malformed: ' + tagName); + } + + if (isVerbatim) { + state.tag = tagName; + + } else if (_hasOwnProperty$1.call(state.tagMap, tagHandle)) { + state.tag = state.tagMap[tagHandle] + tagName; + + } else if (tagHandle === '!') { + state.tag = '!' + tagName; + + } else if (tagHandle === '!!') { + state.tag = 'tag:yaml.org,2002:' + tagName; + + } else { + throwError(state, 'undeclared tag handle "' + tagHandle + '"'); + } + + return true; +} + +function readAnchorProperty(state) { + var _position, + ch; + + ch = state.input.charCodeAt(state.position); + + if (ch !== 0x26/* & */) return false; + + if (state.anchor !== null) { + throwError(state, 'duplication of an anchor property'); + } + + ch = state.input.charCodeAt(++state.position); + _position = state.position; + + while (ch !== 0 && !is_WS_OR_EOL(ch) && !is_FLOW_INDICATOR(ch)) { + ch = state.input.charCodeAt(++state.position); + } + + if (state.position === _position) { + throwError(state, 'name of an anchor node must contain at least one character'); + } + + state.anchor = state.input.slice(_position, state.position); + return true; +} + +function readAlias(state) { + var _position, alias, + ch; + + ch = state.input.charCodeAt(state.position); + + if (ch !== 0x2A/* * */) return false; + + ch = state.input.charCodeAt(++state.position); + _position = state.position; + + while (ch !== 0 && !is_WS_OR_EOL(ch) && !is_FLOW_INDICATOR(ch)) { + ch = state.input.charCodeAt(++state.position); + } + + if (state.position === _position) { + throwError(state, 'name of an alias node must contain at least one character'); + } + + alias = state.input.slice(_position, state.position); + + if (!_hasOwnProperty$1.call(state.anchorMap, alias)) { + throwError(state, 'unidentified alias "' + alias + '"'); + } + + state.result = state.anchorMap[alias]; + skipSeparationSpace(state, true, -1); + return true; +} + +function composeNode(state, parentIndent, nodeContext, allowToSeek, allowCompact) { + var allowBlockStyles, + allowBlockScalars, + allowBlockCollections, + indentStatus = 1, // 1: this>parent, 0: this=parent, -1: this parentIndent) { + indentStatus = 1; + } else if (state.lineIndent === parentIndent) { + indentStatus = 0; + } else if (state.lineIndent < parentIndent) { + indentStatus = -1; + } + } + } + + if (indentStatus === 1) { + while (readTagProperty(state) || readAnchorProperty(state)) { + if (skipSeparationSpace(state, true, -1)) { + atNewLine = true; + allowBlockCollections = allowBlockStyles; + + if (state.lineIndent > parentIndent) { + indentStatus = 1; + } else if (state.lineIndent === parentIndent) { + indentStatus = 0; + } else if (state.lineIndent < parentIndent) { + indentStatus = -1; + } + } else { + allowBlockCollections = false; + } + } + } + + if (allowBlockCollections) { + allowBlockCollections = atNewLine || allowCompact; + } + + if (indentStatus === 1 || CONTEXT_BLOCK_OUT === nodeContext) { + if (CONTEXT_FLOW_IN === nodeContext || CONTEXT_FLOW_OUT === nodeContext) { + flowIndent = parentIndent; + } else { + flowIndent = parentIndent + 1; + } + + blockIndent = state.position - state.lineStart; + + if (indentStatus === 1) { + if (allowBlockCollections && + (readBlockSequence(state, blockIndent) || + readBlockMapping(state, blockIndent, flowIndent)) || + readFlowCollection(state, flowIndent)) { + hasContent = true; + } else { + if ((allowBlockScalars && readBlockScalar(state, flowIndent)) || + readSingleQuotedScalar(state, flowIndent) || + readDoubleQuotedScalar(state, flowIndent)) { + hasContent = true; + + } else if (readAlias(state)) { + hasContent = true; + + if (state.tag !== null || state.anchor !== null) { + throwError(state, 'alias node should not have any properties'); + } + + } else if (readPlainScalar(state, flowIndent, CONTEXT_FLOW_IN === nodeContext)) { + hasContent = true; + + if (state.tag === null) { + state.tag = '?'; + } + } + + if (state.anchor !== null) { + state.anchorMap[state.anchor] = state.result; + } + } + } else if (indentStatus === 0) { + // Special case: block sequences are allowed to have same indentation level as the parent. + // http://www.yaml.org/spec/1.2/spec.html#id2799784 + hasContent = allowBlockCollections && readBlockSequence(state, blockIndent); + } + } + + if (state.tag === null) { + if (state.anchor !== null) { + state.anchorMap[state.anchor] = state.result; + } + + } else if (state.tag === '?') { + // Implicit resolving is not allowed for non-scalar types, and '?' + // non-specific tag is only automatically assigned to plain scalars. + // + // We only need to check kind conformity in case user explicitly assigns '?' + // tag, for example like this: "! [0]" + // + if (state.result !== null && state.kind !== 'scalar') { + throwError(state, 'unacceptable node kind for ! tag; it should be "scalar", not "' + state.kind + '"'); + } + + for (typeIndex = 0, typeQuantity = state.implicitTypes.length; typeIndex < typeQuantity; typeIndex += 1) { + type = state.implicitTypes[typeIndex]; + + if (type.resolve(state.result)) { // `state.result` updated in resolver if matched + state.result = type.construct(state.result); + state.tag = type.tag; + if (state.anchor !== null) { + state.anchorMap[state.anchor] = state.result; + } + break; + } + } + } else if (state.tag !== '!') { + if (_hasOwnProperty$1.call(state.typeMap[state.kind || 'fallback'], state.tag)) { + type = state.typeMap[state.kind || 'fallback'][state.tag]; + } else { + // looking for multi type + type = null; + typeList = state.typeMap.multi[state.kind || 'fallback']; + + for (typeIndex = 0, typeQuantity = typeList.length; typeIndex < typeQuantity; typeIndex += 1) { + if (state.tag.slice(0, typeList[typeIndex].tag.length) === typeList[typeIndex].tag) { + type = typeList[typeIndex]; + break; + } + } + } + + if (!type) { + throwError(state, 'unknown tag !<' + state.tag + '>'); + } + + if (state.result !== null && type.kind !== state.kind) { + throwError(state, 'unacceptable node kind for !<' + state.tag + '> tag; it should be "' + type.kind + '", not "' + state.kind + '"'); + } + + if (!type.resolve(state.result, state.tag)) { // `state.result` updated in resolver if matched + throwError(state, 'cannot resolve a node with !<' + state.tag + '> explicit tag'); + } else { + state.result = type.construct(state.result, state.tag); + if (state.anchor !== null) { + state.anchorMap[state.anchor] = state.result; + } + } + } + + if (state.listener !== null) { + state.listener('close', state); + } + return state.tag !== null || state.anchor !== null || hasContent; +} + +function readDocument(state) { + var documentStart = state.position, + _position, + directiveName, + directiveArgs, + hasDirectives = false, + ch; + + state.version = null; + state.checkLineBreaks = state.legacy; + state.tagMap = Object.create(null); + state.anchorMap = Object.create(null); + + while ((ch = state.input.charCodeAt(state.position)) !== 0) { + skipSeparationSpace(state, true, -1); + + ch = state.input.charCodeAt(state.position); + + if (state.lineIndent > 0 || ch !== 0x25/* % */) { + break; + } + + hasDirectives = true; + ch = state.input.charCodeAt(++state.position); + _position = state.position; + + while (ch !== 0 && !is_WS_OR_EOL(ch)) { + ch = state.input.charCodeAt(++state.position); + } + + directiveName = state.input.slice(_position, state.position); + directiveArgs = []; + + if (directiveName.length < 1) { + throwError(state, 'directive name must not be less than one character in length'); + } + + while (ch !== 0) { + while (is_WHITE_SPACE(ch)) { + ch = state.input.charCodeAt(++state.position); + } + + if (ch === 0x23/* # */) { + do { ch = state.input.charCodeAt(++state.position); } + while (ch !== 0 && !is_EOL(ch)); + break; + } + + if (is_EOL(ch)) break; + + _position = state.position; + + while (ch !== 0 && !is_WS_OR_EOL(ch)) { + ch = state.input.charCodeAt(++state.position); + } + + directiveArgs.push(state.input.slice(_position, state.position)); + } + + if (ch !== 0) readLineBreak(state); + + if (_hasOwnProperty$1.call(directiveHandlers, directiveName)) { + directiveHandlers[directiveName](state, directiveName, directiveArgs); + } else { + throwWarning(state, 'unknown document directive "' + directiveName + '"'); + } + } + + skipSeparationSpace(state, true, -1); + + if (state.lineIndent === 0 && + state.input.charCodeAt(state.position) === 0x2D/* - */ && + state.input.charCodeAt(state.position + 1) === 0x2D/* - */ && + state.input.charCodeAt(state.position + 2) === 0x2D/* - */) { + state.position += 3; + skipSeparationSpace(state, true, -1); + + } else if (hasDirectives) { + throwError(state, 'directives end mark is expected'); + } + + composeNode(state, state.lineIndent - 1, CONTEXT_BLOCK_OUT, false, true); + skipSeparationSpace(state, true, -1); + + if (state.checkLineBreaks && + PATTERN_NON_ASCII_LINE_BREAKS.test(state.input.slice(documentStart, state.position))) { + throwWarning(state, 'non-ASCII line breaks are interpreted as content'); + } + + state.documents.push(state.result); + + if (state.position === state.lineStart && testDocumentSeparator(state)) { + + if (state.input.charCodeAt(state.position) === 0x2E/* . */) { + state.position += 3; + skipSeparationSpace(state, true, -1); + } + return; + } + + if (state.position < (state.length - 1)) { + throwError(state, 'end of the stream or a document separator is expected'); + } else { + return; + } +} + + +function loadDocuments(input, options) { + input = String(input); + options = options || {}; + + if (input.length !== 0) { + + // Add tailing `\n` if not exists + if (input.charCodeAt(input.length - 1) !== 0x0A/* LF */ && + input.charCodeAt(input.length - 1) !== 0x0D/* CR */) { + input += '\n'; + } + + // Strip BOM + if (input.charCodeAt(0) === 0xFEFF) { + input = input.slice(1); + } + } + + var state = new State$1(input, options); + + var nullpos = input.indexOf('\0'); + + if (nullpos !== -1) { + state.position = nullpos; + throwError(state, 'null byte is not allowed in input'); + } + + // Use 0 as string terminator. That significantly simplifies bounds check. + state.input += '\0'; + + while (state.input.charCodeAt(state.position) === 0x20/* Space */) { + state.lineIndent += 1; + state.position += 1; + } + + while (state.position < (state.length - 1)) { + readDocument(state); + } + + return state.documents; +} + + +function loadAll$1(input, iterator, options) { + if (iterator !== null && typeof iterator === 'object' && typeof options === 'undefined') { + options = iterator; + iterator = null; + } + + var documents = loadDocuments(input, options); + + if (typeof iterator !== 'function') { + return documents; + } + + for (var index = 0, length = documents.length; index < length; index += 1) { + iterator(documents[index]); + } +} + + +function load$1(input, options) { + var documents = loadDocuments(input, options); + + if (documents.length === 0) { + /*eslint-disable no-undefined*/ + return undefined; + } else if (documents.length === 1) { + return documents[0]; + } + throw new exception('expected a single document in the stream, but found more'); +} + + +var loadAll_1 = loadAll$1; +var load_1 = load$1; + +var loader = { + loadAll: loadAll_1, + load: load_1 +}; + +/*eslint-disable no-use-before-define*/ + + + + + +var _toString = Object.prototype.toString; +var _hasOwnProperty = Object.prototype.hasOwnProperty; + +var CHAR_BOM = 0xFEFF; +var CHAR_TAB = 0x09; /* Tab */ +var CHAR_LINE_FEED = 0x0A; /* LF */ +var CHAR_CARRIAGE_RETURN = 0x0D; /* CR */ +var CHAR_SPACE = 0x20; /* Space */ +var CHAR_EXCLAMATION = 0x21; /* ! */ +var CHAR_DOUBLE_QUOTE = 0x22; /* " */ +var CHAR_SHARP = 0x23; /* # */ +var CHAR_PERCENT = 0x25; /* % */ +var CHAR_AMPERSAND = 0x26; /* & */ +var CHAR_SINGLE_QUOTE = 0x27; /* ' */ +var CHAR_ASTERISK = 0x2A; /* * */ +var CHAR_COMMA = 0x2C; /* , */ +var CHAR_MINUS = 0x2D; /* - */ +var CHAR_COLON = 0x3A; /* : */ +var CHAR_EQUALS = 0x3D; /* = */ +var CHAR_GREATER_THAN = 0x3E; /* > */ +var CHAR_QUESTION = 0x3F; /* ? */ +var CHAR_COMMERCIAL_AT = 0x40; /* @ */ +var CHAR_LEFT_SQUARE_BRACKET = 0x5B; /* [ */ +var CHAR_RIGHT_SQUARE_BRACKET = 0x5D; /* ] */ +var CHAR_GRAVE_ACCENT = 0x60; /* ` */ +var CHAR_LEFT_CURLY_BRACKET = 0x7B; /* { */ +var CHAR_VERTICAL_LINE = 0x7C; /* | */ +var CHAR_RIGHT_CURLY_BRACKET = 0x7D; /* } */ + +var ESCAPE_SEQUENCES = {}; + +ESCAPE_SEQUENCES[0x00] = '\\0'; +ESCAPE_SEQUENCES[0x07] = '\\a'; +ESCAPE_SEQUENCES[0x08] = '\\b'; +ESCAPE_SEQUENCES[0x09] = '\\t'; +ESCAPE_SEQUENCES[0x0A] = '\\n'; +ESCAPE_SEQUENCES[0x0B] = '\\v'; +ESCAPE_SEQUENCES[0x0C] = '\\f'; +ESCAPE_SEQUENCES[0x0D] = '\\r'; +ESCAPE_SEQUENCES[0x1B] = '\\e'; +ESCAPE_SEQUENCES[0x22] = '\\"'; +ESCAPE_SEQUENCES[0x5C] = '\\\\'; +ESCAPE_SEQUENCES[0x85] = '\\N'; +ESCAPE_SEQUENCES[0xA0] = '\\_'; +ESCAPE_SEQUENCES[0x2028] = '\\L'; +ESCAPE_SEQUENCES[0x2029] = '\\P'; + +var DEPRECATED_BOOLEANS_SYNTAX = [ + 'y', 'Y', 'yes', 'Yes', 'YES', 'on', 'On', 'ON', + 'n', 'N', 'no', 'No', 'NO', 'off', 'Off', 'OFF' +]; + +var DEPRECATED_BASE60_SYNTAX = /^[-+]?[0-9_]+(?::[0-9_]+)+(?:\.[0-9_]*)?$/; + +function compileStyleMap(schema, map) { + var result, keys, index, length, tag, style, type; + + if (map === null) return {}; + + result = {}; + keys = Object.keys(map); + + for (index = 0, length = keys.length; index < length; index += 1) { + tag = keys[index]; + style = String(map[tag]); + + if (tag.slice(0, 2) === '!!') { + tag = 'tag:yaml.org,2002:' + tag.slice(2); + } + type = schema.compiledTypeMap['fallback'][tag]; + + if (type && _hasOwnProperty.call(type.styleAliases, style)) { + style = type.styleAliases[style]; + } + + result[tag] = style; + } + + return result; +} + +function encodeHex(character) { + var string, handle, length; + + string = character.toString(16).toUpperCase(); + + if (character <= 0xFF) { + handle = 'x'; + length = 2; + } else if (character <= 0xFFFF) { + handle = 'u'; + length = 4; + } else if (character <= 0xFFFFFFFF) { + handle = 'U'; + length = 8; + } else { + throw new exception('code point within a string may not be greater than 0xFFFFFFFF'); + } + + return '\\' + handle + common.repeat('0', length - string.length) + string; +} + + +var QUOTING_TYPE_SINGLE = 1, + QUOTING_TYPE_DOUBLE = 2; + +function State(options) { + this.schema = options['schema'] || _default; + this.indent = Math.max(1, (options['indent'] || 2)); + this.noArrayIndent = options['noArrayIndent'] || false; + this.skipInvalid = options['skipInvalid'] || false; + this.flowLevel = (common.isNothing(options['flowLevel']) ? -1 : options['flowLevel']); + this.styleMap = compileStyleMap(this.schema, options['styles'] || null); + this.sortKeys = options['sortKeys'] || false; + this.lineWidth = options['lineWidth'] || 80; + this.noRefs = options['noRefs'] || false; + this.noCompatMode = options['noCompatMode'] || false; + this.condenseFlow = options['condenseFlow'] || false; + this.quotingType = options['quotingType'] === '"' ? QUOTING_TYPE_DOUBLE : QUOTING_TYPE_SINGLE; + this.forceQuotes = options['forceQuotes'] || false; + this.replacer = typeof options['replacer'] === 'function' ? options['replacer'] : null; + + this.implicitTypes = this.schema.compiledImplicit; + this.explicitTypes = this.schema.compiledExplicit; + + this.tag = null; + this.result = ''; + + this.duplicates = []; + this.usedDuplicates = null; +} + +// Indents every line in a string. Empty lines (\n only) are not indented. +function indentString(string, spaces) { + var ind = common.repeat(' ', spaces), + position = 0, + next = -1, + result = '', + line, + length = string.length; + + while (position < length) { + next = string.indexOf('\n', position); + if (next === -1) { + line = string.slice(position); + position = length; + } else { + line = string.slice(position, next + 1); + position = next + 1; + } + + if (line.length && line !== '\n') result += ind; + + result += line; + } + + return result; +} + +function generateNextLine(state, level) { + return '\n' + common.repeat(' ', state.indent * level); +} + +function testImplicitResolving(state, str) { + var index, length, type; + + for (index = 0, length = state.implicitTypes.length; index < length; index += 1) { + type = state.implicitTypes[index]; + + if (type.resolve(str)) { + return true; + } + } + + return false; +} + +// [33] s-white ::= s-space | s-tab +function isWhitespace(c) { + return c === CHAR_SPACE || c === CHAR_TAB; +} + +// Returns true if the character can be printed without escaping. +// From YAML 1.2: "any allowed characters known to be non-printable +// should also be escaped. [However,] This isn’t mandatory" +// Derived from nb-char - \t - #x85 - #xA0 - #x2028 - #x2029. +function isPrintable(c) { + return (0x00020 <= c && c <= 0x00007E) + || ((0x000A1 <= c && c <= 0x00D7FF) && c !== 0x2028 && c !== 0x2029) + || ((0x0E000 <= c && c <= 0x00FFFD) && c !== CHAR_BOM) + || (0x10000 <= c && c <= 0x10FFFF); +} + +// [34] ns-char ::= nb-char - s-white +// [27] nb-char ::= c-printable - b-char - c-byte-order-mark +// [26] b-char ::= b-line-feed | b-carriage-return +// Including s-white (for some reason, examples doesn't match specs in this aspect) +// ns-char ::= c-printable - b-line-feed - b-carriage-return - c-byte-order-mark +function isNsCharOrWhitespace(c) { + return isPrintable(c) + && c !== CHAR_BOM + // - b-char + && c !== CHAR_CARRIAGE_RETURN + && c !== CHAR_LINE_FEED; +} + +// [127] ns-plain-safe(c) ::= c = flow-out ⇒ ns-plain-safe-out +// c = flow-in ⇒ ns-plain-safe-in +// c = block-key ⇒ ns-plain-safe-out +// c = flow-key ⇒ ns-plain-safe-in +// [128] ns-plain-safe-out ::= ns-char +// [129] ns-plain-safe-in ::= ns-char - c-flow-indicator +// [130] ns-plain-char(c) ::= ( ns-plain-safe(c) - “:” - “#” ) +// | ( /* An ns-char preceding */ “#” ) +// | ( “:” /* Followed by an ns-plain-safe(c) */ ) +function isPlainSafe(c, prev, inblock) { + var cIsNsCharOrWhitespace = isNsCharOrWhitespace(c); + var cIsNsChar = cIsNsCharOrWhitespace && !isWhitespace(c); + return ( + // ns-plain-safe + inblock ? // c = flow-in + cIsNsCharOrWhitespace + : cIsNsCharOrWhitespace + // - c-flow-indicator + && c !== CHAR_COMMA + && c !== CHAR_LEFT_SQUARE_BRACKET + && c !== CHAR_RIGHT_SQUARE_BRACKET + && c !== CHAR_LEFT_CURLY_BRACKET + && c !== CHAR_RIGHT_CURLY_BRACKET + ) + // ns-plain-char + && c !== CHAR_SHARP // false on '#' + && !(prev === CHAR_COLON && !cIsNsChar) // false on ': ' + || (isNsCharOrWhitespace(prev) && !isWhitespace(prev) && c === CHAR_SHARP) // change to true on '[^ ]#' + || (prev === CHAR_COLON && cIsNsChar); // change to true on ':[^ ]' +} + +// Simplified test for values allowed as the first character in plain style. +function isPlainSafeFirst(c) { + // Uses a subset of ns-char - c-indicator + // where ns-char = nb-char - s-white. + // No support of ( ( “?” | “:” | “-” ) /* Followed by an ns-plain-safe(c)) */ ) part + return isPrintable(c) && c !== CHAR_BOM + && !isWhitespace(c) // - s-white + // - (c-indicator ::= + // “-” | “?” | “:” | “,” | “[” | “]” | “{” | “}” + && c !== CHAR_MINUS + && c !== CHAR_QUESTION + && c !== CHAR_COLON + && c !== CHAR_COMMA + && c !== CHAR_LEFT_SQUARE_BRACKET + && c !== CHAR_RIGHT_SQUARE_BRACKET + && c !== CHAR_LEFT_CURLY_BRACKET + && c !== CHAR_RIGHT_CURLY_BRACKET + // | “#” | “&” | “*” | “!” | “|” | “=” | “>” | “'” | “"” + && c !== CHAR_SHARP + && c !== CHAR_AMPERSAND + && c !== CHAR_ASTERISK + && c !== CHAR_EXCLAMATION + && c !== CHAR_VERTICAL_LINE + && c !== CHAR_EQUALS + && c !== CHAR_GREATER_THAN + && c !== CHAR_SINGLE_QUOTE + && c !== CHAR_DOUBLE_QUOTE + // | “%” | “@” | “`”) + && c !== CHAR_PERCENT + && c !== CHAR_COMMERCIAL_AT + && c !== CHAR_GRAVE_ACCENT; +} + +// Simplified test for values allowed as the last character in plain style. +function isPlainSafeLast(c) { + // just not whitespace or colon, it will be checked to be plain character later + return !isWhitespace(c) && c !== CHAR_COLON; +} + +// Same as 'string'.codePointAt(pos), but works in older browsers. +function codePointAt(string, pos) { + var first = string.charCodeAt(pos), second; + if (first >= 0xD800 && first <= 0xDBFF && pos + 1 < string.length) { + second = string.charCodeAt(pos + 1); + if (second >= 0xDC00 && second <= 0xDFFF) { + // https://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae + return (first - 0xD800) * 0x400 + second - 0xDC00 + 0x10000; + } + } + return first; +} + +// Determines whether block indentation indicator is required. +function needIndentIndicator(string) { + var leadingSpaceRe = /^\n* /; + return leadingSpaceRe.test(string); +} + +var STYLE_PLAIN = 1, + STYLE_SINGLE = 2, + STYLE_LITERAL = 3, + STYLE_FOLDED = 4, + STYLE_DOUBLE = 5; + +// Determines which scalar styles are possible and returns the preferred style. +// lineWidth = -1 => no limit. +// Pre-conditions: str.length > 0. +// Post-conditions: +// STYLE_PLAIN or STYLE_SINGLE => no \n are in the string. +// STYLE_LITERAL => no lines are suitable for folding (or lineWidth is -1). +// STYLE_FOLDED => a line > lineWidth and can be folded (and lineWidth != -1). +function chooseScalarStyle(string, singleLineOnly, indentPerLevel, lineWidth, + testAmbiguousType, quotingType, forceQuotes, inblock) { + + var i; + var char = 0; + var prevChar = null; + var hasLineBreak = false; + var hasFoldableLine = false; // only checked if shouldTrackWidth + var shouldTrackWidth = lineWidth !== -1; + var previousLineBreak = -1; // count the first line correctly + var plain = isPlainSafeFirst(codePointAt(string, 0)) + && isPlainSafeLast(codePointAt(string, string.length - 1)); + + if (singleLineOnly || forceQuotes) { + // Case: no block styles. + // Check for disallowed characters to rule out plain and single. + for (i = 0; i < string.length; char >= 0x10000 ? i += 2 : i++) { + char = codePointAt(string, i); + if (!isPrintable(char)) { + return STYLE_DOUBLE; + } + plain = plain && isPlainSafe(char, prevChar, inblock); + prevChar = char; + } + } else { + // Case: block styles permitted. + for (i = 0; i < string.length; char >= 0x10000 ? i += 2 : i++) { + char = codePointAt(string, i); + if (char === CHAR_LINE_FEED) { + hasLineBreak = true; + // Check if any line can be folded. + if (shouldTrackWidth) { + hasFoldableLine = hasFoldableLine || + // Foldable line = too long, and not more-indented. + (i - previousLineBreak - 1 > lineWidth && + string[previousLineBreak + 1] !== ' '); + previousLineBreak = i; + } + } else if (!isPrintable(char)) { + return STYLE_DOUBLE; + } + plain = plain && isPlainSafe(char, prevChar, inblock); + prevChar = char; + } + // in case the end is missing a \n + hasFoldableLine = hasFoldableLine || (shouldTrackWidth && + (i - previousLineBreak - 1 > lineWidth && + string[previousLineBreak + 1] !== ' ')); + } + // Although every style can represent \n without escaping, prefer block styles + // for multiline, since they're more readable and they don't add empty lines. + // Also prefer folding a super-long line. + if (!hasLineBreak && !hasFoldableLine) { + // Strings interpretable as another type have to be quoted; + // e.g. the string 'true' vs. the boolean true. + if (plain && !forceQuotes && !testAmbiguousType(string)) { + return STYLE_PLAIN; + } + return quotingType === QUOTING_TYPE_DOUBLE ? STYLE_DOUBLE : STYLE_SINGLE; + } + // Edge case: block indentation indicator can only have one digit. + if (indentPerLevel > 9 && needIndentIndicator(string)) { + return STYLE_DOUBLE; + } + // At this point we know block styles are valid. + // Prefer literal style unless we want to fold. + if (!forceQuotes) { + return hasFoldableLine ? STYLE_FOLDED : STYLE_LITERAL; + } + return quotingType === QUOTING_TYPE_DOUBLE ? STYLE_DOUBLE : STYLE_SINGLE; +} + +// Note: line breaking/folding is implemented for only the folded style. +// NB. We drop the last trailing newline (if any) of a returned block scalar +// since the dumper adds its own newline. This always works: +// • No ending newline => unaffected; already using strip "-" chomping. +// • Ending newline => removed then restored. +// Importantly, this keeps the "+" chomp indicator from gaining an extra line. +function writeScalar(state, string, level, iskey, inblock) { + state.dump = (function () { + if (string.length === 0) { + return state.quotingType === QUOTING_TYPE_DOUBLE ? '""' : "''"; + } + if (!state.noCompatMode) { + if (DEPRECATED_BOOLEANS_SYNTAX.indexOf(string) !== -1 || DEPRECATED_BASE60_SYNTAX.test(string)) { + return state.quotingType === QUOTING_TYPE_DOUBLE ? ('"' + string + '"') : ("'" + string + "'"); + } + } + + var indent = state.indent * Math.max(1, level); // no 0-indent scalars + // As indentation gets deeper, let the width decrease monotonically + // to the lower bound min(state.lineWidth, 40). + // Note that this implies + // state.lineWidth ≤ 40 + state.indent: width is fixed at the lower bound. + // state.lineWidth > 40 + state.indent: width decreases until the lower bound. + // This behaves better than a constant minimum width which disallows narrower options, + // or an indent threshold which causes the width to suddenly increase. + var lineWidth = state.lineWidth === -1 + ? -1 : Math.max(Math.min(state.lineWidth, 40), state.lineWidth - indent); + + // Without knowing if keys are implicit/explicit, assume implicit for safety. + var singleLineOnly = iskey + // No block styles in flow mode. + || (state.flowLevel > -1 && level >= state.flowLevel); + function testAmbiguity(string) { + return testImplicitResolving(state, string); + } + + switch (chooseScalarStyle(string, singleLineOnly, state.indent, lineWidth, + testAmbiguity, state.quotingType, state.forceQuotes && !iskey, inblock)) { + + case STYLE_PLAIN: + return string; + case STYLE_SINGLE: + return "'" + string.replace(/'/g, "''") + "'"; + case STYLE_LITERAL: + return '|' + blockHeader(string, state.indent) + + dropEndingNewline(indentString(string, indent)); + case STYLE_FOLDED: + return '>' + blockHeader(string, state.indent) + + dropEndingNewline(indentString(foldString(string, lineWidth), indent)); + case STYLE_DOUBLE: + return '"' + escapeString(string) + '"'; + default: + throw new exception('impossible error: invalid scalar style'); + } + }()); +} + +// Pre-conditions: string is valid for a block scalar, 1 <= indentPerLevel <= 9. +function blockHeader(string, indentPerLevel) { + var indentIndicator = needIndentIndicator(string) ? String(indentPerLevel) : ''; + + // note the special case: the string '\n' counts as a "trailing" empty line. + var clip = string[string.length - 1] === '\n'; + var keep = clip && (string[string.length - 2] === '\n' || string === '\n'); + var chomp = keep ? '+' : (clip ? '' : '-'); + + return indentIndicator + chomp + '\n'; +} + +// (See the note for writeScalar.) +function dropEndingNewline(string) { + return string[string.length - 1] === '\n' ? string.slice(0, -1) : string; +} + +// Note: a long line without a suitable break point will exceed the width limit. +// Pre-conditions: every char in str isPrintable, str.length > 0, width > 0. +function foldString(string, width) { + // In folded style, $k$ consecutive newlines output as $k+1$ newlines— + // unless they're before or after a more-indented line, or at the very + // beginning or end, in which case $k$ maps to $k$. + // Therefore, parse each chunk as newline(s) followed by a content line. + var lineRe = /(\n+)([^\n]*)/g; + + // first line (possibly an empty line) + var result = (function () { + var nextLF = string.indexOf('\n'); + nextLF = nextLF !== -1 ? nextLF : string.length; + lineRe.lastIndex = nextLF; + return foldLine(string.slice(0, nextLF), width); + }()); + // If we haven't reached the first content line yet, don't add an extra \n. + var prevMoreIndented = string[0] === '\n' || string[0] === ' '; + var moreIndented; + + // rest of the lines + var match; + while ((match = lineRe.exec(string))) { + var prefix = match[1], line = match[2]; + moreIndented = (line[0] === ' '); + result += prefix + + (!prevMoreIndented && !moreIndented && line !== '' + ? '\n' : '') + + foldLine(line, width); + prevMoreIndented = moreIndented; + } + + return result; +} + +// Greedy line breaking. +// Picks the longest line under the limit each time, +// otherwise settles for the shortest line over the limit. +// NB. More-indented lines *cannot* be folded, as that would add an extra \n. +function foldLine(line, width) { + if (line === '' || line[0] === ' ') return line; + + // Since a more-indented line adds a \n, breaks can't be followed by a space. + var breakRe = / [^ ]/g; // note: the match index will always be <= length-2. + var match; + // start is an inclusive index. end, curr, and next are exclusive. + var start = 0, end, curr = 0, next = 0; + var result = ''; + + // Invariants: 0 <= start <= length-1. + // 0 <= curr <= next <= max(0, length-2). curr - start <= width. + // Inside the loop: + // A match implies length >= 2, so curr and next are <= length-2. + while ((match = breakRe.exec(line))) { + next = match.index; + // maintain invariant: curr - start <= width + if (next - start > width) { + end = (curr > start) ? curr : next; // derive end <= length-2 + result += '\n' + line.slice(start, end); + // skip the space that was output as \n + start = end + 1; // derive start <= length-1 + } + curr = next; + } + + // By the invariants, start <= length-1, so there is something left over. + // It is either the whole string or a part starting from non-whitespace. + result += '\n'; + // Insert a break if the remainder is too long and there is a break available. + if (line.length - start > width && curr > start) { + result += line.slice(start, curr) + '\n' + line.slice(curr + 1); + } else { + result += line.slice(start); + } + + return result.slice(1); // drop extra \n joiner +} + +// Escapes a double-quoted string. +function escapeString(string) { + var result = ''; + var char = 0; + var escapeSeq; + + for (var i = 0; i < string.length; char >= 0x10000 ? i += 2 : i++) { + char = codePointAt(string, i); + escapeSeq = ESCAPE_SEQUENCES[char]; + + if (!escapeSeq && isPrintable(char)) { + result += string[i]; + if (char >= 0x10000) result += string[i + 1]; + } else { + result += escapeSeq || encodeHex(char); + } + } + + return result; +} + +function writeFlowSequence(state, level, object) { + var _result = '', + _tag = state.tag, + index, + length, + value; + + for (index = 0, length = object.length; index < length; index += 1) { + value = object[index]; + + if (state.replacer) { + value = state.replacer.call(object, String(index), value); + } + + // Write only valid elements, put null instead of invalid elements. + if (writeNode(state, level, value, false, false) || + (typeof value === 'undefined' && + writeNode(state, level, null, false, false))) { + + if (_result !== '') _result += ',' + (!state.condenseFlow ? ' ' : ''); + _result += state.dump; + } + } + + state.tag = _tag; + state.dump = '[' + _result + ']'; +} + +function writeBlockSequence(state, level, object, compact) { + var _result = '', + _tag = state.tag, + index, + length, + value; + + for (index = 0, length = object.length; index < length; index += 1) { + value = object[index]; + + if (state.replacer) { + value = state.replacer.call(object, String(index), value); + } + + // Write only valid elements, put null instead of invalid elements. + if (writeNode(state, level + 1, value, true, true, false, true) || + (typeof value === 'undefined' && + writeNode(state, level + 1, null, true, true, false, true))) { + + if (!compact || _result !== '') { + _result += generateNextLine(state, level); + } + + if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) { + _result += '-'; + } else { + _result += '- '; + } + + _result += state.dump; + } + } + + state.tag = _tag; + state.dump = _result || '[]'; // Empty sequence if no valid values. +} + +function writeFlowMapping(state, level, object) { + var _result = '', + _tag = state.tag, + objectKeyList = Object.keys(object), + index, + length, + objectKey, + objectValue, + pairBuffer; + + for (index = 0, length = objectKeyList.length; index < length; index += 1) { + + pairBuffer = ''; + if (_result !== '') pairBuffer += ', '; + + if (state.condenseFlow) pairBuffer += '"'; + + objectKey = objectKeyList[index]; + objectValue = object[objectKey]; + + if (state.replacer) { + objectValue = state.replacer.call(object, objectKey, objectValue); + } + + if (!writeNode(state, level, objectKey, false, false)) { + continue; // Skip this pair because of invalid key; + } + + if (state.dump.length > 1024) pairBuffer += '? '; + + pairBuffer += state.dump + (state.condenseFlow ? '"' : '') + ':' + (state.condenseFlow ? '' : ' '); + + if (!writeNode(state, level, objectValue, false, false)) { + continue; // Skip this pair because of invalid value. + } + + pairBuffer += state.dump; + + // Both key and value are valid. + _result += pairBuffer; + } + + state.tag = _tag; + state.dump = '{' + _result + '}'; +} + +function writeBlockMapping(state, level, object, compact) { + var _result = '', + _tag = state.tag, + objectKeyList = Object.keys(object), + index, + length, + objectKey, + objectValue, + explicitPair, + pairBuffer; + + // Allow sorting keys so that the output file is deterministic + if (state.sortKeys === true) { + // Default sorting + objectKeyList.sort(); + } else if (typeof state.sortKeys === 'function') { + // Custom sort function + objectKeyList.sort(state.sortKeys); + } else if (state.sortKeys) { + // Something is wrong + throw new exception('sortKeys must be a boolean or a function'); + } + + for (index = 0, length = objectKeyList.length; index < length; index += 1) { + pairBuffer = ''; + + if (!compact || _result !== '') { + pairBuffer += generateNextLine(state, level); + } + + objectKey = objectKeyList[index]; + objectValue = object[objectKey]; + + if (state.replacer) { + objectValue = state.replacer.call(object, objectKey, objectValue); + } + + if (!writeNode(state, level + 1, objectKey, true, true, true)) { + continue; // Skip this pair because of invalid key. + } + + explicitPair = (state.tag !== null && state.tag !== '?') || + (state.dump && state.dump.length > 1024); + + if (explicitPair) { + if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) { + pairBuffer += '?'; + } else { + pairBuffer += '? '; + } + } + + pairBuffer += state.dump; + + if (explicitPair) { + pairBuffer += generateNextLine(state, level); + } + + if (!writeNode(state, level + 1, objectValue, true, explicitPair)) { + continue; // Skip this pair because of invalid value. + } + + if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) { + pairBuffer += ':'; + } else { + pairBuffer += ': '; + } + + pairBuffer += state.dump; + + // Both key and value are valid. + _result += pairBuffer; + } + + state.tag = _tag; + state.dump = _result || '{}'; // Empty mapping if no valid pairs. +} + +function detectType(state, object, explicit) { + var _result, typeList, index, length, type, style; + + typeList = explicit ? state.explicitTypes : state.implicitTypes; + + for (index = 0, length = typeList.length; index < length; index += 1) { + type = typeList[index]; + + if ((type.instanceOf || type.predicate) && + (!type.instanceOf || ((typeof object === 'object') && (object instanceof type.instanceOf))) && + (!type.predicate || type.predicate(object))) { + + if (explicit) { + if (type.multi && type.representName) { + state.tag = type.representName(object); + } else { + state.tag = type.tag; + } + } else { + state.tag = '?'; + } + + if (type.represent) { + style = state.styleMap[type.tag] || type.defaultStyle; + + if (_toString.call(type.represent) === '[object Function]') { + _result = type.represent(object, style); + } else if (_hasOwnProperty.call(type.represent, style)) { + _result = type.represent[style](object, style); + } else { + throw new exception('!<' + type.tag + '> tag resolver accepts not "' + style + '" style'); + } + + state.dump = _result; + } + + return true; + } + } + + return false; +} + +// Serializes `object` and writes it to global `result`. +// Returns true on success, or false on invalid object. +// +function writeNode(state, level, object, block, compact, iskey, isblockseq) { + state.tag = null; + state.dump = object; + + if (!detectType(state, object, false)) { + detectType(state, object, true); + } + + var type = _toString.call(state.dump); + var inblock = block; + var tagStr; + + if (block) { + block = (state.flowLevel < 0 || state.flowLevel > level); + } + + var objectOrArray = type === '[object Object]' || type === '[object Array]', + duplicateIndex, + duplicate; + + if (objectOrArray) { + duplicateIndex = state.duplicates.indexOf(object); + duplicate = duplicateIndex !== -1; + } + + if ((state.tag !== null && state.tag !== '?') || duplicate || (state.indent !== 2 && level > 0)) { + compact = false; + } + + if (duplicate && state.usedDuplicates[duplicateIndex]) { + state.dump = '*ref_' + duplicateIndex; + } else { + if (objectOrArray && duplicate && !state.usedDuplicates[duplicateIndex]) { + state.usedDuplicates[duplicateIndex] = true; + } + if (type === '[object Object]') { + if (block && (Object.keys(state.dump).length !== 0)) { + writeBlockMapping(state, level, state.dump, compact); + if (duplicate) { + state.dump = '&ref_' + duplicateIndex + state.dump; + } + } else { + writeFlowMapping(state, level, state.dump); + if (duplicate) { + state.dump = '&ref_' + duplicateIndex + ' ' + state.dump; + } + } + } else if (type === '[object Array]') { + if (block && (state.dump.length !== 0)) { + if (state.noArrayIndent && !isblockseq && level > 0) { + writeBlockSequence(state, level - 1, state.dump, compact); + } else { + writeBlockSequence(state, level, state.dump, compact); + } + if (duplicate) { + state.dump = '&ref_' + duplicateIndex + state.dump; + } + } else { + writeFlowSequence(state, level, state.dump); + if (duplicate) { + state.dump = '&ref_' + duplicateIndex + ' ' + state.dump; + } + } + } else if (type === '[object String]') { + if (state.tag !== '?') { + writeScalar(state, state.dump, level, iskey, inblock); + } + } else if (type === '[object Undefined]') { + return false; + } else { + if (state.skipInvalid) return false; + throw new exception('unacceptable kind of an object to dump ' + type); + } + + if (state.tag !== null && state.tag !== '?') { + // Need to encode all characters except those allowed by the spec: + // + // [35] ns-dec-digit ::= [#x30-#x39] /* 0-9 */ + // [36] ns-hex-digit ::= ns-dec-digit + // | [#x41-#x46] /* A-F */ | [#x61-#x66] /* a-f */ + // [37] ns-ascii-letter ::= [#x41-#x5A] /* A-Z */ | [#x61-#x7A] /* a-z */ + // [38] ns-word-char ::= ns-dec-digit | ns-ascii-letter | “-” + // [39] ns-uri-char ::= “%” ns-hex-digit ns-hex-digit | ns-word-char | “#” + // | “;” | “/” | “?” | “:” | “@” | “&” | “=” | “+” | “$” | “,” + // | “_” | “.” | “!” | “~” | “*” | “'” | “(” | “)” | “[” | “]” + // + // Also need to encode '!' because it has special meaning (end of tag prefix). + // + tagStr = encodeURI( + state.tag[0] === '!' ? state.tag.slice(1) : state.tag + ).replace(/!/g, '%21'); + + if (state.tag[0] === '!') { + tagStr = '!' + tagStr; + } else if (tagStr.slice(0, 18) === 'tag:yaml.org,2002:') { + tagStr = '!!' + tagStr.slice(18); + } else { + tagStr = '!<' + tagStr + '>'; + } + + state.dump = tagStr + ' ' + state.dump; + } + } + + return true; +} + +function getDuplicateReferences(object, state) { + var objects = [], + duplicatesIndexes = [], + index, + length; + + inspectNode(object, objects, duplicatesIndexes); + + for (index = 0, length = duplicatesIndexes.length; index < length; index += 1) { + state.duplicates.push(objects[duplicatesIndexes[index]]); + } + state.usedDuplicates = new Array(length); +} + +function inspectNode(object, objects, duplicatesIndexes) { + var objectKeyList, + index, + length; + + if (object !== null && typeof object === 'object') { + index = objects.indexOf(object); + if (index !== -1) { + if (duplicatesIndexes.indexOf(index) === -1) { + duplicatesIndexes.push(index); + } + } else { + objects.push(object); + + if (Array.isArray(object)) { + for (index = 0, length = object.length; index < length; index += 1) { + inspectNode(object[index], objects, duplicatesIndexes); + } + } else { + objectKeyList = Object.keys(object); + + for (index = 0, length = objectKeyList.length; index < length; index += 1) { + inspectNode(object[objectKeyList[index]], objects, duplicatesIndexes); + } + } + } + } +} + +function dump$1(input, options) { + options = options || {}; + + var state = new State(options); + + if (!state.noRefs) getDuplicateReferences(input, state); + + var value = input; + + if (state.replacer) { + value = state.replacer.call({ '': value }, '', value); + } + + if (writeNode(state, 0, value, true, true)) return state.dump + '\n'; + + return ''; +} + +var dump_1 = dump$1; + +var dumper = { + dump: dump_1 +}; + +function renamed(from, to) { + return function () { + throw new Error('Function yaml.' + from + ' is removed in js-yaml 4. ' + + 'Use yaml.' + to + ' instead, which is now safe by default.'); + }; +} + + +var Type = type; +var Schema = schema; +var FAILSAFE_SCHEMA = failsafe; +var JSON_SCHEMA = json; +var CORE_SCHEMA = core; +var DEFAULT_SCHEMA = _default; +var load = loader.load; +var loadAll = loader.loadAll; +var dump = dumper.dump; +var YAMLException = exception; + +// Re-export all types in case user wants to create custom schema +var types = { + binary: binary, + float: float, + map: map, + null: _null, + pairs: pairs, + set: set, + timestamp: timestamp, + bool: bool, + int: int, + merge: merge, + omap: omap, + seq: seq, + str: str +}; + +// Removed functions from JS-YAML 3.0.x +var safeLoad = renamed('safeLoad', 'load'); +var safeLoadAll = renamed('safeLoadAll', 'loadAll'); +var safeDump = renamed('safeDump', 'dump'); + +var jsYaml = { + Type: Type, + Schema: Schema, + FAILSAFE_SCHEMA: FAILSAFE_SCHEMA, + JSON_SCHEMA: JSON_SCHEMA, + CORE_SCHEMA: CORE_SCHEMA, + DEFAULT_SCHEMA: DEFAULT_SCHEMA, + load: load, + loadAll: loadAll, + dump: dump, + YAMLException: YAMLException, + types: types, + safeLoad: safeLoad, + safeLoadAll: safeLoadAll, + safeDump: safeDump +}; + +/* harmony default export */ __webpack_exports__["default"] = (jsYaml); + + + +/***/ }), + +/***/ "./node_modules/jsonschema/lib/attribute.js": +/*!**************************************************!*\ + !*** ./node_modules/jsonschema/lib/attribute.js ***! + \**************************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +var helpers = __webpack_require__(/*! ./helpers */ "./node_modules/jsonschema/lib/helpers.js"); + +/** @type ValidatorResult */ +var ValidatorResult = helpers.ValidatorResult; +/** @type SchemaError */ +var SchemaError = helpers.SchemaError; + +var attribute = {}; + +attribute.ignoreProperties = { + // informative properties + 'id': true, + 'default': true, + 'description': true, + 'title': true, + // arguments to other properties + 'additionalItems': true, + 'then': true, + 'else': true, + // special-handled properties + '$schema': true, + '$ref': true, + 'extends': true, +}; + +/** + * @name validators + */ +var validators = attribute.validators = {}; + +/** + * Validates whether the instance if of a certain type + * @param instance + * @param schema + * @param options + * @param ctx + * @return {ValidatorResult|null} + */ +validators.type = function validateType (instance, schema, options, ctx) { + // Ignore undefined instances + if (instance === undefined) { + return null; + } + var result = new ValidatorResult(instance, schema, options, ctx); + var types = Array.isArray(schema.type) ? schema.type : [schema.type]; + if (!types.some(this.testType.bind(this, instance, schema, options, ctx))) { + var list = types.map(function (v) { + if(!v) return; + var id = v.$id || v.id; + return id ? ('<' + id + '>') : (v+''); + }); + result.addError({ + name: 'type', + argument: list, + message: "is not of a type(s) " + list, + }); + } + return result; +}; + +function testSchemaNoThrow(instance, options, ctx, callback, schema){ + var throwError = options.throwError; + var throwAll = options.throwAll; + options.throwError = false; + options.throwAll = false; + var res = this.validateSchema(instance, schema, options, ctx); + options.throwError = throwError; + options.throwAll = throwAll; + + if (!res.valid && callback instanceof Function) { + callback(res); + } + return res.valid; +} + +/** + * Validates whether the instance matches some of the given schemas + * @param instance + * @param schema + * @param options + * @param ctx + * @return {ValidatorResult|null} + */ +validators.anyOf = function validateAnyOf (instance, schema, options, ctx) { + // Ignore undefined instances + if (instance === undefined) { + return null; + } + var result = new ValidatorResult(instance, schema, options, ctx); + var inner = new ValidatorResult(instance, schema, options, ctx); + if (!Array.isArray(schema.anyOf)){ + throw new SchemaError("anyOf must be an array"); + } + if (!schema.anyOf.some( + testSchemaNoThrow.bind( + this, instance, options, ctx, function(res){inner.importErrors(res);} + ))) { + var list = schema.anyOf.map(function (v, i) { + var id = v.$id || v.id; + if(id) return '<' + id + '>'; + return(v.title && JSON.stringify(v.title)) || (v['$ref'] && ('<' + v['$ref'] + '>')) || '[subschema '+i+']'; + }); + if (options.nestedErrors) { + result.importErrors(inner); + } + result.addError({ + name: 'anyOf', + argument: list, + message: "is not any of " + list.join(','), + }); + } + return result; +}; + +/** + * Validates whether the instance matches every given schema + * @param instance + * @param schema + * @param options + * @param ctx + * @return {String|null} + */ +validators.allOf = function validateAllOf (instance, schema, options, ctx) { + // Ignore undefined instances + if (instance === undefined) { + return null; + } + if (!Array.isArray(schema.allOf)){ + throw new SchemaError("allOf must be an array"); + } + var result = new ValidatorResult(instance, schema, options, ctx); + var self = this; + schema.allOf.forEach(function(v, i){ + var valid = self.validateSchema(instance, v, options, ctx); + if(!valid.valid){ + var id = v.$id || v.id; + var msg = id || (v.title && JSON.stringify(v.title)) || (v['$ref'] && ('<' + v['$ref'] + '>')) || '[subschema '+i+']'; + result.addError({ + name: 'allOf', + argument: { id: msg, length: valid.errors.length, valid: valid }, + message: 'does not match allOf schema ' + msg + ' with ' + valid.errors.length + ' error[s]:', + }); + result.importErrors(valid); + } + }); + return result; +}; + +/** + * Validates whether the instance matches exactly one of the given schemas + * @param instance + * @param schema + * @param options + * @param ctx + * @return {String|null} + */ +validators.oneOf = function validateOneOf (instance, schema, options, ctx) { + // Ignore undefined instances + if (instance === undefined) { + return null; + } + if (!Array.isArray(schema.oneOf)){ + throw new SchemaError("oneOf must be an array"); + } + var result = new ValidatorResult(instance, schema, options, ctx); + var inner = new ValidatorResult(instance, schema, options, ctx); + var count = schema.oneOf.filter( + testSchemaNoThrow.bind( + this, instance, options, ctx, function(res) {inner.importErrors(res);} + ) ).length; + var list = schema.oneOf.map(function (v, i) { + var id = v.$id || v.id; + return id || (v.title && JSON.stringify(v.title)) || (v['$ref'] && ('<' + v['$ref'] + '>')) || '[subschema '+i+']'; + }); + if (count!==1) { + if (options.nestedErrors) { + result.importErrors(inner); + } + result.addError({ + name: 'oneOf', + argument: list, + message: "is not exactly one from " + list.join(','), + }); + } + return result; +}; + +/** + * Validates "then" or "else" depending on the result of validating "if" + * @param instance + * @param schema + * @param options + * @param ctx + * @return {String|null} + */ +validators.if = function validateIf (instance, schema, options, ctx) { + // Ignore undefined instances + if (instance === undefined) return null; + if (!helpers.isSchema(schema.if)) throw new Error('Expected "if" keyword to be a schema'); + var ifValid = testSchemaNoThrow.call(this, instance, options, ctx, null, schema.if); + var result = new ValidatorResult(instance, schema, options, ctx); + var res; + if(ifValid){ + if (schema.then === undefined) return; + if (!helpers.isSchema(schema.then)) throw new Error('Expected "then" keyword to be a schema'); + res = this.validateSchema(instance, schema.then, options, ctx.makeChild(schema.then)); + result.importErrors(res); + }else{ + if (schema.else === undefined) return; + if (!helpers.isSchema(schema.else)) throw new Error('Expected "else" keyword to be a schema'); + res = this.validateSchema(instance, schema.else, options, ctx.makeChild(schema.else)); + result.importErrors(res); + } + return result; +}; + +function getEnumerableProperty(object, key){ + // Determine if `key` shows up in `for(var key in object)` + // First test Object.hasOwnProperty.call as an optimization: that guarantees it does + if(Object.hasOwnProperty.call(object, key)) return object[key]; + // Test `key in object` as an optimization; false means it won't + if(!(key in object)) return; + while( (object = Object.getPrototypeOf(object)) ){ + if(Object.propertyIsEnumerable.call(object, key)) return object[key]; + } +} + +/** + * Validates propertyNames + * @param instance + * @param schema + * @param options + * @param ctx + * @return {String|null|ValidatorResult} + */ +validators.propertyNames = function validatePropertyNames (instance, schema, options, ctx) { + if(!this.types.object(instance)) return; + var result = new ValidatorResult(instance, schema, options, ctx); + var subschema = schema.propertyNames!==undefined ? schema.propertyNames : {}; + if(!helpers.isSchema(subschema)) throw new SchemaError('Expected "propertyNames" to be a schema (object or boolean)'); + + for (var property in instance) { + if(getEnumerableProperty(instance, property) !== undefined){ + var res = this.validateSchema(property, subschema, options, ctx.makeChild(subschema)); + result.importErrors(res); + } + } + + return result; +}; + +/** + * Validates properties + * @param instance + * @param schema + * @param options + * @param ctx + * @return {String|null|ValidatorResult} + */ +validators.properties = function validateProperties (instance, schema, options, ctx) { + if(!this.types.object(instance)) return; + var result = new ValidatorResult(instance, schema, options, ctx); + var properties = schema.properties || {}; + for (var property in properties) { + var subschema = properties[property]; + if(subschema===undefined){ + continue; + }else if(subschema===null){ + throw new SchemaError('Unexpected null, expected schema in "properties"'); + } + if (typeof options.preValidateProperty == 'function') { + options.preValidateProperty(instance, property, subschema, options, ctx); + } + var prop = getEnumerableProperty(instance, property); + var res = this.validateSchema(prop, subschema, options, ctx.makeChild(subschema, property)); + if(res.instance !== result.instance[property]) result.instance[property] = res.instance; + result.importErrors(res); + } + return result; +}; + +/** + * Test a specific property within in instance against the additionalProperties schema attribute + * This ignores properties with definitions in the properties schema attribute, but no other attributes. + * If too many more types of property-existence tests pop up they may need their own class of tests (like `type` has) + * @private + * @return {boolean} + */ +function testAdditionalProperty (instance, schema, options, ctx, property, result) { + if(!this.types.object(instance)) return; + if (schema.properties && schema.properties[property] !== undefined) { + return; + } + if (schema.additionalProperties === false) { + result.addError({ + name: 'additionalProperties', + argument: property, + message: "is not allowed to have the additional property " + JSON.stringify(property), + }); + } else { + var additionalProperties = schema.additionalProperties || {}; + + if (typeof options.preValidateProperty == 'function') { + options.preValidateProperty(instance, property, additionalProperties, options, ctx); + } + + var res = this.validateSchema(instance[property], additionalProperties, options, ctx.makeChild(additionalProperties, property)); + if(res.instance !== result.instance[property]) result.instance[property] = res.instance; + result.importErrors(res); + } +} + +/** + * Validates patternProperties + * @param instance + * @param schema + * @param options + * @param ctx + * @return {String|null|ValidatorResult} + */ +validators.patternProperties = function validatePatternProperties (instance, schema, options, ctx) { + if(!this.types.object(instance)) return; + var result = new ValidatorResult(instance, schema, options, ctx); + var patternProperties = schema.patternProperties || {}; + + for (var property in instance) { + var test = true; + for (var pattern in patternProperties) { + var subschema = patternProperties[pattern]; + if(subschema===undefined){ + continue; + }else if(subschema===null){ + throw new SchemaError('Unexpected null, expected schema in "patternProperties"'); + } + try { + var regexp = new RegExp(pattern, 'u'); + } catch(_e) { + // In the event the stricter handling causes an error, fall back on the forgiving handling + // DEPRECATED + regexp = new RegExp(pattern); + } + if (!regexp.test(property)) { + continue; + } + test = false; + + if (typeof options.preValidateProperty == 'function') { + options.preValidateProperty(instance, property, subschema, options, ctx); + } + + var res = this.validateSchema(instance[property], subschema, options, ctx.makeChild(subschema, property)); + if(res.instance !== result.instance[property]) result.instance[property] = res.instance; + result.importErrors(res); + } + if (test) { + testAdditionalProperty.call(this, instance, schema, options, ctx, property, result); + } + } + + return result; +}; + +/** + * Validates additionalProperties + * @param instance + * @param schema + * @param options + * @param ctx + * @return {String|null|ValidatorResult} + */ +validators.additionalProperties = function validateAdditionalProperties (instance, schema, options, ctx) { + if(!this.types.object(instance)) return; + // if patternProperties is defined then we'll test when that one is called instead + if (schema.patternProperties) { + return null; + } + var result = new ValidatorResult(instance, schema, options, ctx); + for (var property in instance) { + testAdditionalProperty.call(this, instance, schema, options, ctx, property, result); + } + return result; +}; + +/** + * Validates whether the instance value is at least of a certain length, when the instance value is a string. + * @param instance + * @param schema + * @return {String|null} + */ +validators.minProperties = function validateMinProperties (instance, schema, options, ctx) { + if (!this.types.object(instance)) return; + var result = new ValidatorResult(instance, schema, options, ctx); + var keys = Object.keys(instance); + if (!(keys.length >= schema.minProperties)) { + result.addError({ + name: 'minProperties', + argument: schema.minProperties, + message: "does not meet minimum property length of " + schema.minProperties, + }); + } + return result; +}; + +/** + * Validates whether the instance value is at most of a certain length, when the instance value is a string. + * @param instance + * @param schema + * @return {String|null} + */ +validators.maxProperties = function validateMaxProperties (instance, schema, options, ctx) { + if (!this.types.object(instance)) return; + var result = new ValidatorResult(instance, schema, options, ctx); + var keys = Object.keys(instance); + if (!(keys.length <= schema.maxProperties)) { + result.addError({ + name: 'maxProperties', + argument: schema.maxProperties, + message: "does not meet maximum property length of " + schema.maxProperties, + }); + } + return result; +}; + +/** + * Validates items when instance is an array + * @param instance + * @param schema + * @param options + * @param ctx + * @return {String|null|ValidatorResult} + */ +validators.items = function validateItems (instance, schema, options, ctx) { + var self = this; + if (!this.types.array(instance)) return; + if (schema.items===undefined) return; + var result = new ValidatorResult(instance, schema, options, ctx); + instance.every(function (value, i) { + if(Array.isArray(schema.items)){ + var items = schema.items[i]===undefined ? schema.additionalItems : schema.items[i]; + }else{ + var items = schema.items; + } + if (items === undefined) { + return true; + } + if (items === false) { + result.addError({ + name: 'items', + message: "additionalItems not permitted", + }); + return false; + } + var res = self.validateSchema(value, items, options, ctx.makeChild(items, i)); + if(res.instance !== result.instance[i]) result.instance[i] = res.instance; + result.importErrors(res); + return true; + }); + return result; +}; + +/** + * Validates the "contains" keyword + * @param instance + * @param schema + * @param options + * @param ctx + * @return {String|null|ValidatorResult} + */ +validators.contains = function validateContains (instance, schema, options, ctx) { + var self = this; + if (!this.types.array(instance)) return; + if (schema.contains===undefined) return; + if (!helpers.isSchema(schema.contains)) throw new Error('Expected "contains" keyword to be a schema'); + var result = new ValidatorResult(instance, schema, options, ctx); + var count = instance.some(function (value, i) { + var res = self.validateSchema(value, schema.contains, options, ctx.makeChild(schema.contains, i)); + return res.errors.length===0; + }); + if(count===false){ + result.addError({ + name: 'contains', + argument: schema.contains, + message: "must contain an item matching given schema", + }); + } + return result; +}; + +/** + * Validates minimum and exclusiveMinimum when the type of the instance value is a number. + * @param instance + * @param schema + * @return {String|null} + */ +validators.minimum = function validateMinimum (instance, schema, options, ctx) { + if (!this.types.number(instance)) return; + var result = new ValidatorResult(instance, schema, options, ctx); + if (schema.exclusiveMinimum && schema.exclusiveMinimum === true) { + if(!(instance > schema.minimum)){ + result.addError({ + name: 'minimum', + argument: schema.minimum, + message: "must be greater than " + schema.minimum, + }); + } + } else { + if(!(instance >= schema.minimum)){ + result.addError({ + name: 'minimum', + argument: schema.minimum, + message: "must be greater than or equal to " + schema.minimum, + }); + } + } + return result; +}; + +/** + * Validates maximum and exclusiveMaximum when the type of the instance value is a number. + * @param instance + * @param schema + * @return {String|null} + */ +validators.maximum = function validateMaximum (instance, schema, options, ctx) { + if (!this.types.number(instance)) return; + var result = new ValidatorResult(instance, schema, options, ctx); + if (schema.exclusiveMaximum && schema.exclusiveMaximum === true) { + if(!(instance < schema.maximum)){ + result.addError({ + name: 'maximum', + argument: schema.maximum, + message: "must be less than " + schema.maximum, + }); + } + } else { + if(!(instance <= schema.maximum)){ + result.addError({ + name: 'maximum', + argument: schema.maximum, + message: "must be less than or equal to " + schema.maximum, + }); + } + } + return result; +}; + +/** + * Validates the number form of exclusiveMinimum when the type of the instance value is a number. + * @param instance + * @param schema + * @return {String|null} + */ +validators.exclusiveMinimum = function validateExclusiveMinimum (instance, schema, options, ctx) { + // Support the boolean form of exclusiveMinimum, which is handled by the "minimum" keyword. + if(typeof schema.exclusiveMinimum === 'boolean') return; + if (!this.types.number(instance)) return; + var result = new ValidatorResult(instance, schema, options, ctx); + var valid = instance > schema.exclusiveMinimum; + if (!valid) { + result.addError({ + name: 'exclusiveMinimum', + argument: schema.exclusiveMinimum, + message: "must be strictly greater than " + schema.exclusiveMinimum, + }); + } + return result; +}; + +/** + * Validates the number form of exclusiveMaximum when the type of the instance value is a number. + * @param instance + * @param schema + * @return {String|null} + */ +validators.exclusiveMaximum = function validateExclusiveMaximum (instance, schema, options, ctx) { + // Support the boolean form of exclusiveMaximum, which is handled by the "maximum" keyword. + if(typeof schema.exclusiveMaximum === 'boolean') return; + if (!this.types.number(instance)) return; + var result = new ValidatorResult(instance, schema, options, ctx); + var valid = instance < schema.exclusiveMaximum; + if (!valid) { + result.addError({ + name: 'exclusiveMaximum', + argument: schema.exclusiveMaximum, + message: "must be strictly less than " + schema.exclusiveMaximum, + }); + } + return result; +}; + +/** + * Perform validation for multipleOf and divisibleBy, which are essentially the same. + * @param instance + * @param schema + * @param validationType + * @param errorMessage + * @returns {String|null} + */ +var validateMultipleOfOrDivisbleBy = function validateMultipleOfOrDivisbleBy (instance, schema, options, ctx, validationType, errorMessage) { + if (!this.types.number(instance)) return; + + var validationArgument = schema[validationType]; + if (validationArgument == 0) { + throw new SchemaError(validationType + " cannot be zero"); + } + + var result = new ValidatorResult(instance, schema, options, ctx); + + var instanceDecimals = helpers.getDecimalPlaces(instance); + var divisorDecimals = helpers.getDecimalPlaces(validationArgument); + + var maxDecimals = Math.max(instanceDecimals , divisorDecimals); + var multiplier = Math.pow(10, maxDecimals); + + if (Math.round(instance * multiplier) % Math.round(validationArgument * multiplier) !== 0) { + result.addError({ + name: validationType, + argument: validationArgument, + message: errorMessage + JSON.stringify(validationArgument), + }); + } + + return result; +}; + +/** + * Validates divisibleBy when the type of the instance value is a number. + * @param instance + * @param schema + * @return {String|null} + */ +validators.multipleOf = function validateMultipleOf (instance, schema, options, ctx) { + return validateMultipleOfOrDivisbleBy.call(this, instance, schema, options, ctx, "multipleOf", "is not a multiple of (divisible by) "); +}; + +/** + * Validates multipleOf when the type of the instance value is a number. + * @param instance + * @param schema + * @return {String|null} + */ +validators.divisibleBy = function validateDivisibleBy (instance, schema, options, ctx) { + return validateMultipleOfOrDivisbleBy.call(this, instance, schema, options, ctx, "divisibleBy", "is not divisible by (multiple of) "); +}; + +/** + * Validates whether the instance value is present. + * @param instance + * @param schema + * @return {String|null} + */ +validators.required = function validateRequired (instance, schema, options, ctx) { + var result = new ValidatorResult(instance, schema, options, ctx); + if (instance === undefined && schema.required === true) { + // A boolean form is implemented for reverse-compatibility with schemas written against older drafts + result.addError({ + name: 'required', + message: "is required", + }); + } else if (this.types.object(instance) && Array.isArray(schema.required)) { + schema.required.forEach(function(n){ + if(getEnumerableProperty(instance, n)===undefined){ + result.addError({ + name: 'required', + argument: n, + message: "requires property " + JSON.stringify(n), + }); + } + }); + } + return result; +}; + +/** + * Validates whether the instance value matches the regular expression, when the instance value is a string. + * @param instance + * @param schema + * @return {String|null} + */ +validators.pattern = function validatePattern (instance, schema, options, ctx) { + if (!this.types.string(instance)) return; + var result = new ValidatorResult(instance, schema, options, ctx); + var pattern = schema.pattern; + try { + var regexp = new RegExp(pattern, 'u'); + } catch(_e) { + // In the event the stricter handling causes an error, fall back on the forgiving handling + // DEPRECATED + regexp = new RegExp(pattern); + } + if (!instance.match(regexp)) { + result.addError({ + name: 'pattern', + argument: schema.pattern, + message: "does not match pattern " + JSON.stringify(schema.pattern.toString()), + }); + } + return result; +}; + +/** + * Validates whether the instance value is of a certain defined format or a custom + * format. + * The following formats are supported for string types: + * - date-time + * - date + * - time + * - ip-address + * - ipv6 + * - uri + * - color + * - host-name + * - alpha + * - alpha-numeric + * - utc-millisec + * @param instance + * @param schema + * @param [options] + * @param [ctx] + * @return {String|null} + */ +validators.format = function validateFormat (instance, schema, options, ctx) { + if (instance===undefined) return; + var result = new ValidatorResult(instance, schema, options, ctx); + if (!result.disableFormat && !helpers.isFormat(instance, schema.format, this)) { + result.addError({ + name: 'format', + argument: schema.format, + message: "does not conform to the " + JSON.stringify(schema.format) + " format", + }); + } + return result; +}; + +/** + * Validates whether the instance value is at least of a certain length, when the instance value is a string. + * @param instance + * @param schema + * @return {String|null} + */ +validators.minLength = function validateMinLength (instance, schema, options, ctx) { + if (!this.types.string(instance)) return; + var result = new ValidatorResult(instance, schema, options, ctx); + var hsp = instance.match(/[\uDC00-\uDFFF]/g); + var length = instance.length - (hsp ? hsp.length : 0); + if (!(length >= schema.minLength)) { + result.addError({ + name: 'minLength', + argument: schema.minLength, + message: "does not meet minimum length of " + schema.minLength, + }); + } + return result; +}; + +/** + * Validates whether the instance value is at most of a certain length, when the instance value is a string. + * @param instance + * @param schema + * @return {String|null} + */ +validators.maxLength = function validateMaxLength (instance, schema, options, ctx) { + if (!this.types.string(instance)) return; + var result = new ValidatorResult(instance, schema, options, ctx); + // TODO if this was already computed in "minLength", use that value instead of re-computing + var hsp = instance.match(/[\uDC00-\uDFFF]/g); + var length = instance.length - (hsp ? hsp.length : 0); + if (!(length <= schema.maxLength)) { + result.addError({ + name: 'maxLength', + argument: schema.maxLength, + message: "does not meet maximum length of " + schema.maxLength, + }); + } + return result; +}; + +/** + * Validates whether instance contains at least a minimum number of items, when the instance is an Array. + * @param instance + * @param schema + * @return {String|null} + */ +validators.minItems = function validateMinItems (instance, schema, options, ctx) { + if (!this.types.array(instance)) return; + var result = new ValidatorResult(instance, schema, options, ctx); + if (!(instance.length >= schema.minItems)) { + result.addError({ + name: 'minItems', + argument: schema.minItems, + message: "does not meet minimum length of " + schema.minItems, + }); + } + return result; +}; + +/** + * Validates whether instance contains no more than a maximum number of items, when the instance is an Array. + * @param instance + * @param schema + * @return {String|null} + */ +validators.maxItems = function validateMaxItems (instance, schema, options, ctx) { + if (!this.types.array(instance)) return; + var result = new ValidatorResult(instance, schema, options, ctx); + if (!(instance.length <= schema.maxItems)) { + result.addError({ + name: 'maxItems', + argument: schema.maxItems, + message: "does not meet maximum length of " + schema.maxItems, + }); + } + return result; +}; + +/** + * Deep compares arrays for duplicates + * @param v + * @param i + * @param a + * @private + * @return {boolean} + */ +function testArrays (v, i, a) { + var j, len = a.length; + for (j = i + 1, len; j < len; j++) { + if (helpers.deepCompareStrict(v, a[j])) { + return false; + } + } + return true; +} + +/** + * Validates whether there are no duplicates, when the instance is an Array. + * @param instance + * @return {String|null} + */ +validators.uniqueItems = function validateUniqueItems (instance, schema, options, ctx) { + if (schema.uniqueItems!==true) return; + if (!this.types.array(instance)) return; + var result = new ValidatorResult(instance, schema, options, ctx); + if (!instance.every(testArrays)) { + result.addError({ + name: 'uniqueItems', + message: "contains duplicate item", + }); + } + return result; +}; + +/** + * Validate for the presence of dependency properties, if the instance is an object. + * @param instance + * @param schema + * @param options + * @param ctx + * @return {null|ValidatorResult} + */ +validators.dependencies = function validateDependencies (instance, schema, options, ctx) { + if (!this.types.object(instance)) return; + var result = new ValidatorResult(instance, schema, options, ctx); + for (var property in schema.dependencies) { + if (instance[property] === undefined) { + continue; + } + var dep = schema.dependencies[property]; + var childContext = ctx.makeChild(dep, property); + if (typeof dep == 'string') { + dep = [dep]; + } + if (Array.isArray(dep)) { + dep.forEach(function (prop) { + if (instance[prop] === undefined) { + result.addError({ + // FIXME there's two different "dependencies" errors here with slightly different outputs + // Can we make these the same? Or should we create different error types? + name: 'dependencies', + argument: childContext.propertyPath, + message: "property " + prop + " not found, required by " + childContext.propertyPath, + }); + } + }); + } else { + var res = this.validateSchema(instance, dep, options, childContext); + if(result.instance !== res.instance) result.instance = res.instance; + if (res && res.errors.length) { + result.addError({ + name: 'dependencies', + argument: childContext.propertyPath, + message: "does not meet dependency required by " + childContext.propertyPath, + }); + result.importErrors(res); + } + } + } + return result; +}; + +/** + * Validates whether the instance value is one of the enumerated values. + * + * @param instance + * @param schema + * @return {ValidatorResult|null} + */ +validators['enum'] = function validateEnum (instance, schema, options, ctx) { + if (instance === undefined) { + return null; + } + if (!Array.isArray(schema['enum'])) { + throw new SchemaError("enum expects an array", schema); + } + var result = new ValidatorResult(instance, schema, options, ctx); + if (!schema['enum'].some(helpers.deepCompareStrict.bind(null, instance))) { + result.addError({ + name: 'enum', + argument: schema['enum'], + message: "is not one of enum values: " + schema['enum'].map(String).join(','), + }); + } + return result; +}; + +/** + * Validates whether the instance exactly matches a given value + * + * @param instance + * @param schema + * @return {ValidatorResult|null} + */ +validators['const'] = function validateEnum (instance, schema, options, ctx) { + if (instance === undefined) { + return null; + } + var result = new ValidatorResult(instance, schema, options, ctx); + if (!helpers.deepCompareStrict(schema['const'], instance)) { + result.addError({ + name: 'const', + argument: schema['const'], + message: "does not exactly match expected constant: " + schema['const'], + }); + } + return result; +}; + +/** + * Validates whether the instance if of a prohibited type. + * @param instance + * @param schema + * @param options + * @param ctx + * @return {null|ValidatorResult} + */ +validators.not = validators.disallow = function validateNot (instance, schema, options, ctx) { + var self = this; + if(instance===undefined) return null; + var result = new ValidatorResult(instance, schema, options, ctx); + var notTypes = schema.not || schema.disallow; + if(!notTypes) return null; + if(!Array.isArray(notTypes)) notTypes=[notTypes]; + notTypes.forEach(function (type) { + if (self.testType(instance, schema, options, ctx, type)) { + var id = type && (type.$id || type.id); + var schemaId = id || type; + result.addError({ + name: 'not', + argument: schemaId, + message: "is of prohibited type " + schemaId, + }); + } + }); + return result; +}; + +module.exports = attribute; + + +/***/ }), + +/***/ "./node_modules/jsonschema/lib/helpers.js": +/*!************************************************!*\ + !*** ./node_modules/jsonschema/lib/helpers.js ***! + \************************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +var uri = __webpack_require__(/*! url */ "./node_modules/url/url.js"); + +var ValidationError = exports.ValidationError = function ValidationError (message, instance, schema, path, name, argument) { + if(Array.isArray(path)){ + this.path = path; + this.property = path.reduce(function(sum, item){ + return sum + makeSuffix(item); + }, 'instance'); + }else if(path !== undefined){ + this.property = path; + } + if (message) { + this.message = message; + } + if (schema) { + var id = schema.$id || schema.id; + this.schema = id || schema; + } + if (instance !== undefined) { + this.instance = instance; + } + this.name = name; + this.argument = argument; + this.stack = this.toString(); +}; + +ValidationError.prototype.toString = function toString() { + return this.property + ' ' + this.message; +}; + +var ValidatorResult = exports.ValidatorResult = function ValidatorResult(instance, schema, options, ctx) { + this.instance = instance; + this.schema = schema; + this.options = options; + this.path = ctx.path; + this.propertyPath = ctx.propertyPath; + this.errors = []; + this.throwError = options && options.throwError; + this.throwFirst = options && options.throwFirst; + this.throwAll = options && options.throwAll; + this.disableFormat = options && options.disableFormat === true; +}; + +ValidatorResult.prototype.addError = function addError(detail) { + var err; + if (typeof detail == 'string') { + err = new ValidationError(detail, this.instance, this.schema, this.path); + } else { + if (!detail) throw new Error('Missing error detail'); + if (!detail.message) throw new Error('Missing error message'); + if (!detail.name) throw new Error('Missing validator type'); + err = new ValidationError(detail.message, this.instance, this.schema, this.path, detail.name, detail.argument); + } + + this.errors.push(err); + if (this.throwFirst) { + throw new ValidatorResultError(this); + }else if(this.throwError){ + throw err; + } + return err; +}; + +ValidatorResult.prototype.importErrors = function importErrors(res) { + if (typeof res == 'string' || (res && res.validatorType)) { + this.addError(res); + } else if (res && res.errors) { + this.errors = this.errors.concat(res.errors); + } +}; + +function stringizer (v,i){ + return i+': '+v.toString()+'\n'; +} +ValidatorResult.prototype.toString = function toString(res) { + return this.errors.map(stringizer).join(''); +}; + +Object.defineProperty(ValidatorResult.prototype, "valid", { get: function() { + return !this.errors.length; +} }); + +module.exports.ValidatorResultError = ValidatorResultError; +function ValidatorResultError(result) { + if(Error.captureStackTrace){ + Error.captureStackTrace(this, ValidatorResultError); + } + this.instance = result.instance; + this.schema = result.schema; + this.options = result.options; + this.errors = result.errors; +} +ValidatorResultError.prototype = new Error(); +ValidatorResultError.prototype.constructor = ValidatorResultError; +ValidatorResultError.prototype.name = "Validation Error"; + +/** + * Describes a problem with a Schema which prevents validation of an instance + * @name SchemaError + * @constructor + */ +var SchemaError = exports.SchemaError = function SchemaError (msg, schema) { + this.message = msg; + this.schema = schema; + Error.call(this, msg); + Error.captureStackTrace(this, SchemaError); +}; +SchemaError.prototype = Object.create(Error.prototype, + { + constructor: {value: SchemaError, enumerable: false}, + name: {value: 'SchemaError', enumerable: false}, + }); + +var SchemaContext = exports.SchemaContext = function SchemaContext (schema, options, path, base, schemas) { + this.schema = schema; + this.options = options; + if(Array.isArray(path)){ + this.path = path; + this.propertyPath = path.reduce(function(sum, item){ + return sum + makeSuffix(item); + }, 'instance'); + }else{ + this.propertyPath = path; + } + this.base = base; + this.schemas = schemas; +}; + +SchemaContext.prototype.resolve = function resolve (target) { + return uri.resolve(this.base, target); +}; + +SchemaContext.prototype.makeChild = function makeChild(schema, propertyName){ + var path = (propertyName===undefined) ? this.path : this.path.concat([propertyName]); + var id = schema.$id || schema.id; + var base = uri.resolve(this.base, id||''); + var ctx = new SchemaContext(schema, this.options, path, base, Object.create(this.schemas)); + if(id && !ctx.schemas[base]){ + ctx.schemas[base] = schema; + } + return ctx; +}; + +var FORMAT_REGEXPS = exports.FORMAT_REGEXPS = { + // 7.3.1. Dates, Times, and Duration + 'date-time': /^\d{4}-(?:0[0-9]{1}|1[0-2]{1})-(3[01]|0[1-9]|[12][0-9])[tT ](2[0-4]|[01][0-9]):([0-5][0-9]):(60|[0-5][0-9])(\.\d+)?([zZ]|[+-]([0-5][0-9]):(60|[0-5][0-9]))$/, + 'date': /^\d{4}-(?:0[0-9]{1}|1[0-2]{1})-(3[01]|0[1-9]|[12][0-9])$/, + 'time': /^(2[0-4]|[01][0-9]):([0-5][0-9]):(60|[0-5][0-9])$/, + 'duration': /P(T\d+(H(\d+M(\d+S)?)?|M(\d+S)?|S)|\d+(D|M(\d+D)?|Y(\d+M(\d+D)?)?)(T\d+(H(\d+M(\d+S)?)?|M(\d+S)?|S))?|\d+W)/i, + + // 7.3.2. Email Addresses + // TODO: fix the email production + 'email': /^(?:[\w\!\#\$\%\&\'\*\+\-\/\=\?\^\`\{\|\}\~]+\.)*[\w\!\#\$\%\&\'\*\+\-\/\=\?\^\`\{\|\}\~]+@(?:(?:(?:[a-zA-Z0-9](?:[a-zA-Z0-9\-](?!\.)){0,61}[a-zA-Z0-9]?\.)+[a-zA-Z0-9](?:[a-zA-Z0-9\-](?!$)){0,61}[a-zA-Z0-9]?)|(?:\[(?:(?:[01]?\d{1,2}|2[0-4]\d|25[0-5])\.){3}(?:[01]?\d{1,2}|2[0-4]\d|25[0-5])\]))$/, + 'idn-email': /^("(?:[!#-\[\]-\u{10FFFF}]|\\[\t -\u{10FFFF}])*"|[!#-'*+\-/-9=?A-Z\^-\u{10FFFF}](?:\.?[!#-'*+\-/-9=?A-Z\^-\u{10FFFF}])*)@([!#-'*+\-/-9=?A-Z\^-\u{10FFFF}](?:\.?[!#-'*+\-/-9=?A-Z\^-\u{10FFFF}])*|\[[!-Z\^-\u{10FFFF}]*\])$/u, + + // 7.3.3. Hostnames + + // 7.3.4. IP Addresses + 'ip-address': /^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/, + // FIXME whitespace is invalid + 'ipv6': /^\s*((([0-9A-Fa-f]{1,4}:){7}([0-9A-Fa-f]{1,4}|:))|(([0-9A-Fa-f]{1,4}:){6}(:[0-9A-Fa-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){5}(((:[0-9A-Fa-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){4}(((:[0-9A-Fa-f]{1,4}){1,3})|((:[0-9A-Fa-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){3}(((:[0-9A-Fa-f]{1,4}){1,4})|((:[0-9A-Fa-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){2}(((:[0-9A-Fa-f]{1,4}){1,5})|((:[0-9A-Fa-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){1}(((:[0-9A-Fa-f]{1,4}){1,6})|((:[0-9A-Fa-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9A-Fa-f]{1,4}){1,7})|((:[0-9A-Fa-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))(%.+)?\s*$/, + + // 7.3.5. Resource Identifiers + // TODO: A more accurate regular expression for "uri" goes: + // [A-Za-z][+\-.0-9A-Za-z]*:((/(/((%[0-9A-Fa-f]{2}|[!$&-.0-9;=A-Z_a-z~])+|(\[(([Vv][0-9A-Fa-f]+\.[!$&-.0-;=A-Z_a-z~]+)?|[.0-:A-Fa-f]+)\])?)(:\d*)?)?)?#(%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~])*|(/(/((%[0-9A-Fa-f]{2}|[!$&-.0-9;=A-Z_a-z~])+|(\[(([Vv][0-9A-Fa-f]+\.[!$&-.0-;=A-Z_a-z~]+)?|[.0-:A-Fa-f]+)\])?)(:\d*)?[/?]|[!$&-.0-;=?-Z_a-z~])|/?%[0-9A-Fa-f]{2}|[!$&-.0-;=?-Z_a-z~])(%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~])*(#(%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~])*)?|/(/((%[0-9A-Fa-f]{2}|[!$&-.0-9;=A-Z_a-z~])+(:\d*)?|(\[(([Vv][0-9A-Fa-f]+\.[!$&-.0-;=A-Z_a-z~]+)?|[.0-:A-Fa-f]+)\])?:\d*|\[(([Vv][0-9A-Fa-f]+\.[!$&-.0-;=A-Z_a-z~]+)?|[.0-:A-Fa-f]+)\])?)?)? + 'uri': /^[a-zA-Z][a-zA-Z0-9+.-]*:[^\s]*$/, + 'uri-reference': /^(((([A-Za-z][+\-.0-9A-Za-z]*(:%[0-9A-Fa-f]{2}|:[!$&-.0-;=?-Z_a-z~]|[/?])|\?)(%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~])*|([A-Za-z][+\-.0-9A-Za-z]*:?)?)|([A-Za-z][+\-.0-9A-Za-z]*:)?\/((%[0-9A-Fa-f]{2}|\/((%[0-9A-Fa-f]{2}|[!$&-.0-9;=A-Z_a-z~])+|(\[(([Vv][0-9A-Fa-f]+\.[!$&-.0-;=A-Z_a-z~]+)?|[.0-:A-Fa-f]+)\])?)(:\d*)?[/?]|[!$&-.0-;=?-Z_a-z~])(%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~])*|(\/((%[0-9A-Fa-f]{2}|[!$&-.0-9;=A-Z_a-z~])+|(\[(([Vv][0-9A-Fa-f]+\.[!$&-.0-;=A-Z_a-z~]+)?|[.0-:A-Fa-f]+)\])?)(:\d*)?)?))#(%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~])*|(([A-Za-z][+\-.0-9A-Za-z]*)?%[0-9A-Fa-f]{2}|[!$&-.0-9;=@_~]|[A-Za-z][+\-.0-9A-Za-z]*[!$&-*,;=@_~])(%[0-9A-Fa-f]{2}|[!$&-.0-9;=@-Z_a-z~])*((([/?](%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~])*)?#|[/?])(%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~])*)?|([A-Za-z][+\-.0-9A-Za-z]*(:%[0-9A-Fa-f]{2}|:[!$&-.0-;=?-Z_a-z~]|[/?])|\?)(%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~])*|([A-Za-z][+\-.0-9A-Za-z]*:)?\/((%[0-9A-Fa-f]{2}|\/((%[0-9A-Fa-f]{2}|[!$&-.0-9;=A-Z_a-z~])+|(\[(([Vv][0-9A-Fa-f]+\.[!$&-.0-;=A-Z_a-z~]+)?|[.0-:A-Fa-f]+)\])?)(:\d*)?[/?]|[!$&-.0-;=?-Z_a-z~])(%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~])*|\/((%[0-9A-Fa-f]{2}|[!$&-.0-9;=A-Z_a-z~])+(:\d*)?|(\[(([Vv][0-9A-Fa-f]+\.[!$&-.0-;=A-Z_a-z~]+)?|[.0-:A-Fa-f]+)\])?:\d*|\[(([Vv][0-9A-Fa-f]+\.[!$&-.0-;=A-Z_a-z~]+)?|[.0-:A-Fa-f]+)\])?)?|[A-Za-z][+\-.0-9A-Za-z]*:?)?$/, + 'iri': /^[a-zA-Z][a-zA-Z0-9+.-]*:[^\s]*$/, + 'iri-reference': /^(((([A-Za-z][+\-.0-9A-Za-z]*(:%[0-9A-Fa-f]{2}|:[!$&-.0-;=?-Z_a-z~-\u{10FFFF}]|[/?])|\?)(%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~-\u{10FFFF}])*|([A-Za-z][+\-.0-9A-Za-z]*:?)?)|([A-Za-z][+\-.0-9A-Za-z]*:)?\/((%[0-9A-Fa-f]{2}|\/((%[0-9A-Fa-f]{2}|[!$&-.0-9;=A-Z_a-z~-\u{10FFFF}])+|(\[(([Vv][0-9A-Fa-f]+\.[!$&-.0-;=A-Z_a-z~-\u{10FFFF}]+)?|[.0-:A-Fa-f]+)\])?)(:\d*)?[/?]|[!$&-.0-;=?-Z_a-z~-\u{10FFFF}])(%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~-\u{10FFFF}])*|(\/((%[0-9A-Fa-f]{2}|[!$&-.0-9;=A-Z_a-z~-\u{10FFFF}])+|(\[(([Vv][0-9A-Fa-f]+\.[!$&-.0-;=A-Z_a-z~-\u{10FFFF}]+)?|[.0-:A-Fa-f]+)\])?)(:\d*)?)?))#(%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~-\u{10FFFF}])*|(([A-Za-z][+\-.0-9A-Za-z]*)?%[0-9A-Fa-f]{2}|[!$&-.0-9;=@_~-\u{10FFFF}]|[A-Za-z][+\-.0-9A-Za-z]*[!$&-*,;=@_~-\u{10FFFF}])(%[0-9A-Fa-f]{2}|[!$&-.0-9;=@-Z_a-z~-\u{10FFFF}])*((([/?](%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~-\u{10FFFF}])*)?#|[/?])(%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~-\u{10FFFF}])*)?|([A-Za-z][+\-.0-9A-Za-z]*(:%[0-9A-Fa-f]{2}|:[!$&-.0-;=?-Z_a-z~-\u{10FFFF}]|[/?])|\?)(%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~-\u{10FFFF}])*|([A-Za-z][+\-.0-9A-Za-z]*:)?\/((%[0-9A-Fa-f]{2}|\/((%[0-9A-Fa-f]{2}|[!$&-.0-9;=A-Z_a-z~-\u{10FFFF}])+|(\[(([Vv][0-9A-Fa-f]+\.[!$&-.0-;=A-Z_a-z~-\u{10FFFF}]+)?|[.0-:A-Fa-f]+)\])?)(:\d*)?[/?]|[!$&-.0-;=?-Z_a-z~-\u{10FFFF}])(%[0-9A-Fa-f]{2}|[!$&-;=?-Z_a-z~-\u{10FFFF}])*|\/((%[0-9A-Fa-f]{2}|[!$&-.0-9;=A-Z_a-z~-\u{10FFFF}])+(:\d*)?|(\[(([Vv][0-9A-Fa-f]+\.[!$&-.0-;=A-Z_a-z~-\u{10FFFF}]+)?|[.0-:A-Fa-f]+)\])?:\d*|\[(([Vv][0-9A-Fa-f]+\.[!$&-.0-;=A-Z_a-z~-\u{10FFFF}]+)?|[.0-:A-Fa-f]+)\])?)?|[A-Za-z][+\-.0-9A-Za-z]*:?)?$/u, + 'uuid': /^[0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}$/i, + + // 7.3.6. uri-template + 'uri-template': /(%[0-9a-f]{2}|[!#$&(-;=?@\[\]_a-z~]|\{[!#&+,./;=?@|]?(%[0-9a-f]{2}|[0-9_a-z])(\.?(%[0-9a-f]{2}|[0-9_a-z]))*(:[1-9]\d{0,3}|\*)?(,(%[0-9a-f]{2}|[0-9_a-z])(\.?(%[0-9a-f]{2}|[0-9_a-z]))*(:[1-9]\d{0,3}|\*)?)*\})*/iu, + + // 7.3.7. JSON Pointers + 'json-pointer': /^(\/([\x00-\x2e0-@\[-}\x7f]|~[01])*)*$/iu, + 'relative-json-pointer': /^\d+(#|(\/([\x00-\x2e0-@\[-}\x7f]|~[01])*)*)$/iu, + + // hostname regex from: http://stackoverflow.com/a/1420225/5628 + 'hostname': /^(?=.{1,255}$)[0-9A-Za-z](?:(?:[0-9A-Za-z]|-){0,61}[0-9A-Za-z])?(?:\.[0-9A-Za-z](?:(?:[0-9A-Za-z]|-){0,61}[0-9A-Za-z])?)*\.?$/, + 'host-name': /^(?=.{1,255}$)[0-9A-Za-z](?:(?:[0-9A-Za-z]|-){0,61}[0-9A-Za-z])?(?:\.[0-9A-Za-z](?:(?:[0-9A-Za-z]|-){0,61}[0-9A-Za-z])?)*\.?$/, + + 'utc-millisec': function (input) { + return (typeof input === 'string') && parseFloat(input) === parseInt(input, 10) && !isNaN(input); + }, + + // 7.3.8. regex + 'regex': function (input) { + var result = true; + try { + new RegExp(input); + } catch (e) { + result = false; + } + return result; + }, + + // Other definitions + // "style" was removed from JSON Schema in draft-4 and is deprecated + 'style': /[\r\n\t ]*[^\r\n\t ][^:]*:[\r\n\t ]*[^\r\n\t ;]*[\r\n\t ]*;?/, + // "color" was removed from JSON Schema in draft-4 and is deprecated + 'color': /^(#?([0-9A-Fa-f]{3}){1,2}\b|aqua|black|blue|fuchsia|gray|green|lime|maroon|navy|olive|orange|purple|red|silver|teal|white|yellow|(rgb\(\s*\b([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\b\s*,\s*\b([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\b\s*,\s*\b([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\b\s*\))|(rgb\(\s*(\d?\d%|100%)+\s*,\s*(\d?\d%|100%)+\s*,\s*(\d?\d%|100%)+\s*\)))$/, + 'phone': /^\+(?:[0-9] ?){6,14}[0-9]$/, + 'alpha': /^[a-zA-Z]+$/, + 'alphanumeric': /^[a-zA-Z0-9]+$/, +}; + +FORMAT_REGEXPS.regexp = FORMAT_REGEXPS.regex; +FORMAT_REGEXPS.pattern = FORMAT_REGEXPS.regex; +FORMAT_REGEXPS.ipv4 = FORMAT_REGEXPS['ip-address']; + +exports.isFormat = function isFormat (input, format, validator) { + if (typeof input === 'string' && FORMAT_REGEXPS[format] !== undefined) { + if (FORMAT_REGEXPS[format] instanceof RegExp) { + return FORMAT_REGEXPS[format].test(input); + } + if (typeof FORMAT_REGEXPS[format] === 'function') { + return FORMAT_REGEXPS[format](input); + } + } else if (validator && validator.customFormats && + typeof validator.customFormats[format] === 'function') { + return validator.customFormats[format](input); + } + return true; +}; + +var makeSuffix = exports.makeSuffix = function makeSuffix (key) { + key = key.toString(); + // This function could be capable of outputting valid a ECMAScript string, but the + // resulting code for testing which form to use would be tens of thousands of characters long + // That means this will use the name form for some illegal forms + if (!key.match(/[.\s\[\]]/) && !key.match(/^[\d]/)) { + return '.' + key; + } + if (key.match(/^\d+$/)) { + return '[' + key + ']'; + } + return '[' + JSON.stringify(key) + ']'; +}; + +exports.deepCompareStrict = function deepCompareStrict (a, b) { + if (typeof a !== typeof b) { + return false; + } + if (Array.isArray(a)) { + if (!Array.isArray(b)) { + return false; + } + if (a.length !== b.length) { + return false; + } + return a.every(function (v, i) { + return deepCompareStrict(a[i], b[i]); + }); + } + if (typeof a === 'object') { + if (!a || !b) { + return a === b; + } + var aKeys = Object.keys(a); + var bKeys = Object.keys(b); + if (aKeys.length !== bKeys.length) { + return false; + } + return aKeys.every(function (v) { + return deepCompareStrict(a[v], b[v]); + }); + } + return a === b; +}; + +function deepMerger (target, dst, e, i) { + if (typeof e === 'object') { + dst[i] = deepMerge(target[i], e); + } else { + if (target.indexOf(e) === -1) { + dst.push(e); + } + } +} + +function copyist (src, dst, key) { + dst[key] = src[key]; +} + +function copyistWithDeepMerge (target, src, dst, key) { + if (typeof src[key] !== 'object' || !src[key]) { + dst[key] = src[key]; + } + else { + if (!target[key]) { + dst[key] = src[key]; + } else { + dst[key] = deepMerge(target[key], src[key]); + } + } +} + +function deepMerge (target, src) { + var array = Array.isArray(src); + var dst = array && [] || {}; + + if (array) { + target = target || []; + dst = dst.concat(target); + src.forEach(deepMerger.bind(null, target, dst)); + } else { + if (target && typeof target === 'object') { + Object.keys(target).forEach(copyist.bind(null, target, dst)); + } + Object.keys(src).forEach(copyistWithDeepMerge.bind(null, target, src, dst)); + } + + return dst; +} + +module.exports.deepMerge = deepMerge; + +/** + * Validates instance against the provided schema + * Implements URI+JSON Pointer encoding, e.g. "%7e"="~0"=>"~", "~1"="%2f"=>"/" + * @param o + * @param s The path to walk o along + * @return any + */ +exports.objectGetPath = function objectGetPath(o, s) { + var parts = s.split('/').slice(1); + var k; + while (typeof (k=parts.shift()) == 'string') { + var n = decodeURIComponent(k.replace(/~0/,'~').replace(/~1/g,'/')); + if (!(n in o)) return; + o = o[n]; + } + return o; +}; + +function pathEncoder (v) { + return '/'+encodeURIComponent(v).replace(/~/g,'%7E'); +} +/** + * Accept an Array of property names and return a JSON Pointer URI fragment + * @param Array a + * @return {String} + */ +exports.encodePath = function encodePointer(a){ + // ~ must be encoded explicitly because hacks + // the slash is encoded by encodeURIComponent + return a.map(pathEncoder).join(''); +}; + + +/** + * Calculate the number of decimal places a number uses + * We need this to get correct results out of multipleOf and divisibleBy + * when either figure is has decimal places, due to IEEE-754 float issues. + * @param number + * @returns {number} + */ +exports.getDecimalPlaces = function getDecimalPlaces(number) { + + var decimalPlaces = 0; + if (isNaN(number)) return decimalPlaces; + + if (typeof number !== 'number') { + number = Number(number); + } + + var parts = number.toString().split('e'); + if (parts.length === 2) { + if (parts[1][0] !== '-') { + return decimalPlaces; + } else { + decimalPlaces = Number(parts[1].slice(1)); + } + } + + var decimalParts = parts[0].split('.'); + if (decimalParts.length === 2) { + decimalPlaces += decimalParts[1].length; + } + + return decimalPlaces; +}; + +exports.isSchema = function isSchema(val){ + return (typeof val === 'object' && val) || (typeof val === 'boolean'); +}; + + + +/***/ }), + +/***/ "./node_modules/jsonschema/lib/index.js": +/*!**********************************************!*\ + !*** ./node_modules/jsonschema/lib/index.js ***! + \**********************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +var Validator = module.exports.Validator = __webpack_require__(/*! ./validator */ "./node_modules/jsonschema/lib/validator.js"); + +module.exports.ValidatorResult = __webpack_require__(/*! ./helpers */ "./node_modules/jsonschema/lib/helpers.js").ValidatorResult; +module.exports.ValidatorResultError = __webpack_require__(/*! ./helpers */ "./node_modules/jsonschema/lib/helpers.js").ValidatorResultError; +module.exports.ValidationError = __webpack_require__(/*! ./helpers */ "./node_modules/jsonschema/lib/helpers.js").ValidationError; +module.exports.SchemaError = __webpack_require__(/*! ./helpers */ "./node_modules/jsonschema/lib/helpers.js").SchemaError; +module.exports.SchemaScanResult = __webpack_require__(/*! ./scan */ "./node_modules/jsonschema/lib/scan.js").SchemaScanResult; +module.exports.scan = __webpack_require__(/*! ./scan */ "./node_modules/jsonschema/lib/scan.js").scan; + +module.exports.validate = function (instance, schema, options) { + var v = new Validator(); + return v.validate(instance, schema, options); +}; + + +/***/ }), + +/***/ "./node_modules/jsonschema/lib/scan.js": +/*!*********************************************!*\ + !*** ./node_modules/jsonschema/lib/scan.js ***! + \*********************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +var urilib = __webpack_require__(/*! url */ "./node_modules/url/url.js"); +var helpers = __webpack_require__(/*! ./helpers */ "./node_modules/jsonschema/lib/helpers.js"); + +module.exports.SchemaScanResult = SchemaScanResult; +function SchemaScanResult(found, ref){ + this.id = found; + this.ref = ref; +} + +/** + * Adds a schema with a certain urn to the Validator instance. + * @param string uri + * @param object schema + * @return {Object} + */ +module.exports.scan = function scan(base, schema){ + function scanSchema(baseuri, schema){ + if(!schema || typeof schema!='object') return; + // Mark all referenced schemas so we can tell later which schemas are referred to, but never defined + if(schema.$ref){ + var resolvedUri = urilib.resolve(baseuri, schema.$ref); + ref[resolvedUri] = ref[resolvedUri] ? ref[resolvedUri]+1 : 0; + return; + } + var id = schema.$id || schema.id; + var ourBase = id ? urilib.resolve(baseuri, id) : baseuri; + if (ourBase) { + // If there's no fragment, append an empty one + if(ourBase.indexOf('#')<0) ourBase += '#'; + if(found[ourBase]){ + if(!helpers.deepCompareStrict(found[ourBase], schema)){ + throw new Error('Schema <'+ourBase+'> already exists with different definition'); + } + return found[ourBase]; + } + found[ourBase] = schema; + // strip trailing fragment + if(ourBase[ourBase.length-1]=='#'){ + found[ourBase.substring(0, ourBase.length-1)] = schema; + } + } + scanArray(ourBase+'/items', (Array.isArray(schema.items)?schema.items:[schema.items])); + scanArray(ourBase+'/extends', (Array.isArray(schema.extends)?schema.extends:[schema.extends])); + scanSchema(ourBase+'/additionalItems', schema.additionalItems); + scanObject(ourBase+'/properties', schema.properties); + scanSchema(ourBase+'/additionalProperties', schema.additionalProperties); + scanObject(ourBase+'/definitions', schema.definitions); + scanObject(ourBase+'/patternProperties', schema.patternProperties); + scanObject(ourBase+'/dependencies', schema.dependencies); + scanArray(ourBase+'/disallow', schema.disallow); + scanArray(ourBase+'/allOf', schema.allOf); + scanArray(ourBase+'/anyOf', schema.anyOf); + scanArray(ourBase+'/oneOf', schema.oneOf); + scanSchema(ourBase+'/not', schema.not); + } + function scanArray(baseuri, schemas){ + if(!Array.isArray(schemas)) return; + for(var i=0; i", schema); + } + var subschema = helpers.objectGetPath(ctx.schemas[document], fragment.substr(1)); + if(subschema===undefined){ + throw new SchemaError("no such schema " + fragment + " located in <" + document + ">", schema); + } + return {subschema: subschema, switchSchema: switchSchema}; +}; + +/** + * Tests whether the instance if of a certain type. + * @private + * @param instance + * @param schema + * @param options + * @param ctx + * @param type + * @return {boolean} + */ +Validator.prototype.testType = function validateType (instance, schema, options, ctx, type) { + if(type===undefined){ + return; + }else if(type===null){ + throw new SchemaError('Unexpected null in "type" keyword'); + } + if (typeof this.types[type] == 'function') { + return this.types[type].call(this, instance); + } + if (type && typeof type == 'object') { + var res = this.validateSchema(instance, type, options, ctx); + return res === undefined || !(res && res.errors.length); + } + // Undefined or properties not on the list are acceptable, same as not being defined + return true; +}; + +var types = Validator.prototype.types = {}; +types.string = function testString (instance) { + return typeof instance == 'string'; +}; +types.number = function testNumber (instance) { + // isFinite returns false for NaN, Infinity, and -Infinity + return typeof instance == 'number' && isFinite(instance); +}; +types.integer = function testInteger (instance) { + return (typeof instance == 'number') && instance % 1 === 0; +}; +types.boolean = function testBoolean (instance) { + return typeof instance == 'boolean'; +}; +types.array = function testArray (instance) { + return Array.isArray(instance); +}; +types['null'] = function testNull (instance) { + return instance === null; +}; +types.date = function testDate (instance) { + return instance instanceof Date; +}; +types.any = function testAny (instance) { + return true; +}; +types.object = function testObject (instance) { + // TODO: fix this - see #15 + return instance && (typeof instance === 'object') && !(Array.isArray(instance)) && !(instance instanceof Date); +}; + +module.exports = Validator; + + +/***/ }), + +/***/ "./node_modules/kuler/index.js": +/*!*************************************!*\ + !*** ./node_modules/kuler/index.js ***! + \*************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +/** + * Kuler: Color text using CSS colors + * + * @constructor + * @param {String} text The text that needs to be styled + * @param {String} color Optional color for alternate API. + * @api public + */ +function Kuler(text, color) { + if (color) return (new Kuler(text)).style(color); + if (!(this instanceof Kuler)) return new Kuler(text); + + this.text = text; +} + +/** + * ANSI color codes. + * + * @type {String} + * @private + */ +Kuler.prototype.prefix = '\x1b['; +Kuler.prototype.suffix = 'm'; + +/** + * Parse a hex color string and parse it to it's RGB equiv. + * + * @param {String} color + * @returns {Array} + * @api private + */ +Kuler.prototype.hex = function hex(color) { + color = color[0] === '#' ? color.substring(1) : color; + + // + // Pre-parse for shorthand hex colors. + // + if (color.length === 3) { + color = color.split(''); + + color[5] = color[2]; // F60##0 + color[4] = color[2]; // F60#00 + color[3] = color[1]; // F60600 + color[2] = color[1]; // F66600 + color[1] = color[0]; // FF6600 + + color = color.join(''); + } + + var r = color.substring(0, 2) + , g = color.substring(2, 4) + , b = color.substring(4, 6); + + return [ parseInt(r, 16), parseInt(g, 16), parseInt(b, 16) ]; +}; + +/** + * Transform a 255 RGB value to an RGV code. + * + * @param {Number} r Red color channel. + * @param {Number} g Green color channel. + * @param {Number} b Blue color channel. + * @returns {String} + * @api public + */ +Kuler.prototype.rgb = function rgb(r, g, b) { + var red = r / 255 * 5 + , green = g / 255 * 5 + , blue = b / 255 * 5; + + return this.ansi(red, green, blue); +}; + +/** + * Turns RGB 0-5 values into a single ANSI code. + * + * @param {Number} r Red color channel. + * @param {Number} g Green color channel. + * @param {Number} b Blue color channel. + * @returns {String} + * @api public + */ +Kuler.prototype.ansi = function ansi(r, g, b) { + var red = Math.round(r) + , green = Math.round(g) + , blue = Math.round(b); + + return 16 + (red * 36) + (green * 6) + blue; +}; + +/** + * Marks an end of color sequence. + * + * @returns {String} Reset sequence. + * @api public + */ +Kuler.prototype.reset = function reset() { + return this.prefix +'39;49'+ this.suffix; +}; + +/** + * Colour the terminal using CSS. + * + * @param {String} color The HEX color code. + * @returns {String} the escape code. + * @api public + */ +Kuler.prototype.style = function style(color) { + return this.prefix +'38;5;'+ this.rgb.apply(this, this.hex(color)) + this.suffix + this.text + this.reset(); +}; + + +// +// Expose the actual interface. +// +module.exports = Kuler; + + +/***/ }), + +/***/ "./node_modules/localcookies/module/localCookie.js": +/*!*********************************************************!*\ + !*** ./node_modules/localcookies/module/localCookie.js ***! + \*********************************************************/ +/*! exports provided: default */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +class localCookie{constructor(e){return e=e||{},this.forceCookies=e.forceCookies||!1,!0===this._checkIfLocalStorageWorks()&&!0!==e.forceCookies?{getItem:this._getItemLocalStorage,setItem:this._setItemLocalStorage,removeItem:this._removeItemLocalStorage,clear:this._clearLocalStorage,keys:this._getLocalStorageKeys}:{getItem:this._getItemCookie,setItem:this._setItemCookie,removeItem:this._removeItemCookie,clear:this._clearCookies,keys:this._getCookieKeys}}_checkIfLocalStorageWorks(){if("undefined"==typeof localStorage)return!1;try{return localStorage.setItem("feature_test","yes"),"yes"===localStorage.getItem("feature_test")&&(localStorage.removeItem("feature_test"),!0)}catch(e){return!1}}_getItemLocalStorage(e){return window.localStorage.getItem(e)}_setItemLocalStorage(e,t){return window.localStorage.setItem(e,t)}_removeItemLocalStorage(e){return window.localStorage.removeItem(e)}_clearLocalStorage(){return window.localStorage.clear()}_getLocalStorageKeys(){return Object.keys(window.localStorage)}_getItemCookie(e){var t=document.cookie.match(RegExp("(?:^|;\\s*)"+function(e){return e.replace(/([.*+?\^${}()|\[\]\/\\])/g,"\\$1")}(e)+"=([^;]*)"));return t&&""===t[1]&&(t[1]=null),t?t[1]:null}_setItemCookie(e,t){var o=new Date,r=new Date(o.getTime()+15768e7);document.cookie=`${e}=${t}; expires=${r.toUTCString()};`}_removeItemCookie(e){document.cookie=`${e}=;Max-Age=-99999999;`}_clearCookies(){document.cookie.split(";").forEach(e=>{document.cookie=e.replace(/^ +/,"").replace(/=.*/,"=;expires=Max-Age=-99999999")})}_getCookieKeys(){return document.cookie.split(";").map(e=>e.split("=")[0])}}/* harmony default export */ __webpack_exports__["default"] = (localCookie); + + +/***/ }), + +/***/ "./node_modules/lodash/lodash.js": +/*!***************************************!*\ + !*** ./node_modules/lodash/lodash.js ***! + \***************************************/ +/*! no static exports found */ +/***/ (function(module, exports, __webpack_require__) { + +/* WEBPACK VAR INJECTION */(function(global, module) {var __WEBPACK_AMD_DEFINE_RESULT__;/** + * @license + * Lodash + * Copyright OpenJS Foundation and other contributors + * Released under MIT license + * Based on Underscore.js 1.8.3 + * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors + */ +;(function() { + + /** Used as a safe reference for `undefined` in pre-ES5 environments. */ + var undefined; + + /** Used as the semantic version number. */ + var VERSION = '4.17.21'; + + /** Used as the size to enable large array optimizations. */ + var LARGE_ARRAY_SIZE = 200; + + /** Error message constants. */ + var CORE_ERROR_TEXT = 'Unsupported core-js use. Try https://npms.io/search?q=ponyfill.', + FUNC_ERROR_TEXT = 'Expected a function', + INVALID_TEMPL_VAR_ERROR_TEXT = 'Invalid `variable` option passed into `_.template`'; + + /** Used to stand-in for `undefined` hash values. */ + var HASH_UNDEFINED = '__lodash_hash_undefined__'; + + /** Used as the maximum memoize cache size. */ + var MAX_MEMOIZE_SIZE = 500; + + /** Used as the internal argument placeholder. */ + var PLACEHOLDER = '__lodash_placeholder__'; + + /** Used to compose bitmasks for cloning. */ + var CLONE_DEEP_FLAG = 1, + CLONE_FLAT_FLAG = 2, + CLONE_SYMBOLS_FLAG = 4; + + /** Used to compose bitmasks for value comparisons. */ + var COMPARE_PARTIAL_FLAG = 1, + COMPARE_UNORDERED_FLAG = 2; + + /** Used to compose bitmasks for function metadata. */ + var WRAP_BIND_FLAG = 1, + WRAP_BIND_KEY_FLAG = 2, + WRAP_CURRY_BOUND_FLAG = 4, + WRAP_CURRY_FLAG = 8, + WRAP_CURRY_RIGHT_FLAG = 16, + WRAP_PARTIAL_FLAG = 32, + WRAP_PARTIAL_RIGHT_FLAG = 64, + WRAP_ARY_FLAG = 128, + WRAP_REARG_FLAG = 256, + WRAP_FLIP_FLAG = 512; + + /** Used as default options for `_.truncate`. */ + var DEFAULT_TRUNC_LENGTH = 30, + DEFAULT_TRUNC_OMISSION = '...'; + + /** Used to detect hot functions by number of calls within a span of milliseconds. */ + var HOT_COUNT = 800, + HOT_SPAN = 16; + + /** Used to indicate the type of lazy iteratees. */ + var LAZY_FILTER_FLAG = 1, + LAZY_MAP_FLAG = 2, + LAZY_WHILE_FLAG = 3; + + /** Used as references for various `Number` constants. */ + var INFINITY = 1 / 0, + MAX_SAFE_INTEGER = 9007199254740991, + MAX_INTEGER = 1.7976931348623157e+308, + NAN = 0 / 0; + + /** Used as references for the maximum length and index of an array. */ + var MAX_ARRAY_LENGTH = 4294967295, + MAX_ARRAY_INDEX = MAX_ARRAY_LENGTH - 1, + HALF_MAX_ARRAY_LENGTH = MAX_ARRAY_LENGTH >>> 1; + + /** Used to associate wrap methods with their bit flags. */ + var wrapFlags = [ + ['ary', WRAP_ARY_FLAG], + ['bind', WRAP_BIND_FLAG], + ['bindKey', WRAP_BIND_KEY_FLAG], + ['curry', WRAP_CURRY_FLAG], + ['curryRight', WRAP_CURRY_RIGHT_FLAG], + ['flip', WRAP_FLIP_FLAG], + ['partial', WRAP_PARTIAL_FLAG], + ['partialRight', WRAP_PARTIAL_RIGHT_FLAG], + ['rearg', WRAP_REARG_FLAG] + ]; + + /** `Object#toString` result references. */ + var argsTag = '[object Arguments]', + arrayTag = '[object Array]', + asyncTag = '[object AsyncFunction]', + boolTag = '[object Boolean]', + dateTag = '[object Date]', + domExcTag = '[object DOMException]', + errorTag = '[object Error]', + funcTag = '[object Function]', + genTag = '[object GeneratorFunction]', + mapTag = '[object Map]', + numberTag = '[object Number]', + nullTag = '[object Null]', + objectTag = '[object Object]', + promiseTag = '[object Promise]', + proxyTag = '[object Proxy]', + regexpTag = '[object RegExp]', + setTag = '[object Set]', + stringTag = '[object String]', + symbolTag = '[object Symbol]', + undefinedTag = '[object Undefined]', + weakMapTag = '[object WeakMap]', + weakSetTag = '[object WeakSet]'; + + var arrayBufferTag = '[object ArrayBuffer]', + dataViewTag = '[object DataView]', + float32Tag = '[object Float32Array]', + float64Tag = '[object Float64Array]', + int8Tag = '[object Int8Array]', + int16Tag = '[object Int16Array]', + int32Tag = '[object Int32Array]', + uint8Tag = '[object Uint8Array]', + uint8ClampedTag = '[object Uint8ClampedArray]', + uint16Tag = '[object Uint16Array]', + uint32Tag = '[object Uint32Array]'; + + /** Used to match empty string literals in compiled template source. */ + var reEmptyStringLeading = /\b__p \+= '';/g, + reEmptyStringMiddle = /\b(__p \+=) '' \+/g, + reEmptyStringTrailing = /(__e\(.*?\)|\b__t\)) \+\n'';/g; + + /** Used to match HTML entities and HTML characters. */ + var reEscapedHtml = /&(?:amp|lt|gt|quot|#39);/g, + reUnescapedHtml = /[&<>"']/g, + reHasEscapedHtml = RegExp(reEscapedHtml.source), + reHasUnescapedHtml = RegExp(reUnescapedHtml.source); + + /** Used to match template delimiters. */ + var reEscape = /<%-([\s\S]+?)%>/g, + reEvaluate = /<%([\s\S]+?)%>/g, + reInterpolate = /<%=([\s\S]+?)%>/g; + + /** Used to match property names within property paths. */ + var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/, + reIsPlainProp = /^\w*$/, + rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g; + + /** + * Used to match `RegExp` + * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns). + */ + var reRegExpChar = /[\\^$.*+?()[\]{}|]/g, + reHasRegExpChar = RegExp(reRegExpChar.source); + + /** Used to match leading whitespace. */ + var reTrimStart = /^\s+/; + + /** Used to match a single whitespace character. */ + var reWhitespace = /\s/; + + /** Used to match wrap detail comments. */ + var reWrapComment = /\{(?:\n\/\* \[wrapped with .+\] \*\/)?\n?/, + reWrapDetails = /\{\n\/\* \[wrapped with (.+)\] \*/, + reSplitDetails = /,? & /; + + /** Used to match words composed of alphanumeric characters. */ + var reAsciiWord = /[^\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]+/g; + + /** + * Used to validate the `validate` option in `_.template` variable. + * + * Forbids characters which could potentially change the meaning of the function argument definition: + * - "()," (modification of function parameters) + * - "=" (default value) + * - "[]{}" (destructuring of function parameters) + * - "/" (beginning of a comment) + * - whitespace + */ + var reForbiddenIdentifierChars = /[()=,{}\[\]\/\s]/; + + /** Used to match backslashes in property paths. */ + var reEscapeChar = /\\(\\)?/g; + + /** + * Used to match + * [ES template delimiters](http://ecma-international.org/ecma-262/7.0/#sec-template-literal-lexical-components). + */ + var reEsTemplate = /\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g; + + /** Used to match `RegExp` flags from their coerced string values. */ + var reFlags = /\w*$/; + + /** Used to detect bad signed hexadecimal string values. */ + var reIsBadHex = /^[-+]0x[0-9a-f]+$/i; + + /** Used to detect binary string values. */ + var reIsBinary = /^0b[01]+$/i; + + /** Used to detect host constructors (Safari). */ + var reIsHostCtor = /^\[object .+?Constructor\]$/; + + /** Used to detect octal string values. */ + var reIsOctal = /^0o[0-7]+$/i; + + /** Used to detect unsigned integer values. */ + var reIsUint = /^(?:0|[1-9]\d*)$/; + + /** Used to match Latin Unicode letters (excluding mathematical operators). */ + var reLatin = /[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g; + + /** Used to ensure capturing order of template delimiters. */ + var reNoMatch = /($^)/; + + /** Used to match unescaped characters in compiled string literals. */ + var reUnescapedString = /['\n\r\u2028\u2029\\]/g; + + /** Used to compose unicode character classes. */ + var rsAstralRange = '\\ud800-\\udfff', + rsComboMarksRange = '\\u0300-\\u036f', + reComboHalfMarksRange = '\\ufe20-\\ufe2f', + rsComboSymbolsRange = '\\u20d0-\\u20ff', + rsComboRange = rsComboMarksRange + reComboHalfMarksRange + rsComboSymbolsRange, + rsDingbatRange = '\\u2700-\\u27bf', + rsLowerRange = 'a-z\\xdf-\\xf6\\xf8-\\xff', + rsMathOpRange = '\\xac\\xb1\\xd7\\xf7', + rsNonCharRange = '\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf', + rsPunctuationRange = '\\u2000-\\u206f', + rsSpaceRange = ' \\t\\x0b\\f\\xa0\\ufeff\\n\\r\\u2028\\u2029\\u1680\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000', + rsUpperRange = 'A-Z\\xc0-\\xd6\\xd8-\\xde', + rsVarRange = '\\ufe0e\\ufe0f', + rsBreakRange = rsMathOpRange + rsNonCharRange + rsPunctuationRange + rsSpaceRange; + + /** Used to compose unicode capture groups. */ + var rsApos = "['\u2019]", + rsAstral = '[' + rsAstralRange + ']', + rsBreak = '[' + rsBreakRange + ']', + rsCombo = '[' + rsComboRange + ']', + rsDigits = '\\d+', + rsDingbat = '[' + rsDingbatRange + ']', + rsLower = '[' + rsLowerRange + ']', + rsMisc = '[^' + rsAstralRange + rsBreakRange + rsDigits + rsDingbatRange + rsLowerRange + rsUpperRange + ']', + rsFitz = '\\ud83c[\\udffb-\\udfff]', + rsModifier = '(?:' + rsCombo + '|' + rsFitz + ')', + rsNonAstral = '[^' + rsAstralRange + ']', + rsRegional = '(?:\\ud83c[\\udde6-\\uddff]){2}', + rsSurrPair = '[\\ud800-\\udbff][\\udc00-\\udfff]', + rsUpper = '[' + rsUpperRange + ']', + rsZWJ = '\\u200d'; + + /** Used to compose unicode regexes. */ + var rsMiscLower = '(?:' + rsLower + '|' + rsMisc + ')', + rsMiscUpper = '(?:' + rsUpper + '|' + rsMisc + ')', + rsOptContrLower = '(?:' + rsApos + '(?:d|ll|m|re|s|t|ve))?', + rsOptContrUpper = '(?:' + rsApos + '(?:D|LL|M|RE|S|T|VE))?', + reOptMod = rsModifier + '?', + rsOptVar = '[' + rsVarRange + ']?', + rsOptJoin = '(?:' + rsZWJ + '(?:' + [rsNonAstral, rsRegional, rsSurrPair].join('|') + ')' + rsOptVar + reOptMod + ')*', + rsOrdLower = '\\d*(?:1st|2nd|3rd|(?![123])\\dth)(?=\\b|[A-Z_])', + rsOrdUpper = '\\d*(?:1ST|2ND|3RD|(?![123])\\dTH)(?=\\b|[a-z_])', + rsSeq = rsOptVar + reOptMod + rsOptJoin, + rsEmoji = '(?:' + [rsDingbat, rsRegional, rsSurrPair].join('|') + ')' + rsSeq, + rsSymbol = '(?:' + [rsNonAstral + rsCombo + '?', rsCombo, rsRegional, rsSurrPair, rsAstral].join('|') + ')'; + + /** Used to match apostrophes. */ + var reApos = RegExp(rsApos, 'g'); + + /** + * Used to match [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks) and + * [combining diacritical marks for symbols](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks_for_Symbols). + */ + var reComboMark = RegExp(rsCombo, 'g'); + + /** Used to match [string symbols](https://mathiasbynens.be/notes/javascript-unicode). */ + var reUnicode = RegExp(rsFitz + '(?=' + rsFitz + ')|' + rsSymbol + rsSeq, 'g'); + + /** Used to match complex or compound words. */ + var reUnicodeWord = RegExp([ + rsUpper + '?' + rsLower + '+' + rsOptContrLower + '(?=' + [rsBreak, rsUpper, '$'].join('|') + ')', + rsMiscUpper + '+' + rsOptContrUpper + '(?=' + [rsBreak, rsUpper + rsMiscLower, '$'].join('|') + ')', + rsUpper + '?' + rsMiscLower + '+' + rsOptContrLower, + rsUpper + '+' + rsOptContrUpper, + rsOrdUpper, + rsOrdLower, + rsDigits, + rsEmoji + ].join('|'), 'g'); + + /** Used to detect strings with [zero-width joiners or code points from the astral planes](http://eev.ee/blog/2015/09/12/dark-corners-of-unicode/). */ + var reHasUnicode = RegExp('[' + rsZWJ + rsAstralRange + rsComboRange + rsVarRange + ']'); + + /** Used to detect strings that need a more robust regexp to match words. */ + var reHasUnicodeWord = /[a-z][A-Z]|[A-Z]{2}[a-z]|[0-9][a-zA-Z]|[a-zA-Z][0-9]|[^a-zA-Z0-9 ]/; + + /** Used to assign default `context` object properties. */ + var contextProps = [ + 'Array', 'Buffer', 'DataView', 'Date', 'Error', 'Float32Array', 'Float64Array', + 'Function', 'Int8Array', 'Int16Array', 'Int32Array', 'Map', 'Math', 'Object', + 'Promise', 'RegExp', 'Set', 'String', 'Symbol', 'TypeError', 'Uint8Array', + 'Uint8ClampedArray', 'Uint16Array', 'Uint32Array', 'WeakMap', + '_', 'clearTimeout', 'isFinite', 'parseInt', 'setTimeout' + ]; + + /** Used to make template sourceURLs easier to identify. */ + var templateCounter = -1; + + /** Used to identify `toStringTag` values of typed arrays. */ + var typedArrayTags = {}; + typedArrayTags[float32Tag] = typedArrayTags[float64Tag] = + typedArrayTags[int8Tag] = typedArrayTags[int16Tag] = + typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] = + typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] = + typedArrayTags[uint32Tag] = true; + typedArrayTags[argsTag] = typedArrayTags[arrayTag] = + typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] = + typedArrayTags[dataViewTag] = typedArrayTags[dateTag] = + typedArrayTags[errorTag] = typedArrayTags[funcTag] = + typedArrayTags[mapTag] = typedArrayTags[numberTag] = + typedArrayTags[objectTag] = typedArrayTags[regexpTag] = + typedArrayTags[setTag] = typedArrayTags[stringTag] = + typedArrayTags[weakMapTag] = false; + + /** Used to identify `toStringTag` values supported by `_.clone`. */ + var cloneableTags = {}; + cloneableTags[argsTag] = cloneableTags[arrayTag] = + cloneableTags[arrayBufferTag] = cloneableTags[dataViewTag] = + cloneableTags[boolTag] = cloneableTags[dateTag] = + cloneableTags[float32Tag] = cloneableTags[float64Tag] = + cloneableTags[int8Tag] = cloneableTags[int16Tag] = + cloneableTags[int32Tag] = cloneableTags[mapTag] = + cloneableTags[numberTag] = cloneableTags[objectTag] = + cloneableTags[regexpTag] = cloneableTags[setTag] = + cloneableTags[stringTag] = cloneableTags[symbolTag] = + cloneableTags[uint8Tag] = cloneableTags[uint8ClampedTag] = + cloneableTags[uint16Tag] = cloneableTags[uint32Tag] = true; + cloneableTags[errorTag] = cloneableTags[funcTag] = + cloneableTags[weakMapTag] = false; + + /** Used to map Latin Unicode letters to basic Latin letters. */ + var deburredLetters = { + // Latin-1 Supplement block. + '\xc0': 'A', '\xc1': 'A', '\xc2': 'A', '\xc3': 'A', '\xc4': 'A', '\xc5': 'A', + '\xe0': 'a', '\xe1': 'a', '\xe2': 'a', '\xe3': 'a', '\xe4': 'a', '\xe5': 'a', + '\xc7': 'C', '\xe7': 'c', + '\xd0': 'D', '\xf0': 'd', + '\xc8': 'E', '\xc9': 'E', '\xca': 'E', '\xcb': 'E', + '\xe8': 'e', '\xe9': 'e', '\xea': 'e', '\xeb': 'e', + '\xcc': 'I', '\xcd': 'I', '\xce': 'I', '\xcf': 'I', + '\xec': 'i', '\xed': 'i', '\xee': 'i', '\xef': 'i', + '\xd1': 'N', '\xf1': 'n', + '\xd2': 'O', '\xd3': 'O', '\xd4': 'O', '\xd5': 'O', '\xd6': 'O', '\xd8': 'O', + '\xf2': 'o', '\xf3': 'o', '\xf4': 'o', '\xf5': 'o', '\xf6': 'o', '\xf8': 'o', + '\xd9': 'U', '\xda': 'U', '\xdb': 'U', '\xdc': 'U', + '\xf9': 'u', '\xfa': 'u', '\xfb': 'u', '\xfc': 'u', + '\xdd': 'Y', '\xfd': 'y', '\xff': 'y', + '\xc6': 'Ae', '\xe6': 'ae', + '\xde': 'Th', '\xfe': 'th', + '\xdf': 'ss', + // Latin Extended-A block. + '\u0100': 'A', '\u0102': 'A', '\u0104': 'A', + '\u0101': 'a', '\u0103': 'a', '\u0105': 'a', + '\u0106': 'C', '\u0108': 'C', '\u010a': 'C', '\u010c': 'C', + '\u0107': 'c', '\u0109': 'c', '\u010b': 'c', '\u010d': 'c', + '\u010e': 'D', '\u0110': 'D', '\u010f': 'd', '\u0111': 'd', + '\u0112': 'E', '\u0114': 'E', '\u0116': 'E', '\u0118': 'E', '\u011a': 'E', + '\u0113': 'e', '\u0115': 'e', '\u0117': 'e', '\u0119': 'e', '\u011b': 'e', + '\u011c': 'G', '\u011e': 'G', '\u0120': 'G', '\u0122': 'G', + '\u011d': 'g', '\u011f': 'g', '\u0121': 'g', '\u0123': 'g', + '\u0124': 'H', '\u0126': 'H', '\u0125': 'h', '\u0127': 'h', + '\u0128': 'I', '\u012a': 'I', '\u012c': 'I', '\u012e': 'I', '\u0130': 'I', + '\u0129': 'i', '\u012b': 'i', '\u012d': 'i', '\u012f': 'i', '\u0131': 'i', + '\u0134': 'J', '\u0135': 'j', + '\u0136': 'K', '\u0137': 'k', '\u0138': 'k', + '\u0139': 'L', '\u013b': 'L', '\u013d': 'L', '\u013f': 'L', '\u0141': 'L', + '\u013a': 'l', '\u013c': 'l', '\u013e': 'l', '\u0140': 'l', '\u0142': 'l', + '\u0143': 'N', '\u0145': 'N', '\u0147': 'N', '\u014a': 'N', + '\u0144': 'n', '\u0146': 'n', '\u0148': 'n', '\u014b': 'n', + '\u014c': 'O', '\u014e': 'O', '\u0150': 'O', + '\u014d': 'o', '\u014f': 'o', '\u0151': 'o', + '\u0154': 'R', '\u0156': 'R', '\u0158': 'R', + '\u0155': 'r', '\u0157': 'r', '\u0159': 'r', + '\u015a': 'S', '\u015c': 'S', '\u015e': 'S', '\u0160': 'S', + '\u015b': 's', '\u015d': 's', '\u015f': 's', '\u0161': 's', + '\u0162': 'T', '\u0164': 'T', '\u0166': 'T', + '\u0163': 't', '\u0165': 't', '\u0167': 't', + '\u0168': 'U', '\u016a': 'U', '\u016c': 'U', '\u016e': 'U', '\u0170': 'U', '\u0172': 'U', + '\u0169': 'u', '\u016b': 'u', '\u016d': 'u', '\u016f': 'u', '\u0171': 'u', '\u0173': 'u', + '\u0174': 'W', '\u0175': 'w', + '\u0176': 'Y', '\u0177': 'y', '\u0178': 'Y', + '\u0179': 'Z', '\u017b': 'Z', '\u017d': 'Z', + '\u017a': 'z', '\u017c': 'z', '\u017e': 'z', + '\u0132': 'IJ', '\u0133': 'ij', + '\u0152': 'Oe', '\u0153': 'oe', + '\u0149': "'n", '\u017f': 's' + }; + + /** Used to map characters to HTML entities. */ + var htmlEscapes = { + '&': '&', + '<': '<', + '>': '>', + '"': '"', + "'": ''' + }; + + /** Used to map HTML entities to characters. */ + var htmlUnescapes = { + '&': '&', + '<': '<', + '>': '>', + '"': '"', + ''': "'" + }; + + /** Used to escape characters for inclusion in compiled string literals. */ + var stringEscapes = { + '\\': '\\', + "'": "'", + '\n': 'n', + '\r': 'r', + '\u2028': 'u2028', + '\u2029': 'u2029' + }; + + /** Built-in method references without a dependency on `root`. */ + var freeParseFloat = parseFloat, + freeParseInt = parseInt; + + /** Detect free variable `global` from Node.js. */ + var freeGlobal = typeof global == 'object' && global && global.Object === Object && global; + + /** Detect free variable `self`. */ + var freeSelf = typeof self == 'object' && self && self.Object === Object && self; + + /** Used as a reference to the global object. */ + var root = freeGlobal || freeSelf || Function('return this')(); + + /** Detect free variable `exports`. */ + var freeExports = true && exports && !exports.nodeType && exports; + + /** Detect free variable `module`. */ + var freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module; + + /** Detect the popular CommonJS extension `module.exports`. */ + var moduleExports = freeModule && freeModule.exports === freeExports; + + /** Detect free variable `process` from Node.js. */ + var freeProcess = moduleExports && freeGlobal.process; + + /** Used to access faster Node.js helpers. */ + var nodeUtil = (function() { + try { + // Use `util.types` for Node.js 10+. + var types = freeModule && freeModule.require && freeModule.require('util').types; + + if (types) { + return types; + } + + // Legacy `process.binding('util')` for Node.js < 10. + return freeProcess && freeProcess.binding && freeProcess.binding('util'); + } catch (e) {} + }()); + + /* Node.js helper references. */ + var nodeIsArrayBuffer = nodeUtil && nodeUtil.isArrayBuffer, + nodeIsDate = nodeUtil && nodeUtil.isDate, + nodeIsMap = nodeUtil && nodeUtil.isMap, + nodeIsRegExp = nodeUtil && nodeUtil.isRegExp, + nodeIsSet = nodeUtil && nodeUtil.isSet, + nodeIsTypedArray = nodeUtil && nodeUtil.isTypedArray; + + /*--------------------------------------------------------------------------*/ + + /** + * A faster alternative to `Function#apply`, this function invokes `func` + * with the `this` binding of `thisArg` and the arguments of `args`. + * + * @private + * @param {Function} func The function to invoke. + * @param {*} thisArg The `this` binding of `func`. + * @param {Array} args The arguments to invoke `func` with. + * @returns {*} Returns the result of `func`. + */ + function apply(func, thisArg, args) { + switch (args.length) { + case 0: return func.call(thisArg); + case 1: return func.call(thisArg, args[0]); + case 2: return func.call(thisArg, args[0], args[1]); + case 3: return func.call(thisArg, args[0], args[1], args[2]); + } + return func.apply(thisArg, args); + } + + /** + * A specialized version of `baseAggregator` for arrays. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} setter The function to set `accumulator` values. + * @param {Function} iteratee The iteratee to transform keys. + * @param {Object} accumulator The initial aggregated object. + * @returns {Function} Returns `accumulator`. + */ + function arrayAggregator(array, setter, iteratee, accumulator) { + var index = -1, + length = array == null ? 0 : array.length; + + while (++index < length) { + var value = array[index]; + setter(accumulator, value, iteratee(value), array); + } + return accumulator; + } + + /** + * A specialized version of `_.forEach` for arrays without support for + * iteratee shorthands. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array} Returns `array`. + */ + function arrayEach(array, iteratee) { + var index = -1, + length = array == null ? 0 : array.length; + + while (++index < length) { + if (iteratee(array[index], index, array) === false) { + break; + } + } + return array; + } + + /** + * A specialized version of `_.forEachRight` for arrays without support for + * iteratee shorthands. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array} Returns `array`. + */ + function arrayEachRight(array, iteratee) { + var length = array == null ? 0 : array.length; + + while (length--) { + if (iteratee(array[length], length, array) === false) { + break; + } + } + return array; + } + + /** + * A specialized version of `_.every` for arrays without support for + * iteratee shorthands. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} predicate The function invoked per iteration. + * @returns {boolean} Returns `true` if all elements pass the predicate check, + * else `false`. + */ + function arrayEvery(array, predicate) { + var index = -1, + length = array == null ? 0 : array.length; + + while (++index < length) { + if (!predicate(array[index], index, array)) { + return false; + } + } + return true; + } + + /** + * A specialized version of `_.filter` for arrays without support for + * iteratee shorthands. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} predicate The function invoked per iteration. + * @returns {Array} Returns the new filtered array. + */ + function arrayFilter(array, predicate) { + var index = -1, + length = array == null ? 0 : array.length, + resIndex = 0, + result = []; + + while (++index < length) { + var value = array[index]; + if (predicate(value, index, array)) { + result[resIndex++] = value; + } + } + return result; + } + + /** + * A specialized version of `_.includes` for arrays without support for + * specifying an index to search from. + * + * @private + * @param {Array} [array] The array to inspect. + * @param {*} target The value to search for. + * @returns {boolean} Returns `true` if `target` is found, else `false`. + */ + function arrayIncludes(array, value) { + var length = array == null ? 0 : array.length; + return !!length && baseIndexOf(array, value, 0) > -1; + } + + /** + * This function is like `arrayIncludes` except that it accepts a comparator. + * + * @private + * @param {Array} [array] The array to inspect. + * @param {*} target The value to search for. + * @param {Function} comparator The comparator invoked per element. + * @returns {boolean} Returns `true` if `target` is found, else `false`. + */ + function arrayIncludesWith(array, value, comparator) { + var index = -1, + length = array == null ? 0 : array.length; + + while (++index < length) { + if (comparator(value, array[index])) { + return true; + } + } + return false; + } + + /** + * A specialized version of `_.map` for arrays without support for iteratee + * shorthands. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array} Returns the new mapped array. + */ + function arrayMap(array, iteratee) { + var index = -1, + length = array == null ? 0 : array.length, + result = Array(length); + + while (++index < length) { + result[index] = iteratee(array[index], index, array); + } + return result; + } + + /** + * Appends the elements of `values` to `array`. + * + * @private + * @param {Array} array The array to modify. + * @param {Array} values The values to append. + * @returns {Array} Returns `array`. + */ + function arrayPush(array, values) { + var index = -1, + length = values.length, + offset = array.length; + + while (++index < length) { + array[offset + index] = values[index]; + } + return array; + } + + /** + * A specialized version of `_.reduce` for arrays without support for + * iteratee shorthands. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @param {*} [accumulator] The initial value. + * @param {boolean} [initAccum] Specify using the first element of `array` as + * the initial value. + * @returns {*} Returns the accumulated value. + */ + function arrayReduce(array, iteratee, accumulator, initAccum) { + var index = -1, + length = array == null ? 0 : array.length; + + if (initAccum && length) { + accumulator = array[++index]; + } + while (++index < length) { + accumulator = iteratee(accumulator, array[index], index, array); + } + return accumulator; + } + + /** + * A specialized version of `_.reduceRight` for arrays without support for + * iteratee shorthands. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @param {*} [accumulator] The initial value. + * @param {boolean} [initAccum] Specify using the last element of `array` as + * the initial value. + * @returns {*} Returns the accumulated value. + */ + function arrayReduceRight(array, iteratee, accumulator, initAccum) { + var length = array == null ? 0 : array.length; + if (initAccum && length) { + accumulator = array[--length]; + } + while (length--) { + accumulator = iteratee(accumulator, array[length], length, array); + } + return accumulator; + } + + /** + * A specialized version of `_.some` for arrays without support for iteratee + * shorthands. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} predicate The function invoked per iteration. + * @returns {boolean} Returns `true` if any element passes the predicate check, + * else `false`. + */ + function arraySome(array, predicate) { + var index = -1, + length = array == null ? 0 : array.length; + + while (++index < length) { + if (predicate(array[index], index, array)) { + return true; + } + } + return false; + } + + /** + * Gets the size of an ASCII `string`. + * + * @private + * @param {string} string The string inspect. + * @returns {number} Returns the string size. + */ + var asciiSize = baseProperty('length'); + + /** + * Converts an ASCII `string` to an array. + * + * @private + * @param {string} string The string to convert. + * @returns {Array} Returns the converted array. + */ + function asciiToArray(string) { + return string.split(''); + } + + /** + * Splits an ASCII `string` into an array of its words. + * + * @private + * @param {string} The string to inspect. + * @returns {Array} Returns the words of `string`. + */ + function asciiWords(string) { + return string.match(reAsciiWord) || []; + } + + /** + * The base implementation of methods like `_.findKey` and `_.findLastKey`, + * without support for iteratee shorthands, which iterates over `collection` + * using `eachFunc`. + * + * @private + * @param {Array|Object} collection The collection to inspect. + * @param {Function} predicate The function invoked per iteration. + * @param {Function} eachFunc The function to iterate over `collection`. + * @returns {*} Returns the found element or its key, else `undefined`. + */ + function baseFindKey(collection, predicate, eachFunc) { + var result; + eachFunc(collection, function(value, key, collection) { + if (predicate(value, key, collection)) { + result = key; + return false; + } + }); + return result; + } + + /** + * The base implementation of `_.findIndex` and `_.findLastIndex` without + * support for iteratee shorthands. + * + * @private + * @param {Array} array The array to inspect. + * @param {Function} predicate The function invoked per iteration. + * @param {number} fromIndex The index to search from. + * @param {boolean} [fromRight] Specify iterating from right to left. + * @returns {number} Returns the index of the matched value, else `-1`. + */ + function baseFindIndex(array, predicate, fromIndex, fromRight) { + var length = array.length, + index = fromIndex + (fromRight ? 1 : -1); + + while ((fromRight ? index-- : ++index < length)) { + if (predicate(array[index], index, array)) { + return index; + } + } + return -1; + } + + /** + * The base implementation of `_.indexOf` without `fromIndex` bounds checks. + * + * @private + * @param {Array} array The array to inspect. + * @param {*} value The value to search for. + * @param {number} fromIndex The index to search from. + * @returns {number} Returns the index of the matched value, else `-1`. + */ + function baseIndexOf(array, value, fromIndex) { + return value === value + ? strictIndexOf(array, value, fromIndex) + : baseFindIndex(array, baseIsNaN, fromIndex); + } + + /** + * This function is like `baseIndexOf` except that it accepts a comparator. + * + * @private + * @param {Array} array The array to inspect. + * @param {*} value The value to search for. + * @param {number} fromIndex The index to search from. + * @param {Function} comparator The comparator invoked per element. + * @returns {number} Returns the index of the matched value, else `-1`. + */ + function baseIndexOfWith(array, value, fromIndex, comparator) { + var index = fromIndex - 1, + length = array.length; + + while (++index < length) { + if (comparator(array[index], value)) { + return index; + } + } + return -1; + } + + /** + * The base implementation of `_.isNaN` without support for number objects. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`. + */ + function baseIsNaN(value) { + return value !== value; + } + + /** + * The base implementation of `_.mean` and `_.meanBy` without support for + * iteratee shorthands. + * + * @private + * @param {Array} array The array to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {number} Returns the mean. + */ + function baseMean(array, iteratee) { + var length = array == null ? 0 : array.length; + return length ? (baseSum(array, iteratee) / length) : NAN; + } + + /** + * The base implementation of `_.property` without support for deep paths. + * + * @private + * @param {string} key The key of the property to get. + * @returns {Function} Returns the new accessor function. + */ + function baseProperty(key) { + return function(object) { + return object == null ? undefined : object[key]; + }; + } + + /** + * The base implementation of `_.propertyOf` without support for deep paths. + * + * @private + * @param {Object} object The object to query. + * @returns {Function} Returns the new accessor function. + */ + function basePropertyOf(object) { + return function(key) { + return object == null ? undefined : object[key]; + }; + } + + /** + * The base implementation of `_.reduce` and `_.reduceRight`, without support + * for iteratee shorthands, which iterates over `collection` using `eachFunc`. + * + * @private + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @param {*} accumulator The initial value. + * @param {boolean} initAccum Specify using the first or last element of + * `collection` as the initial value. + * @param {Function} eachFunc The function to iterate over `collection`. + * @returns {*} Returns the accumulated value. + */ + function baseReduce(collection, iteratee, accumulator, initAccum, eachFunc) { + eachFunc(collection, function(value, index, collection) { + accumulator = initAccum + ? (initAccum = false, value) + : iteratee(accumulator, value, index, collection); + }); + return accumulator; + } + + /** + * The base implementation of `_.sortBy` which uses `comparer` to define the + * sort order of `array` and replaces criteria objects with their corresponding + * values. + * + * @private + * @param {Array} array The array to sort. + * @param {Function} comparer The function to define sort order. + * @returns {Array} Returns `array`. + */ + function baseSortBy(array, comparer) { + var length = array.length; + + array.sort(comparer); + while (length--) { + array[length] = array[length].value; + } + return array; + } + + /** + * The base implementation of `_.sum` and `_.sumBy` without support for + * iteratee shorthands. + * + * @private + * @param {Array} array The array to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {number} Returns the sum. + */ + function baseSum(array, iteratee) { + var result, + index = -1, + length = array.length; + + while (++index < length) { + var current = iteratee(array[index]); + if (current !== undefined) { + result = result === undefined ? current : (result + current); + } + } + return result; + } + + /** + * The base implementation of `_.times` without support for iteratee shorthands + * or max array length checks. + * + * @private + * @param {number} n The number of times to invoke `iteratee`. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array} Returns the array of results. + */ + function baseTimes(n, iteratee) { + var index = -1, + result = Array(n); + + while (++index < n) { + result[index] = iteratee(index); + } + return result; + } + + /** + * The base implementation of `_.toPairs` and `_.toPairsIn` which creates an array + * of key-value pairs for `object` corresponding to the property names of `props`. + * + * @private + * @param {Object} object The object to query. + * @param {Array} props The property names to get values for. + * @returns {Object} Returns the key-value pairs. + */ + function baseToPairs(object, props) { + return arrayMap(props, function(key) { + return [key, object[key]]; + }); + } + + /** + * The base implementation of `_.trim`. + * + * @private + * @param {string} string The string to trim. + * @returns {string} Returns the trimmed string. + */ + function baseTrim(string) { + return string + ? string.slice(0, trimmedEndIndex(string) + 1).replace(reTrimStart, '') + : string; + } + + /** + * The base implementation of `_.unary` without support for storing metadata. + * + * @private + * @param {Function} func The function to cap arguments for. + * @returns {Function} Returns the new capped function. + */ + function baseUnary(func) { + return function(value) { + return func(value); + }; + } + + /** + * The base implementation of `_.values` and `_.valuesIn` which creates an + * array of `object` property values corresponding to the property names + * of `props`. + * + * @private + * @param {Object} object The object to query. + * @param {Array} props The property names to get values for. + * @returns {Object} Returns the array of property values. + */ + function baseValues(object, props) { + return arrayMap(props, function(key) { + return object[key]; + }); + } + + /** + * Checks if a `cache` value for `key` exists. + * + * @private + * @param {Object} cache The cache to query. + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. + */ + function cacheHas(cache, key) { + return cache.has(key); + } + + /** + * Used by `_.trim` and `_.trimStart` to get the index of the first string symbol + * that is not found in the character symbols. + * + * @private + * @param {Array} strSymbols The string symbols to inspect. + * @param {Array} chrSymbols The character symbols to find. + * @returns {number} Returns the index of the first unmatched string symbol. + */ + function charsStartIndex(strSymbols, chrSymbols) { + var index = -1, + length = strSymbols.length; + + while (++index < length && baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) {} + return index; + } + + /** + * Used by `_.trim` and `_.trimEnd` to get the index of the last string symbol + * that is not found in the character symbols. + * + * @private + * @param {Array} strSymbols The string symbols to inspect. + * @param {Array} chrSymbols The character symbols to find. + * @returns {number} Returns the index of the last unmatched string symbol. + */ + function charsEndIndex(strSymbols, chrSymbols) { + var index = strSymbols.length; + + while (index-- && baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) {} + return index; + } + + /** + * Gets the number of `placeholder` occurrences in `array`. + * + * @private + * @param {Array} array The array to inspect. + * @param {*} placeholder The placeholder to search for. + * @returns {number} Returns the placeholder count. + */ + function countHolders(array, placeholder) { + var length = array.length, + result = 0; + + while (length--) { + if (array[length] === placeholder) { + ++result; + } + } + return result; + } + + /** + * Used by `_.deburr` to convert Latin-1 Supplement and Latin Extended-A + * letters to basic Latin letters. + * + * @private + * @param {string} letter The matched letter to deburr. + * @returns {string} Returns the deburred letter. + */ + var deburrLetter = basePropertyOf(deburredLetters); + + /** + * Used by `_.escape` to convert characters to HTML entities. + * + * @private + * @param {string} chr The matched character to escape. + * @returns {string} Returns the escaped character. + */ + var escapeHtmlChar = basePropertyOf(htmlEscapes); + + /** + * Used by `_.template` to escape characters for inclusion in compiled string literals. + * + * @private + * @param {string} chr The matched character to escape. + * @returns {string} Returns the escaped character. + */ + function escapeStringChar(chr) { + return '\\' + stringEscapes[chr]; + } + + /** + * Gets the value at `key` of `object`. + * + * @private + * @param {Object} [object] The object to query. + * @param {string} key The key of the property to get. + * @returns {*} Returns the property value. + */ + function getValue(object, key) { + return object == null ? undefined : object[key]; + } + + /** + * Checks if `string` contains Unicode symbols. + * + * @private + * @param {string} string The string to inspect. + * @returns {boolean} Returns `true` if a symbol is found, else `false`. + */ + function hasUnicode(string) { + return reHasUnicode.test(string); + } + + /** + * Checks if `string` contains a word composed of Unicode symbols. + * + * @private + * @param {string} string The string to inspect. + * @returns {boolean} Returns `true` if a word is found, else `false`. + */ + function hasUnicodeWord(string) { + return reHasUnicodeWord.test(string); + } + + /** + * Converts `iterator` to an array. + * + * @private + * @param {Object} iterator The iterator to convert. + * @returns {Array} Returns the converted array. + */ + function iteratorToArray(iterator) { + var data, + result = []; + + while (!(data = iterator.next()).done) { + result.push(data.value); + } + return result; + } + + /** + * Converts `map` to its key-value pairs. + * + * @private + * @param {Object} map The map to convert. + * @returns {Array} Returns the key-value pairs. + */ + function mapToArray(map) { + var index = -1, + result = Array(map.size); + + map.forEach(function(value, key) { + result[++index] = [key, value]; + }); + return result; + } + + /** + * Creates a unary function that invokes `func` with its argument transformed. + * + * @private + * @param {Function} func The function to wrap. + * @param {Function} transform The argument transform. + * @returns {Function} Returns the new function. + */ + function overArg(func, transform) { + return function(arg) { + return func(transform(arg)); + }; + } + + /** + * Replaces all `placeholder` elements in `array` with an internal placeholder + * and returns an array of their indexes. + * + * @private + * @param {Array} array The array to modify. + * @param {*} placeholder The placeholder to replace. + * @returns {Array} Returns the new array of placeholder indexes. + */ + function replaceHolders(array, placeholder) { + var index = -1, + length = array.length, + resIndex = 0, + result = []; + + while (++index < length) { + var value = array[index]; + if (value === placeholder || value === PLACEHOLDER) { + array[index] = PLACEHOLDER; + result[resIndex++] = index; + } + } + return result; + } + + /** + * Converts `set` to an array of its values. + * + * @private + * @param {Object} set The set to convert. + * @returns {Array} Returns the values. + */ + function setToArray(set) { + var index = -1, + result = Array(set.size); + + set.forEach(function(value) { + result[++index] = value; + }); + return result; + } + + /** + * Converts `set` to its value-value pairs. + * + * @private + * @param {Object} set The set to convert. + * @returns {Array} Returns the value-value pairs. + */ + function setToPairs(set) { + var index = -1, + result = Array(set.size); + + set.forEach(function(value) { + result[++index] = [value, value]; + }); + return result; + } + + /** + * A specialized version of `_.indexOf` which performs strict equality + * comparisons of values, i.e. `===`. + * + * @private + * @param {Array} array The array to inspect. + * @param {*} value The value to search for. + * @param {number} fromIndex The index to search from. + * @returns {number} Returns the index of the matched value, else `-1`. + */ + function strictIndexOf(array, value, fromIndex) { + var index = fromIndex - 1, + length = array.length; + + while (++index < length) { + if (array[index] === value) { + return index; + } + } + return -1; + } + + /** + * A specialized version of `_.lastIndexOf` which performs strict equality + * comparisons of values, i.e. `===`. + * + * @private + * @param {Array} array The array to inspect. + * @param {*} value The value to search for. + * @param {number} fromIndex The index to search from. + * @returns {number} Returns the index of the matched value, else `-1`. + */ + function strictLastIndexOf(array, value, fromIndex) { + var index = fromIndex + 1; + while (index--) { + if (array[index] === value) { + return index; + } + } + return index; + } + + /** + * Gets the number of symbols in `string`. + * + * @private + * @param {string} string The string to inspect. + * @returns {number} Returns the string size. + */ + function stringSize(string) { + return hasUnicode(string) + ? unicodeSize(string) + : asciiSize(string); + } + + /** + * Converts `string` to an array. + * + * @private + * @param {string} string The string to convert. + * @returns {Array} Returns the converted array. + */ + function stringToArray(string) { + return hasUnicode(string) + ? unicodeToArray(string) + : asciiToArray(string); + } + + /** + * Used by `_.trim` and `_.trimEnd` to get the index of the last non-whitespace + * character of `string`. + * + * @private + * @param {string} string The string to inspect. + * @returns {number} Returns the index of the last non-whitespace character. + */ + function trimmedEndIndex(string) { + var index = string.length; + + while (index-- && reWhitespace.test(string.charAt(index))) {} + return index; + } + + /** + * Used by `_.unescape` to convert HTML entities to characters. + * + * @private + * @param {string} chr The matched character to unescape. + * @returns {string} Returns the unescaped character. + */ + var unescapeHtmlChar = basePropertyOf(htmlUnescapes); + + /** + * Gets the size of a Unicode `string`. + * + * @private + * @param {string} string The string inspect. + * @returns {number} Returns the string size. + */ + function unicodeSize(string) { + var result = reUnicode.lastIndex = 0; + while (reUnicode.test(string)) { + ++result; + } + return result; + } + + /** + * Converts a Unicode `string` to an array. + * + * @private + * @param {string} string The string to convert. + * @returns {Array} Returns the converted array. + */ + function unicodeToArray(string) { + return string.match(reUnicode) || []; + } + + /** + * Splits a Unicode `string` into an array of its words. + * + * @private + * @param {string} The string to inspect. + * @returns {Array} Returns the words of `string`. + */ + function unicodeWords(string) { + return string.match(reUnicodeWord) || []; + } + + /*--------------------------------------------------------------------------*/ + + /** + * Create a new pristine `lodash` function using the `context` object. + * + * @static + * @memberOf _ + * @since 1.1.0 + * @category Util + * @param {Object} [context=root] The context object. + * @returns {Function} Returns a new `lodash` function. + * @example + * + * _.mixin({ 'foo': _.constant('foo') }); + * + * var lodash = _.runInContext(); + * lodash.mixin({ 'bar': lodash.constant('bar') }); + * + * _.isFunction(_.foo); + * // => true + * _.isFunction(_.bar); + * // => false + * + * lodash.isFunction(lodash.foo); + * // => false + * lodash.isFunction(lodash.bar); + * // => true + * + * // Create a suped-up `defer` in Node.js. + * var defer = _.runInContext({ 'setTimeout': setImmediate }).defer; + */ + var runInContext = (function runInContext(context) { + context = context == null ? root : _.defaults(root.Object(), context, _.pick(root, contextProps)); + + /** Built-in constructor references. */ + var Array = context.Array, + Date = context.Date, + Error = context.Error, + Function = context.Function, + Math = context.Math, + Object = context.Object, + RegExp = context.RegExp, + String = context.String, + TypeError = context.TypeError; + + /** Used for built-in method references. */ + var arrayProto = Array.prototype, + funcProto = Function.prototype, + objectProto = Object.prototype; + + /** Used to detect overreaching core-js shims. */ + var coreJsData = context['__core-js_shared__']; + + /** Used to resolve the decompiled source of functions. */ + var funcToString = funcProto.toString; + + /** Used to check objects for own properties. */ + var hasOwnProperty = objectProto.hasOwnProperty; + + /** Used to generate unique IDs. */ + var idCounter = 0; + + /** Used to detect methods masquerading as native. */ + var maskSrcKey = (function() { + var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || ''); + return uid ? ('Symbol(src)_1.' + uid) : ''; + }()); + + /** + * Used to resolve the + * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) + * of values. + */ + var nativeObjectToString = objectProto.toString; + + /** Used to infer the `Object` constructor. */ + var objectCtorString = funcToString.call(Object); + + /** Used to restore the original `_` reference in `_.noConflict`. */ + var oldDash = root._; + + /** Used to detect if a method is native. */ + var reIsNative = RegExp('^' + + funcToString.call(hasOwnProperty).replace(reRegExpChar, '\\$&') + .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$' + ); + + /** Built-in value references. */ + var Buffer = moduleExports ? context.Buffer : undefined, + Symbol = context.Symbol, + Uint8Array = context.Uint8Array, + allocUnsafe = Buffer ? Buffer.allocUnsafe : undefined, + getPrototype = overArg(Object.getPrototypeOf, Object), + objectCreate = Object.create, + propertyIsEnumerable = objectProto.propertyIsEnumerable, + splice = arrayProto.splice, + spreadableSymbol = Symbol ? Symbol.isConcatSpreadable : undefined, + symIterator = Symbol ? Symbol.iterator : undefined, + symToStringTag = Symbol ? Symbol.toStringTag : undefined; + + var defineProperty = (function() { + try { + var func = getNative(Object, 'defineProperty'); + func({}, '', {}); + return func; + } catch (e) {} + }()); + + /** Mocked built-ins. */ + var ctxClearTimeout = context.clearTimeout !== root.clearTimeout && context.clearTimeout, + ctxNow = Date && Date.now !== root.Date.now && Date.now, + ctxSetTimeout = context.setTimeout !== root.setTimeout && context.setTimeout; + + /* Built-in method references for those with the same name as other `lodash` methods. */ + var nativeCeil = Math.ceil, + nativeFloor = Math.floor, + nativeGetSymbols = Object.getOwnPropertySymbols, + nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined, + nativeIsFinite = context.isFinite, + nativeJoin = arrayProto.join, + nativeKeys = overArg(Object.keys, Object), + nativeMax = Math.max, + nativeMin = Math.min, + nativeNow = Date.now, + nativeParseInt = context.parseInt, + nativeRandom = Math.random, + nativeReverse = arrayProto.reverse; + + /* Built-in method references that are verified to be native. */ + var DataView = getNative(context, 'DataView'), + Map = getNative(context, 'Map'), + Promise = getNative(context, 'Promise'), + Set = getNative(context, 'Set'), + WeakMap = getNative(context, 'WeakMap'), + nativeCreate = getNative(Object, 'create'); + + /** Used to store function metadata. */ + var metaMap = WeakMap && new WeakMap; + + /** Used to lookup unminified function names. */ + var realNames = {}; + + /** Used to detect maps, sets, and weakmaps. */ + var dataViewCtorString = toSource(DataView), + mapCtorString = toSource(Map), + promiseCtorString = toSource(Promise), + setCtorString = toSource(Set), + weakMapCtorString = toSource(WeakMap); + + /** Used to convert symbols to primitives and strings. */ + var symbolProto = Symbol ? Symbol.prototype : undefined, + symbolValueOf = symbolProto ? symbolProto.valueOf : undefined, + symbolToString = symbolProto ? symbolProto.toString : undefined; + + /*------------------------------------------------------------------------*/ + + /** + * Creates a `lodash` object which wraps `value` to enable implicit method + * chain sequences. Methods that operate on and return arrays, collections, + * and functions can be chained together. Methods that retrieve a single value + * or may return a primitive value will automatically end the chain sequence + * and return the unwrapped value. Otherwise, the value must be unwrapped + * with `_#value`. + * + * Explicit chain sequences, which must be unwrapped with `_#value`, may be + * enabled using `_.chain`. + * + * The execution of chained methods is lazy, that is, it's deferred until + * `_#value` is implicitly or explicitly called. + * + * Lazy evaluation allows several methods to support shortcut fusion. + * Shortcut fusion is an optimization to merge iteratee calls; this avoids + * the creation of intermediate arrays and can greatly reduce the number of + * iteratee executions. Sections of a chain sequence qualify for shortcut + * fusion if the section is applied to an array and iteratees accept only + * one argument. The heuristic for whether a section qualifies for shortcut + * fusion is subject to change. + * + * Chaining is supported in custom builds as long as the `_#value` method is + * directly or indirectly included in the build. + * + * In addition to lodash methods, wrappers have `Array` and `String` methods. + * + * The wrapper `Array` methods are: + * `concat`, `join`, `pop`, `push`, `shift`, `sort`, `splice`, and `unshift` + * + * The wrapper `String` methods are: + * `replace` and `split` + * + * The wrapper methods that support shortcut fusion are: + * `at`, `compact`, `drop`, `dropRight`, `dropWhile`, `filter`, `find`, + * `findLast`, `head`, `initial`, `last`, `map`, `reject`, `reverse`, `slice`, + * `tail`, `take`, `takeRight`, `takeRightWhile`, `takeWhile`, and `toArray` + * + * The chainable wrapper methods are: + * `after`, `ary`, `assign`, `assignIn`, `assignInWith`, `assignWith`, `at`, + * `before`, `bind`, `bindAll`, `bindKey`, `castArray`, `chain`, `chunk`, + * `commit`, `compact`, `concat`, `conforms`, `constant`, `countBy`, `create`, + * `curry`, `debounce`, `defaults`, `defaultsDeep`, `defer`, `delay`, + * `difference`, `differenceBy`, `differenceWith`, `drop`, `dropRight`, + * `dropRightWhile`, `dropWhile`, `extend`, `extendWith`, `fill`, `filter`, + * `flatMap`, `flatMapDeep`, `flatMapDepth`, `flatten`, `flattenDeep`, + * `flattenDepth`, `flip`, `flow`, `flowRight`, `fromPairs`, `functions`, + * `functionsIn`, `groupBy`, `initial`, `intersection`, `intersectionBy`, + * `intersectionWith`, `invert`, `invertBy`, `invokeMap`, `iteratee`, `keyBy`, + * `keys`, `keysIn`, `map`, `mapKeys`, `mapValues`, `matches`, `matchesProperty`, + * `memoize`, `merge`, `mergeWith`, `method`, `methodOf`, `mixin`, `negate`, + * `nthArg`, `omit`, `omitBy`, `once`, `orderBy`, `over`, `overArgs`, + * `overEvery`, `overSome`, `partial`, `partialRight`, `partition`, `pick`, + * `pickBy`, `plant`, `property`, `propertyOf`, `pull`, `pullAll`, `pullAllBy`, + * `pullAllWith`, `pullAt`, `push`, `range`, `rangeRight`, `rearg`, `reject`, + * `remove`, `rest`, `reverse`, `sampleSize`, `set`, `setWith`, `shuffle`, + * `slice`, `sort`, `sortBy`, `splice`, `spread`, `tail`, `take`, `takeRight`, + * `takeRightWhile`, `takeWhile`, `tap`, `throttle`, `thru`, `toArray`, + * `toPairs`, `toPairsIn`, `toPath`, `toPlainObject`, `transform`, `unary`, + * `union`, `unionBy`, `unionWith`, `uniq`, `uniqBy`, `uniqWith`, `unset`, + * `unshift`, `unzip`, `unzipWith`, `update`, `updateWith`, `values`, + * `valuesIn`, `without`, `wrap`, `xor`, `xorBy`, `xorWith`, `zip`, + * `zipObject`, `zipObjectDeep`, and `zipWith` + * + * The wrapper methods that are **not** chainable by default are: + * `add`, `attempt`, `camelCase`, `capitalize`, `ceil`, `clamp`, `clone`, + * `cloneDeep`, `cloneDeepWith`, `cloneWith`, `conformsTo`, `deburr`, + * `defaultTo`, `divide`, `each`, `eachRight`, `endsWith`, `eq`, `escape`, + * `escapeRegExp`, `every`, `find`, `findIndex`, `findKey`, `findLast`, + * `findLastIndex`, `findLastKey`, `first`, `floor`, `forEach`, `forEachRight`, + * `forIn`, `forInRight`, `forOwn`, `forOwnRight`, `get`, `gt`, `gte`, `has`, + * `hasIn`, `head`, `identity`, `includes`, `indexOf`, `inRange`, `invoke`, + * `isArguments`, `isArray`, `isArrayBuffer`, `isArrayLike`, `isArrayLikeObject`, + * `isBoolean`, `isBuffer`, `isDate`, `isElement`, `isEmpty`, `isEqual`, + * `isEqualWith`, `isError`, `isFinite`, `isFunction`, `isInteger`, `isLength`, + * `isMap`, `isMatch`, `isMatchWith`, `isNaN`, `isNative`, `isNil`, `isNull`, + * `isNumber`, `isObject`, `isObjectLike`, `isPlainObject`, `isRegExp`, + * `isSafeInteger`, `isSet`, `isString`, `isUndefined`, `isTypedArray`, + * `isWeakMap`, `isWeakSet`, `join`, `kebabCase`, `last`, `lastIndexOf`, + * `lowerCase`, `lowerFirst`, `lt`, `lte`, `max`, `maxBy`, `mean`, `meanBy`, + * `min`, `minBy`, `multiply`, `noConflict`, `noop`, `now`, `nth`, `pad`, + * `padEnd`, `padStart`, `parseInt`, `pop`, `random`, `reduce`, `reduceRight`, + * `repeat`, `result`, `round`, `runInContext`, `sample`, `shift`, `size`, + * `snakeCase`, `some`, `sortedIndex`, `sortedIndexBy`, `sortedLastIndex`, + * `sortedLastIndexBy`, `startCase`, `startsWith`, `stubArray`, `stubFalse`, + * `stubObject`, `stubString`, `stubTrue`, `subtract`, `sum`, `sumBy`, + * `template`, `times`, `toFinite`, `toInteger`, `toJSON`, `toLength`, + * `toLower`, `toNumber`, `toSafeInteger`, `toString`, `toUpper`, `trim`, + * `trimEnd`, `trimStart`, `truncate`, `unescape`, `uniqueId`, `upperCase`, + * `upperFirst`, `value`, and `words` + * + * @name _ + * @constructor + * @category Seq + * @param {*} value The value to wrap in a `lodash` instance. + * @returns {Object} Returns the new `lodash` wrapper instance. + * @example + * + * function square(n) { + * return n * n; + * } + * + * var wrapped = _([1, 2, 3]); + * + * // Returns an unwrapped value. + * wrapped.reduce(_.add); + * // => 6 + * + * // Returns a wrapped value. + * var squares = wrapped.map(square); + * + * _.isArray(squares); + * // => false + * + * _.isArray(squares.value()); + * // => true + */ + function lodash(value) { + if (isObjectLike(value) && !isArray(value) && !(value instanceof LazyWrapper)) { + if (value instanceof LodashWrapper) { + return value; + } + if (hasOwnProperty.call(value, '__wrapped__')) { + return wrapperClone(value); + } + } + return new LodashWrapper(value); + } + + /** + * The base implementation of `_.create` without support for assigning + * properties to the created object. + * + * @private + * @param {Object} proto The object to inherit from. + * @returns {Object} Returns the new object. + */ + var baseCreate = (function() { + function object() {} + return function(proto) { + if (!isObject(proto)) { + return {}; + } + if (objectCreate) { + return objectCreate(proto); + } + object.prototype = proto; + var result = new object; + object.prototype = undefined; + return result; + }; + }()); + + /** + * The function whose prototype chain sequence wrappers inherit from. + * + * @private + */ + function baseLodash() { + // No operation performed. + } + + /** + * The base constructor for creating `lodash` wrapper objects. + * + * @private + * @param {*} value The value to wrap. + * @param {boolean} [chainAll] Enable explicit method chain sequences. + */ + function LodashWrapper(value, chainAll) { + this.__wrapped__ = value; + this.__actions__ = []; + this.__chain__ = !!chainAll; + this.__index__ = 0; + this.__values__ = undefined; + } + + /** + * By default, the template delimiters used by lodash are like those in + * embedded Ruby (ERB) as well as ES2015 template strings. Change the + * following template settings to use alternative delimiters. + * + * @static + * @memberOf _ + * @type {Object} + */ + lodash.templateSettings = { + + /** + * Used to detect `data` property values to be HTML-escaped. + * + * @memberOf _.templateSettings + * @type {RegExp} + */ + 'escape': reEscape, + + /** + * Used to detect code to be evaluated. + * + * @memberOf _.templateSettings + * @type {RegExp} + */ + 'evaluate': reEvaluate, + + /** + * Used to detect `data` property values to inject. + * + * @memberOf _.templateSettings + * @type {RegExp} + */ + 'interpolate': reInterpolate, + + /** + * Used to reference the data object in the template text. + * + * @memberOf _.templateSettings + * @type {string} + */ + 'variable': '', + + /** + * Used to import variables into the compiled template. + * + * @memberOf _.templateSettings + * @type {Object} + */ + 'imports': { + + /** + * A reference to the `lodash` function. + * + * @memberOf _.templateSettings.imports + * @type {Function} + */ + '_': lodash + } + }; + + // Ensure wrappers are instances of `baseLodash`. + lodash.prototype = baseLodash.prototype; + lodash.prototype.constructor = lodash; + + LodashWrapper.prototype = baseCreate(baseLodash.prototype); + LodashWrapper.prototype.constructor = LodashWrapper; + + /*------------------------------------------------------------------------*/ + + /** + * Creates a lazy wrapper object which wraps `value` to enable lazy evaluation. + * + * @private + * @constructor + * @param {*} value The value to wrap. + */ + function LazyWrapper(value) { + this.__wrapped__ = value; + this.__actions__ = []; + this.__dir__ = 1; + this.__filtered__ = false; + this.__iteratees__ = []; + this.__takeCount__ = MAX_ARRAY_LENGTH; + this.__views__ = []; + } + + /** + * Creates a clone of the lazy wrapper object. + * + * @private + * @name clone + * @memberOf LazyWrapper + * @returns {Object} Returns the cloned `LazyWrapper` object. + */ + function lazyClone() { + var result = new LazyWrapper(this.__wrapped__); + result.__actions__ = copyArray(this.__actions__); + result.__dir__ = this.__dir__; + result.__filtered__ = this.__filtered__; + result.__iteratees__ = copyArray(this.__iteratees__); + result.__takeCount__ = this.__takeCount__; + result.__views__ = copyArray(this.__views__); + return result; + } + + /** + * Reverses the direction of lazy iteration. + * + * @private + * @name reverse + * @memberOf LazyWrapper + * @returns {Object} Returns the new reversed `LazyWrapper` object. + */ + function lazyReverse() { + if (this.__filtered__) { + var result = new LazyWrapper(this); + result.__dir__ = -1; + result.__filtered__ = true; + } else { + result = this.clone(); + result.__dir__ *= -1; + } + return result; + } + + /** + * Extracts the unwrapped value from its lazy wrapper. + * + * @private + * @name value + * @memberOf LazyWrapper + * @returns {*} Returns the unwrapped value. + */ + function lazyValue() { + var array = this.__wrapped__.value(), + dir = this.__dir__, + isArr = isArray(array), + isRight = dir < 0, + arrLength = isArr ? array.length : 0, + view = getView(0, arrLength, this.__views__), + start = view.start, + end = view.end, + length = end - start, + index = isRight ? end : (start - 1), + iteratees = this.__iteratees__, + iterLength = iteratees.length, + resIndex = 0, + takeCount = nativeMin(length, this.__takeCount__); + + if (!isArr || (!isRight && arrLength == length && takeCount == length)) { + return baseWrapperValue(array, this.__actions__); + } + var result = []; + + outer: + while (length-- && resIndex < takeCount) { + index += dir; + + var iterIndex = -1, + value = array[index]; + + while (++iterIndex < iterLength) { + var data = iteratees[iterIndex], + iteratee = data.iteratee, + type = data.type, + computed = iteratee(value); + + if (type == LAZY_MAP_FLAG) { + value = computed; + } else if (!computed) { + if (type == LAZY_FILTER_FLAG) { + continue outer; + } else { + break outer; + } + } + } + result[resIndex++] = value; + } + return result; + } + + // Ensure `LazyWrapper` is an instance of `baseLodash`. + LazyWrapper.prototype = baseCreate(baseLodash.prototype); + LazyWrapper.prototype.constructor = LazyWrapper; + + /*------------------------------------------------------------------------*/ + + /** + * Creates a hash object. + * + * @private + * @constructor + * @param {Array} [entries] The key-value pairs to cache. + */ + function Hash(entries) { + var index = -1, + length = entries == null ? 0 : entries.length; + + this.clear(); + while (++index < length) { + var entry = entries[index]; + this.set(entry[0], entry[1]); + } + } + + /** + * Removes all key-value entries from the hash. + * + * @private + * @name clear + * @memberOf Hash + */ + function hashClear() { + this.__data__ = nativeCreate ? nativeCreate(null) : {}; + this.size = 0; + } + + /** + * Removes `key` and its value from the hash. + * + * @private + * @name delete + * @memberOf Hash + * @param {Object} hash The hash to modify. + * @param {string} key The key of the value to remove. + * @returns {boolean} Returns `true` if the entry was removed, else `false`. + */ + function hashDelete(key) { + var result = this.has(key) && delete this.__data__[key]; + this.size -= result ? 1 : 0; + return result; + } + + /** + * Gets the hash value for `key`. + * + * @private + * @name get + * @memberOf Hash + * @param {string} key The key of the value to get. + * @returns {*} Returns the entry value. + */ + function hashGet(key) { + var data = this.__data__; + if (nativeCreate) { + var result = data[key]; + return result === HASH_UNDEFINED ? undefined : result; + } + return hasOwnProperty.call(data, key) ? data[key] : undefined; + } + + /** + * Checks if a hash value for `key` exists. + * + * @private + * @name has + * @memberOf Hash + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. + */ + function hashHas(key) { + var data = this.__data__; + return nativeCreate ? (data[key] !== undefined) : hasOwnProperty.call(data, key); + } + + /** + * Sets the hash `key` to `value`. + * + * @private + * @name set + * @memberOf Hash + * @param {string} key The key of the value to set. + * @param {*} value The value to set. + * @returns {Object} Returns the hash instance. + */ + function hashSet(key, value) { + var data = this.__data__; + this.size += this.has(key) ? 0 : 1; + data[key] = (nativeCreate && value === undefined) ? HASH_UNDEFINED : value; + return this; + } + + // Add methods to `Hash`. + Hash.prototype.clear = hashClear; + Hash.prototype['delete'] = hashDelete; + Hash.prototype.get = hashGet; + Hash.prototype.has = hashHas; + Hash.prototype.set = hashSet; + + /*------------------------------------------------------------------------*/ + + /** + * Creates an list cache object. + * + * @private + * @constructor + * @param {Array} [entries] The key-value pairs to cache. + */ + function ListCache(entries) { + var index = -1, + length = entries == null ? 0 : entries.length; + + this.clear(); + while (++index < length) { + var entry = entries[index]; + this.set(entry[0], entry[1]); + } + } + + /** + * Removes all key-value entries from the list cache. + * + * @private + * @name clear + * @memberOf ListCache + */ + function listCacheClear() { + this.__data__ = []; + this.size = 0; + } + + /** + * Removes `key` and its value from the list cache. + * + * @private + * @name delete + * @memberOf ListCache + * @param {string} key The key of the value to remove. + * @returns {boolean} Returns `true` if the entry was removed, else `false`. + */ + function listCacheDelete(key) { + var data = this.__data__, + index = assocIndexOf(data, key); + + if (index < 0) { + return false; + } + var lastIndex = data.length - 1; + if (index == lastIndex) { + data.pop(); + } else { + splice.call(data, index, 1); + } + --this.size; + return true; + } + + /** + * Gets the list cache value for `key`. + * + * @private + * @name get + * @memberOf ListCache + * @param {string} key The key of the value to get. + * @returns {*} Returns the entry value. + */ + function listCacheGet(key) { + var data = this.__data__, + index = assocIndexOf(data, key); + + return index < 0 ? undefined : data[index][1]; + } + + /** + * Checks if a list cache value for `key` exists. + * + * @private + * @name has + * @memberOf ListCache + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. + */ + function listCacheHas(key) { + return assocIndexOf(this.__data__, key) > -1; + } + + /** + * Sets the list cache `key` to `value`. + * + * @private + * @name set + * @memberOf ListCache + * @param {string} key The key of the value to set. + * @param {*} value The value to set. + * @returns {Object} Returns the list cache instance. + */ + function listCacheSet(key, value) { + var data = this.__data__, + index = assocIndexOf(data, key); + + if (index < 0) { + ++this.size; + data.push([key, value]); + } else { + data[index][1] = value; + } + return this; + } + + // Add methods to `ListCache`. + ListCache.prototype.clear = listCacheClear; + ListCache.prototype['delete'] = listCacheDelete; + ListCache.prototype.get = listCacheGet; + ListCache.prototype.has = listCacheHas; + ListCache.prototype.set = listCacheSet; + + /*------------------------------------------------------------------------*/ + + /** + * Creates a map cache object to store key-value pairs. + * + * @private + * @constructor + * @param {Array} [entries] The key-value pairs to cache. + */ + function MapCache(entries) { + var index = -1, + length = entries == null ? 0 : entries.length; + + this.clear(); + while (++index < length) { + var entry = entries[index]; + this.set(entry[0], entry[1]); + } + } + + /** + * Removes all key-value entries from the map. + * + * @private + * @name clear + * @memberOf MapCache + */ + function mapCacheClear() { + this.size = 0; + this.__data__ = { + 'hash': new Hash, + 'map': new (Map || ListCache), + 'string': new Hash + }; + } + + /** + * Removes `key` and its value from the map. + * + * @private + * @name delete + * @memberOf MapCache + * @param {string} key The key of the value to remove. + * @returns {boolean} Returns `true` if the entry was removed, else `false`. + */ + function mapCacheDelete(key) { + var result = getMapData(this, key)['delete'](key); + this.size -= result ? 1 : 0; + return result; + } + + /** + * Gets the map value for `key`. + * + * @private + * @name get + * @memberOf MapCache + * @param {string} key The key of the value to get. + * @returns {*} Returns the entry value. + */ + function mapCacheGet(key) { + return getMapData(this, key).get(key); + } + + /** + * Checks if a map value for `key` exists. + * + * @private + * @name has + * @memberOf MapCache + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. + */ + function mapCacheHas(key) { + return getMapData(this, key).has(key); + } + + /** + * Sets the map `key` to `value`. + * + * @private + * @name set + * @memberOf MapCache + * @param {string} key The key of the value to set. + * @param {*} value The value to set. + * @returns {Object} Returns the map cache instance. + */ + function mapCacheSet(key, value) { + var data = getMapData(this, key), + size = data.size; + + data.set(key, value); + this.size += data.size == size ? 0 : 1; + return this; + } + + // Add methods to `MapCache`. + MapCache.prototype.clear = mapCacheClear; + MapCache.prototype['delete'] = mapCacheDelete; + MapCache.prototype.get = mapCacheGet; + MapCache.prototype.has = mapCacheHas; + MapCache.prototype.set = mapCacheSet; + + /*------------------------------------------------------------------------*/ + + /** + * + * Creates an array cache object to store unique values. + * + * @private + * @constructor + * @param {Array} [values] The values to cache. + */ + function SetCache(values) { + var index = -1, + length = values == null ? 0 : values.length; + + this.__data__ = new MapCache; + while (++index < length) { + this.add(values[index]); + } + } + + /** + * Adds `value` to the array cache. + * + * @private + * @name add + * @memberOf SetCache + * @alias push + * @param {*} value The value to cache. + * @returns {Object} Returns the cache instance. + */ + function setCacheAdd(value) { + this.__data__.set(value, HASH_UNDEFINED); + return this; + } + + /** + * Checks if `value` is in the array cache. + * + * @private + * @name has + * @memberOf SetCache + * @param {*} value The value to search for. + * @returns {number} Returns `true` if `value` is found, else `false`. + */ + function setCacheHas(value) { + return this.__data__.has(value); + } + + // Add methods to `SetCache`. + SetCache.prototype.add = SetCache.prototype.push = setCacheAdd; + SetCache.prototype.has = setCacheHas; + + /*------------------------------------------------------------------------*/ + + /** + * Creates a stack cache object to store key-value pairs. + * + * @private + * @constructor + * @param {Array} [entries] The key-value pairs to cache. + */ + function Stack(entries) { + var data = this.__data__ = new ListCache(entries); + this.size = data.size; + } + + /** + * Removes all key-value entries from the stack. + * + * @private + * @name clear + * @memberOf Stack + */ + function stackClear() { + this.__data__ = new ListCache; + this.size = 0; + } + + /** + * Removes `key` and its value from the stack. + * + * @private + * @name delete + * @memberOf Stack + * @param {string} key The key of the value to remove. + * @returns {boolean} Returns `true` if the entry was removed, else `false`. + */ + function stackDelete(key) { + var data = this.__data__, + result = data['delete'](key); + + this.size = data.size; + return result; + } + + /** + * Gets the stack value for `key`. + * + * @private + * @name get + * @memberOf Stack + * @param {string} key The key of the value to get. + * @returns {*} Returns the entry value. + */ + function stackGet(key) { + return this.__data__.get(key); + } + + /** + * Checks if a stack value for `key` exists. + * + * @private + * @name has + * @memberOf Stack + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. + */ + function stackHas(key) { + return this.__data__.has(key); + } + + /** + * Sets the stack `key` to `value`. + * + * @private + * @name set + * @memberOf Stack + * @param {string} key The key of the value to set. + * @param {*} value The value to set. + * @returns {Object} Returns the stack cache instance. + */ + function stackSet(key, value) { + var data = this.__data__; + if (data instanceof ListCache) { + var pairs = data.__data__; + if (!Map || (pairs.length < LARGE_ARRAY_SIZE - 1)) { + pairs.push([key, value]); + this.size = ++data.size; + return this; + } + data = this.__data__ = new MapCache(pairs); + } + data.set(key, value); + this.size = data.size; + return this; + } + + // Add methods to `Stack`. + Stack.prototype.clear = stackClear; + Stack.prototype['delete'] = stackDelete; + Stack.prototype.get = stackGet; + Stack.prototype.has = stackHas; + Stack.prototype.set = stackSet; + + /*------------------------------------------------------------------------*/ + + /** + * Creates an array of the enumerable property names of the array-like `value`. + * + * @private + * @param {*} value The value to query. + * @param {boolean} inherited Specify returning inherited property names. + * @returns {Array} Returns the array of property names. + */ + function arrayLikeKeys(value, inherited) { + var isArr = isArray(value), + isArg = !isArr && isArguments(value), + isBuff = !isArr && !isArg && isBuffer(value), + isType = !isArr && !isArg && !isBuff && isTypedArray(value), + skipIndexes = isArr || isArg || isBuff || isType, + result = skipIndexes ? baseTimes(value.length, String) : [], + length = result.length; + + for (var key in value) { + if ((inherited || hasOwnProperty.call(value, key)) && + !(skipIndexes && ( + // Safari 9 has enumerable `arguments.length` in strict mode. + key == 'length' || + // Node.js 0.10 has enumerable non-index properties on buffers. + (isBuff && (key == 'offset' || key == 'parent')) || + // PhantomJS 2 has enumerable non-index properties on typed arrays. + (isType && (key == 'buffer' || key == 'byteLength' || key == 'byteOffset')) || + // Skip index properties. + isIndex(key, length) + ))) { + result.push(key); + } + } + return result; + } + + /** + * A specialized version of `_.sample` for arrays. + * + * @private + * @param {Array} array The array to sample. + * @returns {*} Returns the random element. + */ + function arraySample(array) { + var length = array.length; + return length ? array[baseRandom(0, length - 1)] : undefined; + } + + /** + * A specialized version of `_.sampleSize` for arrays. + * + * @private + * @param {Array} array The array to sample. + * @param {number} n The number of elements to sample. + * @returns {Array} Returns the random elements. + */ + function arraySampleSize(array, n) { + return shuffleSelf(copyArray(array), baseClamp(n, 0, array.length)); + } + + /** + * A specialized version of `_.shuffle` for arrays. + * + * @private + * @param {Array} array The array to shuffle. + * @returns {Array} Returns the new shuffled array. + */ + function arrayShuffle(array) { + return shuffleSelf(copyArray(array)); + } + + /** + * This function is like `assignValue` except that it doesn't assign + * `undefined` values. + * + * @private + * @param {Object} object The object to modify. + * @param {string} key The key of the property to assign. + * @param {*} value The value to assign. + */ + function assignMergeValue(object, key, value) { + if ((value !== undefined && !eq(object[key], value)) || + (value === undefined && !(key in object))) { + baseAssignValue(object, key, value); + } + } + + /** + * Assigns `value` to `key` of `object` if the existing value is not equivalent + * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * for equality comparisons. + * + * @private + * @param {Object} object The object to modify. + * @param {string} key The key of the property to assign. + * @param {*} value The value to assign. + */ + function assignValue(object, key, value) { + var objValue = object[key]; + if (!(hasOwnProperty.call(object, key) && eq(objValue, value)) || + (value === undefined && !(key in object))) { + baseAssignValue(object, key, value); + } + } + + /** + * Gets the index at which the `key` is found in `array` of key-value pairs. + * + * @private + * @param {Array} array The array to inspect. + * @param {*} key The key to search for. + * @returns {number} Returns the index of the matched value, else `-1`. + */ + function assocIndexOf(array, key) { + var length = array.length; + while (length--) { + if (eq(array[length][0], key)) { + return length; + } + } + return -1; + } + + /** + * Aggregates elements of `collection` on `accumulator` with keys transformed + * by `iteratee` and values set by `setter`. + * + * @private + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} setter The function to set `accumulator` values. + * @param {Function} iteratee The iteratee to transform keys. + * @param {Object} accumulator The initial aggregated object. + * @returns {Function} Returns `accumulator`. + */ + function baseAggregator(collection, setter, iteratee, accumulator) { + baseEach(collection, function(value, key, collection) { + setter(accumulator, value, iteratee(value), collection); + }); + return accumulator; + } + + /** + * The base implementation of `_.assign` without support for multiple sources + * or `customizer` functions. + * + * @private + * @param {Object} object The destination object. + * @param {Object} source The source object. + * @returns {Object} Returns `object`. + */ + function baseAssign(object, source) { + return object && copyObject(source, keys(source), object); + } + + /** + * The base implementation of `_.assignIn` without support for multiple sources + * or `customizer` functions. + * + * @private + * @param {Object} object The destination object. + * @param {Object} source The source object. + * @returns {Object} Returns `object`. + */ + function baseAssignIn(object, source) { + return object && copyObject(source, keysIn(source), object); + } + + /** + * The base implementation of `assignValue` and `assignMergeValue` without + * value checks. + * + * @private + * @param {Object} object The object to modify. + * @param {string} key The key of the property to assign. + * @param {*} value The value to assign. + */ + function baseAssignValue(object, key, value) { + if (key == '__proto__' && defineProperty) { + defineProperty(object, key, { + 'configurable': true, + 'enumerable': true, + 'value': value, + 'writable': true + }); + } else { + object[key] = value; + } + } + + /** + * The base implementation of `_.at` without support for individual paths. + * + * @private + * @param {Object} object The object to iterate over. + * @param {string[]} paths The property paths to pick. + * @returns {Array} Returns the picked elements. + */ + function baseAt(object, paths) { + var index = -1, + length = paths.length, + result = Array(length), + skip = object == null; + + while (++index < length) { + result[index] = skip ? undefined : get(object, paths[index]); + } + return result; + } + + /** + * The base implementation of `_.clamp` which doesn't coerce arguments. + * + * @private + * @param {number} number The number to clamp. + * @param {number} [lower] The lower bound. + * @param {number} upper The upper bound. + * @returns {number} Returns the clamped number. + */ + function baseClamp(number, lower, upper) { + if (number === number) { + if (upper !== undefined) { + number = number <= upper ? number : upper; + } + if (lower !== undefined) { + number = number >= lower ? number : lower; + } + } + return number; + } + + /** + * The base implementation of `_.clone` and `_.cloneDeep` which tracks + * traversed objects. + * + * @private + * @param {*} value The value to clone. + * @param {boolean} bitmask The bitmask flags. + * 1 - Deep clone + * 2 - Flatten inherited properties + * 4 - Clone symbols + * @param {Function} [customizer] The function to customize cloning. + * @param {string} [key] The key of `value`. + * @param {Object} [object] The parent object of `value`. + * @param {Object} [stack] Tracks traversed objects and their clone counterparts. + * @returns {*} Returns the cloned value. + */ + function baseClone(value, bitmask, customizer, key, object, stack) { + var result, + isDeep = bitmask & CLONE_DEEP_FLAG, + isFlat = bitmask & CLONE_FLAT_FLAG, + isFull = bitmask & CLONE_SYMBOLS_FLAG; + + if (customizer) { + result = object ? customizer(value, key, object, stack) : customizer(value); + } + if (result !== undefined) { + return result; + } + if (!isObject(value)) { + return value; + } + var isArr = isArray(value); + if (isArr) { + result = initCloneArray(value); + if (!isDeep) { + return copyArray(value, result); + } + } else { + var tag = getTag(value), + isFunc = tag == funcTag || tag == genTag; + + if (isBuffer(value)) { + return cloneBuffer(value, isDeep); + } + if (tag == objectTag || tag == argsTag || (isFunc && !object)) { + result = (isFlat || isFunc) ? {} : initCloneObject(value); + if (!isDeep) { + return isFlat + ? copySymbolsIn(value, baseAssignIn(result, value)) + : copySymbols(value, baseAssign(result, value)); + } + } else { + if (!cloneableTags[tag]) { + return object ? value : {}; + } + result = initCloneByTag(value, tag, isDeep); + } + } + // Check for circular references and return its corresponding clone. + stack || (stack = new Stack); + var stacked = stack.get(value); + if (stacked) { + return stacked; + } + stack.set(value, result); + + if (isSet(value)) { + value.forEach(function(subValue) { + result.add(baseClone(subValue, bitmask, customizer, subValue, value, stack)); + }); + } else if (isMap(value)) { + value.forEach(function(subValue, key) { + result.set(key, baseClone(subValue, bitmask, customizer, key, value, stack)); + }); + } + + var keysFunc = isFull + ? (isFlat ? getAllKeysIn : getAllKeys) + : (isFlat ? keysIn : keys); + + var props = isArr ? undefined : keysFunc(value); + arrayEach(props || value, function(subValue, key) { + if (props) { + key = subValue; + subValue = value[key]; + } + // Recursively populate clone (susceptible to call stack limits). + assignValue(result, key, baseClone(subValue, bitmask, customizer, key, value, stack)); + }); + return result; + } + + /** + * The base implementation of `_.conforms` which doesn't clone `source`. + * + * @private + * @param {Object} source The object of property predicates to conform to. + * @returns {Function} Returns the new spec function. + */ + function baseConforms(source) { + var props = keys(source); + return function(object) { + return baseConformsTo(object, source, props); + }; + } + + /** + * The base implementation of `_.conformsTo` which accepts `props` to check. + * + * @private + * @param {Object} object The object to inspect. + * @param {Object} source The object of property predicates to conform to. + * @returns {boolean} Returns `true` if `object` conforms, else `false`. + */ + function baseConformsTo(object, source, props) { + var length = props.length; + if (object == null) { + return !length; + } + object = Object(object); + while (length--) { + var key = props[length], + predicate = source[key], + value = object[key]; + + if ((value === undefined && !(key in object)) || !predicate(value)) { + return false; + } + } + return true; + } + + /** + * The base implementation of `_.delay` and `_.defer` which accepts `args` + * to provide to `func`. + * + * @private + * @param {Function} func The function to delay. + * @param {number} wait The number of milliseconds to delay invocation. + * @param {Array} args The arguments to provide to `func`. + * @returns {number|Object} Returns the timer id or timeout object. + */ + function baseDelay(func, wait, args) { + if (typeof func != 'function') { + throw new TypeError(FUNC_ERROR_TEXT); + } + return setTimeout(function() { func.apply(undefined, args); }, wait); + } + + /** + * The base implementation of methods like `_.difference` without support + * for excluding multiple arrays or iteratee shorthands. + * + * @private + * @param {Array} array The array to inspect. + * @param {Array} values The values to exclude. + * @param {Function} [iteratee] The iteratee invoked per element. + * @param {Function} [comparator] The comparator invoked per element. + * @returns {Array} Returns the new array of filtered values. + */ + function baseDifference(array, values, iteratee, comparator) { + var index = -1, + includes = arrayIncludes, + isCommon = true, + length = array.length, + result = [], + valuesLength = values.length; + + if (!length) { + return result; + } + if (iteratee) { + values = arrayMap(values, baseUnary(iteratee)); + } + if (comparator) { + includes = arrayIncludesWith; + isCommon = false; + } + else if (values.length >= LARGE_ARRAY_SIZE) { + includes = cacheHas; + isCommon = false; + values = new SetCache(values); + } + outer: + while (++index < length) { + var value = array[index], + computed = iteratee == null ? value : iteratee(value); + + value = (comparator || value !== 0) ? value : 0; + if (isCommon && computed === computed) { + var valuesIndex = valuesLength; + while (valuesIndex--) { + if (values[valuesIndex] === computed) { + continue outer; + } + } + result.push(value); + } + else if (!includes(values, computed, comparator)) { + result.push(value); + } + } + return result; + } + + /** + * The base implementation of `_.forEach` without support for iteratee shorthands. + * + * @private + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array|Object} Returns `collection`. + */ + var baseEach = createBaseEach(baseForOwn); + + /** + * The base implementation of `_.forEachRight` without support for iteratee shorthands. + * + * @private + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array|Object} Returns `collection`. + */ + var baseEachRight = createBaseEach(baseForOwnRight, true); + + /** + * The base implementation of `_.every` without support for iteratee shorthands. + * + * @private + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} predicate The function invoked per iteration. + * @returns {boolean} Returns `true` if all elements pass the predicate check, + * else `false` + */ + function baseEvery(collection, predicate) { + var result = true; + baseEach(collection, function(value, index, collection) { + result = !!predicate(value, index, collection); + return result; + }); + return result; + } + + /** + * The base implementation of methods like `_.max` and `_.min` which accepts a + * `comparator` to determine the extremum value. + * + * @private + * @param {Array} array The array to iterate over. + * @param {Function} iteratee The iteratee invoked per iteration. + * @param {Function} comparator The comparator used to compare values. + * @returns {*} Returns the extremum value. + */ + function baseExtremum(array, iteratee, comparator) { + var index = -1, + length = array.length; + + while (++index < length) { + var value = array[index], + current = iteratee(value); + + if (current != null && (computed === undefined + ? (current === current && !isSymbol(current)) + : comparator(current, computed) + )) { + var computed = current, + result = value; + } + } + return result; + } + + /** + * The base implementation of `_.fill` without an iteratee call guard. + * + * @private + * @param {Array} array The array to fill. + * @param {*} value The value to fill `array` with. + * @param {number} [start=0] The start position. + * @param {number} [end=array.length] The end position. + * @returns {Array} Returns `array`. + */ + function baseFill(array, value, start, end) { + var length = array.length; + + start = toInteger(start); + if (start < 0) { + start = -start > length ? 0 : (length + start); + } + end = (end === undefined || end > length) ? length : toInteger(end); + if (end < 0) { + end += length; + } + end = start > end ? 0 : toLength(end); + while (start < end) { + array[start++] = value; + } + return array; + } + + /** + * The base implementation of `_.filter` without support for iteratee shorthands. + * + * @private + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} predicate The function invoked per iteration. + * @returns {Array} Returns the new filtered array. + */ + function baseFilter(collection, predicate) { + var result = []; + baseEach(collection, function(value, index, collection) { + if (predicate(value, index, collection)) { + result.push(value); + } + }); + return result; + } + + /** + * The base implementation of `_.flatten` with support for restricting flattening. + * + * @private + * @param {Array} array The array to flatten. + * @param {number} depth The maximum recursion depth. + * @param {boolean} [predicate=isFlattenable] The function invoked per iteration. + * @param {boolean} [isStrict] Restrict to values that pass `predicate` checks. + * @param {Array} [result=[]] The initial result value. + * @returns {Array} Returns the new flattened array. + */ + function baseFlatten(array, depth, predicate, isStrict, result) { + var index = -1, + length = array.length; + + predicate || (predicate = isFlattenable); + result || (result = []); + + while (++index < length) { + var value = array[index]; + if (depth > 0 && predicate(value)) { + if (depth > 1) { + // Recursively flatten arrays (susceptible to call stack limits). + baseFlatten(value, depth - 1, predicate, isStrict, result); + } else { + arrayPush(result, value); + } + } else if (!isStrict) { + result[result.length] = value; + } + } + return result; + } + + /** + * The base implementation of `baseForOwn` which iterates over `object` + * properties returned by `keysFunc` and invokes `iteratee` for each property. + * Iteratee functions may exit iteration early by explicitly returning `false`. + * + * @private + * @param {Object} object The object to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @param {Function} keysFunc The function to get the keys of `object`. + * @returns {Object} Returns `object`. + */ + var baseFor = createBaseFor(); + + /** + * This function is like `baseFor` except that it iterates over properties + * in the opposite order. + * + * @private + * @param {Object} object The object to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @param {Function} keysFunc The function to get the keys of `object`. + * @returns {Object} Returns `object`. + */ + var baseForRight = createBaseFor(true); + + /** + * The base implementation of `_.forOwn` without support for iteratee shorthands. + * + * @private + * @param {Object} object The object to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Object} Returns `object`. + */ + function baseForOwn(object, iteratee) { + return object && baseFor(object, iteratee, keys); + } + + /** + * The base implementation of `_.forOwnRight` without support for iteratee shorthands. + * + * @private + * @param {Object} object The object to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Object} Returns `object`. + */ + function baseForOwnRight(object, iteratee) { + return object && baseForRight(object, iteratee, keys); + } + + /** + * The base implementation of `_.functions` which creates an array of + * `object` function property names filtered from `props`. + * + * @private + * @param {Object} object The object to inspect. + * @param {Array} props The property names to filter. + * @returns {Array} Returns the function names. + */ + function baseFunctions(object, props) { + return arrayFilter(props, function(key) { + return isFunction(object[key]); + }); + } + + /** + * The base implementation of `_.get` without support for default values. + * + * @private + * @param {Object} object The object to query. + * @param {Array|string} path The path of the property to get. + * @returns {*} Returns the resolved value. + */ + function baseGet(object, path) { + path = castPath(path, object); + + var index = 0, + length = path.length; + + while (object != null && index < length) { + object = object[toKey(path[index++])]; + } + return (index && index == length) ? object : undefined; + } + + /** + * The base implementation of `getAllKeys` and `getAllKeysIn` which uses + * `keysFunc` and `symbolsFunc` to get the enumerable property names and + * symbols of `object`. + * + * @private + * @param {Object} object The object to query. + * @param {Function} keysFunc The function to get the keys of `object`. + * @param {Function} symbolsFunc The function to get the symbols of `object`. + * @returns {Array} Returns the array of property names and symbols. + */ + function baseGetAllKeys(object, keysFunc, symbolsFunc) { + var result = keysFunc(object); + return isArray(object) ? result : arrayPush(result, symbolsFunc(object)); + } + + /** + * The base implementation of `getTag` without fallbacks for buggy environments. + * + * @private + * @param {*} value The value to query. + * @returns {string} Returns the `toStringTag`. + */ + function baseGetTag(value) { + if (value == null) { + return value === undefined ? undefinedTag : nullTag; + } + return (symToStringTag && symToStringTag in Object(value)) + ? getRawTag(value) + : objectToString(value); + } + + /** + * The base implementation of `_.gt` which doesn't coerce arguments. + * + * @private + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {boolean} Returns `true` if `value` is greater than `other`, + * else `false`. + */ + function baseGt(value, other) { + return value > other; + } + + /** + * The base implementation of `_.has` without support for deep paths. + * + * @private + * @param {Object} [object] The object to query. + * @param {Array|string} key The key to check. + * @returns {boolean} Returns `true` if `key` exists, else `false`. + */ + function baseHas(object, key) { + return object != null && hasOwnProperty.call(object, key); + } + + /** + * The base implementation of `_.hasIn` without support for deep paths. + * + * @private + * @param {Object} [object] The object to query. + * @param {Array|string} key The key to check. + * @returns {boolean} Returns `true` if `key` exists, else `false`. + */ + function baseHasIn(object, key) { + return object != null && key in Object(object); + } + + /** + * The base implementation of `_.inRange` which doesn't coerce arguments. + * + * @private + * @param {number} number The number to check. + * @param {number} start The start of the range. + * @param {number} end The end of the range. + * @returns {boolean} Returns `true` if `number` is in the range, else `false`. + */ + function baseInRange(number, start, end) { + return number >= nativeMin(start, end) && number < nativeMax(start, end); + } + + /** + * The base implementation of methods like `_.intersection`, without support + * for iteratee shorthands, that accepts an array of arrays to inspect. + * + * @private + * @param {Array} arrays The arrays to inspect. + * @param {Function} [iteratee] The iteratee invoked per element. + * @param {Function} [comparator] The comparator invoked per element. + * @returns {Array} Returns the new array of shared values. + */ + function baseIntersection(arrays, iteratee, comparator) { + var includes = comparator ? arrayIncludesWith : arrayIncludes, + length = arrays[0].length, + othLength = arrays.length, + othIndex = othLength, + caches = Array(othLength), + maxLength = Infinity, + result = []; + + while (othIndex--) { + var array = arrays[othIndex]; + if (othIndex && iteratee) { + array = arrayMap(array, baseUnary(iteratee)); + } + maxLength = nativeMin(array.length, maxLength); + caches[othIndex] = !comparator && (iteratee || (length >= 120 && array.length >= 120)) + ? new SetCache(othIndex && array) + : undefined; + } + array = arrays[0]; + + var index = -1, + seen = caches[0]; + + outer: + while (++index < length && result.length < maxLength) { + var value = array[index], + computed = iteratee ? iteratee(value) : value; + + value = (comparator || value !== 0) ? value : 0; + if (!(seen + ? cacheHas(seen, computed) + : includes(result, computed, comparator) + )) { + othIndex = othLength; + while (--othIndex) { + var cache = caches[othIndex]; + if (!(cache + ? cacheHas(cache, computed) + : includes(arrays[othIndex], computed, comparator)) + ) { + continue outer; + } + } + if (seen) { + seen.push(computed); + } + result.push(value); + } + } + return result; + } + + /** + * The base implementation of `_.invert` and `_.invertBy` which inverts + * `object` with values transformed by `iteratee` and set by `setter`. + * + * @private + * @param {Object} object The object to iterate over. + * @param {Function} setter The function to set `accumulator` values. + * @param {Function} iteratee The iteratee to transform values. + * @param {Object} accumulator The initial inverted object. + * @returns {Function} Returns `accumulator`. + */ + function baseInverter(object, setter, iteratee, accumulator) { + baseForOwn(object, function(value, key, object) { + setter(accumulator, iteratee(value), key, object); + }); + return accumulator; + } + + /** + * The base implementation of `_.invoke` without support for individual + * method arguments. + * + * @private + * @param {Object} object The object to query. + * @param {Array|string} path The path of the method to invoke. + * @param {Array} args The arguments to invoke the method with. + * @returns {*} Returns the result of the invoked method. + */ + function baseInvoke(object, path, args) { + path = castPath(path, object); + object = parent(object, path); + var func = object == null ? object : object[toKey(last(path))]; + return func == null ? undefined : apply(func, object, args); + } + + /** + * The base implementation of `_.isArguments`. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an `arguments` object, + */ + function baseIsArguments(value) { + return isObjectLike(value) && baseGetTag(value) == argsTag; + } + + /** + * The base implementation of `_.isArrayBuffer` without Node.js optimizations. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an array buffer, else `false`. + */ + function baseIsArrayBuffer(value) { + return isObjectLike(value) && baseGetTag(value) == arrayBufferTag; + } + + /** + * The base implementation of `_.isDate` without Node.js optimizations. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a date object, else `false`. + */ + function baseIsDate(value) { + return isObjectLike(value) && baseGetTag(value) == dateTag; + } + + /** + * The base implementation of `_.isEqual` which supports partial comparisons + * and tracks traversed objects. + * + * @private + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @param {boolean} bitmask The bitmask flags. + * 1 - Unordered comparison + * 2 - Partial comparison + * @param {Function} [customizer] The function to customize comparisons. + * @param {Object} [stack] Tracks traversed `value` and `other` objects. + * @returns {boolean} Returns `true` if the values are equivalent, else `false`. + */ + function baseIsEqual(value, other, bitmask, customizer, stack) { + if (value === other) { + return true; + } + if (value == null || other == null || (!isObjectLike(value) && !isObjectLike(other))) { + return value !== value && other !== other; + } + return baseIsEqualDeep(value, other, bitmask, customizer, baseIsEqual, stack); + } + + /** + * A specialized version of `baseIsEqual` for arrays and objects which performs + * deep comparisons and tracks traversed objects enabling objects with circular + * references to be compared. + * + * @private + * @param {Object} object The object to compare. + * @param {Object} other The other object to compare. + * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. + * @param {Function} customizer The function to customize comparisons. + * @param {Function} equalFunc The function to determine equivalents of values. + * @param {Object} [stack] Tracks traversed `object` and `other` objects. + * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. + */ + function baseIsEqualDeep(object, other, bitmask, customizer, equalFunc, stack) { + var objIsArr = isArray(object), + othIsArr = isArray(other), + objTag = objIsArr ? arrayTag : getTag(object), + othTag = othIsArr ? arrayTag : getTag(other); + + objTag = objTag == argsTag ? objectTag : objTag; + othTag = othTag == argsTag ? objectTag : othTag; + + var objIsObj = objTag == objectTag, + othIsObj = othTag == objectTag, + isSameTag = objTag == othTag; + + if (isSameTag && isBuffer(object)) { + if (!isBuffer(other)) { + return false; + } + objIsArr = true; + objIsObj = false; + } + if (isSameTag && !objIsObj) { + stack || (stack = new Stack); + return (objIsArr || isTypedArray(object)) + ? equalArrays(object, other, bitmask, customizer, equalFunc, stack) + : equalByTag(object, other, objTag, bitmask, customizer, equalFunc, stack); + } + if (!(bitmask & COMPARE_PARTIAL_FLAG)) { + var objIsWrapped = objIsObj && hasOwnProperty.call(object, '__wrapped__'), + othIsWrapped = othIsObj && hasOwnProperty.call(other, '__wrapped__'); + + if (objIsWrapped || othIsWrapped) { + var objUnwrapped = objIsWrapped ? object.value() : object, + othUnwrapped = othIsWrapped ? other.value() : other; + + stack || (stack = new Stack); + return equalFunc(objUnwrapped, othUnwrapped, bitmask, customizer, stack); + } + } + if (!isSameTag) { + return false; + } + stack || (stack = new Stack); + return equalObjects(object, other, bitmask, customizer, equalFunc, stack); + } + + /** + * The base implementation of `_.isMap` without Node.js optimizations. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a map, else `false`. + */ + function baseIsMap(value) { + return isObjectLike(value) && getTag(value) == mapTag; + } + + /** + * The base implementation of `_.isMatch` without support for iteratee shorthands. + * + * @private + * @param {Object} object The object to inspect. + * @param {Object} source The object of property values to match. + * @param {Array} matchData The property names, values, and compare flags to match. + * @param {Function} [customizer] The function to customize comparisons. + * @returns {boolean} Returns `true` if `object` is a match, else `false`. + */ + function baseIsMatch(object, source, matchData, customizer) { + var index = matchData.length, + length = index, + noCustomizer = !customizer; + + if (object == null) { + return !length; + } + object = Object(object); + while (index--) { + var data = matchData[index]; + if ((noCustomizer && data[2]) + ? data[1] !== object[data[0]] + : !(data[0] in object) + ) { + return false; + } + } + while (++index < length) { + data = matchData[index]; + var key = data[0], + objValue = object[key], + srcValue = data[1]; + + if (noCustomizer && data[2]) { + if (objValue === undefined && !(key in object)) { + return false; + } + } else { + var stack = new Stack; + if (customizer) { + var result = customizer(objValue, srcValue, key, object, source, stack); + } + if (!(result === undefined + ? baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG | COMPARE_UNORDERED_FLAG, customizer, stack) + : result + )) { + return false; + } + } + } + return true; + } + + /** + * The base implementation of `_.isNative` without bad shim checks. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a native function, + * else `false`. + */ + function baseIsNative(value) { + if (!isObject(value) || isMasked(value)) { + return false; + } + var pattern = isFunction(value) ? reIsNative : reIsHostCtor; + return pattern.test(toSource(value)); + } + + /** + * The base implementation of `_.isRegExp` without Node.js optimizations. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a regexp, else `false`. + */ + function baseIsRegExp(value) { + return isObjectLike(value) && baseGetTag(value) == regexpTag; + } + + /** + * The base implementation of `_.isSet` without Node.js optimizations. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a set, else `false`. + */ + function baseIsSet(value) { + return isObjectLike(value) && getTag(value) == setTag; + } + + /** + * The base implementation of `_.isTypedArray` without Node.js optimizations. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. + */ + function baseIsTypedArray(value) { + return isObjectLike(value) && + isLength(value.length) && !!typedArrayTags[baseGetTag(value)]; + } + + /** + * The base implementation of `_.iteratee`. + * + * @private + * @param {*} [value=_.identity] The value to convert to an iteratee. + * @returns {Function} Returns the iteratee. + */ + function baseIteratee(value) { + // Don't store the `typeof` result in a variable to avoid a JIT bug in Safari 9. + // See https://bugs.webkit.org/show_bug.cgi?id=156034 for more details. + if (typeof value == 'function') { + return value; + } + if (value == null) { + return identity; + } + if (typeof value == 'object') { + return isArray(value) + ? baseMatchesProperty(value[0], value[1]) + : baseMatches(value); + } + return property(value); + } + + /** + * The base implementation of `_.keys` which doesn't treat sparse arrays as dense. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names. + */ + function baseKeys(object) { + if (!isPrototype(object)) { + return nativeKeys(object); + } + var result = []; + for (var key in Object(object)) { + if (hasOwnProperty.call(object, key) && key != 'constructor') { + result.push(key); + } + } + return result; + } + + /** + * The base implementation of `_.keysIn` which doesn't treat sparse arrays as dense. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names. + */ + function baseKeysIn(object) { + if (!isObject(object)) { + return nativeKeysIn(object); + } + var isProto = isPrototype(object), + result = []; + + for (var key in object) { + if (!(key == 'constructor' && (isProto || !hasOwnProperty.call(object, key)))) { + result.push(key); + } + } + return result; + } + + /** + * The base implementation of `_.lt` which doesn't coerce arguments. + * + * @private + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {boolean} Returns `true` if `value` is less than `other`, + * else `false`. + */ + function baseLt(value, other) { + return value < other; + } + + /** + * The base implementation of `_.map` without support for iteratee shorthands. + * + * @private + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array} Returns the new mapped array. + */ + function baseMap(collection, iteratee) { + var index = -1, + result = isArrayLike(collection) ? Array(collection.length) : []; + + baseEach(collection, function(value, key, collection) { + result[++index] = iteratee(value, key, collection); + }); + return result; + } + + /** + * The base implementation of `_.matches` which doesn't clone `source`. + * + * @private + * @param {Object} source The object of property values to match. + * @returns {Function} Returns the new spec function. + */ + function baseMatches(source) { + var matchData = getMatchData(source); + if (matchData.length == 1 && matchData[0][2]) { + return matchesStrictComparable(matchData[0][0], matchData[0][1]); + } + return function(object) { + return object === source || baseIsMatch(object, source, matchData); + }; + } + + /** + * The base implementation of `_.matchesProperty` which doesn't clone `srcValue`. + * + * @private + * @param {string} path The path of the property to get. + * @param {*} srcValue The value to match. + * @returns {Function} Returns the new spec function. + */ + function baseMatchesProperty(path, srcValue) { + if (isKey(path) && isStrictComparable(srcValue)) { + return matchesStrictComparable(toKey(path), srcValue); + } + return function(object) { + var objValue = get(object, path); + return (objValue === undefined && objValue === srcValue) + ? hasIn(object, path) + : baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG | COMPARE_UNORDERED_FLAG); + }; + } + + /** + * The base implementation of `_.merge` without support for multiple sources. + * + * @private + * @param {Object} object The destination object. + * @param {Object} source The source object. + * @param {number} srcIndex The index of `source`. + * @param {Function} [customizer] The function to customize merged values. + * @param {Object} [stack] Tracks traversed source values and their merged + * counterparts. + */ + function baseMerge(object, source, srcIndex, customizer, stack) { + if (object === source) { + return; + } + baseFor(source, function(srcValue, key) { + stack || (stack = new Stack); + if (isObject(srcValue)) { + baseMergeDeep(object, source, key, srcIndex, baseMerge, customizer, stack); + } + else { + var newValue = customizer + ? customizer(safeGet(object, key), srcValue, (key + ''), object, source, stack) + : undefined; + + if (newValue === undefined) { + newValue = srcValue; + } + assignMergeValue(object, key, newValue); + } + }, keysIn); + } + + /** + * A specialized version of `baseMerge` for arrays and objects which performs + * deep merges and tracks traversed objects enabling objects with circular + * references to be merged. + * + * @private + * @param {Object} object The destination object. + * @param {Object} source The source object. + * @param {string} key The key of the value to merge. + * @param {number} srcIndex The index of `source`. + * @param {Function} mergeFunc The function to merge values. + * @param {Function} [customizer] The function to customize assigned values. + * @param {Object} [stack] Tracks traversed source values and their merged + * counterparts. + */ + function baseMergeDeep(object, source, key, srcIndex, mergeFunc, customizer, stack) { + var objValue = safeGet(object, key), + srcValue = safeGet(source, key), + stacked = stack.get(srcValue); + + if (stacked) { + assignMergeValue(object, key, stacked); + return; + } + var newValue = customizer + ? customizer(objValue, srcValue, (key + ''), object, source, stack) + : undefined; + + var isCommon = newValue === undefined; + + if (isCommon) { + var isArr = isArray(srcValue), + isBuff = !isArr && isBuffer(srcValue), + isTyped = !isArr && !isBuff && isTypedArray(srcValue); + + newValue = srcValue; + if (isArr || isBuff || isTyped) { + if (isArray(objValue)) { + newValue = objValue; + } + else if (isArrayLikeObject(objValue)) { + newValue = copyArray(objValue); + } + else if (isBuff) { + isCommon = false; + newValue = cloneBuffer(srcValue, true); + } + else if (isTyped) { + isCommon = false; + newValue = cloneTypedArray(srcValue, true); + } + else { + newValue = []; + } + } + else if (isPlainObject(srcValue) || isArguments(srcValue)) { + newValue = objValue; + if (isArguments(objValue)) { + newValue = toPlainObject(objValue); + } + else if (!isObject(objValue) || isFunction(objValue)) { + newValue = initCloneObject(srcValue); + } + } + else { + isCommon = false; + } + } + if (isCommon) { + // Recursively merge objects and arrays (susceptible to call stack limits). + stack.set(srcValue, newValue); + mergeFunc(newValue, srcValue, srcIndex, customizer, stack); + stack['delete'](srcValue); + } + assignMergeValue(object, key, newValue); + } + + /** + * The base implementation of `_.nth` which doesn't coerce arguments. + * + * @private + * @param {Array} array The array to query. + * @param {number} n The index of the element to return. + * @returns {*} Returns the nth element of `array`. + */ + function baseNth(array, n) { + var length = array.length; + if (!length) { + return; + } + n += n < 0 ? length : 0; + return isIndex(n, length) ? array[n] : undefined; + } + + /** + * The base implementation of `_.orderBy` without param guards. + * + * @private + * @param {Array|Object} collection The collection to iterate over. + * @param {Function[]|Object[]|string[]} iteratees The iteratees to sort by. + * @param {string[]} orders The sort orders of `iteratees`. + * @returns {Array} Returns the new sorted array. + */ + function baseOrderBy(collection, iteratees, orders) { + if (iteratees.length) { + iteratees = arrayMap(iteratees, function(iteratee) { + if (isArray(iteratee)) { + return function(value) { + return baseGet(value, iteratee.length === 1 ? iteratee[0] : iteratee); + } + } + return iteratee; + }); + } else { + iteratees = [identity]; + } + + var index = -1; + iteratees = arrayMap(iteratees, baseUnary(getIteratee())); + + var result = baseMap(collection, function(value, key, collection) { + var criteria = arrayMap(iteratees, function(iteratee) { + return iteratee(value); + }); + return { 'criteria': criteria, 'index': ++index, 'value': value }; + }); + + return baseSortBy(result, function(object, other) { + return compareMultiple(object, other, orders); + }); + } + + /** + * The base implementation of `_.pick` without support for individual + * property identifiers. + * + * @private + * @param {Object} object The source object. + * @param {string[]} paths The property paths to pick. + * @returns {Object} Returns the new object. + */ + function basePick(object, paths) { + return basePickBy(object, paths, function(value, path) { + return hasIn(object, path); + }); + } + + /** + * The base implementation of `_.pickBy` without support for iteratee shorthands. + * + * @private + * @param {Object} object The source object. + * @param {string[]} paths The property paths to pick. + * @param {Function} predicate The function invoked per property. + * @returns {Object} Returns the new object. + */ + function basePickBy(object, paths, predicate) { + var index = -1, + length = paths.length, + result = {}; + + while (++index < length) { + var path = paths[index], + value = baseGet(object, path); + + if (predicate(value, path)) { + baseSet(result, castPath(path, object), value); + } + } + return result; + } + + /** + * A specialized version of `baseProperty` which supports deep paths. + * + * @private + * @param {Array|string} path The path of the property to get. + * @returns {Function} Returns the new accessor function. + */ + function basePropertyDeep(path) { + return function(object) { + return baseGet(object, path); + }; + } + + /** + * The base implementation of `_.pullAllBy` without support for iteratee + * shorthands. + * + * @private + * @param {Array} array The array to modify. + * @param {Array} values The values to remove. + * @param {Function} [iteratee] The iteratee invoked per element. + * @param {Function} [comparator] The comparator invoked per element. + * @returns {Array} Returns `array`. + */ + function basePullAll(array, values, iteratee, comparator) { + var indexOf = comparator ? baseIndexOfWith : baseIndexOf, + index = -1, + length = values.length, + seen = array; + + if (array === values) { + values = copyArray(values); + } + if (iteratee) { + seen = arrayMap(array, baseUnary(iteratee)); + } + while (++index < length) { + var fromIndex = 0, + value = values[index], + computed = iteratee ? iteratee(value) : value; + + while ((fromIndex = indexOf(seen, computed, fromIndex, comparator)) > -1) { + if (seen !== array) { + splice.call(seen, fromIndex, 1); + } + splice.call(array, fromIndex, 1); + } + } + return array; + } + + /** + * The base implementation of `_.pullAt` without support for individual + * indexes or capturing the removed elements. + * + * @private + * @param {Array} array The array to modify. + * @param {number[]} indexes The indexes of elements to remove. + * @returns {Array} Returns `array`. + */ + function basePullAt(array, indexes) { + var length = array ? indexes.length : 0, + lastIndex = length - 1; + + while (length--) { + var index = indexes[length]; + if (length == lastIndex || index !== previous) { + var previous = index; + if (isIndex(index)) { + splice.call(array, index, 1); + } else { + baseUnset(array, index); + } + } + } + return array; + } + + /** + * The base implementation of `_.random` without support for returning + * floating-point numbers. + * + * @private + * @param {number} lower The lower bound. + * @param {number} upper The upper bound. + * @returns {number} Returns the random number. + */ + function baseRandom(lower, upper) { + return lower + nativeFloor(nativeRandom() * (upper - lower + 1)); + } + + /** + * The base implementation of `_.range` and `_.rangeRight` which doesn't + * coerce arguments. + * + * @private + * @param {number} start The start of the range. + * @param {number} end The end of the range. + * @param {number} step The value to increment or decrement by. + * @param {boolean} [fromRight] Specify iterating from right to left. + * @returns {Array} Returns the range of numbers. + */ + function baseRange(start, end, step, fromRight) { + var index = -1, + length = nativeMax(nativeCeil((end - start) / (step || 1)), 0), + result = Array(length); + + while (length--) { + result[fromRight ? length : ++index] = start; + start += step; + } + return result; + } + + /** + * The base implementation of `_.repeat` which doesn't coerce arguments. + * + * @private + * @param {string} string The string to repeat. + * @param {number} n The number of times to repeat the string. + * @returns {string} Returns the repeated string. + */ + function baseRepeat(string, n) { + var result = ''; + if (!string || n < 1 || n > MAX_SAFE_INTEGER) { + return result; + } + // Leverage the exponentiation by squaring algorithm for a faster repeat. + // See https://en.wikipedia.org/wiki/Exponentiation_by_squaring for more details. + do { + if (n % 2) { + result += string; + } + n = nativeFloor(n / 2); + if (n) { + string += string; + } + } while (n); + + return result; + } + + /** + * The base implementation of `_.rest` which doesn't validate or coerce arguments. + * + * @private + * @param {Function} func The function to apply a rest parameter to. + * @param {number} [start=func.length-1] The start position of the rest parameter. + * @returns {Function} Returns the new function. + */ + function baseRest(func, start) { + return setToString(overRest(func, start, identity), func + ''); + } + + /** + * The base implementation of `_.sample`. + * + * @private + * @param {Array|Object} collection The collection to sample. + * @returns {*} Returns the random element. + */ + function baseSample(collection) { + return arraySample(values(collection)); + } + + /** + * The base implementation of `_.sampleSize` without param guards. + * + * @private + * @param {Array|Object} collection The collection to sample. + * @param {number} n The number of elements to sample. + * @returns {Array} Returns the random elements. + */ + function baseSampleSize(collection, n) { + var array = values(collection); + return shuffleSelf(array, baseClamp(n, 0, array.length)); + } + + /** + * The base implementation of `_.set`. + * + * @private + * @param {Object} object The object to modify. + * @param {Array|string} path The path of the property to set. + * @param {*} value The value to set. + * @param {Function} [customizer] The function to customize path creation. + * @returns {Object} Returns `object`. + */ + function baseSet(object, path, value, customizer) { + if (!isObject(object)) { + return object; + } + path = castPath(path, object); + + var index = -1, + length = path.length, + lastIndex = length - 1, + nested = object; + + while (nested != null && ++index < length) { + var key = toKey(path[index]), + newValue = value; + + if (key === '__proto__' || key === 'constructor' || key === 'prototype') { + return object; + } + + if (index != lastIndex) { + var objValue = nested[key]; + newValue = customizer ? customizer(objValue, key, nested) : undefined; + if (newValue === undefined) { + newValue = isObject(objValue) + ? objValue + : (isIndex(path[index + 1]) ? [] : {}); + } + } + assignValue(nested, key, newValue); + nested = nested[key]; + } + return object; + } + + /** + * The base implementation of `setData` without support for hot loop shorting. + * + * @private + * @param {Function} func The function to associate metadata with. + * @param {*} data The metadata. + * @returns {Function} Returns `func`. + */ + var baseSetData = !metaMap ? identity : function(func, data) { + metaMap.set(func, data); + return func; + }; + + /** + * The base implementation of `setToString` without support for hot loop shorting. + * + * @private + * @param {Function} func The function to modify. + * @param {Function} string The `toString` result. + * @returns {Function} Returns `func`. + */ + var baseSetToString = !defineProperty ? identity : function(func, string) { + return defineProperty(func, 'toString', { + 'configurable': true, + 'enumerable': false, + 'value': constant(string), + 'writable': true + }); + }; + + /** + * The base implementation of `_.shuffle`. + * + * @private + * @param {Array|Object} collection The collection to shuffle. + * @returns {Array} Returns the new shuffled array. + */ + function baseShuffle(collection) { + return shuffleSelf(values(collection)); + } + + /** + * The base implementation of `_.slice` without an iteratee call guard. + * + * @private + * @param {Array} array The array to slice. + * @param {number} [start=0] The start position. + * @param {number} [end=array.length] The end position. + * @returns {Array} Returns the slice of `array`. + */ + function baseSlice(array, start, end) { + var index = -1, + length = array.length; + + if (start < 0) { + start = -start > length ? 0 : (length + start); + } + end = end > length ? length : end; + if (end < 0) { + end += length; + } + length = start > end ? 0 : ((end - start) >>> 0); + start >>>= 0; + + var result = Array(length); + while (++index < length) { + result[index] = array[index + start]; + } + return result; + } + + /** + * The base implementation of `_.some` without support for iteratee shorthands. + * + * @private + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} predicate The function invoked per iteration. + * @returns {boolean} Returns `true` if any element passes the predicate check, + * else `false`. + */ + function baseSome(collection, predicate) { + var result; + + baseEach(collection, function(value, index, collection) { + result = predicate(value, index, collection); + return !result; + }); + return !!result; + } + + /** + * The base implementation of `_.sortedIndex` and `_.sortedLastIndex` which + * performs a binary search of `array` to determine the index at which `value` + * should be inserted into `array` in order to maintain its sort order. + * + * @private + * @param {Array} array The sorted array to inspect. + * @param {*} value The value to evaluate. + * @param {boolean} [retHighest] Specify returning the highest qualified index. + * @returns {number} Returns the index at which `value` should be inserted + * into `array`. + */ + function baseSortedIndex(array, value, retHighest) { + var low = 0, + high = array == null ? low : array.length; + + if (typeof value == 'number' && value === value && high <= HALF_MAX_ARRAY_LENGTH) { + while (low < high) { + var mid = (low + high) >>> 1, + computed = array[mid]; + + if (computed !== null && !isSymbol(computed) && + (retHighest ? (computed <= value) : (computed < value))) { + low = mid + 1; + } else { + high = mid; + } + } + return high; + } + return baseSortedIndexBy(array, value, identity, retHighest); + } + + /** + * The base implementation of `_.sortedIndexBy` and `_.sortedLastIndexBy` + * which invokes `iteratee` for `value` and each element of `array` to compute + * their sort ranking. The iteratee is invoked with one argument; (value). + * + * @private + * @param {Array} array The sorted array to inspect. + * @param {*} value The value to evaluate. + * @param {Function} iteratee The iteratee invoked per element. + * @param {boolean} [retHighest] Specify returning the highest qualified index. + * @returns {number} Returns the index at which `value` should be inserted + * into `array`. + */ + function baseSortedIndexBy(array, value, iteratee, retHighest) { + var low = 0, + high = array == null ? 0 : array.length; + if (high === 0) { + return 0; + } + + value = iteratee(value); + var valIsNaN = value !== value, + valIsNull = value === null, + valIsSymbol = isSymbol(value), + valIsUndefined = value === undefined; + + while (low < high) { + var mid = nativeFloor((low + high) / 2), + computed = iteratee(array[mid]), + othIsDefined = computed !== undefined, + othIsNull = computed === null, + othIsReflexive = computed === computed, + othIsSymbol = isSymbol(computed); + + if (valIsNaN) { + var setLow = retHighest || othIsReflexive; + } else if (valIsUndefined) { + setLow = othIsReflexive && (retHighest || othIsDefined); + } else if (valIsNull) { + setLow = othIsReflexive && othIsDefined && (retHighest || !othIsNull); + } else if (valIsSymbol) { + setLow = othIsReflexive && othIsDefined && !othIsNull && (retHighest || !othIsSymbol); + } else if (othIsNull || othIsSymbol) { + setLow = false; + } else { + setLow = retHighest ? (computed <= value) : (computed < value); + } + if (setLow) { + low = mid + 1; + } else { + high = mid; + } + } + return nativeMin(high, MAX_ARRAY_INDEX); + } + + /** + * The base implementation of `_.sortedUniq` and `_.sortedUniqBy` without + * support for iteratee shorthands. + * + * @private + * @param {Array} array The array to inspect. + * @param {Function} [iteratee] The iteratee invoked per element. + * @returns {Array} Returns the new duplicate free array. + */ + function baseSortedUniq(array, iteratee) { + var index = -1, + length = array.length, + resIndex = 0, + result = []; + + while (++index < length) { + var value = array[index], + computed = iteratee ? iteratee(value) : value; + + if (!index || !eq(computed, seen)) { + var seen = computed; + result[resIndex++] = value === 0 ? 0 : value; + } + } + return result; + } + + /** + * The base implementation of `_.toNumber` which doesn't ensure correct + * conversions of binary, hexadecimal, or octal string values. + * + * @private + * @param {*} value The value to process. + * @returns {number} Returns the number. + */ + function baseToNumber(value) { + if (typeof value == 'number') { + return value; + } + if (isSymbol(value)) { + return NAN; + } + return +value; + } + + /** + * The base implementation of `_.toString` which doesn't convert nullish + * values to empty strings. + * + * @private + * @param {*} value The value to process. + * @returns {string} Returns the string. + */ + function baseToString(value) { + // Exit early for strings to avoid a performance hit in some environments. + if (typeof value == 'string') { + return value; + } + if (isArray(value)) { + // Recursively convert values (susceptible to call stack limits). + return arrayMap(value, baseToString) + ''; + } + if (isSymbol(value)) { + return symbolToString ? symbolToString.call(value) : ''; + } + var result = (value + ''); + return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result; + } + + /** + * The base implementation of `_.uniqBy` without support for iteratee shorthands. + * + * @private + * @param {Array} array The array to inspect. + * @param {Function} [iteratee] The iteratee invoked per element. + * @param {Function} [comparator] The comparator invoked per element. + * @returns {Array} Returns the new duplicate free array. + */ + function baseUniq(array, iteratee, comparator) { + var index = -1, + includes = arrayIncludes, + length = array.length, + isCommon = true, + result = [], + seen = result; + + if (comparator) { + isCommon = false; + includes = arrayIncludesWith; + } + else if (length >= LARGE_ARRAY_SIZE) { + var set = iteratee ? null : createSet(array); + if (set) { + return setToArray(set); + } + isCommon = false; + includes = cacheHas; + seen = new SetCache; + } + else { + seen = iteratee ? [] : result; + } + outer: + while (++index < length) { + var value = array[index], + computed = iteratee ? iteratee(value) : value; + + value = (comparator || value !== 0) ? value : 0; + if (isCommon && computed === computed) { + var seenIndex = seen.length; + while (seenIndex--) { + if (seen[seenIndex] === computed) { + continue outer; + } + } + if (iteratee) { + seen.push(computed); + } + result.push(value); + } + else if (!includes(seen, computed, comparator)) { + if (seen !== result) { + seen.push(computed); + } + result.push(value); + } + } + return result; + } + + /** + * The base implementation of `_.unset`. + * + * @private + * @param {Object} object The object to modify. + * @param {Array|string} path The property path to unset. + * @returns {boolean} Returns `true` if the property is deleted, else `false`. + */ + function baseUnset(object, path) { + path = castPath(path, object); + object = parent(object, path); + return object == null || delete object[toKey(last(path))]; + } + + /** + * The base implementation of `_.update`. + * + * @private + * @param {Object} object The object to modify. + * @param {Array|string} path The path of the property to update. + * @param {Function} updater The function to produce the updated value. + * @param {Function} [customizer] The function to customize path creation. + * @returns {Object} Returns `object`. + */ + function baseUpdate(object, path, updater, customizer) { + return baseSet(object, path, updater(baseGet(object, path)), customizer); + } + + /** + * The base implementation of methods like `_.dropWhile` and `_.takeWhile` + * without support for iteratee shorthands. + * + * @private + * @param {Array} array The array to query. + * @param {Function} predicate The function invoked per iteration. + * @param {boolean} [isDrop] Specify dropping elements instead of taking them. + * @param {boolean} [fromRight] Specify iterating from right to left. + * @returns {Array} Returns the slice of `array`. + */ + function baseWhile(array, predicate, isDrop, fromRight) { + var length = array.length, + index = fromRight ? length : -1; + + while ((fromRight ? index-- : ++index < length) && + predicate(array[index], index, array)) {} + + return isDrop + ? baseSlice(array, (fromRight ? 0 : index), (fromRight ? index + 1 : length)) + : baseSlice(array, (fromRight ? index + 1 : 0), (fromRight ? length : index)); + } + + /** + * The base implementation of `wrapperValue` which returns the result of + * performing a sequence of actions on the unwrapped `value`, where each + * successive action is supplied the return value of the previous. + * + * @private + * @param {*} value The unwrapped value. + * @param {Array} actions Actions to perform to resolve the unwrapped value. + * @returns {*} Returns the resolved value. + */ + function baseWrapperValue(value, actions) { + var result = value; + if (result instanceof LazyWrapper) { + result = result.value(); + } + return arrayReduce(actions, function(result, action) { + return action.func.apply(action.thisArg, arrayPush([result], action.args)); + }, result); + } + + /** + * The base implementation of methods like `_.xor`, without support for + * iteratee shorthands, that accepts an array of arrays to inspect. + * + * @private + * @param {Array} arrays The arrays to inspect. + * @param {Function} [iteratee] The iteratee invoked per element. + * @param {Function} [comparator] The comparator invoked per element. + * @returns {Array} Returns the new array of values. + */ + function baseXor(arrays, iteratee, comparator) { + var length = arrays.length; + if (length < 2) { + return length ? baseUniq(arrays[0]) : []; + } + var index = -1, + result = Array(length); + + while (++index < length) { + var array = arrays[index], + othIndex = -1; + + while (++othIndex < length) { + if (othIndex != index) { + result[index] = baseDifference(result[index] || array, arrays[othIndex], iteratee, comparator); + } + } + } + return baseUniq(baseFlatten(result, 1), iteratee, comparator); + } + + /** + * This base implementation of `_.zipObject` which assigns values using `assignFunc`. + * + * @private + * @param {Array} props The property identifiers. + * @param {Array} values The property values. + * @param {Function} assignFunc The function to assign values. + * @returns {Object} Returns the new object. + */ + function baseZipObject(props, values, assignFunc) { + var index = -1, + length = props.length, + valsLength = values.length, + result = {}; + + while (++index < length) { + var value = index < valsLength ? values[index] : undefined; + assignFunc(result, props[index], value); + } + return result; + } + + /** + * Casts `value` to an empty array if it's not an array like object. + * + * @private + * @param {*} value The value to inspect. + * @returns {Array|Object} Returns the cast array-like object. + */ + function castArrayLikeObject(value) { + return isArrayLikeObject(value) ? value : []; + } + + /** + * Casts `value` to `identity` if it's not a function. + * + * @private + * @param {*} value The value to inspect. + * @returns {Function} Returns cast function. + */ + function castFunction(value) { + return typeof value == 'function' ? value : identity; + } + + /** + * Casts `value` to a path array if it's not one. + * + * @private + * @param {*} value The value to inspect. + * @param {Object} [object] The object to query keys on. + * @returns {Array} Returns the cast property path array. + */ + function castPath(value, object) { + if (isArray(value)) { + return value; + } + return isKey(value, object) ? [value] : stringToPath(toString(value)); + } + + /** + * A `baseRest` alias which can be replaced with `identity` by module + * replacement plugins. + * + * @private + * @type {Function} + * @param {Function} func The function to apply a rest parameter to. + * @returns {Function} Returns the new function. + */ + var castRest = baseRest; + + /** + * Casts `array` to a slice if it's needed. + * + * @private + * @param {Array} array The array to inspect. + * @param {number} start The start position. + * @param {number} [end=array.length] The end position. + * @returns {Array} Returns the cast slice. + */ + function castSlice(array, start, end) { + var length = array.length; + end = end === undefined ? length : end; + return (!start && end >= length) ? array : baseSlice(array, start, end); + } + + /** + * A simple wrapper around the global [`clearTimeout`](https://mdn.io/clearTimeout). + * + * @private + * @param {number|Object} id The timer id or timeout object of the timer to clear. + */ + var clearTimeout = ctxClearTimeout || function(id) { + return root.clearTimeout(id); + }; + + /** + * Creates a clone of `buffer`. + * + * @private + * @param {Buffer} buffer The buffer to clone. + * @param {boolean} [isDeep] Specify a deep clone. + * @returns {Buffer} Returns the cloned buffer. + */ + function cloneBuffer(buffer, isDeep) { + if (isDeep) { + return buffer.slice(); + } + var length = buffer.length, + result = allocUnsafe ? allocUnsafe(length) : new buffer.constructor(length); + + buffer.copy(result); + return result; + } + + /** + * Creates a clone of `arrayBuffer`. + * + * @private + * @param {ArrayBuffer} arrayBuffer The array buffer to clone. + * @returns {ArrayBuffer} Returns the cloned array buffer. + */ + function cloneArrayBuffer(arrayBuffer) { + var result = new arrayBuffer.constructor(arrayBuffer.byteLength); + new Uint8Array(result).set(new Uint8Array(arrayBuffer)); + return result; + } + + /** + * Creates a clone of `dataView`. + * + * @private + * @param {Object} dataView The data view to clone. + * @param {boolean} [isDeep] Specify a deep clone. + * @returns {Object} Returns the cloned data view. + */ + function cloneDataView(dataView, isDeep) { + var buffer = isDeep ? cloneArrayBuffer(dataView.buffer) : dataView.buffer; + return new dataView.constructor(buffer, dataView.byteOffset, dataView.byteLength); + } + + /** + * Creates a clone of `regexp`. + * + * @private + * @param {Object} regexp The regexp to clone. + * @returns {Object} Returns the cloned regexp. + */ + function cloneRegExp(regexp) { + var result = new regexp.constructor(regexp.source, reFlags.exec(regexp)); + result.lastIndex = regexp.lastIndex; + return result; + } + + /** + * Creates a clone of the `symbol` object. + * + * @private + * @param {Object} symbol The symbol object to clone. + * @returns {Object} Returns the cloned symbol object. + */ + function cloneSymbol(symbol) { + return symbolValueOf ? Object(symbolValueOf.call(symbol)) : {}; + } + + /** + * Creates a clone of `typedArray`. + * + * @private + * @param {Object} typedArray The typed array to clone. + * @param {boolean} [isDeep] Specify a deep clone. + * @returns {Object} Returns the cloned typed array. + */ + function cloneTypedArray(typedArray, isDeep) { + var buffer = isDeep ? cloneArrayBuffer(typedArray.buffer) : typedArray.buffer; + return new typedArray.constructor(buffer, typedArray.byteOffset, typedArray.length); + } + + /** + * Compares values to sort them in ascending order. + * + * @private + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {number} Returns the sort order indicator for `value`. + */ + function compareAscending(value, other) { + if (value !== other) { + var valIsDefined = value !== undefined, + valIsNull = value === null, + valIsReflexive = value === value, + valIsSymbol = isSymbol(value); + + var othIsDefined = other !== undefined, + othIsNull = other === null, + othIsReflexive = other === other, + othIsSymbol = isSymbol(other); + + if ((!othIsNull && !othIsSymbol && !valIsSymbol && value > other) || + (valIsSymbol && othIsDefined && othIsReflexive && !othIsNull && !othIsSymbol) || + (valIsNull && othIsDefined && othIsReflexive) || + (!valIsDefined && othIsReflexive) || + !valIsReflexive) { + return 1; + } + if ((!valIsNull && !valIsSymbol && !othIsSymbol && value < other) || + (othIsSymbol && valIsDefined && valIsReflexive && !valIsNull && !valIsSymbol) || + (othIsNull && valIsDefined && valIsReflexive) || + (!othIsDefined && valIsReflexive) || + !othIsReflexive) { + return -1; + } + } + return 0; + } + + /** + * Used by `_.orderBy` to compare multiple properties of a value to another + * and stable sort them. + * + * If `orders` is unspecified, all values are sorted in ascending order. Otherwise, + * specify an order of "desc" for descending or "asc" for ascending sort order + * of corresponding values. + * + * @private + * @param {Object} object The object to compare. + * @param {Object} other The other object to compare. + * @param {boolean[]|string[]} orders The order to sort by for each property. + * @returns {number} Returns the sort order indicator for `object`. + */ + function compareMultiple(object, other, orders) { + var index = -1, + objCriteria = object.criteria, + othCriteria = other.criteria, + length = objCriteria.length, + ordersLength = orders.length; + + while (++index < length) { + var result = compareAscending(objCriteria[index], othCriteria[index]); + if (result) { + if (index >= ordersLength) { + return result; + } + var order = orders[index]; + return result * (order == 'desc' ? -1 : 1); + } + } + // Fixes an `Array#sort` bug in the JS engine embedded in Adobe applications + // that causes it, under certain circumstances, to provide the same value for + // `object` and `other`. See https://github.com/jashkenas/underscore/pull/1247 + // for more details. + // + // This also ensures a stable sort in V8 and other engines. + // See https://bugs.chromium.org/p/v8/issues/detail?id=90 for more details. + return object.index - other.index; + } + + /** + * Creates an array that is the composition of partially applied arguments, + * placeholders, and provided arguments into a single array of arguments. + * + * @private + * @param {Array} args The provided arguments. + * @param {Array} partials The arguments to prepend to those provided. + * @param {Array} holders The `partials` placeholder indexes. + * @params {boolean} [isCurried] Specify composing for a curried function. + * @returns {Array} Returns the new array of composed arguments. + */ + function composeArgs(args, partials, holders, isCurried) { + var argsIndex = -1, + argsLength = args.length, + holdersLength = holders.length, + leftIndex = -1, + leftLength = partials.length, + rangeLength = nativeMax(argsLength - holdersLength, 0), + result = Array(leftLength + rangeLength), + isUncurried = !isCurried; + + while (++leftIndex < leftLength) { + result[leftIndex] = partials[leftIndex]; + } + while (++argsIndex < holdersLength) { + if (isUncurried || argsIndex < argsLength) { + result[holders[argsIndex]] = args[argsIndex]; + } + } + while (rangeLength--) { + result[leftIndex++] = args[argsIndex++]; + } + return result; + } + + /** + * This function is like `composeArgs` except that the arguments composition + * is tailored for `_.partialRight`. + * + * @private + * @param {Array} args The provided arguments. + * @param {Array} partials The arguments to append to those provided. + * @param {Array} holders The `partials` placeholder indexes. + * @params {boolean} [isCurried] Specify composing for a curried function. + * @returns {Array} Returns the new array of composed arguments. + */ + function composeArgsRight(args, partials, holders, isCurried) { + var argsIndex = -1, + argsLength = args.length, + holdersIndex = -1, + holdersLength = holders.length, + rightIndex = -1, + rightLength = partials.length, + rangeLength = nativeMax(argsLength - holdersLength, 0), + result = Array(rangeLength + rightLength), + isUncurried = !isCurried; + + while (++argsIndex < rangeLength) { + result[argsIndex] = args[argsIndex]; + } + var offset = argsIndex; + while (++rightIndex < rightLength) { + result[offset + rightIndex] = partials[rightIndex]; + } + while (++holdersIndex < holdersLength) { + if (isUncurried || argsIndex < argsLength) { + result[offset + holders[holdersIndex]] = args[argsIndex++]; + } + } + return result; + } + + /** + * Copies the values of `source` to `array`. + * + * @private + * @param {Array} source The array to copy values from. + * @param {Array} [array=[]] The array to copy values to. + * @returns {Array} Returns `array`. + */ + function copyArray(source, array) { + var index = -1, + length = source.length; + + array || (array = Array(length)); + while (++index < length) { + array[index] = source[index]; + } + return array; + } + + /** + * Copies properties of `source` to `object`. + * + * @private + * @param {Object} source The object to copy properties from. + * @param {Array} props The property identifiers to copy. + * @param {Object} [object={}] The object to copy properties to. + * @param {Function} [customizer] The function to customize copied values. + * @returns {Object} Returns `object`. + */ + function copyObject(source, props, object, customizer) { + var isNew = !object; + object || (object = {}); + + var index = -1, + length = props.length; + + while (++index < length) { + var key = props[index]; + + var newValue = customizer + ? customizer(object[key], source[key], key, object, source) + : undefined; + + if (newValue === undefined) { + newValue = source[key]; + } + if (isNew) { + baseAssignValue(object, key, newValue); + } else { + assignValue(object, key, newValue); + } + } + return object; + } + + /** + * Copies own symbols of `source` to `object`. + * + * @private + * @param {Object} source The object to copy symbols from. + * @param {Object} [object={}] The object to copy symbols to. + * @returns {Object} Returns `object`. + */ + function copySymbols(source, object) { + return copyObject(source, getSymbols(source), object); + } + + /** + * Copies own and inherited symbols of `source` to `object`. + * + * @private + * @param {Object} source The object to copy symbols from. + * @param {Object} [object={}] The object to copy symbols to. + * @returns {Object} Returns `object`. + */ + function copySymbolsIn(source, object) { + return copyObject(source, getSymbolsIn(source), object); + } + + /** + * Creates a function like `_.groupBy`. + * + * @private + * @param {Function} setter The function to set accumulator values. + * @param {Function} [initializer] The accumulator object initializer. + * @returns {Function} Returns the new aggregator function. + */ + function createAggregator(setter, initializer) { + return function(collection, iteratee) { + var func = isArray(collection) ? arrayAggregator : baseAggregator, + accumulator = initializer ? initializer() : {}; + + return func(collection, setter, getIteratee(iteratee, 2), accumulator); + }; + } + + /** + * Creates a function like `_.assign`. + * + * @private + * @param {Function} assigner The function to assign values. + * @returns {Function} Returns the new assigner function. + */ + function createAssigner(assigner) { + return baseRest(function(object, sources) { + var index = -1, + length = sources.length, + customizer = length > 1 ? sources[length - 1] : undefined, + guard = length > 2 ? sources[2] : undefined; + + customizer = (assigner.length > 3 && typeof customizer == 'function') + ? (length--, customizer) + : undefined; + + if (guard && isIterateeCall(sources[0], sources[1], guard)) { + customizer = length < 3 ? undefined : customizer; + length = 1; + } + object = Object(object); + while (++index < length) { + var source = sources[index]; + if (source) { + assigner(object, source, index, customizer); + } + } + return object; + }); + } + + /** + * Creates a `baseEach` or `baseEachRight` function. + * + * @private + * @param {Function} eachFunc The function to iterate over a collection. + * @param {boolean} [fromRight] Specify iterating from right to left. + * @returns {Function} Returns the new base function. + */ + function createBaseEach(eachFunc, fromRight) { + return function(collection, iteratee) { + if (collection == null) { + return collection; + } + if (!isArrayLike(collection)) { + return eachFunc(collection, iteratee); + } + var length = collection.length, + index = fromRight ? length : -1, + iterable = Object(collection); + + while ((fromRight ? index-- : ++index < length)) { + if (iteratee(iterable[index], index, iterable) === false) { + break; + } + } + return collection; + }; + } + + /** + * Creates a base function for methods like `_.forIn` and `_.forOwn`. + * + * @private + * @param {boolean} [fromRight] Specify iterating from right to left. + * @returns {Function} Returns the new base function. + */ + function createBaseFor(fromRight) { + return function(object, iteratee, keysFunc) { + var index = -1, + iterable = Object(object), + props = keysFunc(object), + length = props.length; + + while (length--) { + var key = props[fromRight ? length : ++index]; + if (iteratee(iterable[key], key, iterable) === false) { + break; + } + } + return object; + }; + } + + /** + * Creates a function that wraps `func` to invoke it with the optional `this` + * binding of `thisArg`. + * + * @private + * @param {Function} func The function to wrap. + * @param {number} bitmask The bitmask flags. See `createWrap` for more details. + * @param {*} [thisArg] The `this` binding of `func`. + * @returns {Function} Returns the new wrapped function. + */ + function createBind(func, bitmask, thisArg) { + var isBind = bitmask & WRAP_BIND_FLAG, + Ctor = createCtor(func); + + function wrapper() { + var fn = (this && this !== root && this instanceof wrapper) ? Ctor : func; + return fn.apply(isBind ? thisArg : this, arguments); + } + return wrapper; + } + + /** + * Creates a function like `_.lowerFirst`. + * + * @private + * @param {string} methodName The name of the `String` case method to use. + * @returns {Function} Returns the new case function. + */ + function createCaseFirst(methodName) { + return function(string) { + string = toString(string); + + var strSymbols = hasUnicode(string) + ? stringToArray(string) + : undefined; + + var chr = strSymbols + ? strSymbols[0] + : string.charAt(0); + + var trailing = strSymbols + ? castSlice(strSymbols, 1).join('') + : string.slice(1); + + return chr[methodName]() + trailing; + }; + } + + /** + * Creates a function like `_.camelCase`. + * + * @private + * @param {Function} callback The function to combine each word. + * @returns {Function} Returns the new compounder function. + */ + function createCompounder(callback) { + return function(string) { + return arrayReduce(words(deburr(string).replace(reApos, '')), callback, ''); + }; + } + + /** + * Creates a function that produces an instance of `Ctor` regardless of + * whether it was invoked as part of a `new` expression or by `call` or `apply`. + * + * @private + * @param {Function} Ctor The constructor to wrap. + * @returns {Function} Returns the new wrapped function. + */ + function createCtor(Ctor) { + return function() { + // Use a `switch` statement to work with class constructors. See + // http://ecma-international.org/ecma-262/7.0/#sec-ecmascript-function-objects-call-thisargument-argumentslist + // for more details. + var args = arguments; + switch (args.length) { + case 0: return new Ctor; + case 1: return new Ctor(args[0]); + case 2: return new Ctor(args[0], args[1]); + case 3: return new Ctor(args[0], args[1], args[2]); + case 4: return new Ctor(args[0], args[1], args[2], args[3]); + case 5: return new Ctor(args[0], args[1], args[2], args[3], args[4]); + case 6: return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5]); + case 7: return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5], args[6]); + } + var thisBinding = baseCreate(Ctor.prototype), + result = Ctor.apply(thisBinding, args); + + // Mimic the constructor's `return` behavior. + // See https://es5.github.io/#x13.2.2 for more details. + return isObject(result) ? result : thisBinding; + }; + } + + /** + * Creates a function that wraps `func` to enable currying. + * + * @private + * @param {Function} func The function to wrap. + * @param {number} bitmask The bitmask flags. See `createWrap` for more details. + * @param {number} arity The arity of `func`. + * @returns {Function} Returns the new wrapped function. + */ + function createCurry(func, bitmask, arity) { + var Ctor = createCtor(func); + + function wrapper() { + var length = arguments.length, + args = Array(length), + index = length, + placeholder = getHolder(wrapper); + + while (index--) { + args[index] = arguments[index]; + } + var holders = (length < 3 && args[0] !== placeholder && args[length - 1] !== placeholder) + ? [] + : replaceHolders(args, placeholder); + + length -= holders.length; + if (length < arity) { + return createRecurry( + func, bitmask, createHybrid, wrapper.placeholder, undefined, + args, holders, undefined, undefined, arity - length); + } + var fn = (this && this !== root && this instanceof wrapper) ? Ctor : func; + return apply(fn, this, args); + } + return wrapper; + } + + /** + * Creates a `_.find` or `_.findLast` function. + * + * @private + * @param {Function} findIndexFunc The function to find the collection index. + * @returns {Function} Returns the new find function. + */ + function createFind(findIndexFunc) { + return function(collection, predicate, fromIndex) { + var iterable = Object(collection); + if (!isArrayLike(collection)) { + var iteratee = getIteratee(predicate, 3); + collection = keys(collection); + predicate = function(key) { return iteratee(iterable[key], key, iterable); }; + } + var index = findIndexFunc(collection, predicate, fromIndex); + return index > -1 ? iterable[iteratee ? collection[index] : index] : undefined; + }; + } + + /** + * Creates a `_.flow` or `_.flowRight` function. + * + * @private + * @param {boolean} [fromRight] Specify iterating from right to left. + * @returns {Function} Returns the new flow function. + */ + function createFlow(fromRight) { + return flatRest(function(funcs) { + var length = funcs.length, + index = length, + prereq = LodashWrapper.prototype.thru; + + if (fromRight) { + funcs.reverse(); + } + while (index--) { + var func = funcs[index]; + if (typeof func != 'function') { + throw new TypeError(FUNC_ERROR_TEXT); + } + if (prereq && !wrapper && getFuncName(func) == 'wrapper') { + var wrapper = new LodashWrapper([], true); + } + } + index = wrapper ? index : length; + while (++index < length) { + func = funcs[index]; + + var funcName = getFuncName(func), + data = funcName == 'wrapper' ? getData(func) : undefined; + + if (data && isLaziable(data[0]) && + data[1] == (WRAP_ARY_FLAG | WRAP_CURRY_FLAG | WRAP_PARTIAL_FLAG | WRAP_REARG_FLAG) && + !data[4].length && data[9] == 1 + ) { + wrapper = wrapper[getFuncName(data[0])].apply(wrapper, data[3]); + } else { + wrapper = (func.length == 1 && isLaziable(func)) + ? wrapper[funcName]() + : wrapper.thru(func); + } + } + return function() { + var args = arguments, + value = args[0]; + + if (wrapper && args.length == 1 && isArray(value)) { + return wrapper.plant(value).value(); + } + var index = 0, + result = length ? funcs[index].apply(this, args) : value; + + while (++index < length) { + result = funcs[index].call(this, result); + } + return result; + }; + }); + } + + /** + * Creates a function that wraps `func` to invoke it with optional `this` + * binding of `thisArg`, partial application, and currying. + * + * @private + * @param {Function|string} func The function or method name to wrap. + * @param {number} bitmask The bitmask flags. See `createWrap` for more details. + * @param {*} [thisArg] The `this` binding of `func`. + * @param {Array} [partials] The arguments to prepend to those provided to + * the new function. + * @param {Array} [holders] The `partials` placeholder indexes. + * @param {Array} [partialsRight] The arguments to append to those provided + * to the new function. + * @param {Array} [holdersRight] The `partialsRight` placeholder indexes. + * @param {Array} [argPos] The argument positions of the new function. + * @param {number} [ary] The arity cap of `func`. + * @param {number} [arity] The arity of `func`. + * @returns {Function} Returns the new wrapped function. + */ + function createHybrid(func, bitmask, thisArg, partials, holders, partialsRight, holdersRight, argPos, ary, arity) { + var isAry = bitmask & WRAP_ARY_FLAG, + isBind = bitmask & WRAP_BIND_FLAG, + isBindKey = bitmask & WRAP_BIND_KEY_FLAG, + isCurried = bitmask & (WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG), + isFlip = bitmask & WRAP_FLIP_FLAG, + Ctor = isBindKey ? undefined : createCtor(func); + + function wrapper() { + var length = arguments.length, + args = Array(length), + index = length; + + while (index--) { + args[index] = arguments[index]; + } + if (isCurried) { + var placeholder = getHolder(wrapper), + holdersCount = countHolders(args, placeholder); + } + if (partials) { + args = composeArgs(args, partials, holders, isCurried); + } + if (partialsRight) { + args = composeArgsRight(args, partialsRight, holdersRight, isCurried); + } + length -= holdersCount; + if (isCurried && length < arity) { + var newHolders = replaceHolders(args, placeholder); + return createRecurry( + func, bitmask, createHybrid, wrapper.placeholder, thisArg, + args, newHolders, argPos, ary, arity - length + ); + } + var thisBinding = isBind ? thisArg : this, + fn = isBindKey ? thisBinding[func] : func; + + length = args.length; + if (argPos) { + args = reorder(args, argPos); + } else if (isFlip && length > 1) { + args.reverse(); + } + if (isAry && ary < length) { + args.length = ary; + } + if (this && this !== root && this instanceof wrapper) { + fn = Ctor || createCtor(fn); + } + return fn.apply(thisBinding, args); + } + return wrapper; + } + + /** + * Creates a function like `_.invertBy`. + * + * @private + * @param {Function} setter The function to set accumulator values. + * @param {Function} toIteratee The function to resolve iteratees. + * @returns {Function} Returns the new inverter function. + */ + function createInverter(setter, toIteratee) { + return function(object, iteratee) { + return baseInverter(object, setter, toIteratee(iteratee), {}); + }; + } + + /** + * Creates a function that performs a mathematical operation on two values. + * + * @private + * @param {Function} operator The function to perform the operation. + * @param {number} [defaultValue] The value used for `undefined` arguments. + * @returns {Function} Returns the new mathematical operation function. + */ + function createMathOperation(operator, defaultValue) { + return function(value, other) { + var result; + if (value === undefined && other === undefined) { + return defaultValue; + } + if (value !== undefined) { + result = value; + } + if (other !== undefined) { + if (result === undefined) { + return other; + } + if (typeof value == 'string' || typeof other == 'string') { + value = baseToString(value); + other = baseToString(other); + } else { + value = baseToNumber(value); + other = baseToNumber(other); + } + result = operator(value, other); + } + return result; + }; + } + + /** + * Creates a function like `_.over`. + * + * @private + * @param {Function} arrayFunc The function to iterate over iteratees. + * @returns {Function} Returns the new over function. + */ + function createOver(arrayFunc) { + return flatRest(function(iteratees) { + iteratees = arrayMap(iteratees, baseUnary(getIteratee())); + return baseRest(function(args) { + var thisArg = this; + return arrayFunc(iteratees, function(iteratee) { + return apply(iteratee, thisArg, args); + }); + }); + }); + } + + /** + * Creates the padding for `string` based on `length`. The `chars` string + * is truncated if the number of characters exceeds `length`. + * + * @private + * @param {number} length The padding length. + * @param {string} [chars=' '] The string used as padding. + * @returns {string} Returns the padding for `string`. + */ + function createPadding(length, chars) { + chars = chars === undefined ? ' ' : baseToString(chars); + + var charsLength = chars.length; + if (charsLength < 2) { + return charsLength ? baseRepeat(chars, length) : chars; + } + var result = baseRepeat(chars, nativeCeil(length / stringSize(chars))); + return hasUnicode(chars) + ? castSlice(stringToArray(result), 0, length).join('') + : result.slice(0, length); + } + + /** + * Creates a function that wraps `func` to invoke it with the `this` binding + * of `thisArg` and `partials` prepended to the arguments it receives. + * + * @private + * @param {Function} func The function to wrap. + * @param {number} bitmask The bitmask flags. See `createWrap` for more details. + * @param {*} thisArg The `this` binding of `func`. + * @param {Array} partials The arguments to prepend to those provided to + * the new function. + * @returns {Function} Returns the new wrapped function. + */ + function createPartial(func, bitmask, thisArg, partials) { + var isBind = bitmask & WRAP_BIND_FLAG, + Ctor = createCtor(func); + + function wrapper() { + var argsIndex = -1, + argsLength = arguments.length, + leftIndex = -1, + leftLength = partials.length, + args = Array(leftLength + argsLength), + fn = (this && this !== root && this instanceof wrapper) ? Ctor : func; + + while (++leftIndex < leftLength) { + args[leftIndex] = partials[leftIndex]; + } + while (argsLength--) { + args[leftIndex++] = arguments[++argsIndex]; + } + return apply(fn, isBind ? thisArg : this, args); + } + return wrapper; + } + + /** + * Creates a `_.range` or `_.rangeRight` function. + * + * @private + * @param {boolean} [fromRight] Specify iterating from right to left. + * @returns {Function} Returns the new range function. + */ + function createRange(fromRight) { + return function(start, end, step) { + if (step && typeof step != 'number' && isIterateeCall(start, end, step)) { + end = step = undefined; + } + // Ensure the sign of `-0` is preserved. + start = toFinite(start); + if (end === undefined) { + end = start; + start = 0; + } else { + end = toFinite(end); + } + step = step === undefined ? (start < end ? 1 : -1) : toFinite(step); + return baseRange(start, end, step, fromRight); + }; + } + + /** + * Creates a function that performs a relational operation on two values. + * + * @private + * @param {Function} operator The function to perform the operation. + * @returns {Function} Returns the new relational operation function. + */ + function createRelationalOperation(operator) { + return function(value, other) { + if (!(typeof value == 'string' && typeof other == 'string')) { + value = toNumber(value); + other = toNumber(other); + } + return operator(value, other); + }; + } + + /** + * Creates a function that wraps `func` to continue currying. + * + * @private + * @param {Function} func The function to wrap. + * @param {number} bitmask The bitmask flags. See `createWrap` for more details. + * @param {Function} wrapFunc The function to create the `func` wrapper. + * @param {*} placeholder The placeholder value. + * @param {*} [thisArg] The `this` binding of `func`. + * @param {Array} [partials] The arguments to prepend to those provided to + * the new function. + * @param {Array} [holders] The `partials` placeholder indexes. + * @param {Array} [argPos] The argument positions of the new function. + * @param {number} [ary] The arity cap of `func`. + * @param {number} [arity] The arity of `func`. + * @returns {Function} Returns the new wrapped function. + */ + function createRecurry(func, bitmask, wrapFunc, placeholder, thisArg, partials, holders, argPos, ary, arity) { + var isCurry = bitmask & WRAP_CURRY_FLAG, + newHolders = isCurry ? holders : undefined, + newHoldersRight = isCurry ? undefined : holders, + newPartials = isCurry ? partials : undefined, + newPartialsRight = isCurry ? undefined : partials; + + bitmask |= (isCurry ? WRAP_PARTIAL_FLAG : WRAP_PARTIAL_RIGHT_FLAG); + bitmask &= ~(isCurry ? WRAP_PARTIAL_RIGHT_FLAG : WRAP_PARTIAL_FLAG); + + if (!(bitmask & WRAP_CURRY_BOUND_FLAG)) { + bitmask &= ~(WRAP_BIND_FLAG | WRAP_BIND_KEY_FLAG); + } + var newData = [ + func, bitmask, thisArg, newPartials, newHolders, newPartialsRight, + newHoldersRight, argPos, ary, arity + ]; + + var result = wrapFunc.apply(undefined, newData); + if (isLaziable(func)) { + setData(result, newData); + } + result.placeholder = placeholder; + return setWrapToString(result, func, bitmask); + } + + /** + * Creates a function like `_.round`. + * + * @private + * @param {string} methodName The name of the `Math` method to use when rounding. + * @returns {Function} Returns the new round function. + */ + function createRound(methodName) { + var func = Math[methodName]; + return function(number, precision) { + number = toNumber(number); + precision = precision == null ? 0 : nativeMin(toInteger(precision), 292); + if (precision && nativeIsFinite(number)) { + // Shift with exponential notation to avoid floating-point issues. + // See [MDN](https://mdn.io/round#Examples) for more details. + var pair = (toString(number) + 'e').split('e'), + value = func(pair[0] + 'e' + (+pair[1] + precision)); + + pair = (toString(value) + 'e').split('e'); + return +(pair[0] + 'e' + (+pair[1] - precision)); + } + return func(number); + }; + } + + /** + * Creates a set object of `values`. + * + * @private + * @param {Array} values The values to add to the set. + * @returns {Object} Returns the new set. + */ + var createSet = !(Set && (1 / setToArray(new Set([,-0]))[1]) == INFINITY) ? noop : function(values) { + return new Set(values); + }; + + /** + * Creates a `_.toPairs` or `_.toPairsIn` function. + * + * @private + * @param {Function} keysFunc The function to get the keys of a given object. + * @returns {Function} Returns the new pairs function. + */ + function createToPairs(keysFunc) { + return function(object) { + var tag = getTag(object); + if (tag == mapTag) { + return mapToArray(object); + } + if (tag == setTag) { + return setToPairs(object); + } + return baseToPairs(object, keysFunc(object)); + }; + } + + /** + * Creates a function that either curries or invokes `func` with optional + * `this` binding and partially applied arguments. + * + * @private + * @param {Function|string} func The function or method name to wrap. + * @param {number} bitmask The bitmask flags. + * 1 - `_.bind` + * 2 - `_.bindKey` + * 4 - `_.curry` or `_.curryRight` of a bound function + * 8 - `_.curry` + * 16 - `_.curryRight` + * 32 - `_.partial` + * 64 - `_.partialRight` + * 128 - `_.rearg` + * 256 - `_.ary` + * 512 - `_.flip` + * @param {*} [thisArg] The `this` binding of `func`. + * @param {Array} [partials] The arguments to be partially applied. + * @param {Array} [holders] The `partials` placeholder indexes. + * @param {Array} [argPos] The argument positions of the new function. + * @param {number} [ary] The arity cap of `func`. + * @param {number} [arity] The arity of `func`. + * @returns {Function} Returns the new wrapped function. + */ + function createWrap(func, bitmask, thisArg, partials, holders, argPos, ary, arity) { + var isBindKey = bitmask & WRAP_BIND_KEY_FLAG; + if (!isBindKey && typeof func != 'function') { + throw new TypeError(FUNC_ERROR_TEXT); + } + var length = partials ? partials.length : 0; + if (!length) { + bitmask &= ~(WRAP_PARTIAL_FLAG | WRAP_PARTIAL_RIGHT_FLAG); + partials = holders = undefined; + } + ary = ary === undefined ? ary : nativeMax(toInteger(ary), 0); + arity = arity === undefined ? arity : toInteger(arity); + length -= holders ? holders.length : 0; + + if (bitmask & WRAP_PARTIAL_RIGHT_FLAG) { + var partialsRight = partials, + holdersRight = holders; + + partials = holders = undefined; + } + var data = isBindKey ? undefined : getData(func); + + var newData = [ + func, bitmask, thisArg, partials, holders, partialsRight, holdersRight, + argPos, ary, arity + ]; + + if (data) { + mergeData(newData, data); + } + func = newData[0]; + bitmask = newData[1]; + thisArg = newData[2]; + partials = newData[3]; + holders = newData[4]; + arity = newData[9] = newData[9] === undefined + ? (isBindKey ? 0 : func.length) + : nativeMax(newData[9] - length, 0); + + if (!arity && bitmask & (WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG)) { + bitmask &= ~(WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG); + } + if (!bitmask || bitmask == WRAP_BIND_FLAG) { + var result = createBind(func, bitmask, thisArg); + } else if (bitmask == WRAP_CURRY_FLAG || bitmask == WRAP_CURRY_RIGHT_FLAG) { + result = createCurry(func, bitmask, arity); + } else if ((bitmask == WRAP_PARTIAL_FLAG || bitmask == (WRAP_BIND_FLAG | WRAP_PARTIAL_FLAG)) && !holders.length) { + result = createPartial(func, bitmask, thisArg, partials); + } else { + result = createHybrid.apply(undefined, newData); + } + var setter = data ? baseSetData : setData; + return setWrapToString(setter(result, newData), func, bitmask); + } + + /** + * Used by `_.defaults` to customize its `_.assignIn` use to assign properties + * of source objects to the destination object for all destination properties + * that resolve to `undefined`. + * + * @private + * @param {*} objValue The destination value. + * @param {*} srcValue The source value. + * @param {string} key The key of the property to assign. + * @param {Object} object The parent object of `objValue`. + * @returns {*} Returns the value to assign. + */ + function customDefaultsAssignIn(objValue, srcValue, key, object) { + if (objValue === undefined || + (eq(objValue, objectProto[key]) && !hasOwnProperty.call(object, key))) { + return srcValue; + } + return objValue; + } + + /** + * Used by `_.defaultsDeep` to customize its `_.merge` use to merge source + * objects into destination objects that are passed thru. + * + * @private + * @param {*} objValue The destination value. + * @param {*} srcValue The source value. + * @param {string} key The key of the property to merge. + * @param {Object} object The parent object of `objValue`. + * @param {Object} source The parent object of `srcValue`. + * @param {Object} [stack] Tracks traversed source values and their merged + * counterparts. + * @returns {*} Returns the value to assign. + */ + function customDefaultsMerge(objValue, srcValue, key, object, source, stack) { + if (isObject(objValue) && isObject(srcValue)) { + // Recursively merge objects and arrays (susceptible to call stack limits). + stack.set(srcValue, objValue); + baseMerge(objValue, srcValue, undefined, customDefaultsMerge, stack); + stack['delete'](srcValue); + } + return objValue; + } + + /** + * Used by `_.omit` to customize its `_.cloneDeep` use to only clone plain + * objects. + * + * @private + * @param {*} value The value to inspect. + * @param {string} key The key of the property to inspect. + * @returns {*} Returns the uncloned value or `undefined` to defer cloning to `_.cloneDeep`. + */ + function customOmitClone(value) { + return isPlainObject(value) ? undefined : value; + } + + /** + * A specialized version of `baseIsEqualDeep` for arrays with support for + * partial deep comparisons. + * + * @private + * @param {Array} array The array to compare. + * @param {Array} other The other array to compare. + * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. + * @param {Function} customizer The function to customize comparisons. + * @param {Function} equalFunc The function to determine equivalents of values. + * @param {Object} stack Tracks traversed `array` and `other` objects. + * @returns {boolean} Returns `true` if the arrays are equivalent, else `false`. + */ + function equalArrays(array, other, bitmask, customizer, equalFunc, stack) { + var isPartial = bitmask & COMPARE_PARTIAL_FLAG, + arrLength = array.length, + othLength = other.length; + + if (arrLength != othLength && !(isPartial && othLength > arrLength)) { + return false; + } + // Check that cyclic values are equal. + var arrStacked = stack.get(array); + var othStacked = stack.get(other); + if (arrStacked && othStacked) { + return arrStacked == other && othStacked == array; + } + var index = -1, + result = true, + seen = (bitmask & COMPARE_UNORDERED_FLAG) ? new SetCache : undefined; + + stack.set(array, other); + stack.set(other, array); + + // Ignore non-index properties. + while (++index < arrLength) { + var arrValue = array[index], + othValue = other[index]; + + if (customizer) { + var compared = isPartial + ? customizer(othValue, arrValue, index, other, array, stack) + : customizer(arrValue, othValue, index, array, other, stack); + } + if (compared !== undefined) { + if (compared) { + continue; + } + result = false; + break; + } + // Recursively compare arrays (susceptible to call stack limits). + if (seen) { + if (!arraySome(other, function(othValue, othIndex) { + if (!cacheHas(seen, othIndex) && + (arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) { + return seen.push(othIndex); + } + })) { + result = false; + break; + } + } else if (!( + arrValue === othValue || + equalFunc(arrValue, othValue, bitmask, customizer, stack) + )) { + result = false; + break; + } + } + stack['delete'](array); + stack['delete'](other); + return result; + } + + /** + * A specialized version of `baseIsEqualDeep` for comparing objects of + * the same `toStringTag`. + * + * **Note:** This function only supports comparing values with tags of + * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`. + * + * @private + * @param {Object} object The object to compare. + * @param {Object} other The other object to compare. + * @param {string} tag The `toStringTag` of the objects to compare. + * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. + * @param {Function} customizer The function to customize comparisons. + * @param {Function} equalFunc The function to determine equivalents of values. + * @param {Object} stack Tracks traversed `object` and `other` objects. + * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. + */ + function equalByTag(object, other, tag, bitmask, customizer, equalFunc, stack) { + switch (tag) { + case dataViewTag: + if ((object.byteLength != other.byteLength) || + (object.byteOffset != other.byteOffset)) { + return false; + } + object = object.buffer; + other = other.buffer; + + case arrayBufferTag: + if ((object.byteLength != other.byteLength) || + !equalFunc(new Uint8Array(object), new Uint8Array(other))) { + return false; + } + return true; + + case boolTag: + case dateTag: + case numberTag: + // Coerce booleans to `1` or `0` and dates to milliseconds. + // Invalid dates are coerced to `NaN`. + return eq(+object, +other); + + case errorTag: + return object.name == other.name && object.message == other.message; + + case regexpTag: + case stringTag: + // Coerce regexes to strings and treat strings, primitives and objects, + // as equal. See http://www.ecma-international.org/ecma-262/7.0/#sec-regexp.prototype.tostring + // for more details. + return object == (other + ''); + + case mapTag: + var convert = mapToArray; + + case setTag: + var isPartial = bitmask & COMPARE_PARTIAL_FLAG; + convert || (convert = setToArray); + + if (object.size != other.size && !isPartial) { + return false; + } + // Assume cyclic values are equal. + var stacked = stack.get(object); + if (stacked) { + return stacked == other; + } + bitmask |= COMPARE_UNORDERED_FLAG; + + // Recursively compare objects (susceptible to call stack limits). + stack.set(object, other); + var result = equalArrays(convert(object), convert(other), bitmask, customizer, equalFunc, stack); + stack['delete'](object); + return result; + + case symbolTag: + if (symbolValueOf) { + return symbolValueOf.call(object) == symbolValueOf.call(other); + } + } + return false; + } + + /** + * A specialized version of `baseIsEqualDeep` for objects with support for + * partial deep comparisons. + * + * @private + * @param {Object} object The object to compare. + * @param {Object} other The other object to compare. + * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. + * @param {Function} customizer The function to customize comparisons. + * @param {Function} equalFunc The function to determine equivalents of values. + * @param {Object} stack Tracks traversed `object` and `other` objects. + * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. + */ + function equalObjects(object, other, bitmask, customizer, equalFunc, stack) { + var isPartial = bitmask & COMPARE_PARTIAL_FLAG, + objProps = getAllKeys(object), + objLength = objProps.length, + othProps = getAllKeys(other), + othLength = othProps.length; + + if (objLength != othLength && !isPartial) { + return false; + } + var index = objLength; + while (index--) { + var key = objProps[index]; + if (!(isPartial ? key in other : hasOwnProperty.call(other, key))) { + return false; + } + } + // Check that cyclic values are equal. + var objStacked = stack.get(object); + var othStacked = stack.get(other); + if (objStacked && othStacked) { + return objStacked == other && othStacked == object; + } + var result = true; + stack.set(object, other); + stack.set(other, object); + + var skipCtor = isPartial; + while (++index < objLength) { + key = objProps[index]; + var objValue = object[key], + othValue = other[key]; + + if (customizer) { + var compared = isPartial + ? customizer(othValue, objValue, key, other, object, stack) + : customizer(objValue, othValue, key, object, other, stack); + } + // Recursively compare objects (susceptible to call stack limits). + if (!(compared === undefined + ? (objValue === othValue || equalFunc(objValue, othValue, bitmask, customizer, stack)) + : compared + )) { + result = false; + break; + } + skipCtor || (skipCtor = key == 'constructor'); + } + if (result && !skipCtor) { + var objCtor = object.constructor, + othCtor = other.constructor; + + // Non `Object` object instances with different constructors are not equal. + if (objCtor != othCtor && + ('constructor' in object && 'constructor' in other) && + !(typeof objCtor == 'function' && objCtor instanceof objCtor && + typeof othCtor == 'function' && othCtor instanceof othCtor)) { + result = false; + } + } + stack['delete'](object); + stack['delete'](other); + return result; + } + + /** + * A specialized version of `baseRest` which flattens the rest array. + * + * @private + * @param {Function} func The function to apply a rest parameter to. + * @returns {Function} Returns the new function. + */ + function flatRest(func) { + return setToString(overRest(func, undefined, flatten), func + ''); + } + + /** + * Creates an array of own enumerable property names and symbols of `object`. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names and symbols. + */ + function getAllKeys(object) { + return baseGetAllKeys(object, keys, getSymbols); + } + + /** + * Creates an array of own and inherited enumerable property names and + * symbols of `object`. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names and symbols. + */ + function getAllKeysIn(object) { + return baseGetAllKeys(object, keysIn, getSymbolsIn); + } + + /** + * Gets metadata for `func`. + * + * @private + * @param {Function} func The function to query. + * @returns {*} Returns the metadata for `func`. + */ + var getData = !metaMap ? noop : function(func) { + return metaMap.get(func); + }; + + /** + * Gets the name of `func`. + * + * @private + * @param {Function} func The function to query. + * @returns {string} Returns the function name. + */ + function getFuncName(func) { + var result = (func.name + ''), + array = realNames[result], + length = hasOwnProperty.call(realNames, result) ? array.length : 0; + + while (length--) { + var data = array[length], + otherFunc = data.func; + if (otherFunc == null || otherFunc == func) { + return data.name; + } + } + return result; + } + + /** + * Gets the argument placeholder value for `func`. + * + * @private + * @param {Function} func The function to inspect. + * @returns {*} Returns the placeholder value. + */ + function getHolder(func) { + var object = hasOwnProperty.call(lodash, 'placeholder') ? lodash : func; + return object.placeholder; + } + + /** + * Gets the appropriate "iteratee" function. If `_.iteratee` is customized, + * this function returns the custom method, otherwise it returns `baseIteratee`. + * If arguments are provided, the chosen function is invoked with them and + * its result is returned. + * + * @private + * @param {*} [value] The value to convert to an iteratee. + * @param {number} [arity] The arity of the created iteratee. + * @returns {Function} Returns the chosen function or its result. + */ + function getIteratee() { + var result = lodash.iteratee || iteratee; + result = result === iteratee ? baseIteratee : result; + return arguments.length ? result(arguments[0], arguments[1]) : result; + } + + /** + * Gets the data for `map`. + * + * @private + * @param {Object} map The map to query. + * @param {string} key The reference key. + * @returns {*} Returns the map data. + */ + function getMapData(map, key) { + var data = map.__data__; + return isKeyable(key) + ? data[typeof key == 'string' ? 'string' : 'hash'] + : data.map; + } + + /** + * Gets the property names, values, and compare flags of `object`. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the match data of `object`. + */ + function getMatchData(object) { + var result = keys(object), + length = result.length; + + while (length--) { + var key = result[length], + value = object[key]; + + result[length] = [key, value, isStrictComparable(value)]; + } + return result; + } + + /** + * Gets the native function at `key` of `object`. + * + * @private + * @param {Object} object The object to query. + * @param {string} key The key of the method to get. + * @returns {*} Returns the function if it's native, else `undefined`. + */ + function getNative(object, key) { + var value = getValue(object, key); + return baseIsNative(value) ? value : undefined; + } + + /** + * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values. + * + * @private + * @param {*} value The value to query. + * @returns {string} Returns the raw `toStringTag`. + */ + function getRawTag(value) { + var isOwn = hasOwnProperty.call(value, symToStringTag), + tag = value[symToStringTag]; + + try { + value[symToStringTag] = undefined; + var unmasked = true; + } catch (e) {} + + var result = nativeObjectToString.call(value); + if (unmasked) { + if (isOwn) { + value[symToStringTag] = tag; + } else { + delete value[symToStringTag]; + } + } + return result; + } + + /** + * Creates an array of the own enumerable symbols of `object`. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of symbols. + */ + var getSymbols = !nativeGetSymbols ? stubArray : function(object) { + if (object == null) { + return []; + } + object = Object(object); + return arrayFilter(nativeGetSymbols(object), function(symbol) { + return propertyIsEnumerable.call(object, symbol); + }); + }; + + /** + * Creates an array of the own and inherited enumerable symbols of `object`. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of symbols. + */ + var getSymbolsIn = !nativeGetSymbols ? stubArray : function(object) { + var result = []; + while (object) { + arrayPush(result, getSymbols(object)); + object = getPrototype(object); + } + return result; + }; + + /** + * Gets the `toStringTag` of `value`. + * + * @private + * @param {*} value The value to query. + * @returns {string} Returns the `toStringTag`. + */ + var getTag = baseGetTag; + + // Fallback for data views, maps, sets, and weak maps in IE 11 and promises in Node.js < 6. + if ((DataView && getTag(new DataView(new ArrayBuffer(1))) != dataViewTag) || + (Map && getTag(new Map) != mapTag) || + (Promise && getTag(Promise.resolve()) != promiseTag) || + (Set && getTag(new Set) != setTag) || + (WeakMap && getTag(new WeakMap) != weakMapTag)) { + getTag = function(value) { + var result = baseGetTag(value), + Ctor = result == objectTag ? value.constructor : undefined, + ctorString = Ctor ? toSource(Ctor) : ''; + + if (ctorString) { + switch (ctorString) { + case dataViewCtorString: return dataViewTag; + case mapCtorString: return mapTag; + case promiseCtorString: return promiseTag; + case setCtorString: return setTag; + case weakMapCtorString: return weakMapTag; + } + } + return result; + }; + } + + /** + * Gets the view, applying any `transforms` to the `start` and `end` positions. + * + * @private + * @param {number} start The start of the view. + * @param {number} end The end of the view. + * @param {Array} transforms The transformations to apply to the view. + * @returns {Object} Returns an object containing the `start` and `end` + * positions of the view. + */ + function getView(start, end, transforms) { + var index = -1, + length = transforms.length; + + while (++index < length) { + var data = transforms[index], + size = data.size; + + switch (data.type) { + case 'drop': start += size; break; + case 'dropRight': end -= size; break; + case 'take': end = nativeMin(end, start + size); break; + case 'takeRight': start = nativeMax(start, end - size); break; + } + } + return { 'start': start, 'end': end }; + } + + /** + * Extracts wrapper details from the `source` body comment. + * + * @private + * @param {string} source The source to inspect. + * @returns {Array} Returns the wrapper details. + */ + function getWrapDetails(source) { + var match = source.match(reWrapDetails); + return match ? match[1].split(reSplitDetails) : []; + } + + /** + * Checks if `path` exists on `object`. + * + * @private + * @param {Object} object The object to query. + * @param {Array|string} path The path to check. + * @param {Function} hasFunc The function to check properties. + * @returns {boolean} Returns `true` if `path` exists, else `false`. + */ + function hasPath(object, path, hasFunc) { + path = castPath(path, object); + + var index = -1, + length = path.length, + result = false; + + while (++index < length) { + var key = toKey(path[index]); + if (!(result = object != null && hasFunc(object, key))) { + break; + } + object = object[key]; + } + if (result || ++index != length) { + return result; + } + length = object == null ? 0 : object.length; + return !!length && isLength(length) && isIndex(key, length) && + (isArray(object) || isArguments(object)); + } + + /** + * Initializes an array clone. + * + * @private + * @param {Array} array The array to clone. + * @returns {Array} Returns the initialized clone. + */ + function initCloneArray(array) { + var length = array.length, + result = new array.constructor(length); + + // Add properties assigned by `RegExp#exec`. + if (length && typeof array[0] == 'string' && hasOwnProperty.call(array, 'index')) { + result.index = array.index; + result.input = array.input; + } + return result; + } + + /** + * Initializes an object clone. + * + * @private + * @param {Object} object The object to clone. + * @returns {Object} Returns the initialized clone. + */ + function initCloneObject(object) { + return (typeof object.constructor == 'function' && !isPrototype(object)) + ? baseCreate(getPrototype(object)) + : {}; + } + + /** + * Initializes an object clone based on its `toStringTag`. + * + * **Note:** This function only supports cloning values with tags of + * `Boolean`, `Date`, `Error`, `Map`, `Number`, `RegExp`, `Set`, or `String`. + * + * @private + * @param {Object} object The object to clone. + * @param {string} tag The `toStringTag` of the object to clone. + * @param {boolean} [isDeep] Specify a deep clone. + * @returns {Object} Returns the initialized clone. + */ + function initCloneByTag(object, tag, isDeep) { + var Ctor = object.constructor; + switch (tag) { + case arrayBufferTag: + return cloneArrayBuffer(object); + + case boolTag: + case dateTag: + return new Ctor(+object); + + case dataViewTag: + return cloneDataView(object, isDeep); + + case float32Tag: case float64Tag: + case int8Tag: case int16Tag: case int32Tag: + case uint8Tag: case uint8ClampedTag: case uint16Tag: case uint32Tag: + return cloneTypedArray(object, isDeep); + + case mapTag: + return new Ctor; + + case numberTag: + case stringTag: + return new Ctor(object); + + case regexpTag: + return cloneRegExp(object); + + case setTag: + return new Ctor; + + case symbolTag: + return cloneSymbol(object); + } + } + + /** + * Inserts wrapper `details` in a comment at the top of the `source` body. + * + * @private + * @param {string} source The source to modify. + * @returns {Array} details The details to insert. + * @returns {string} Returns the modified source. + */ + function insertWrapDetails(source, details) { + var length = details.length; + if (!length) { + return source; + } + var lastIndex = length - 1; + details[lastIndex] = (length > 1 ? '& ' : '') + details[lastIndex]; + details = details.join(length > 2 ? ', ' : ' '); + return source.replace(reWrapComment, '{\n/* [wrapped with ' + details + '] */\n'); + } + + /** + * Checks if `value` is a flattenable `arguments` object or array. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is flattenable, else `false`. + */ + function isFlattenable(value) { + return isArray(value) || isArguments(value) || + !!(spreadableSymbol && value && value[spreadableSymbol]); + } + + /** + * Checks if `value` is a valid array-like index. + * + * @private + * @param {*} value The value to check. + * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index. + * @returns {boolean} Returns `true` if `value` is a valid index, else `false`. + */ + function isIndex(value, length) { + var type = typeof value; + length = length == null ? MAX_SAFE_INTEGER : length; + + return !!length && + (type == 'number' || + (type != 'symbol' && reIsUint.test(value))) && + (value > -1 && value % 1 == 0 && value < length); + } + + /** + * Checks if the given arguments are from an iteratee call. + * + * @private + * @param {*} value The potential iteratee value argument. + * @param {*} index The potential iteratee index or key argument. + * @param {*} object The potential iteratee object argument. + * @returns {boolean} Returns `true` if the arguments are from an iteratee call, + * else `false`. + */ + function isIterateeCall(value, index, object) { + if (!isObject(object)) { + return false; + } + var type = typeof index; + if (type == 'number' + ? (isArrayLike(object) && isIndex(index, object.length)) + : (type == 'string' && index in object) + ) { + return eq(object[index], value); + } + return false; + } + + /** + * Checks if `value` is a property name and not a property path. + * + * @private + * @param {*} value The value to check. + * @param {Object} [object] The object to query keys on. + * @returns {boolean} Returns `true` if `value` is a property name, else `false`. + */ + function isKey(value, object) { + if (isArray(value)) { + return false; + } + var type = typeof value; + if (type == 'number' || type == 'symbol' || type == 'boolean' || + value == null || isSymbol(value)) { + return true; + } + return reIsPlainProp.test(value) || !reIsDeepProp.test(value) || + (object != null && value in Object(object)); + } + + /** + * Checks if `value` is suitable for use as unique object key. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is suitable, else `false`. + */ + function isKeyable(value) { + var type = typeof value; + return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean') + ? (value !== '__proto__') + : (value === null); + } + + /** + * Checks if `func` has a lazy counterpart. + * + * @private + * @param {Function} func The function to check. + * @returns {boolean} Returns `true` if `func` has a lazy counterpart, + * else `false`. + */ + function isLaziable(func) { + var funcName = getFuncName(func), + other = lodash[funcName]; + + if (typeof other != 'function' || !(funcName in LazyWrapper.prototype)) { + return false; + } + if (func === other) { + return true; + } + var data = getData(other); + return !!data && func === data[0]; + } + + /** + * Checks if `func` has its source masked. + * + * @private + * @param {Function} func The function to check. + * @returns {boolean} Returns `true` if `func` is masked, else `false`. + */ + function isMasked(func) { + return !!maskSrcKey && (maskSrcKey in func); + } + + /** + * Checks if `func` is capable of being masked. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `func` is maskable, else `false`. + */ + var isMaskable = coreJsData ? isFunction : stubFalse; + + /** + * Checks if `value` is likely a prototype object. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a prototype, else `false`. + */ + function isPrototype(value) { + var Ctor = value && value.constructor, + proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto; + + return value === proto; + } + + /** + * Checks if `value` is suitable for strict equality comparisons, i.e. `===`. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` if suitable for strict + * equality comparisons, else `false`. + */ + function isStrictComparable(value) { + return value === value && !isObject(value); + } + + /** + * A specialized version of `matchesProperty` for source values suitable + * for strict equality comparisons, i.e. `===`. + * + * @private + * @param {string} key The key of the property to get. + * @param {*} srcValue The value to match. + * @returns {Function} Returns the new spec function. + */ + function matchesStrictComparable(key, srcValue) { + return function(object) { + if (object == null) { + return false; + } + return object[key] === srcValue && + (srcValue !== undefined || (key in Object(object))); + }; + } + + /** + * A specialized version of `_.memoize` which clears the memoized function's + * cache when it exceeds `MAX_MEMOIZE_SIZE`. + * + * @private + * @param {Function} func The function to have its output memoized. + * @returns {Function} Returns the new memoized function. + */ + function memoizeCapped(func) { + var result = memoize(func, function(key) { + if (cache.size === MAX_MEMOIZE_SIZE) { + cache.clear(); + } + return key; + }); + + var cache = result.cache; + return result; + } + + /** + * Merges the function metadata of `source` into `data`. + * + * Merging metadata reduces the number of wrappers used to invoke a function. + * This is possible because methods like `_.bind`, `_.curry`, and `_.partial` + * may be applied regardless of execution order. Methods like `_.ary` and + * `_.rearg` modify function arguments, making the order in which they are + * executed important, preventing the merging of metadata. However, we make + * an exception for a safe combined case where curried functions have `_.ary` + * and or `_.rearg` applied. + * + * @private + * @param {Array} data The destination metadata. + * @param {Array} source The source metadata. + * @returns {Array} Returns `data`. + */ + function mergeData(data, source) { + var bitmask = data[1], + srcBitmask = source[1], + newBitmask = bitmask | srcBitmask, + isCommon = newBitmask < (WRAP_BIND_FLAG | WRAP_BIND_KEY_FLAG | WRAP_ARY_FLAG); + + var isCombo = + ((srcBitmask == WRAP_ARY_FLAG) && (bitmask == WRAP_CURRY_FLAG)) || + ((srcBitmask == WRAP_ARY_FLAG) && (bitmask == WRAP_REARG_FLAG) && (data[7].length <= source[8])) || + ((srcBitmask == (WRAP_ARY_FLAG | WRAP_REARG_FLAG)) && (source[7].length <= source[8]) && (bitmask == WRAP_CURRY_FLAG)); + + // Exit early if metadata can't be merged. + if (!(isCommon || isCombo)) { + return data; + } + // Use source `thisArg` if available. + if (srcBitmask & WRAP_BIND_FLAG) { + data[2] = source[2]; + // Set when currying a bound function. + newBitmask |= bitmask & WRAP_BIND_FLAG ? 0 : WRAP_CURRY_BOUND_FLAG; + } + // Compose partial arguments. + var value = source[3]; + if (value) { + var partials = data[3]; + data[3] = partials ? composeArgs(partials, value, source[4]) : value; + data[4] = partials ? replaceHolders(data[3], PLACEHOLDER) : source[4]; + } + // Compose partial right arguments. + value = source[5]; + if (value) { + partials = data[5]; + data[5] = partials ? composeArgsRight(partials, value, source[6]) : value; + data[6] = partials ? replaceHolders(data[5], PLACEHOLDER) : source[6]; + } + // Use source `argPos` if available. + value = source[7]; + if (value) { + data[7] = value; + } + // Use source `ary` if it's smaller. + if (srcBitmask & WRAP_ARY_FLAG) { + data[8] = data[8] == null ? source[8] : nativeMin(data[8], source[8]); + } + // Use source `arity` if one is not provided. + if (data[9] == null) { + data[9] = source[9]; + } + // Use source `func` and merge bitmasks. + data[0] = source[0]; + data[1] = newBitmask; + + return data; + } + + /** + * This function is like + * [`Object.keys`](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) + * except that it includes inherited enumerable properties. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names. + */ + function nativeKeysIn(object) { + var result = []; + if (object != null) { + for (var key in Object(object)) { + result.push(key); + } + } + return result; + } + + /** + * Converts `value` to a string using `Object.prototype.toString`. + * + * @private + * @param {*} value The value to convert. + * @returns {string} Returns the converted string. + */ + function objectToString(value) { + return nativeObjectToString.call(value); + } + + /** + * A specialized version of `baseRest` which transforms the rest array. + * + * @private + * @param {Function} func The function to apply a rest parameter to. + * @param {number} [start=func.length-1] The start position of the rest parameter. + * @param {Function} transform The rest array transform. + * @returns {Function} Returns the new function. + */ + function overRest(func, start, transform) { + start = nativeMax(start === undefined ? (func.length - 1) : start, 0); + return function() { + var args = arguments, + index = -1, + length = nativeMax(args.length - start, 0), + array = Array(length); + + while (++index < length) { + array[index] = args[start + index]; + } + index = -1; + var otherArgs = Array(start + 1); + while (++index < start) { + otherArgs[index] = args[index]; + } + otherArgs[start] = transform(array); + return apply(func, this, otherArgs); + }; + } + + /** + * Gets the parent value at `path` of `object`. + * + * @private + * @param {Object} object The object to query. + * @param {Array} path The path to get the parent value of. + * @returns {*} Returns the parent value. + */ + function parent(object, path) { + return path.length < 2 ? object : baseGet(object, baseSlice(path, 0, -1)); + } + + /** + * Reorder `array` according to the specified indexes where the element at + * the first index is assigned as the first element, the element at + * the second index is assigned as the second element, and so on. + * + * @private + * @param {Array} array The array to reorder. + * @param {Array} indexes The arranged array indexes. + * @returns {Array} Returns `array`. + */ + function reorder(array, indexes) { + var arrLength = array.length, + length = nativeMin(indexes.length, arrLength), + oldArray = copyArray(array); + + while (length--) { + var index = indexes[length]; + array[length] = isIndex(index, arrLength) ? oldArray[index] : undefined; + } + return array; + } + + /** + * Gets the value at `key`, unless `key` is "__proto__" or "constructor". + * + * @private + * @param {Object} object The object to query. + * @param {string} key The key of the property to get. + * @returns {*} Returns the property value. + */ + function safeGet(object, key) { + if (key === 'constructor' && typeof object[key] === 'function') { + return; + } + + if (key == '__proto__') { + return; + } + + return object[key]; + } + + /** + * Sets metadata for `func`. + * + * **Note:** If this function becomes hot, i.e. is invoked a lot in a short + * period of time, it will trip its breaker and transition to an identity + * function to avoid garbage collection pauses in V8. See + * [V8 issue 2070](https://bugs.chromium.org/p/v8/issues/detail?id=2070) + * for more details. + * + * @private + * @param {Function} func The function to associate metadata with. + * @param {*} data The metadata. + * @returns {Function} Returns `func`. + */ + var setData = shortOut(baseSetData); + + /** + * A simple wrapper around the global [`setTimeout`](https://mdn.io/setTimeout). + * + * @private + * @param {Function} func The function to delay. + * @param {number} wait The number of milliseconds to delay invocation. + * @returns {number|Object} Returns the timer id or timeout object. + */ + var setTimeout = ctxSetTimeout || function(func, wait) { + return root.setTimeout(func, wait); + }; + + /** + * Sets the `toString` method of `func` to return `string`. + * + * @private + * @param {Function} func The function to modify. + * @param {Function} string The `toString` result. + * @returns {Function} Returns `func`. + */ + var setToString = shortOut(baseSetToString); + + /** + * Sets the `toString` method of `wrapper` to mimic the source of `reference` + * with wrapper details in a comment at the top of the source body. + * + * @private + * @param {Function} wrapper The function to modify. + * @param {Function} reference The reference function. + * @param {number} bitmask The bitmask flags. See `createWrap` for more details. + * @returns {Function} Returns `wrapper`. + */ + function setWrapToString(wrapper, reference, bitmask) { + var source = (reference + ''); + return setToString(wrapper, insertWrapDetails(source, updateWrapDetails(getWrapDetails(source), bitmask))); + } + + /** + * Creates a function that'll short out and invoke `identity` instead + * of `func` when it's called `HOT_COUNT` or more times in `HOT_SPAN` + * milliseconds. + * + * @private + * @param {Function} func The function to restrict. + * @returns {Function} Returns the new shortable function. + */ + function shortOut(func) { + var count = 0, + lastCalled = 0; + + return function() { + var stamp = nativeNow(), + remaining = HOT_SPAN - (stamp - lastCalled); + + lastCalled = stamp; + if (remaining > 0) { + if (++count >= HOT_COUNT) { + return arguments[0]; + } + } else { + count = 0; + } + return func.apply(undefined, arguments); + }; + } + + /** + * A specialized version of `_.shuffle` which mutates and sets the size of `array`. + * + * @private + * @param {Array} array The array to shuffle. + * @param {number} [size=array.length] The size of `array`. + * @returns {Array} Returns `array`. + */ + function shuffleSelf(array, size) { + var index = -1, + length = array.length, + lastIndex = length - 1; + + size = size === undefined ? length : size; + while (++index < size) { + var rand = baseRandom(index, lastIndex), + value = array[rand]; + + array[rand] = array[index]; + array[index] = value; + } + array.length = size; + return array; + } + + /** + * Converts `string` to a property path array. + * + * @private + * @param {string} string The string to convert. + * @returns {Array} Returns the property path array. + */ + var stringToPath = memoizeCapped(function(string) { + var result = []; + if (string.charCodeAt(0) === 46 /* . */) { + result.push(''); + } + string.replace(rePropName, function(match, number, quote, subString) { + result.push(quote ? subString.replace(reEscapeChar, '$1') : (number || match)); + }); + return result; + }); + + /** + * Converts `value` to a string key if it's not a string or symbol. + * + * @private + * @param {*} value The value to inspect. + * @returns {string|symbol} Returns the key. + */ + function toKey(value) { + if (typeof value == 'string' || isSymbol(value)) { + return value; + } + var result = (value + ''); + return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result; + } + + /** + * Converts `func` to its source code. + * + * @private + * @param {Function} func The function to convert. + * @returns {string} Returns the source code. + */ + function toSource(func) { + if (func != null) { + try { + return funcToString.call(func); + } catch (e) {} + try { + return (func + ''); + } catch (e) {} + } + return ''; + } + + /** + * Updates wrapper `details` based on `bitmask` flags. + * + * @private + * @returns {Array} details The details to modify. + * @param {number} bitmask The bitmask flags. See `createWrap` for more details. + * @returns {Array} Returns `details`. + */ + function updateWrapDetails(details, bitmask) { + arrayEach(wrapFlags, function(pair) { + var value = '_.' + pair[0]; + if ((bitmask & pair[1]) && !arrayIncludes(details, value)) { + details.push(value); + } + }); + return details.sort(); + } + + /** + * Creates a clone of `wrapper`. + * + * @private + * @param {Object} wrapper The wrapper to clone. + * @returns {Object} Returns the cloned wrapper. + */ + function wrapperClone(wrapper) { + if (wrapper instanceof LazyWrapper) { + return wrapper.clone(); + } + var result = new LodashWrapper(wrapper.__wrapped__, wrapper.__chain__); + result.__actions__ = copyArray(wrapper.__actions__); + result.__index__ = wrapper.__index__; + result.__values__ = wrapper.__values__; + return result; + } + + /*------------------------------------------------------------------------*/ + + /** + * Creates an array of elements split into groups the length of `size`. + * If `array` can't be split evenly, the final chunk will be the remaining + * elements. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Array + * @param {Array} array The array to process. + * @param {number} [size=1] The length of each chunk + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {Array} Returns the new array of chunks. + * @example + * + * _.chunk(['a', 'b', 'c', 'd'], 2); + * // => [['a', 'b'], ['c', 'd']] + * + * _.chunk(['a', 'b', 'c', 'd'], 3); + * // => [['a', 'b', 'c'], ['d']] + */ + function chunk(array, size, guard) { + if ((guard ? isIterateeCall(array, size, guard) : size === undefined)) { + size = 1; + } else { + size = nativeMax(toInteger(size), 0); + } + var length = array == null ? 0 : array.length; + if (!length || size < 1) { + return []; + } + var index = 0, + resIndex = 0, + result = Array(nativeCeil(length / size)); + + while (index < length) { + result[resIndex++] = baseSlice(array, index, (index += size)); + } + return result; + } + + /** + * Creates an array with all falsey values removed. The values `false`, `null`, + * `0`, `""`, `undefined`, and `NaN` are falsey. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {Array} array The array to compact. + * @returns {Array} Returns the new array of filtered values. + * @example + * + * _.compact([0, 1, false, 2, '', 3]); + * // => [1, 2, 3] + */ + function compact(array) { + var index = -1, + length = array == null ? 0 : array.length, + resIndex = 0, + result = []; + + while (++index < length) { + var value = array[index]; + if (value) { + result[resIndex++] = value; + } + } + return result; + } + + /** + * Creates a new array concatenating `array` with any additional arrays + * and/or values. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The array to concatenate. + * @param {...*} [values] The values to concatenate. + * @returns {Array} Returns the new concatenated array. + * @example + * + * var array = [1]; + * var other = _.concat(array, 2, [3], [[4]]); + * + * console.log(other); + * // => [1, 2, 3, [4]] + * + * console.log(array); + * // => [1] + */ + function concat() { + var length = arguments.length; + if (!length) { + return []; + } + var args = Array(length - 1), + array = arguments[0], + index = length; + + while (index--) { + args[index - 1] = arguments[index]; + } + return arrayPush(isArray(array) ? copyArray(array) : [array], baseFlatten(args, 1)); + } + + /** + * Creates an array of `array` values not included in the other given arrays + * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * for equality comparisons. The order and references of result values are + * determined by the first array. + * + * **Note:** Unlike `_.pullAll`, this method returns a new array. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {...Array} [values] The values to exclude. + * @returns {Array} Returns the new array of filtered values. + * @see _.without, _.xor + * @example + * + * _.difference([2, 1], [2, 3]); + * // => [1] + */ + var difference = baseRest(function(array, values) { + return isArrayLikeObject(array) + ? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true)) + : []; + }); + + /** + * This method is like `_.difference` except that it accepts `iteratee` which + * is invoked for each element of `array` and `values` to generate the criterion + * by which they're compared. The order and references of result values are + * determined by the first array. The iteratee is invoked with one argument: + * (value). + * + * **Note:** Unlike `_.pullAllBy`, this method returns a new array. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {...Array} [values] The values to exclude. + * @param {Function} [iteratee=_.identity] The iteratee invoked per element. + * @returns {Array} Returns the new array of filtered values. + * @example + * + * _.differenceBy([2.1, 1.2], [2.3, 3.4], Math.floor); + * // => [1.2] + * + * // The `_.property` iteratee shorthand. + * _.differenceBy([{ 'x': 2 }, { 'x': 1 }], [{ 'x': 1 }], 'x'); + * // => [{ 'x': 2 }] + */ + var differenceBy = baseRest(function(array, values) { + var iteratee = last(values); + if (isArrayLikeObject(iteratee)) { + iteratee = undefined; + } + return isArrayLikeObject(array) + ? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true), getIteratee(iteratee, 2)) + : []; + }); + + /** + * This method is like `_.difference` except that it accepts `comparator` + * which is invoked to compare elements of `array` to `values`. The order and + * references of result values are determined by the first array. The comparator + * is invoked with two arguments: (arrVal, othVal). + * + * **Note:** Unlike `_.pullAllWith`, this method returns a new array. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {...Array} [values] The values to exclude. + * @param {Function} [comparator] The comparator invoked per element. + * @returns {Array} Returns the new array of filtered values. + * @example + * + * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]; + * + * _.differenceWith(objects, [{ 'x': 1, 'y': 2 }], _.isEqual); + * // => [{ 'x': 2, 'y': 1 }] + */ + var differenceWith = baseRest(function(array, values) { + var comparator = last(values); + if (isArrayLikeObject(comparator)) { + comparator = undefined; + } + return isArrayLikeObject(array) + ? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true), undefined, comparator) + : []; + }); + + /** + * Creates a slice of `array` with `n` elements dropped from the beginning. + * + * @static + * @memberOf _ + * @since 0.5.0 + * @category Array + * @param {Array} array The array to query. + * @param {number} [n=1] The number of elements to drop. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {Array} Returns the slice of `array`. + * @example + * + * _.drop([1, 2, 3]); + * // => [2, 3] + * + * _.drop([1, 2, 3], 2); + * // => [3] + * + * _.drop([1, 2, 3], 5); + * // => [] + * + * _.drop([1, 2, 3], 0); + * // => [1, 2, 3] + */ + function drop(array, n, guard) { + var length = array == null ? 0 : array.length; + if (!length) { + return []; + } + n = (guard || n === undefined) ? 1 : toInteger(n); + return baseSlice(array, n < 0 ? 0 : n, length); + } + + /** + * Creates a slice of `array` with `n` elements dropped from the end. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Array + * @param {Array} array The array to query. + * @param {number} [n=1] The number of elements to drop. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {Array} Returns the slice of `array`. + * @example + * + * _.dropRight([1, 2, 3]); + * // => [1, 2] + * + * _.dropRight([1, 2, 3], 2); + * // => [1] + * + * _.dropRight([1, 2, 3], 5); + * // => [] + * + * _.dropRight([1, 2, 3], 0); + * // => [1, 2, 3] + */ + function dropRight(array, n, guard) { + var length = array == null ? 0 : array.length; + if (!length) { + return []; + } + n = (guard || n === undefined) ? 1 : toInteger(n); + n = length - n; + return baseSlice(array, 0, n < 0 ? 0 : n); + } + + /** + * Creates a slice of `array` excluding elements dropped from the end. + * Elements are dropped until `predicate` returns falsey. The predicate is + * invoked with three arguments: (value, index, array). + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Array + * @param {Array} array The array to query. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @returns {Array} Returns the slice of `array`. + * @example + * + * var users = [ + * { 'user': 'barney', 'active': true }, + * { 'user': 'fred', 'active': false }, + * { 'user': 'pebbles', 'active': false } + * ]; + * + * _.dropRightWhile(users, function(o) { return !o.active; }); + * // => objects for ['barney'] + * + * // The `_.matches` iteratee shorthand. + * _.dropRightWhile(users, { 'user': 'pebbles', 'active': false }); + * // => objects for ['barney', 'fred'] + * + * // The `_.matchesProperty` iteratee shorthand. + * _.dropRightWhile(users, ['active', false]); + * // => objects for ['barney'] + * + * // The `_.property` iteratee shorthand. + * _.dropRightWhile(users, 'active'); + * // => objects for ['barney', 'fred', 'pebbles'] + */ + function dropRightWhile(array, predicate) { + return (array && array.length) + ? baseWhile(array, getIteratee(predicate, 3), true, true) + : []; + } + + /** + * Creates a slice of `array` excluding elements dropped from the beginning. + * Elements are dropped until `predicate` returns falsey. The predicate is + * invoked with three arguments: (value, index, array). + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Array + * @param {Array} array The array to query. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @returns {Array} Returns the slice of `array`. + * @example + * + * var users = [ + * { 'user': 'barney', 'active': false }, + * { 'user': 'fred', 'active': false }, + * { 'user': 'pebbles', 'active': true } + * ]; + * + * _.dropWhile(users, function(o) { return !o.active; }); + * // => objects for ['pebbles'] + * + * // The `_.matches` iteratee shorthand. + * _.dropWhile(users, { 'user': 'barney', 'active': false }); + * // => objects for ['fred', 'pebbles'] + * + * // The `_.matchesProperty` iteratee shorthand. + * _.dropWhile(users, ['active', false]); + * // => objects for ['pebbles'] + * + * // The `_.property` iteratee shorthand. + * _.dropWhile(users, 'active'); + * // => objects for ['barney', 'fred', 'pebbles'] + */ + function dropWhile(array, predicate) { + return (array && array.length) + ? baseWhile(array, getIteratee(predicate, 3), true) + : []; + } + + /** + * Fills elements of `array` with `value` from `start` up to, but not + * including, `end`. + * + * **Note:** This method mutates `array`. + * + * @static + * @memberOf _ + * @since 3.2.0 + * @category Array + * @param {Array} array The array to fill. + * @param {*} value The value to fill `array` with. + * @param {number} [start=0] The start position. + * @param {number} [end=array.length] The end position. + * @returns {Array} Returns `array`. + * @example + * + * var array = [1, 2, 3]; + * + * _.fill(array, 'a'); + * console.log(array); + * // => ['a', 'a', 'a'] + * + * _.fill(Array(3), 2); + * // => [2, 2, 2] + * + * _.fill([4, 6, 8, 10], '*', 1, 3); + * // => [4, '*', '*', 10] + */ + function fill(array, value, start, end) { + var length = array == null ? 0 : array.length; + if (!length) { + return []; + } + if (start && typeof start != 'number' && isIterateeCall(array, value, start)) { + start = 0; + end = length; + } + return baseFill(array, value, start, end); + } + + /** + * This method is like `_.find` except that it returns the index of the first + * element `predicate` returns truthy for instead of the element itself. + * + * @static + * @memberOf _ + * @since 1.1.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @param {number} [fromIndex=0] The index to search from. + * @returns {number} Returns the index of the found element, else `-1`. + * @example + * + * var users = [ + * { 'user': 'barney', 'active': false }, + * { 'user': 'fred', 'active': false }, + * { 'user': 'pebbles', 'active': true } + * ]; + * + * _.findIndex(users, function(o) { return o.user == 'barney'; }); + * // => 0 + * + * // The `_.matches` iteratee shorthand. + * _.findIndex(users, { 'user': 'fred', 'active': false }); + * // => 1 + * + * // The `_.matchesProperty` iteratee shorthand. + * _.findIndex(users, ['active', false]); + * // => 0 + * + * // The `_.property` iteratee shorthand. + * _.findIndex(users, 'active'); + * // => 2 + */ + function findIndex(array, predicate, fromIndex) { + var length = array == null ? 0 : array.length; + if (!length) { + return -1; + } + var index = fromIndex == null ? 0 : toInteger(fromIndex); + if (index < 0) { + index = nativeMax(length + index, 0); + } + return baseFindIndex(array, getIteratee(predicate, 3), index); + } + + /** + * This method is like `_.findIndex` except that it iterates over elements + * of `collection` from right to left. + * + * @static + * @memberOf _ + * @since 2.0.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @param {number} [fromIndex=array.length-1] The index to search from. + * @returns {number} Returns the index of the found element, else `-1`. + * @example + * + * var users = [ + * { 'user': 'barney', 'active': true }, + * { 'user': 'fred', 'active': false }, + * { 'user': 'pebbles', 'active': false } + * ]; + * + * _.findLastIndex(users, function(o) { return o.user == 'pebbles'; }); + * // => 2 + * + * // The `_.matches` iteratee shorthand. + * _.findLastIndex(users, { 'user': 'barney', 'active': true }); + * // => 0 + * + * // The `_.matchesProperty` iteratee shorthand. + * _.findLastIndex(users, ['active', false]); + * // => 2 + * + * // The `_.property` iteratee shorthand. + * _.findLastIndex(users, 'active'); + * // => 0 + */ + function findLastIndex(array, predicate, fromIndex) { + var length = array == null ? 0 : array.length; + if (!length) { + return -1; + } + var index = length - 1; + if (fromIndex !== undefined) { + index = toInteger(fromIndex); + index = fromIndex < 0 + ? nativeMax(length + index, 0) + : nativeMin(index, length - 1); + } + return baseFindIndex(array, getIteratee(predicate, 3), index, true); + } + + /** + * Flattens `array` a single level deep. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {Array} array The array to flatten. + * @returns {Array} Returns the new flattened array. + * @example + * + * _.flatten([1, [2, [3, [4]], 5]]); + * // => [1, 2, [3, [4]], 5] + */ + function flatten(array) { + var length = array == null ? 0 : array.length; + return length ? baseFlatten(array, 1) : []; + } + + /** + * Recursively flattens `array`. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Array + * @param {Array} array The array to flatten. + * @returns {Array} Returns the new flattened array. + * @example + * + * _.flattenDeep([1, [2, [3, [4]], 5]]); + * // => [1, 2, 3, 4, 5] + */ + function flattenDeep(array) { + var length = array == null ? 0 : array.length; + return length ? baseFlatten(array, INFINITY) : []; + } + + /** + * Recursively flatten `array` up to `depth` times. + * + * @static + * @memberOf _ + * @since 4.4.0 + * @category Array + * @param {Array} array The array to flatten. + * @param {number} [depth=1] The maximum recursion depth. + * @returns {Array} Returns the new flattened array. + * @example + * + * var array = [1, [2, [3, [4]], 5]]; + * + * _.flattenDepth(array, 1); + * // => [1, 2, [3, [4]], 5] + * + * _.flattenDepth(array, 2); + * // => [1, 2, 3, [4], 5] + */ + function flattenDepth(array, depth) { + var length = array == null ? 0 : array.length; + if (!length) { + return []; + } + depth = depth === undefined ? 1 : toInteger(depth); + return baseFlatten(array, depth); + } + + /** + * The inverse of `_.toPairs`; this method returns an object composed + * from key-value `pairs`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} pairs The key-value pairs. + * @returns {Object} Returns the new object. + * @example + * + * _.fromPairs([['a', 1], ['b', 2]]); + * // => { 'a': 1, 'b': 2 } + */ + function fromPairs(pairs) { + var index = -1, + length = pairs == null ? 0 : pairs.length, + result = {}; + + while (++index < length) { + var pair = pairs[index]; + result[pair[0]] = pair[1]; + } + return result; + } + + /** + * Gets the first element of `array`. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @alias first + * @category Array + * @param {Array} array The array to query. + * @returns {*} Returns the first element of `array`. + * @example + * + * _.head([1, 2, 3]); + * // => 1 + * + * _.head([]); + * // => undefined + */ + function head(array) { + return (array && array.length) ? array[0] : undefined; + } + + /** + * Gets the index at which the first occurrence of `value` is found in `array` + * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * for equality comparisons. If `fromIndex` is negative, it's used as the + * offset from the end of `array`. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {*} value The value to search for. + * @param {number} [fromIndex=0] The index to search from. + * @returns {number} Returns the index of the matched value, else `-1`. + * @example + * + * _.indexOf([1, 2, 1, 2], 2); + * // => 1 + * + * // Search from the `fromIndex`. + * _.indexOf([1, 2, 1, 2], 2, 2); + * // => 3 + */ + function indexOf(array, value, fromIndex) { + var length = array == null ? 0 : array.length; + if (!length) { + return -1; + } + var index = fromIndex == null ? 0 : toInteger(fromIndex); + if (index < 0) { + index = nativeMax(length + index, 0); + } + return baseIndexOf(array, value, index); + } + + /** + * Gets all but the last element of `array`. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {Array} array The array to query. + * @returns {Array} Returns the slice of `array`. + * @example + * + * _.initial([1, 2, 3]); + * // => [1, 2] + */ + function initial(array) { + var length = array == null ? 0 : array.length; + return length ? baseSlice(array, 0, -1) : []; + } + + /** + * Creates an array of unique values that are included in all given arrays + * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * for equality comparisons. The order and references of result values are + * determined by the first array. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {...Array} [arrays] The arrays to inspect. + * @returns {Array} Returns the new array of intersecting values. + * @example + * + * _.intersection([2, 1], [2, 3]); + * // => [2] + */ + var intersection = baseRest(function(arrays) { + var mapped = arrayMap(arrays, castArrayLikeObject); + return (mapped.length && mapped[0] === arrays[0]) + ? baseIntersection(mapped) + : []; + }); + + /** + * This method is like `_.intersection` except that it accepts `iteratee` + * which is invoked for each element of each `arrays` to generate the criterion + * by which they're compared. The order and references of result values are + * determined by the first array. The iteratee is invoked with one argument: + * (value). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {...Array} [arrays] The arrays to inspect. + * @param {Function} [iteratee=_.identity] The iteratee invoked per element. + * @returns {Array} Returns the new array of intersecting values. + * @example + * + * _.intersectionBy([2.1, 1.2], [2.3, 3.4], Math.floor); + * // => [2.1] + * + * // The `_.property` iteratee shorthand. + * _.intersectionBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x'); + * // => [{ 'x': 1 }] + */ + var intersectionBy = baseRest(function(arrays) { + var iteratee = last(arrays), + mapped = arrayMap(arrays, castArrayLikeObject); + + if (iteratee === last(mapped)) { + iteratee = undefined; + } else { + mapped.pop(); + } + return (mapped.length && mapped[0] === arrays[0]) + ? baseIntersection(mapped, getIteratee(iteratee, 2)) + : []; + }); + + /** + * This method is like `_.intersection` except that it accepts `comparator` + * which is invoked to compare elements of `arrays`. The order and references + * of result values are determined by the first array. The comparator is + * invoked with two arguments: (arrVal, othVal). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {...Array} [arrays] The arrays to inspect. + * @param {Function} [comparator] The comparator invoked per element. + * @returns {Array} Returns the new array of intersecting values. + * @example + * + * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]; + * var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }]; + * + * _.intersectionWith(objects, others, _.isEqual); + * // => [{ 'x': 1, 'y': 2 }] + */ + var intersectionWith = baseRest(function(arrays) { + var comparator = last(arrays), + mapped = arrayMap(arrays, castArrayLikeObject); + + comparator = typeof comparator == 'function' ? comparator : undefined; + if (comparator) { + mapped.pop(); + } + return (mapped.length && mapped[0] === arrays[0]) + ? baseIntersection(mapped, undefined, comparator) + : []; + }); + + /** + * Converts all elements in `array` into a string separated by `separator`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The array to convert. + * @param {string} [separator=','] The element separator. + * @returns {string} Returns the joined string. + * @example + * + * _.join(['a', 'b', 'c'], '~'); + * // => 'a~b~c' + */ + function join(array, separator) { + return array == null ? '' : nativeJoin.call(array, separator); + } + + /** + * Gets the last element of `array`. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {Array} array The array to query. + * @returns {*} Returns the last element of `array`. + * @example + * + * _.last([1, 2, 3]); + * // => 3 + */ + function last(array) { + var length = array == null ? 0 : array.length; + return length ? array[length - 1] : undefined; + } + + /** + * This method is like `_.indexOf` except that it iterates over elements of + * `array` from right to left. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {*} value The value to search for. + * @param {number} [fromIndex=array.length-1] The index to search from. + * @returns {number} Returns the index of the matched value, else `-1`. + * @example + * + * _.lastIndexOf([1, 2, 1, 2], 2); + * // => 3 + * + * // Search from the `fromIndex`. + * _.lastIndexOf([1, 2, 1, 2], 2, 2); + * // => 1 + */ + function lastIndexOf(array, value, fromIndex) { + var length = array == null ? 0 : array.length; + if (!length) { + return -1; + } + var index = length; + if (fromIndex !== undefined) { + index = toInteger(fromIndex); + index = index < 0 ? nativeMax(length + index, 0) : nativeMin(index, length - 1); + } + return value === value + ? strictLastIndexOf(array, value, index) + : baseFindIndex(array, baseIsNaN, index, true); + } + + /** + * Gets the element at index `n` of `array`. If `n` is negative, the nth + * element from the end is returned. + * + * @static + * @memberOf _ + * @since 4.11.0 + * @category Array + * @param {Array} array The array to query. + * @param {number} [n=0] The index of the element to return. + * @returns {*} Returns the nth element of `array`. + * @example + * + * var array = ['a', 'b', 'c', 'd']; + * + * _.nth(array, 1); + * // => 'b' + * + * _.nth(array, -2); + * // => 'c'; + */ + function nth(array, n) { + return (array && array.length) ? baseNth(array, toInteger(n)) : undefined; + } + + /** + * Removes all given values from `array` using + * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * for equality comparisons. + * + * **Note:** Unlike `_.without`, this method mutates `array`. Use `_.remove` + * to remove elements from an array by predicate. + * + * @static + * @memberOf _ + * @since 2.0.0 + * @category Array + * @param {Array} array The array to modify. + * @param {...*} [values] The values to remove. + * @returns {Array} Returns `array`. + * @example + * + * var array = ['a', 'b', 'c', 'a', 'b', 'c']; + * + * _.pull(array, 'a', 'c'); + * console.log(array); + * // => ['b', 'b'] + */ + var pull = baseRest(pullAll); + + /** + * This method is like `_.pull` except that it accepts an array of values to remove. + * + * **Note:** Unlike `_.difference`, this method mutates `array`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The array to modify. + * @param {Array} values The values to remove. + * @returns {Array} Returns `array`. + * @example + * + * var array = ['a', 'b', 'c', 'a', 'b', 'c']; + * + * _.pullAll(array, ['a', 'c']); + * console.log(array); + * // => ['b', 'b'] + */ + function pullAll(array, values) { + return (array && array.length && values && values.length) + ? basePullAll(array, values) + : array; + } + + /** + * This method is like `_.pullAll` except that it accepts `iteratee` which is + * invoked for each element of `array` and `values` to generate the criterion + * by which they're compared. The iteratee is invoked with one argument: (value). + * + * **Note:** Unlike `_.differenceBy`, this method mutates `array`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The array to modify. + * @param {Array} values The values to remove. + * @param {Function} [iteratee=_.identity] The iteratee invoked per element. + * @returns {Array} Returns `array`. + * @example + * + * var array = [{ 'x': 1 }, { 'x': 2 }, { 'x': 3 }, { 'x': 1 }]; + * + * _.pullAllBy(array, [{ 'x': 1 }, { 'x': 3 }], 'x'); + * console.log(array); + * // => [{ 'x': 2 }] + */ + function pullAllBy(array, values, iteratee) { + return (array && array.length && values && values.length) + ? basePullAll(array, values, getIteratee(iteratee, 2)) + : array; + } + + /** + * This method is like `_.pullAll` except that it accepts `comparator` which + * is invoked to compare elements of `array` to `values`. The comparator is + * invoked with two arguments: (arrVal, othVal). + * + * **Note:** Unlike `_.differenceWith`, this method mutates `array`. + * + * @static + * @memberOf _ + * @since 4.6.0 + * @category Array + * @param {Array} array The array to modify. + * @param {Array} values The values to remove. + * @param {Function} [comparator] The comparator invoked per element. + * @returns {Array} Returns `array`. + * @example + * + * var array = [{ 'x': 1, 'y': 2 }, { 'x': 3, 'y': 4 }, { 'x': 5, 'y': 6 }]; + * + * _.pullAllWith(array, [{ 'x': 3, 'y': 4 }], _.isEqual); + * console.log(array); + * // => [{ 'x': 1, 'y': 2 }, { 'x': 5, 'y': 6 }] + */ + function pullAllWith(array, values, comparator) { + return (array && array.length && values && values.length) + ? basePullAll(array, values, undefined, comparator) + : array; + } + + /** + * Removes elements from `array` corresponding to `indexes` and returns an + * array of removed elements. + * + * **Note:** Unlike `_.at`, this method mutates `array`. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Array + * @param {Array} array The array to modify. + * @param {...(number|number[])} [indexes] The indexes of elements to remove. + * @returns {Array} Returns the new array of removed elements. + * @example + * + * var array = ['a', 'b', 'c', 'd']; + * var pulled = _.pullAt(array, [1, 3]); + * + * console.log(array); + * // => ['a', 'c'] + * + * console.log(pulled); + * // => ['b', 'd'] + */ + var pullAt = flatRest(function(array, indexes) { + var length = array == null ? 0 : array.length, + result = baseAt(array, indexes); + + basePullAt(array, arrayMap(indexes, function(index) { + return isIndex(index, length) ? +index : index; + }).sort(compareAscending)); + + return result; + }); + + /** + * Removes all elements from `array` that `predicate` returns truthy for + * and returns an array of the removed elements. The predicate is invoked + * with three arguments: (value, index, array). + * + * **Note:** Unlike `_.filter`, this method mutates `array`. Use `_.pull` + * to pull elements from an array by value. + * + * @static + * @memberOf _ + * @since 2.0.0 + * @category Array + * @param {Array} array The array to modify. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @returns {Array} Returns the new array of removed elements. + * @example + * + * var array = [1, 2, 3, 4]; + * var evens = _.remove(array, function(n) { + * return n % 2 == 0; + * }); + * + * console.log(array); + * // => [1, 3] + * + * console.log(evens); + * // => [2, 4] + */ + function remove(array, predicate) { + var result = []; + if (!(array && array.length)) { + return result; + } + var index = -1, + indexes = [], + length = array.length; + + predicate = getIteratee(predicate, 3); + while (++index < length) { + var value = array[index]; + if (predicate(value, index, array)) { + result.push(value); + indexes.push(index); + } + } + basePullAt(array, indexes); + return result; + } + + /** + * Reverses `array` so that the first element becomes the last, the second + * element becomes the second to last, and so on. + * + * **Note:** This method mutates `array` and is based on + * [`Array#reverse`](https://mdn.io/Array/reverse). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The array to modify. + * @returns {Array} Returns `array`. + * @example + * + * var array = [1, 2, 3]; + * + * _.reverse(array); + * // => [3, 2, 1] + * + * console.log(array); + * // => [3, 2, 1] + */ + function reverse(array) { + return array == null ? array : nativeReverse.call(array); + } + + /** + * Creates a slice of `array` from `start` up to, but not including, `end`. + * + * **Note:** This method is used instead of + * [`Array#slice`](https://mdn.io/Array/slice) to ensure dense arrays are + * returned. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Array + * @param {Array} array The array to slice. + * @param {number} [start=0] The start position. + * @param {number} [end=array.length] The end position. + * @returns {Array} Returns the slice of `array`. + */ + function slice(array, start, end) { + var length = array == null ? 0 : array.length; + if (!length) { + return []; + } + if (end && typeof end != 'number' && isIterateeCall(array, start, end)) { + start = 0; + end = length; + } + else { + start = start == null ? 0 : toInteger(start); + end = end === undefined ? length : toInteger(end); + } + return baseSlice(array, start, end); + } + + /** + * Uses a binary search to determine the lowest index at which `value` + * should be inserted into `array` in order to maintain its sort order. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {Array} array The sorted array to inspect. + * @param {*} value The value to evaluate. + * @returns {number} Returns the index at which `value` should be inserted + * into `array`. + * @example + * + * _.sortedIndex([30, 50], 40); + * // => 1 + */ + function sortedIndex(array, value) { + return baseSortedIndex(array, value); + } + + /** + * This method is like `_.sortedIndex` except that it accepts `iteratee` + * which is invoked for `value` and each element of `array` to compute their + * sort ranking. The iteratee is invoked with one argument: (value). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The sorted array to inspect. + * @param {*} value The value to evaluate. + * @param {Function} [iteratee=_.identity] The iteratee invoked per element. + * @returns {number} Returns the index at which `value` should be inserted + * into `array`. + * @example + * + * var objects = [{ 'x': 4 }, { 'x': 5 }]; + * + * _.sortedIndexBy(objects, { 'x': 4 }, function(o) { return o.x; }); + * // => 0 + * + * // The `_.property` iteratee shorthand. + * _.sortedIndexBy(objects, { 'x': 4 }, 'x'); + * // => 0 + */ + function sortedIndexBy(array, value, iteratee) { + return baseSortedIndexBy(array, value, getIteratee(iteratee, 2)); + } + + /** + * This method is like `_.indexOf` except that it performs a binary + * search on a sorted `array`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {*} value The value to search for. + * @returns {number} Returns the index of the matched value, else `-1`. + * @example + * + * _.sortedIndexOf([4, 5, 5, 5, 6], 5); + * // => 1 + */ + function sortedIndexOf(array, value) { + var length = array == null ? 0 : array.length; + if (length) { + var index = baseSortedIndex(array, value); + if (index < length && eq(array[index], value)) { + return index; + } + } + return -1; + } + + /** + * This method is like `_.sortedIndex` except that it returns the highest + * index at which `value` should be inserted into `array` in order to + * maintain its sort order. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Array + * @param {Array} array The sorted array to inspect. + * @param {*} value The value to evaluate. + * @returns {number} Returns the index at which `value` should be inserted + * into `array`. + * @example + * + * _.sortedLastIndex([4, 5, 5, 5, 6], 5); + * // => 4 + */ + function sortedLastIndex(array, value) { + return baseSortedIndex(array, value, true); + } + + /** + * This method is like `_.sortedLastIndex` except that it accepts `iteratee` + * which is invoked for `value` and each element of `array` to compute their + * sort ranking. The iteratee is invoked with one argument: (value). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The sorted array to inspect. + * @param {*} value The value to evaluate. + * @param {Function} [iteratee=_.identity] The iteratee invoked per element. + * @returns {number} Returns the index at which `value` should be inserted + * into `array`. + * @example + * + * var objects = [{ 'x': 4 }, { 'x': 5 }]; + * + * _.sortedLastIndexBy(objects, { 'x': 4 }, function(o) { return o.x; }); + * // => 1 + * + * // The `_.property` iteratee shorthand. + * _.sortedLastIndexBy(objects, { 'x': 4 }, 'x'); + * // => 1 + */ + function sortedLastIndexBy(array, value, iteratee) { + return baseSortedIndexBy(array, value, getIteratee(iteratee, 2), true); + } + + /** + * This method is like `_.lastIndexOf` except that it performs a binary + * search on a sorted `array`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {*} value The value to search for. + * @returns {number} Returns the index of the matched value, else `-1`. + * @example + * + * _.sortedLastIndexOf([4, 5, 5, 5, 6], 5); + * // => 3 + */ + function sortedLastIndexOf(array, value) { + var length = array == null ? 0 : array.length; + if (length) { + var index = baseSortedIndex(array, value, true) - 1; + if (eq(array[index], value)) { + return index; + } + } + return -1; + } + + /** + * This method is like `_.uniq` except that it's designed and optimized + * for sorted arrays. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The array to inspect. + * @returns {Array} Returns the new duplicate free array. + * @example + * + * _.sortedUniq([1, 1, 2]); + * // => [1, 2] + */ + function sortedUniq(array) { + return (array && array.length) + ? baseSortedUniq(array) + : []; + } + + /** + * This method is like `_.uniqBy` except that it's designed and optimized + * for sorted arrays. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {Function} [iteratee] The iteratee invoked per element. + * @returns {Array} Returns the new duplicate free array. + * @example + * + * _.sortedUniqBy([1.1, 1.2, 2.3, 2.4], Math.floor); + * // => [1.1, 2.3] + */ + function sortedUniqBy(array, iteratee) { + return (array && array.length) + ? baseSortedUniq(array, getIteratee(iteratee, 2)) + : []; + } + + /** + * Gets all but the first element of `array`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The array to query. + * @returns {Array} Returns the slice of `array`. + * @example + * + * _.tail([1, 2, 3]); + * // => [2, 3] + */ + function tail(array) { + var length = array == null ? 0 : array.length; + return length ? baseSlice(array, 1, length) : []; + } + + /** + * Creates a slice of `array` with `n` elements taken from the beginning. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {Array} array The array to query. + * @param {number} [n=1] The number of elements to take. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {Array} Returns the slice of `array`. + * @example + * + * _.take([1, 2, 3]); + * // => [1] + * + * _.take([1, 2, 3], 2); + * // => [1, 2] + * + * _.take([1, 2, 3], 5); + * // => [1, 2, 3] + * + * _.take([1, 2, 3], 0); + * // => [] + */ + function take(array, n, guard) { + if (!(array && array.length)) { + return []; + } + n = (guard || n === undefined) ? 1 : toInteger(n); + return baseSlice(array, 0, n < 0 ? 0 : n); + } + + /** + * Creates a slice of `array` with `n` elements taken from the end. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Array + * @param {Array} array The array to query. + * @param {number} [n=1] The number of elements to take. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {Array} Returns the slice of `array`. + * @example + * + * _.takeRight([1, 2, 3]); + * // => [3] + * + * _.takeRight([1, 2, 3], 2); + * // => [2, 3] + * + * _.takeRight([1, 2, 3], 5); + * // => [1, 2, 3] + * + * _.takeRight([1, 2, 3], 0); + * // => [] + */ + function takeRight(array, n, guard) { + var length = array == null ? 0 : array.length; + if (!length) { + return []; + } + n = (guard || n === undefined) ? 1 : toInteger(n); + n = length - n; + return baseSlice(array, n < 0 ? 0 : n, length); + } + + /** + * Creates a slice of `array` with elements taken from the end. Elements are + * taken until `predicate` returns falsey. The predicate is invoked with + * three arguments: (value, index, array). + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Array + * @param {Array} array The array to query. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @returns {Array} Returns the slice of `array`. + * @example + * + * var users = [ + * { 'user': 'barney', 'active': true }, + * { 'user': 'fred', 'active': false }, + * { 'user': 'pebbles', 'active': false } + * ]; + * + * _.takeRightWhile(users, function(o) { return !o.active; }); + * // => objects for ['fred', 'pebbles'] + * + * // The `_.matches` iteratee shorthand. + * _.takeRightWhile(users, { 'user': 'pebbles', 'active': false }); + * // => objects for ['pebbles'] + * + * // The `_.matchesProperty` iteratee shorthand. + * _.takeRightWhile(users, ['active', false]); + * // => objects for ['fred', 'pebbles'] + * + * // The `_.property` iteratee shorthand. + * _.takeRightWhile(users, 'active'); + * // => [] + */ + function takeRightWhile(array, predicate) { + return (array && array.length) + ? baseWhile(array, getIteratee(predicate, 3), false, true) + : []; + } + + /** + * Creates a slice of `array` with elements taken from the beginning. Elements + * are taken until `predicate` returns falsey. The predicate is invoked with + * three arguments: (value, index, array). + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Array + * @param {Array} array The array to query. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @returns {Array} Returns the slice of `array`. + * @example + * + * var users = [ + * { 'user': 'barney', 'active': false }, + * { 'user': 'fred', 'active': false }, + * { 'user': 'pebbles', 'active': true } + * ]; + * + * _.takeWhile(users, function(o) { return !o.active; }); + * // => objects for ['barney', 'fred'] + * + * // The `_.matches` iteratee shorthand. + * _.takeWhile(users, { 'user': 'barney', 'active': false }); + * // => objects for ['barney'] + * + * // The `_.matchesProperty` iteratee shorthand. + * _.takeWhile(users, ['active', false]); + * // => objects for ['barney', 'fred'] + * + * // The `_.property` iteratee shorthand. + * _.takeWhile(users, 'active'); + * // => [] + */ + function takeWhile(array, predicate) { + return (array && array.length) + ? baseWhile(array, getIteratee(predicate, 3)) + : []; + } + + /** + * Creates an array of unique values, in order, from all given arrays using + * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * for equality comparisons. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {...Array} [arrays] The arrays to inspect. + * @returns {Array} Returns the new array of combined values. + * @example + * + * _.union([2], [1, 2]); + * // => [2, 1] + */ + var union = baseRest(function(arrays) { + return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true)); + }); + + /** + * This method is like `_.union` except that it accepts `iteratee` which is + * invoked for each element of each `arrays` to generate the criterion by + * which uniqueness is computed. Result values are chosen from the first + * array in which the value occurs. The iteratee is invoked with one argument: + * (value). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {...Array} [arrays] The arrays to inspect. + * @param {Function} [iteratee=_.identity] The iteratee invoked per element. + * @returns {Array} Returns the new array of combined values. + * @example + * + * _.unionBy([2.1], [1.2, 2.3], Math.floor); + * // => [2.1, 1.2] + * + * // The `_.property` iteratee shorthand. + * _.unionBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x'); + * // => [{ 'x': 1 }, { 'x': 2 }] + */ + var unionBy = baseRest(function(arrays) { + var iteratee = last(arrays); + if (isArrayLikeObject(iteratee)) { + iteratee = undefined; + } + return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true), getIteratee(iteratee, 2)); + }); + + /** + * This method is like `_.union` except that it accepts `comparator` which + * is invoked to compare elements of `arrays`. Result values are chosen from + * the first array in which the value occurs. The comparator is invoked + * with two arguments: (arrVal, othVal). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {...Array} [arrays] The arrays to inspect. + * @param {Function} [comparator] The comparator invoked per element. + * @returns {Array} Returns the new array of combined values. + * @example + * + * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]; + * var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }]; + * + * _.unionWith(objects, others, _.isEqual); + * // => [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }, { 'x': 1, 'y': 1 }] + */ + var unionWith = baseRest(function(arrays) { + var comparator = last(arrays); + comparator = typeof comparator == 'function' ? comparator : undefined; + return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true), undefined, comparator); + }); + + /** + * Creates a duplicate-free version of an array, using + * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * for equality comparisons, in which only the first occurrence of each element + * is kept. The order of result values is determined by the order they occur + * in the array. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {Array} array The array to inspect. + * @returns {Array} Returns the new duplicate free array. + * @example + * + * _.uniq([2, 1, 2]); + * // => [2, 1] + */ + function uniq(array) { + return (array && array.length) ? baseUniq(array) : []; + } + + /** + * This method is like `_.uniq` except that it accepts `iteratee` which is + * invoked for each element in `array` to generate the criterion by which + * uniqueness is computed. The order of result values is determined by the + * order they occur in the array. The iteratee is invoked with one argument: + * (value). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {Function} [iteratee=_.identity] The iteratee invoked per element. + * @returns {Array} Returns the new duplicate free array. + * @example + * + * _.uniqBy([2.1, 1.2, 2.3], Math.floor); + * // => [2.1, 1.2] + * + * // The `_.property` iteratee shorthand. + * _.uniqBy([{ 'x': 1 }, { 'x': 2 }, { 'x': 1 }], 'x'); + * // => [{ 'x': 1 }, { 'x': 2 }] + */ + function uniqBy(array, iteratee) { + return (array && array.length) ? baseUniq(array, getIteratee(iteratee, 2)) : []; + } + + /** + * This method is like `_.uniq` except that it accepts `comparator` which + * is invoked to compare elements of `array`. The order of result values is + * determined by the order they occur in the array.The comparator is invoked + * with two arguments: (arrVal, othVal). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {Function} [comparator] The comparator invoked per element. + * @returns {Array} Returns the new duplicate free array. + * @example + * + * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }, { 'x': 1, 'y': 2 }]; + * + * _.uniqWith(objects, _.isEqual); + * // => [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }] + */ + function uniqWith(array, comparator) { + comparator = typeof comparator == 'function' ? comparator : undefined; + return (array && array.length) ? baseUniq(array, undefined, comparator) : []; + } + + /** + * This method is like `_.zip` except that it accepts an array of grouped + * elements and creates an array regrouping the elements to their pre-zip + * configuration. + * + * @static + * @memberOf _ + * @since 1.2.0 + * @category Array + * @param {Array} array The array of grouped elements to process. + * @returns {Array} Returns the new array of regrouped elements. + * @example + * + * var zipped = _.zip(['a', 'b'], [1, 2], [true, false]); + * // => [['a', 1, true], ['b', 2, false]] + * + * _.unzip(zipped); + * // => [['a', 'b'], [1, 2], [true, false]] + */ + function unzip(array) { + if (!(array && array.length)) { + return []; + } + var length = 0; + array = arrayFilter(array, function(group) { + if (isArrayLikeObject(group)) { + length = nativeMax(group.length, length); + return true; + } + }); + return baseTimes(length, function(index) { + return arrayMap(array, baseProperty(index)); + }); + } + + /** + * This method is like `_.unzip` except that it accepts `iteratee` to specify + * how regrouped values should be combined. The iteratee is invoked with the + * elements of each group: (...group). + * + * @static + * @memberOf _ + * @since 3.8.0 + * @category Array + * @param {Array} array The array of grouped elements to process. + * @param {Function} [iteratee=_.identity] The function to combine + * regrouped values. + * @returns {Array} Returns the new array of regrouped elements. + * @example + * + * var zipped = _.zip([1, 2], [10, 20], [100, 200]); + * // => [[1, 10, 100], [2, 20, 200]] + * + * _.unzipWith(zipped, _.add); + * // => [3, 30, 300] + */ + function unzipWith(array, iteratee) { + if (!(array && array.length)) { + return []; + } + var result = unzip(array); + if (iteratee == null) { + return result; + } + return arrayMap(result, function(group) { + return apply(iteratee, undefined, group); + }); + } + + /** + * Creates an array excluding all given values using + * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * for equality comparisons. + * + * **Note:** Unlike `_.pull`, this method returns a new array. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {...*} [values] The values to exclude. + * @returns {Array} Returns the new array of filtered values. + * @see _.difference, _.xor + * @example + * + * _.without([2, 1, 2, 3], 1, 2); + * // => [3] + */ + var without = baseRest(function(array, values) { + return isArrayLikeObject(array) + ? baseDifference(array, values) + : []; + }); + + /** + * Creates an array of unique values that is the + * [symmetric difference](https://en.wikipedia.org/wiki/Symmetric_difference) + * of the given arrays. The order of result values is determined by the order + * they occur in the arrays. + * + * @static + * @memberOf _ + * @since 2.4.0 + * @category Array + * @param {...Array} [arrays] The arrays to inspect. + * @returns {Array} Returns the new array of filtered values. + * @see _.difference, _.without + * @example + * + * _.xor([2, 1], [2, 3]); + * // => [1, 3] + */ + var xor = baseRest(function(arrays) { + return baseXor(arrayFilter(arrays, isArrayLikeObject)); + }); + + /** + * This method is like `_.xor` except that it accepts `iteratee` which is + * invoked for each element of each `arrays` to generate the criterion by + * which by which they're compared. The order of result values is determined + * by the order they occur in the arrays. The iteratee is invoked with one + * argument: (value). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {...Array} [arrays] The arrays to inspect. + * @param {Function} [iteratee=_.identity] The iteratee invoked per element. + * @returns {Array} Returns the new array of filtered values. + * @example + * + * _.xorBy([2.1, 1.2], [2.3, 3.4], Math.floor); + * // => [1.2, 3.4] + * + * // The `_.property` iteratee shorthand. + * _.xorBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x'); + * // => [{ 'x': 2 }] + */ + var xorBy = baseRest(function(arrays) { + var iteratee = last(arrays); + if (isArrayLikeObject(iteratee)) { + iteratee = undefined; + } + return baseXor(arrayFilter(arrays, isArrayLikeObject), getIteratee(iteratee, 2)); + }); + + /** + * This method is like `_.xor` except that it accepts `comparator` which is + * invoked to compare elements of `arrays`. The order of result values is + * determined by the order they occur in the arrays. The comparator is invoked + * with two arguments: (arrVal, othVal). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {...Array} [arrays] The arrays to inspect. + * @param {Function} [comparator] The comparator invoked per element. + * @returns {Array} Returns the new array of filtered values. + * @example + * + * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]; + * var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }]; + * + * _.xorWith(objects, others, _.isEqual); + * // => [{ 'x': 2, 'y': 1 }, { 'x': 1, 'y': 1 }] + */ + var xorWith = baseRest(function(arrays) { + var comparator = last(arrays); + comparator = typeof comparator == 'function' ? comparator : undefined; + return baseXor(arrayFilter(arrays, isArrayLikeObject), undefined, comparator); + }); + + /** + * Creates an array of grouped elements, the first of which contains the + * first elements of the given arrays, the second of which contains the + * second elements of the given arrays, and so on. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {...Array} [arrays] The arrays to process. + * @returns {Array} Returns the new array of grouped elements. + * @example + * + * _.zip(['a', 'b'], [1, 2], [true, false]); + * // => [['a', 1, true], ['b', 2, false]] + */ + var zip = baseRest(unzip); + + /** + * This method is like `_.fromPairs` except that it accepts two arrays, + * one of property identifiers and one of corresponding values. + * + * @static + * @memberOf _ + * @since 0.4.0 + * @category Array + * @param {Array} [props=[]] The property identifiers. + * @param {Array} [values=[]] The property values. + * @returns {Object} Returns the new object. + * @example + * + * _.zipObject(['a', 'b'], [1, 2]); + * // => { 'a': 1, 'b': 2 } + */ + function zipObject(props, values) { + return baseZipObject(props || [], values || [], assignValue); + } + + /** + * This method is like `_.zipObject` except that it supports property paths. + * + * @static + * @memberOf _ + * @since 4.1.0 + * @category Array + * @param {Array} [props=[]] The property identifiers. + * @param {Array} [values=[]] The property values. + * @returns {Object} Returns the new object. + * @example + * + * _.zipObjectDeep(['a.b[0].c', 'a.b[1].d'], [1, 2]); + * // => { 'a': { 'b': [{ 'c': 1 }, { 'd': 2 }] } } + */ + function zipObjectDeep(props, values) { + return baseZipObject(props || [], values || [], baseSet); + } + + /** + * This method is like `_.zip` except that it accepts `iteratee` to specify + * how grouped values should be combined. The iteratee is invoked with the + * elements of each group: (...group). + * + * @static + * @memberOf _ + * @since 3.8.0 + * @category Array + * @param {...Array} [arrays] The arrays to process. + * @param {Function} [iteratee=_.identity] The function to combine + * grouped values. + * @returns {Array} Returns the new array of grouped elements. + * @example + * + * _.zipWith([1, 2], [10, 20], [100, 200], function(a, b, c) { + * return a + b + c; + * }); + * // => [111, 222] + */ + var zipWith = baseRest(function(arrays) { + var length = arrays.length, + iteratee = length > 1 ? arrays[length - 1] : undefined; + + iteratee = typeof iteratee == 'function' ? (arrays.pop(), iteratee) : undefined; + return unzipWith(arrays, iteratee); + }); + + /*------------------------------------------------------------------------*/ + + /** + * Creates a `lodash` wrapper instance that wraps `value` with explicit method + * chain sequences enabled. The result of such sequences must be unwrapped + * with `_#value`. + * + * @static + * @memberOf _ + * @since 1.3.0 + * @category Seq + * @param {*} value The value to wrap. + * @returns {Object} Returns the new `lodash` wrapper instance. + * @example + * + * var users = [ + * { 'user': 'barney', 'age': 36 }, + * { 'user': 'fred', 'age': 40 }, + * { 'user': 'pebbles', 'age': 1 } + * ]; + * + * var youngest = _ + * .chain(users) + * .sortBy('age') + * .map(function(o) { + * return o.user + ' is ' + o.age; + * }) + * .head() + * .value(); + * // => 'pebbles is 1' + */ + function chain(value) { + var result = lodash(value); + result.__chain__ = true; + return result; + } + + /** + * This method invokes `interceptor` and returns `value`. The interceptor + * is invoked with one argument; (value). The purpose of this method is to + * "tap into" a method chain sequence in order to modify intermediate results. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Seq + * @param {*} value The value to provide to `interceptor`. + * @param {Function} interceptor The function to invoke. + * @returns {*} Returns `value`. + * @example + * + * _([1, 2, 3]) + * .tap(function(array) { + * // Mutate input array. + * array.pop(); + * }) + * .reverse() + * .value(); + * // => [2, 1] + */ + function tap(value, interceptor) { + interceptor(value); + return value; + } + + /** + * This method is like `_.tap` except that it returns the result of `interceptor`. + * The purpose of this method is to "pass thru" values replacing intermediate + * results in a method chain sequence. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Seq + * @param {*} value The value to provide to `interceptor`. + * @param {Function} interceptor The function to invoke. + * @returns {*} Returns the result of `interceptor`. + * @example + * + * _(' abc ') + * .chain() + * .trim() + * .thru(function(value) { + * return [value]; + * }) + * .value(); + * // => ['abc'] + */ + function thru(value, interceptor) { + return interceptor(value); + } + + /** + * This method is the wrapper version of `_.at`. + * + * @name at + * @memberOf _ + * @since 1.0.0 + * @category Seq + * @param {...(string|string[])} [paths] The property paths to pick. + * @returns {Object} Returns the new `lodash` wrapper instance. + * @example + * + * var object = { 'a': [{ 'b': { 'c': 3 } }, 4] }; + * + * _(object).at(['a[0].b.c', 'a[1]']).value(); + * // => [3, 4] + */ + var wrapperAt = flatRest(function(paths) { + var length = paths.length, + start = length ? paths[0] : 0, + value = this.__wrapped__, + interceptor = function(object) { return baseAt(object, paths); }; + + if (length > 1 || this.__actions__.length || + !(value instanceof LazyWrapper) || !isIndex(start)) { + return this.thru(interceptor); + } + value = value.slice(start, +start + (length ? 1 : 0)); + value.__actions__.push({ + 'func': thru, + 'args': [interceptor], + 'thisArg': undefined + }); + return new LodashWrapper(value, this.__chain__).thru(function(array) { + if (length && !array.length) { + array.push(undefined); + } + return array; + }); + }); + + /** + * Creates a `lodash` wrapper instance with explicit method chain sequences enabled. + * + * @name chain + * @memberOf _ + * @since 0.1.0 + * @category Seq + * @returns {Object} Returns the new `lodash` wrapper instance. + * @example + * + * var users = [ + * { 'user': 'barney', 'age': 36 }, + * { 'user': 'fred', 'age': 40 } + * ]; + * + * // A sequence without explicit chaining. + * _(users).head(); + * // => { 'user': 'barney', 'age': 36 } + * + * // A sequence with explicit chaining. + * _(users) + * .chain() + * .head() + * .pick('user') + * .value(); + * // => { 'user': 'barney' } + */ + function wrapperChain() { + return chain(this); + } + + /** + * Executes the chain sequence and returns the wrapped result. + * + * @name commit + * @memberOf _ + * @since 3.2.0 + * @category Seq + * @returns {Object} Returns the new `lodash` wrapper instance. + * @example + * + * var array = [1, 2]; + * var wrapped = _(array).push(3); + * + * console.log(array); + * // => [1, 2] + * + * wrapped = wrapped.commit(); + * console.log(array); + * // => [1, 2, 3] + * + * wrapped.last(); + * // => 3 + * + * console.log(array); + * // => [1, 2, 3] + */ + function wrapperCommit() { + return new LodashWrapper(this.value(), this.__chain__); + } + + /** + * Gets the next value on a wrapped object following the + * [iterator protocol](https://mdn.io/iteration_protocols#iterator). + * + * @name next + * @memberOf _ + * @since 4.0.0 + * @category Seq + * @returns {Object} Returns the next iterator value. + * @example + * + * var wrapped = _([1, 2]); + * + * wrapped.next(); + * // => { 'done': false, 'value': 1 } + * + * wrapped.next(); + * // => { 'done': false, 'value': 2 } + * + * wrapped.next(); + * // => { 'done': true, 'value': undefined } + */ + function wrapperNext() { + if (this.__values__ === undefined) { + this.__values__ = toArray(this.value()); + } + var done = this.__index__ >= this.__values__.length, + value = done ? undefined : this.__values__[this.__index__++]; + + return { 'done': done, 'value': value }; + } + + /** + * Enables the wrapper to be iterable. + * + * @name Symbol.iterator + * @memberOf _ + * @since 4.0.0 + * @category Seq + * @returns {Object} Returns the wrapper object. + * @example + * + * var wrapped = _([1, 2]); + * + * wrapped[Symbol.iterator]() === wrapped; + * // => true + * + * Array.from(wrapped); + * // => [1, 2] + */ + function wrapperToIterator() { + return this; + } + + /** + * Creates a clone of the chain sequence planting `value` as the wrapped value. + * + * @name plant + * @memberOf _ + * @since 3.2.0 + * @category Seq + * @param {*} value The value to plant. + * @returns {Object} Returns the new `lodash` wrapper instance. + * @example + * + * function square(n) { + * return n * n; + * } + * + * var wrapped = _([1, 2]).map(square); + * var other = wrapped.plant([3, 4]); + * + * other.value(); + * // => [9, 16] + * + * wrapped.value(); + * // => [1, 4] + */ + function wrapperPlant(value) { + var result, + parent = this; + + while (parent instanceof baseLodash) { + var clone = wrapperClone(parent); + clone.__index__ = 0; + clone.__values__ = undefined; + if (result) { + previous.__wrapped__ = clone; + } else { + result = clone; + } + var previous = clone; + parent = parent.__wrapped__; + } + previous.__wrapped__ = value; + return result; + } + + /** + * This method is the wrapper version of `_.reverse`. + * + * **Note:** This method mutates the wrapped array. + * + * @name reverse + * @memberOf _ + * @since 0.1.0 + * @category Seq + * @returns {Object} Returns the new `lodash` wrapper instance. + * @example + * + * var array = [1, 2, 3]; + * + * _(array).reverse().value() + * // => [3, 2, 1] + * + * console.log(array); + * // => [3, 2, 1] + */ + function wrapperReverse() { + var value = this.__wrapped__; + if (value instanceof LazyWrapper) { + var wrapped = value; + if (this.__actions__.length) { + wrapped = new LazyWrapper(this); + } + wrapped = wrapped.reverse(); + wrapped.__actions__.push({ + 'func': thru, + 'args': [reverse], + 'thisArg': undefined + }); + return new LodashWrapper(wrapped, this.__chain__); + } + return this.thru(reverse); + } + + /** + * Executes the chain sequence to resolve the unwrapped value. + * + * @name value + * @memberOf _ + * @since 0.1.0 + * @alias toJSON, valueOf + * @category Seq + * @returns {*} Returns the resolved unwrapped value. + * @example + * + * _([1, 2, 3]).value(); + * // => [1, 2, 3] + */ + function wrapperValue() { + return baseWrapperValue(this.__wrapped__, this.__actions__); + } + + /*------------------------------------------------------------------------*/ + + /** + * Creates an object composed of keys generated from the results of running + * each element of `collection` thru `iteratee`. The corresponding value of + * each key is the number of times the key was returned by `iteratee`. The + * iteratee is invoked with one argument: (value). + * + * @static + * @memberOf _ + * @since 0.5.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [iteratee=_.identity] The iteratee to transform keys. + * @returns {Object} Returns the composed aggregate object. + * @example + * + * _.countBy([6.1, 4.2, 6.3], Math.floor); + * // => { '4': 1, '6': 2 } + * + * // The `_.property` iteratee shorthand. + * _.countBy(['one', 'two', 'three'], 'length'); + * // => { '3': 2, '5': 1 } + */ + var countBy = createAggregator(function(result, value, key) { + if (hasOwnProperty.call(result, key)) { + ++result[key]; + } else { + baseAssignValue(result, key, 1); + } + }); + + /** + * Checks if `predicate` returns truthy for **all** elements of `collection`. + * Iteration is stopped once `predicate` returns falsey. The predicate is + * invoked with three arguments: (value, index|key, collection). + * + * **Note:** This method returns `true` for + * [empty collections](https://en.wikipedia.org/wiki/Empty_set) because + * [everything is true](https://en.wikipedia.org/wiki/Vacuous_truth) of + * elements of empty collections. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {boolean} Returns `true` if all elements pass the predicate check, + * else `false`. + * @example + * + * _.every([true, 1, null, 'yes'], Boolean); + * // => false + * + * var users = [ + * { 'user': 'barney', 'age': 36, 'active': false }, + * { 'user': 'fred', 'age': 40, 'active': false } + * ]; + * + * // The `_.matches` iteratee shorthand. + * _.every(users, { 'user': 'barney', 'active': false }); + * // => false + * + * // The `_.matchesProperty` iteratee shorthand. + * _.every(users, ['active', false]); + * // => true + * + * // The `_.property` iteratee shorthand. + * _.every(users, 'active'); + * // => false + */ + function every(collection, predicate, guard) { + var func = isArray(collection) ? arrayEvery : baseEvery; + if (guard && isIterateeCall(collection, predicate, guard)) { + predicate = undefined; + } + return func(collection, getIteratee(predicate, 3)); + } + + /** + * Iterates over elements of `collection`, returning an array of all elements + * `predicate` returns truthy for. The predicate is invoked with three + * arguments: (value, index|key, collection). + * + * **Note:** Unlike `_.remove`, this method returns a new array. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @returns {Array} Returns the new filtered array. + * @see _.reject + * @example + * + * var users = [ + * { 'user': 'barney', 'age': 36, 'active': true }, + * { 'user': 'fred', 'age': 40, 'active': false } + * ]; + * + * _.filter(users, function(o) { return !o.active; }); + * // => objects for ['fred'] + * + * // The `_.matches` iteratee shorthand. + * _.filter(users, { 'age': 36, 'active': true }); + * // => objects for ['barney'] + * + * // The `_.matchesProperty` iteratee shorthand. + * _.filter(users, ['active', false]); + * // => objects for ['fred'] + * + * // The `_.property` iteratee shorthand. + * _.filter(users, 'active'); + * // => objects for ['barney'] + * + * // Combining several predicates using `_.overEvery` or `_.overSome`. + * _.filter(users, _.overSome([{ 'age': 36 }, ['age', 40]])); + * // => objects for ['fred', 'barney'] + */ + function filter(collection, predicate) { + var func = isArray(collection) ? arrayFilter : baseFilter; + return func(collection, getIteratee(predicate, 3)); + } + + /** + * Iterates over elements of `collection`, returning the first element + * `predicate` returns truthy for. The predicate is invoked with three + * arguments: (value, index|key, collection). + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Collection + * @param {Array|Object} collection The collection to inspect. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @param {number} [fromIndex=0] The index to search from. + * @returns {*} Returns the matched element, else `undefined`. + * @example + * + * var users = [ + * { 'user': 'barney', 'age': 36, 'active': true }, + * { 'user': 'fred', 'age': 40, 'active': false }, + * { 'user': 'pebbles', 'age': 1, 'active': true } + * ]; + * + * _.find(users, function(o) { return o.age < 40; }); + * // => object for 'barney' + * + * // The `_.matches` iteratee shorthand. + * _.find(users, { 'age': 1, 'active': true }); + * // => object for 'pebbles' + * + * // The `_.matchesProperty` iteratee shorthand. + * _.find(users, ['active', false]); + * // => object for 'fred' + * + * // The `_.property` iteratee shorthand. + * _.find(users, 'active'); + * // => object for 'barney' + */ + var find = createFind(findIndex); + + /** + * This method is like `_.find` except that it iterates over elements of + * `collection` from right to left. + * + * @static + * @memberOf _ + * @since 2.0.0 + * @category Collection + * @param {Array|Object} collection The collection to inspect. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @param {number} [fromIndex=collection.length-1] The index to search from. + * @returns {*} Returns the matched element, else `undefined`. + * @example + * + * _.findLast([1, 2, 3, 4], function(n) { + * return n % 2 == 1; + * }); + * // => 3 + */ + var findLast = createFind(findLastIndex); + + /** + * Creates a flattened array of values by running each element in `collection` + * thru `iteratee` and flattening the mapped results. The iteratee is invoked + * with three arguments: (value, index|key, collection). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @returns {Array} Returns the new flattened array. + * @example + * + * function duplicate(n) { + * return [n, n]; + * } + * + * _.flatMap([1, 2], duplicate); + * // => [1, 1, 2, 2] + */ + function flatMap(collection, iteratee) { + return baseFlatten(map(collection, iteratee), 1); + } + + /** + * This method is like `_.flatMap` except that it recursively flattens the + * mapped results. + * + * @static + * @memberOf _ + * @since 4.7.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @returns {Array} Returns the new flattened array. + * @example + * + * function duplicate(n) { + * return [[[n, n]]]; + * } + * + * _.flatMapDeep([1, 2], duplicate); + * // => [1, 1, 2, 2] + */ + function flatMapDeep(collection, iteratee) { + return baseFlatten(map(collection, iteratee), INFINITY); + } + + /** + * This method is like `_.flatMap` except that it recursively flattens the + * mapped results up to `depth` times. + * + * @static + * @memberOf _ + * @since 4.7.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @param {number} [depth=1] The maximum recursion depth. + * @returns {Array} Returns the new flattened array. + * @example + * + * function duplicate(n) { + * return [[[n, n]]]; + * } + * + * _.flatMapDepth([1, 2], duplicate, 2); + * // => [[1, 1], [2, 2]] + */ + function flatMapDepth(collection, iteratee, depth) { + depth = depth === undefined ? 1 : toInteger(depth); + return baseFlatten(map(collection, iteratee), depth); + } + + /** + * Iterates over elements of `collection` and invokes `iteratee` for each element. + * The iteratee is invoked with three arguments: (value, index|key, collection). + * Iteratee functions may exit iteration early by explicitly returning `false`. + * + * **Note:** As with other "Collections" methods, objects with a "length" + * property are iterated like arrays. To avoid this behavior use `_.forIn` + * or `_.forOwn` for object iteration. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @alias each + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @returns {Array|Object} Returns `collection`. + * @see _.forEachRight + * @example + * + * _.forEach([1, 2], function(value) { + * console.log(value); + * }); + * // => Logs `1` then `2`. + * + * _.forEach({ 'a': 1, 'b': 2 }, function(value, key) { + * console.log(key); + * }); + * // => Logs 'a' then 'b' (iteration order is not guaranteed). + */ + function forEach(collection, iteratee) { + var func = isArray(collection) ? arrayEach : baseEach; + return func(collection, getIteratee(iteratee, 3)); + } + + /** + * This method is like `_.forEach` except that it iterates over elements of + * `collection` from right to left. + * + * @static + * @memberOf _ + * @since 2.0.0 + * @alias eachRight + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @returns {Array|Object} Returns `collection`. + * @see _.forEach + * @example + * + * _.forEachRight([1, 2], function(value) { + * console.log(value); + * }); + * // => Logs `2` then `1`. + */ + function forEachRight(collection, iteratee) { + var func = isArray(collection) ? arrayEachRight : baseEachRight; + return func(collection, getIteratee(iteratee, 3)); + } + + /** + * Creates an object composed of keys generated from the results of running + * each element of `collection` thru `iteratee`. The order of grouped values + * is determined by the order they occur in `collection`. The corresponding + * value of each key is an array of elements responsible for generating the + * key. The iteratee is invoked with one argument: (value). + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [iteratee=_.identity] The iteratee to transform keys. + * @returns {Object} Returns the composed aggregate object. + * @example + * + * _.groupBy([6.1, 4.2, 6.3], Math.floor); + * // => { '4': [4.2], '6': [6.1, 6.3] } + * + * // The `_.property` iteratee shorthand. + * _.groupBy(['one', 'two', 'three'], 'length'); + * // => { '3': ['one', 'two'], '5': ['three'] } + */ + var groupBy = createAggregator(function(result, value, key) { + if (hasOwnProperty.call(result, key)) { + result[key].push(value); + } else { + baseAssignValue(result, key, [value]); + } + }); + + /** + * Checks if `value` is in `collection`. If `collection` is a string, it's + * checked for a substring of `value`, otherwise + * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * is used for equality comparisons. If `fromIndex` is negative, it's used as + * the offset from the end of `collection`. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Collection + * @param {Array|Object|string} collection The collection to inspect. + * @param {*} value The value to search for. + * @param {number} [fromIndex=0] The index to search from. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.reduce`. + * @returns {boolean} Returns `true` if `value` is found, else `false`. + * @example + * + * _.includes([1, 2, 3], 1); + * // => true + * + * _.includes([1, 2, 3], 1, 2); + * // => false + * + * _.includes({ 'a': 1, 'b': 2 }, 1); + * // => true + * + * _.includes('abcd', 'bc'); + * // => true + */ + function includes(collection, value, fromIndex, guard) { + collection = isArrayLike(collection) ? collection : values(collection); + fromIndex = (fromIndex && !guard) ? toInteger(fromIndex) : 0; + + var length = collection.length; + if (fromIndex < 0) { + fromIndex = nativeMax(length + fromIndex, 0); + } + return isString(collection) + ? (fromIndex <= length && collection.indexOf(value, fromIndex) > -1) + : (!!length && baseIndexOf(collection, value, fromIndex) > -1); + } + + /** + * Invokes the method at `path` of each element in `collection`, returning + * an array of the results of each invoked method. Any additional arguments + * are provided to each invoked method. If `path` is a function, it's invoked + * for, and `this` bound to, each element in `collection`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Array|Function|string} path The path of the method to invoke or + * the function invoked per iteration. + * @param {...*} [args] The arguments to invoke each method with. + * @returns {Array} Returns the array of results. + * @example + * + * _.invokeMap([[5, 1, 7], [3, 2, 1]], 'sort'); + * // => [[1, 5, 7], [1, 2, 3]] + * + * _.invokeMap([123, 456], String.prototype.split, ''); + * // => [['1', '2', '3'], ['4', '5', '6']] + */ + var invokeMap = baseRest(function(collection, path, args) { + var index = -1, + isFunc = typeof path == 'function', + result = isArrayLike(collection) ? Array(collection.length) : []; + + baseEach(collection, function(value) { + result[++index] = isFunc ? apply(path, value, args) : baseInvoke(value, path, args); + }); + return result; + }); + + /** + * Creates an object composed of keys generated from the results of running + * each element of `collection` thru `iteratee`. The corresponding value of + * each key is the last element responsible for generating the key. The + * iteratee is invoked with one argument: (value). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [iteratee=_.identity] The iteratee to transform keys. + * @returns {Object} Returns the composed aggregate object. + * @example + * + * var array = [ + * { 'dir': 'left', 'code': 97 }, + * { 'dir': 'right', 'code': 100 } + * ]; + * + * _.keyBy(array, function(o) { + * return String.fromCharCode(o.code); + * }); + * // => { 'a': { 'dir': 'left', 'code': 97 }, 'd': { 'dir': 'right', 'code': 100 } } + * + * _.keyBy(array, 'dir'); + * // => { 'left': { 'dir': 'left', 'code': 97 }, 'right': { 'dir': 'right', 'code': 100 } } + */ + var keyBy = createAggregator(function(result, value, key) { + baseAssignValue(result, key, value); + }); + + /** + * Creates an array of values by running each element in `collection` thru + * `iteratee`. The iteratee is invoked with three arguments: + * (value, index|key, collection). + * + * Many lodash methods are guarded to work as iteratees for methods like + * `_.every`, `_.filter`, `_.map`, `_.mapValues`, `_.reject`, and `_.some`. + * + * The guarded methods are: + * `ary`, `chunk`, `curry`, `curryRight`, `drop`, `dropRight`, `every`, + * `fill`, `invert`, `parseInt`, `random`, `range`, `rangeRight`, `repeat`, + * `sampleSize`, `slice`, `some`, `sortBy`, `split`, `take`, `takeRight`, + * `template`, `trim`, `trimEnd`, `trimStart`, and `words` + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @returns {Array} Returns the new mapped array. + * @example + * + * function square(n) { + * return n * n; + * } + * + * _.map([4, 8], square); + * // => [16, 64] + * + * _.map({ 'a': 4, 'b': 8 }, square); + * // => [16, 64] (iteration order is not guaranteed) + * + * var users = [ + * { 'user': 'barney' }, + * { 'user': 'fred' } + * ]; + * + * // The `_.property` iteratee shorthand. + * _.map(users, 'user'); + * // => ['barney', 'fred'] + */ + function map(collection, iteratee) { + var func = isArray(collection) ? arrayMap : baseMap; + return func(collection, getIteratee(iteratee, 3)); + } + + /** + * This method is like `_.sortBy` except that it allows specifying the sort + * orders of the iteratees to sort by. If `orders` is unspecified, all values + * are sorted in ascending order. Otherwise, specify an order of "desc" for + * descending or "asc" for ascending sort order of corresponding values. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Array[]|Function[]|Object[]|string[]} [iteratees=[_.identity]] + * The iteratees to sort by. + * @param {string[]} [orders] The sort orders of `iteratees`. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.reduce`. + * @returns {Array} Returns the new sorted array. + * @example + * + * var users = [ + * { 'user': 'fred', 'age': 48 }, + * { 'user': 'barney', 'age': 34 }, + * { 'user': 'fred', 'age': 40 }, + * { 'user': 'barney', 'age': 36 } + * ]; + * + * // Sort by `user` in ascending order and by `age` in descending order. + * _.orderBy(users, ['user', 'age'], ['asc', 'desc']); + * // => objects for [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 40]] + */ + function orderBy(collection, iteratees, orders, guard) { + if (collection == null) { + return []; + } + if (!isArray(iteratees)) { + iteratees = iteratees == null ? [] : [iteratees]; + } + orders = guard ? undefined : orders; + if (!isArray(orders)) { + orders = orders == null ? [] : [orders]; + } + return baseOrderBy(collection, iteratees, orders); + } + + /** + * Creates an array of elements split into two groups, the first of which + * contains elements `predicate` returns truthy for, the second of which + * contains elements `predicate` returns falsey for. The predicate is + * invoked with one argument: (value). + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @returns {Array} Returns the array of grouped elements. + * @example + * + * var users = [ + * { 'user': 'barney', 'age': 36, 'active': false }, + * { 'user': 'fred', 'age': 40, 'active': true }, + * { 'user': 'pebbles', 'age': 1, 'active': false } + * ]; + * + * _.partition(users, function(o) { return o.active; }); + * // => objects for [['fred'], ['barney', 'pebbles']] + * + * // The `_.matches` iteratee shorthand. + * _.partition(users, { 'age': 1, 'active': false }); + * // => objects for [['pebbles'], ['barney', 'fred']] + * + * // The `_.matchesProperty` iteratee shorthand. + * _.partition(users, ['active', false]); + * // => objects for [['barney', 'pebbles'], ['fred']] + * + * // The `_.property` iteratee shorthand. + * _.partition(users, 'active'); + * // => objects for [['fred'], ['barney', 'pebbles']] + */ + var partition = createAggregator(function(result, value, key) { + result[key ? 0 : 1].push(value); + }, function() { return [[], []]; }); + + /** + * Reduces `collection` to a value which is the accumulated result of running + * each element in `collection` thru `iteratee`, where each successive + * invocation is supplied the return value of the previous. If `accumulator` + * is not given, the first element of `collection` is used as the initial + * value. The iteratee is invoked with four arguments: + * (accumulator, value, index|key, collection). + * + * Many lodash methods are guarded to work as iteratees for methods like + * `_.reduce`, `_.reduceRight`, and `_.transform`. + * + * The guarded methods are: + * `assign`, `defaults`, `defaultsDeep`, `includes`, `merge`, `orderBy`, + * and `sortBy` + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @param {*} [accumulator] The initial value. + * @returns {*} Returns the accumulated value. + * @see _.reduceRight + * @example + * + * _.reduce([1, 2], function(sum, n) { + * return sum + n; + * }, 0); + * // => 3 + * + * _.reduce({ 'a': 1, 'b': 2, 'c': 1 }, function(result, value, key) { + * (result[value] || (result[value] = [])).push(key); + * return result; + * }, {}); + * // => { '1': ['a', 'c'], '2': ['b'] } (iteration order is not guaranteed) + */ + function reduce(collection, iteratee, accumulator) { + var func = isArray(collection) ? arrayReduce : baseReduce, + initAccum = arguments.length < 3; + + return func(collection, getIteratee(iteratee, 4), accumulator, initAccum, baseEach); + } + + /** + * This method is like `_.reduce` except that it iterates over elements of + * `collection` from right to left. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @param {*} [accumulator] The initial value. + * @returns {*} Returns the accumulated value. + * @see _.reduce + * @example + * + * var array = [[0, 1], [2, 3], [4, 5]]; + * + * _.reduceRight(array, function(flattened, other) { + * return flattened.concat(other); + * }, []); + * // => [4, 5, 2, 3, 0, 1] + */ + function reduceRight(collection, iteratee, accumulator) { + var func = isArray(collection) ? arrayReduceRight : baseReduce, + initAccum = arguments.length < 3; + + return func(collection, getIteratee(iteratee, 4), accumulator, initAccum, baseEachRight); + } + + /** + * The opposite of `_.filter`; this method returns the elements of `collection` + * that `predicate` does **not** return truthy for. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @returns {Array} Returns the new filtered array. + * @see _.filter + * @example + * + * var users = [ + * { 'user': 'barney', 'age': 36, 'active': false }, + * { 'user': 'fred', 'age': 40, 'active': true } + * ]; + * + * _.reject(users, function(o) { return !o.active; }); + * // => objects for ['fred'] + * + * // The `_.matches` iteratee shorthand. + * _.reject(users, { 'age': 40, 'active': true }); + * // => objects for ['barney'] + * + * // The `_.matchesProperty` iteratee shorthand. + * _.reject(users, ['active', false]); + * // => objects for ['fred'] + * + * // The `_.property` iteratee shorthand. + * _.reject(users, 'active'); + * // => objects for ['barney'] + */ + function reject(collection, predicate) { + var func = isArray(collection) ? arrayFilter : baseFilter; + return func(collection, negate(getIteratee(predicate, 3))); + } + + /** + * Gets a random element from `collection`. + * + * @static + * @memberOf _ + * @since 2.0.0 + * @category Collection + * @param {Array|Object} collection The collection to sample. + * @returns {*} Returns the random element. + * @example + * + * _.sample([1, 2, 3, 4]); + * // => 2 + */ + function sample(collection) { + var func = isArray(collection) ? arraySample : baseSample; + return func(collection); + } + + /** + * Gets `n` random elements at unique keys from `collection` up to the + * size of `collection`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Collection + * @param {Array|Object} collection The collection to sample. + * @param {number} [n=1] The number of elements to sample. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {Array} Returns the random elements. + * @example + * + * _.sampleSize([1, 2, 3], 2); + * // => [3, 1] + * + * _.sampleSize([1, 2, 3], 4); + * // => [2, 3, 1] + */ + function sampleSize(collection, n, guard) { + if ((guard ? isIterateeCall(collection, n, guard) : n === undefined)) { + n = 1; + } else { + n = toInteger(n); + } + var func = isArray(collection) ? arraySampleSize : baseSampleSize; + return func(collection, n); + } + + /** + * Creates an array of shuffled values, using a version of the + * [Fisher-Yates shuffle](https://en.wikipedia.org/wiki/Fisher-Yates_shuffle). + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Collection + * @param {Array|Object} collection The collection to shuffle. + * @returns {Array} Returns the new shuffled array. + * @example + * + * _.shuffle([1, 2, 3, 4]); + * // => [4, 1, 3, 2] + */ + function shuffle(collection) { + var func = isArray(collection) ? arrayShuffle : baseShuffle; + return func(collection); + } + + /** + * Gets the size of `collection` by returning its length for array-like + * values or the number of own enumerable string keyed properties for objects. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Collection + * @param {Array|Object|string} collection The collection to inspect. + * @returns {number} Returns the collection size. + * @example + * + * _.size([1, 2, 3]); + * // => 3 + * + * _.size({ 'a': 1, 'b': 2 }); + * // => 2 + * + * _.size('pebbles'); + * // => 7 + */ + function size(collection) { + if (collection == null) { + return 0; + } + if (isArrayLike(collection)) { + return isString(collection) ? stringSize(collection) : collection.length; + } + var tag = getTag(collection); + if (tag == mapTag || tag == setTag) { + return collection.size; + } + return baseKeys(collection).length; + } + + /** + * Checks if `predicate` returns truthy for **any** element of `collection`. + * Iteration is stopped once `predicate` returns truthy. The predicate is + * invoked with three arguments: (value, index|key, collection). + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {boolean} Returns `true` if any element passes the predicate check, + * else `false`. + * @example + * + * _.some([null, 0, 'yes', false], Boolean); + * // => true + * + * var users = [ + * { 'user': 'barney', 'active': true }, + * { 'user': 'fred', 'active': false } + * ]; + * + * // The `_.matches` iteratee shorthand. + * _.some(users, { 'user': 'barney', 'active': false }); + * // => false + * + * // The `_.matchesProperty` iteratee shorthand. + * _.some(users, ['active', false]); + * // => true + * + * // The `_.property` iteratee shorthand. + * _.some(users, 'active'); + * // => true + */ + function some(collection, predicate, guard) { + var func = isArray(collection) ? arraySome : baseSome; + if (guard && isIterateeCall(collection, predicate, guard)) { + predicate = undefined; + } + return func(collection, getIteratee(predicate, 3)); + } + + /** + * Creates an array of elements, sorted in ascending order by the results of + * running each element in a collection thru each iteratee. This method + * performs a stable sort, that is, it preserves the original sort order of + * equal elements. The iteratees are invoked with one argument: (value). + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {...(Function|Function[])} [iteratees=[_.identity]] + * The iteratees to sort by. + * @returns {Array} Returns the new sorted array. + * @example + * + * var users = [ + * { 'user': 'fred', 'age': 48 }, + * { 'user': 'barney', 'age': 36 }, + * { 'user': 'fred', 'age': 30 }, + * { 'user': 'barney', 'age': 34 } + * ]; + * + * _.sortBy(users, [function(o) { return o.user; }]); + * // => objects for [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 30]] + * + * _.sortBy(users, ['user', 'age']); + * // => objects for [['barney', 34], ['barney', 36], ['fred', 30], ['fred', 48]] + */ + var sortBy = baseRest(function(collection, iteratees) { + if (collection == null) { + return []; + } + var length = iteratees.length; + if (length > 1 && isIterateeCall(collection, iteratees[0], iteratees[1])) { + iteratees = []; + } else if (length > 2 && isIterateeCall(iteratees[0], iteratees[1], iteratees[2])) { + iteratees = [iteratees[0]]; + } + return baseOrderBy(collection, baseFlatten(iteratees, 1), []); + }); + + /*------------------------------------------------------------------------*/ + + /** + * Gets the timestamp of the number of milliseconds that have elapsed since + * the Unix epoch (1 January 1970 00:00:00 UTC). + * + * @static + * @memberOf _ + * @since 2.4.0 + * @category Date + * @returns {number} Returns the timestamp. + * @example + * + * _.defer(function(stamp) { + * console.log(_.now() - stamp); + * }, _.now()); + * // => Logs the number of milliseconds it took for the deferred invocation. + */ + var now = ctxNow || function() { + return root.Date.now(); + }; + + /*------------------------------------------------------------------------*/ + + /** + * The opposite of `_.before`; this method creates a function that invokes + * `func` once it's called `n` or more times. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Function + * @param {number} n The number of calls before `func` is invoked. + * @param {Function} func The function to restrict. + * @returns {Function} Returns the new restricted function. + * @example + * + * var saves = ['profile', 'settings']; + * + * var done = _.after(saves.length, function() { + * console.log('done saving!'); + * }); + * + * _.forEach(saves, function(type) { + * asyncSave({ 'type': type, 'complete': done }); + * }); + * // => Logs 'done saving!' after the two async saves have completed. + */ + function after(n, func) { + if (typeof func != 'function') { + throw new TypeError(FUNC_ERROR_TEXT); + } + n = toInteger(n); + return function() { + if (--n < 1) { + return func.apply(this, arguments); + } + }; + } + + /** + * Creates a function that invokes `func`, with up to `n` arguments, + * ignoring any additional arguments. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Function + * @param {Function} func The function to cap arguments for. + * @param {number} [n=func.length] The arity cap. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {Function} Returns the new capped function. + * @example + * + * _.map(['6', '8', '10'], _.ary(parseInt, 1)); + * // => [6, 8, 10] + */ + function ary(func, n, guard) { + n = guard ? undefined : n; + n = (func && n == null) ? func.length : n; + return createWrap(func, WRAP_ARY_FLAG, undefined, undefined, undefined, undefined, n); + } + + /** + * Creates a function that invokes `func`, with the `this` binding and arguments + * of the created function, while it's called less than `n` times. Subsequent + * calls to the created function return the result of the last `func` invocation. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Function + * @param {number} n The number of calls at which `func` is no longer invoked. + * @param {Function} func The function to restrict. + * @returns {Function} Returns the new restricted function. + * @example + * + * jQuery(element).on('click', _.before(5, addContactToList)); + * // => Allows adding up to 4 contacts to the list. + */ + function before(n, func) { + var result; + if (typeof func != 'function') { + throw new TypeError(FUNC_ERROR_TEXT); + } + n = toInteger(n); + return function() { + if (--n > 0) { + result = func.apply(this, arguments); + } + if (n <= 1) { + func = undefined; + } + return result; + }; + } + + /** + * Creates a function that invokes `func` with the `this` binding of `thisArg` + * and `partials` prepended to the arguments it receives. + * + * The `_.bind.placeholder` value, which defaults to `_` in monolithic builds, + * may be used as a placeholder for partially applied arguments. + * + * **Note:** Unlike native `Function#bind`, this method doesn't set the "length" + * property of bound functions. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Function + * @param {Function} func The function to bind. + * @param {*} thisArg The `this` binding of `func`. + * @param {...*} [partials] The arguments to be partially applied. + * @returns {Function} Returns the new bound function. + * @example + * + * function greet(greeting, punctuation) { + * return greeting + ' ' + this.user + punctuation; + * } + * + * var object = { 'user': 'fred' }; + * + * var bound = _.bind(greet, object, 'hi'); + * bound('!'); + * // => 'hi fred!' + * + * // Bound with placeholders. + * var bound = _.bind(greet, object, _, '!'); + * bound('hi'); + * // => 'hi fred!' + */ + var bind = baseRest(function(func, thisArg, partials) { + var bitmask = WRAP_BIND_FLAG; + if (partials.length) { + var holders = replaceHolders(partials, getHolder(bind)); + bitmask |= WRAP_PARTIAL_FLAG; + } + return createWrap(func, bitmask, thisArg, partials, holders); + }); + + /** + * Creates a function that invokes the method at `object[key]` with `partials` + * prepended to the arguments it receives. + * + * This method differs from `_.bind` by allowing bound functions to reference + * methods that may be redefined or don't yet exist. See + * [Peter Michaux's article](http://peter.michaux.ca/articles/lazy-function-definition-pattern) + * for more details. + * + * The `_.bindKey.placeholder` value, which defaults to `_` in monolithic + * builds, may be used as a placeholder for partially applied arguments. + * + * @static + * @memberOf _ + * @since 0.10.0 + * @category Function + * @param {Object} object The object to invoke the method on. + * @param {string} key The key of the method. + * @param {...*} [partials] The arguments to be partially applied. + * @returns {Function} Returns the new bound function. + * @example + * + * var object = { + * 'user': 'fred', + * 'greet': function(greeting, punctuation) { + * return greeting + ' ' + this.user + punctuation; + * } + * }; + * + * var bound = _.bindKey(object, 'greet', 'hi'); + * bound('!'); + * // => 'hi fred!' + * + * object.greet = function(greeting, punctuation) { + * return greeting + 'ya ' + this.user + punctuation; + * }; + * + * bound('!'); + * // => 'hiya fred!' + * + * // Bound with placeholders. + * var bound = _.bindKey(object, 'greet', _, '!'); + * bound('hi'); + * // => 'hiya fred!' + */ + var bindKey = baseRest(function(object, key, partials) { + var bitmask = WRAP_BIND_FLAG | WRAP_BIND_KEY_FLAG; + if (partials.length) { + var holders = replaceHolders(partials, getHolder(bindKey)); + bitmask |= WRAP_PARTIAL_FLAG; + } + return createWrap(key, bitmask, object, partials, holders); + }); + + /** + * Creates a function that accepts arguments of `func` and either invokes + * `func` returning its result, if at least `arity` number of arguments have + * been provided, or returns a function that accepts the remaining `func` + * arguments, and so on. The arity of `func` may be specified if `func.length` + * is not sufficient. + * + * The `_.curry.placeholder` value, which defaults to `_` in monolithic builds, + * may be used as a placeholder for provided arguments. + * + * **Note:** This method doesn't set the "length" property of curried functions. + * + * @static + * @memberOf _ + * @since 2.0.0 + * @category Function + * @param {Function} func The function to curry. + * @param {number} [arity=func.length] The arity of `func`. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {Function} Returns the new curried function. + * @example + * + * var abc = function(a, b, c) { + * return [a, b, c]; + * }; + * + * var curried = _.curry(abc); + * + * curried(1)(2)(3); + * // => [1, 2, 3] + * + * curried(1, 2)(3); + * // => [1, 2, 3] + * + * curried(1, 2, 3); + * // => [1, 2, 3] + * + * // Curried with placeholders. + * curried(1)(_, 3)(2); + * // => [1, 2, 3] + */ + function curry(func, arity, guard) { + arity = guard ? undefined : arity; + var result = createWrap(func, WRAP_CURRY_FLAG, undefined, undefined, undefined, undefined, undefined, arity); + result.placeholder = curry.placeholder; + return result; + } + + /** + * This method is like `_.curry` except that arguments are applied to `func` + * in the manner of `_.partialRight` instead of `_.partial`. + * + * The `_.curryRight.placeholder` value, which defaults to `_` in monolithic + * builds, may be used as a placeholder for provided arguments. + * + * **Note:** This method doesn't set the "length" property of curried functions. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Function + * @param {Function} func The function to curry. + * @param {number} [arity=func.length] The arity of `func`. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {Function} Returns the new curried function. + * @example + * + * var abc = function(a, b, c) { + * return [a, b, c]; + * }; + * + * var curried = _.curryRight(abc); + * + * curried(3)(2)(1); + * // => [1, 2, 3] + * + * curried(2, 3)(1); + * // => [1, 2, 3] + * + * curried(1, 2, 3); + * // => [1, 2, 3] + * + * // Curried with placeholders. + * curried(3)(1, _)(2); + * // => [1, 2, 3] + */ + function curryRight(func, arity, guard) { + arity = guard ? undefined : arity; + var result = createWrap(func, WRAP_CURRY_RIGHT_FLAG, undefined, undefined, undefined, undefined, undefined, arity); + result.placeholder = curryRight.placeholder; + return result; + } + + /** + * Creates a debounced function that delays invoking `func` until after `wait` + * milliseconds have elapsed since the last time the debounced function was + * invoked. The debounced function comes with a `cancel` method to cancel + * delayed `func` invocations and a `flush` method to immediately invoke them. + * Provide `options` to indicate whether `func` should be invoked on the + * leading and/or trailing edge of the `wait` timeout. The `func` is invoked + * with the last arguments provided to the debounced function. Subsequent + * calls to the debounced function return the result of the last `func` + * invocation. + * + * **Note:** If `leading` and `trailing` options are `true`, `func` is + * invoked on the trailing edge of the timeout only if the debounced function + * is invoked more than once during the `wait` timeout. + * + * If `wait` is `0` and `leading` is `false`, `func` invocation is deferred + * until to the next tick, similar to `setTimeout` with a timeout of `0`. + * + * See [David Corbacho's article](https://css-tricks.com/debouncing-throttling-explained-examples/) + * for details over the differences between `_.debounce` and `_.throttle`. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Function + * @param {Function} func The function to debounce. + * @param {number} [wait=0] The number of milliseconds to delay. + * @param {Object} [options={}] The options object. + * @param {boolean} [options.leading=false] + * Specify invoking on the leading edge of the timeout. + * @param {number} [options.maxWait] + * The maximum time `func` is allowed to be delayed before it's invoked. + * @param {boolean} [options.trailing=true] + * Specify invoking on the trailing edge of the timeout. + * @returns {Function} Returns the new debounced function. + * @example + * + * // Avoid costly calculations while the window size is in flux. + * jQuery(window).on('resize', _.debounce(calculateLayout, 150)); + * + * // Invoke `sendMail` when clicked, debouncing subsequent calls. + * jQuery(element).on('click', _.debounce(sendMail, 300, { + * 'leading': true, + * 'trailing': false + * })); + * + * // Ensure `batchLog` is invoked once after 1 second of debounced calls. + * var debounced = _.debounce(batchLog, 250, { 'maxWait': 1000 }); + * var source = new EventSource('/stream'); + * jQuery(source).on('message', debounced); + * + * // Cancel the trailing debounced invocation. + * jQuery(window).on('popstate', debounced.cancel); + */ + function debounce(func, wait, options) { + var lastArgs, + lastThis, + maxWait, + result, + timerId, + lastCallTime, + lastInvokeTime = 0, + leading = false, + maxing = false, + trailing = true; + + if (typeof func != 'function') { + throw new TypeError(FUNC_ERROR_TEXT); + } + wait = toNumber(wait) || 0; + if (isObject(options)) { + leading = !!options.leading; + maxing = 'maxWait' in options; + maxWait = maxing ? nativeMax(toNumber(options.maxWait) || 0, wait) : maxWait; + trailing = 'trailing' in options ? !!options.trailing : trailing; + } + + function invokeFunc(time) { + var args = lastArgs, + thisArg = lastThis; + + lastArgs = lastThis = undefined; + lastInvokeTime = time; + result = func.apply(thisArg, args); + return result; + } + + function leadingEdge(time) { + // Reset any `maxWait` timer. + lastInvokeTime = time; + // Start the timer for the trailing edge. + timerId = setTimeout(timerExpired, wait); + // Invoke the leading edge. + return leading ? invokeFunc(time) : result; + } + + function remainingWait(time) { + var timeSinceLastCall = time - lastCallTime, + timeSinceLastInvoke = time - lastInvokeTime, + timeWaiting = wait - timeSinceLastCall; + + return maxing + ? nativeMin(timeWaiting, maxWait - timeSinceLastInvoke) + : timeWaiting; + } + + function shouldInvoke(time) { + var timeSinceLastCall = time - lastCallTime, + timeSinceLastInvoke = time - lastInvokeTime; + + // Either this is the first call, activity has stopped and we're at the + // trailing edge, the system time has gone backwards and we're treating + // it as the trailing edge, or we've hit the `maxWait` limit. + return (lastCallTime === undefined || (timeSinceLastCall >= wait) || + (timeSinceLastCall < 0) || (maxing && timeSinceLastInvoke >= maxWait)); + } + + function timerExpired() { + var time = now(); + if (shouldInvoke(time)) { + return trailingEdge(time); + } + // Restart the timer. + timerId = setTimeout(timerExpired, remainingWait(time)); + } + + function trailingEdge(time) { + timerId = undefined; + + // Only invoke if we have `lastArgs` which means `func` has been + // debounced at least once. + if (trailing && lastArgs) { + return invokeFunc(time); + } + lastArgs = lastThis = undefined; + return result; + } + + function cancel() { + if (timerId !== undefined) { + clearTimeout(timerId); + } + lastInvokeTime = 0; + lastArgs = lastCallTime = lastThis = timerId = undefined; + } + + function flush() { + return timerId === undefined ? result : trailingEdge(now()); + } + + function debounced() { + var time = now(), + isInvoking = shouldInvoke(time); + + lastArgs = arguments; + lastThis = this; + lastCallTime = time; + + if (isInvoking) { + if (timerId === undefined) { + return leadingEdge(lastCallTime); + } + if (maxing) { + // Handle invocations in a tight loop. + clearTimeout(timerId); + timerId = setTimeout(timerExpired, wait); + return invokeFunc(lastCallTime); + } + } + if (timerId === undefined) { + timerId = setTimeout(timerExpired, wait); + } + return result; + } + debounced.cancel = cancel; + debounced.flush = flush; + return debounced; + } + + /** + * Defers invoking the `func` until the current call stack has cleared. Any + * additional arguments are provided to `func` when it's invoked. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Function + * @param {Function} func The function to defer. + * @param {...*} [args] The arguments to invoke `func` with. + * @returns {number} Returns the timer id. + * @example + * + * _.defer(function(text) { + * console.log(text); + * }, 'deferred'); + * // => Logs 'deferred' after one millisecond. + */ + var defer = baseRest(function(func, args) { + return baseDelay(func, 1, args); + }); + + /** + * Invokes `func` after `wait` milliseconds. Any additional arguments are + * provided to `func` when it's invoked. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Function + * @param {Function} func The function to delay. + * @param {number} wait The number of milliseconds to delay invocation. + * @param {...*} [args] The arguments to invoke `func` with. + * @returns {number} Returns the timer id. + * @example + * + * _.delay(function(text) { + * console.log(text); + * }, 1000, 'later'); + * // => Logs 'later' after one second. + */ + var delay = baseRest(function(func, wait, args) { + return baseDelay(func, toNumber(wait) || 0, args); + }); + + /** + * Creates a function that invokes `func` with arguments reversed. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Function + * @param {Function} func The function to flip arguments for. + * @returns {Function} Returns the new flipped function. + * @example + * + * var flipped = _.flip(function() { + * return _.toArray(arguments); + * }); + * + * flipped('a', 'b', 'c', 'd'); + * // => ['d', 'c', 'b', 'a'] + */ + function flip(func) { + return createWrap(func, WRAP_FLIP_FLAG); + } + + /** + * Creates a function that memoizes the result of `func`. If `resolver` is + * provided, it determines the cache key for storing the result based on the + * arguments provided to the memoized function. By default, the first argument + * provided to the memoized function is used as the map cache key. The `func` + * is invoked with the `this` binding of the memoized function. + * + * **Note:** The cache is exposed as the `cache` property on the memoized + * function. Its creation may be customized by replacing the `_.memoize.Cache` + * constructor with one whose instances implement the + * [`Map`](http://ecma-international.org/ecma-262/7.0/#sec-properties-of-the-map-prototype-object) + * method interface of `clear`, `delete`, `get`, `has`, and `set`. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Function + * @param {Function} func The function to have its output memoized. + * @param {Function} [resolver] The function to resolve the cache key. + * @returns {Function} Returns the new memoized function. + * @example + * + * var object = { 'a': 1, 'b': 2 }; + * var other = { 'c': 3, 'd': 4 }; + * + * var values = _.memoize(_.values); + * values(object); + * // => [1, 2] + * + * values(other); + * // => [3, 4] + * + * object.a = 2; + * values(object); + * // => [1, 2] + * + * // Modify the result cache. + * values.cache.set(object, ['a', 'b']); + * values(object); + * // => ['a', 'b'] + * + * // Replace `_.memoize.Cache`. + * _.memoize.Cache = WeakMap; + */ + function memoize(func, resolver) { + if (typeof func != 'function' || (resolver != null && typeof resolver != 'function')) { + throw new TypeError(FUNC_ERROR_TEXT); + } + var memoized = function() { + var args = arguments, + key = resolver ? resolver.apply(this, args) : args[0], + cache = memoized.cache; + + if (cache.has(key)) { + return cache.get(key); + } + var result = func.apply(this, args); + memoized.cache = cache.set(key, result) || cache; + return result; + }; + memoized.cache = new (memoize.Cache || MapCache); + return memoized; + } + + // Expose `MapCache`. + memoize.Cache = MapCache; + + /** + * Creates a function that negates the result of the predicate `func`. The + * `func` predicate is invoked with the `this` binding and arguments of the + * created function. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Function + * @param {Function} predicate The predicate to negate. + * @returns {Function} Returns the new negated function. + * @example + * + * function isEven(n) { + * return n % 2 == 0; + * } + * + * _.filter([1, 2, 3, 4, 5, 6], _.negate(isEven)); + * // => [1, 3, 5] + */ + function negate(predicate) { + if (typeof predicate != 'function') { + throw new TypeError(FUNC_ERROR_TEXT); + } + return function() { + var args = arguments; + switch (args.length) { + case 0: return !predicate.call(this); + case 1: return !predicate.call(this, args[0]); + case 2: return !predicate.call(this, args[0], args[1]); + case 3: return !predicate.call(this, args[0], args[1], args[2]); + } + return !predicate.apply(this, args); + }; + } + + /** + * Creates a function that is restricted to invoking `func` once. Repeat calls + * to the function return the value of the first invocation. The `func` is + * invoked with the `this` binding and arguments of the created function. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Function + * @param {Function} func The function to restrict. + * @returns {Function} Returns the new restricted function. + * @example + * + * var initialize = _.once(createApplication); + * initialize(); + * initialize(); + * // => `createApplication` is invoked once + */ + function once(func) { + return before(2, func); + } + + /** + * Creates a function that invokes `func` with its arguments transformed. + * + * @static + * @since 4.0.0 + * @memberOf _ + * @category Function + * @param {Function} func The function to wrap. + * @param {...(Function|Function[])} [transforms=[_.identity]] + * The argument transforms. + * @returns {Function} Returns the new function. + * @example + * + * function doubled(n) { + * return n * 2; + * } + * + * function square(n) { + * return n * n; + * } + * + * var func = _.overArgs(function(x, y) { + * return [x, y]; + * }, [square, doubled]); + * + * func(9, 3); + * // => [81, 6] + * + * func(10, 5); + * // => [100, 10] + */ + var overArgs = castRest(function(func, transforms) { + transforms = (transforms.length == 1 && isArray(transforms[0])) + ? arrayMap(transforms[0], baseUnary(getIteratee())) + : arrayMap(baseFlatten(transforms, 1), baseUnary(getIteratee())); + + var funcsLength = transforms.length; + return baseRest(function(args) { + var index = -1, + length = nativeMin(args.length, funcsLength); + + while (++index < length) { + args[index] = transforms[index].call(this, args[index]); + } + return apply(func, this, args); + }); + }); + + /** + * Creates a function that invokes `func` with `partials` prepended to the + * arguments it receives. This method is like `_.bind` except it does **not** + * alter the `this` binding. + * + * The `_.partial.placeholder` value, which defaults to `_` in monolithic + * builds, may be used as a placeholder for partially applied arguments. + * + * **Note:** This method doesn't set the "length" property of partially + * applied functions. + * + * @static + * @memberOf _ + * @since 0.2.0 + * @category Function + * @param {Function} func The function to partially apply arguments to. + * @param {...*} [partials] The arguments to be partially applied. + * @returns {Function} Returns the new partially applied function. + * @example + * + * function greet(greeting, name) { + * return greeting + ' ' + name; + * } + * + * var sayHelloTo = _.partial(greet, 'hello'); + * sayHelloTo('fred'); + * // => 'hello fred' + * + * // Partially applied with placeholders. + * var greetFred = _.partial(greet, _, 'fred'); + * greetFred('hi'); + * // => 'hi fred' + */ + var partial = baseRest(function(func, partials) { + var holders = replaceHolders(partials, getHolder(partial)); + return createWrap(func, WRAP_PARTIAL_FLAG, undefined, partials, holders); + }); + + /** + * This method is like `_.partial` except that partially applied arguments + * are appended to the arguments it receives. + * + * The `_.partialRight.placeholder` value, which defaults to `_` in monolithic + * builds, may be used as a placeholder for partially applied arguments. + * + * **Note:** This method doesn't set the "length" property of partially + * applied functions. + * + * @static + * @memberOf _ + * @since 1.0.0 + * @category Function + * @param {Function} func The function to partially apply arguments to. + * @param {...*} [partials] The arguments to be partially applied. + * @returns {Function} Returns the new partially applied function. + * @example + * + * function greet(greeting, name) { + * return greeting + ' ' + name; + * } + * + * var greetFred = _.partialRight(greet, 'fred'); + * greetFred('hi'); + * // => 'hi fred' + * + * // Partially applied with placeholders. + * var sayHelloTo = _.partialRight(greet, 'hello', _); + * sayHelloTo('fred'); + * // => 'hello fred' + */ + var partialRight = baseRest(function(func, partials) { + var holders = replaceHolders(partials, getHolder(partialRight)); + return createWrap(func, WRAP_PARTIAL_RIGHT_FLAG, undefined, partials, holders); + }); + + /** + * Creates a function that invokes `func` with arguments arranged according + * to the specified `indexes` where the argument value at the first index is + * provided as the first argument, the argument value at the second index is + * provided as the second argument, and so on. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Function + * @param {Function} func The function to rearrange arguments for. + * @param {...(number|number[])} indexes The arranged argument indexes. + * @returns {Function} Returns the new function. + * @example + * + * var rearged = _.rearg(function(a, b, c) { + * return [a, b, c]; + * }, [2, 0, 1]); + * + * rearged('b', 'c', 'a') + * // => ['a', 'b', 'c'] + */ + var rearg = flatRest(function(func, indexes) { + return createWrap(func, WRAP_REARG_FLAG, undefined, undefined, undefined, indexes); + }); + + /** + * Creates a function that invokes `func` with the `this` binding of the + * created function and arguments from `start` and beyond provided as + * an array. + * + * **Note:** This method is based on the + * [rest parameter](https://mdn.io/rest_parameters). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Function + * @param {Function} func The function to apply a rest parameter to. + * @param {number} [start=func.length-1] The start position of the rest parameter. + * @returns {Function} Returns the new function. + * @example + * + * var say = _.rest(function(what, names) { + * return what + ' ' + _.initial(names).join(', ') + + * (_.size(names) > 1 ? ', & ' : '') + _.last(names); + * }); + * + * say('hello', 'fred', 'barney', 'pebbles'); + * // => 'hello fred, barney, & pebbles' + */ + function rest(func, start) { + if (typeof func != 'function') { + throw new TypeError(FUNC_ERROR_TEXT); + } + start = start === undefined ? start : toInteger(start); + return baseRest(func, start); + } + + /** + * Creates a function that invokes `func` with the `this` binding of the + * create function and an array of arguments much like + * [`Function#apply`](http://www.ecma-international.org/ecma-262/7.0/#sec-function.prototype.apply). + * + * **Note:** This method is based on the + * [spread operator](https://mdn.io/spread_operator). + * + * @static + * @memberOf _ + * @since 3.2.0 + * @category Function + * @param {Function} func The function to spread arguments over. + * @param {number} [start=0] The start position of the spread. + * @returns {Function} Returns the new function. + * @example + * + * var say = _.spread(function(who, what) { + * return who + ' says ' + what; + * }); + * + * say(['fred', 'hello']); + * // => 'fred says hello' + * + * var numbers = Promise.all([ + * Promise.resolve(40), + * Promise.resolve(36) + * ]); + * + * numbers.then(_.spread(function(x, y) { + * return x + y; + * })); + * // => a Promise of 76 + */ + function spread(func, start) { + if (typeof func != 'function') { + throw new TypeError(FUNC_ERROR_TEXT); + } + start = start == null ? 0 : nativeMax(toInteger(start), 0); + return baseRest(function(args) { + var array = args[start], + otherArgs = castSlice(args, 0, start); + + if (array) { + arrayPush(otherArgs, array); + } + return apply(func, this, otherArgs); + }); + } + + /** + * Creates a throttled function that only invokes `func` at most once per + * every `wait` milliseconds. The throttled function comes with a `cancel` + * method to cancel delayed `func` invocations and a `flush` method to + * immediately invoke them. Provide `options` to indicate whether `func` + * should be invoked on the leading and/or trailing edge of the `wait` + * timeout. The `func` is invoked with the last arguments provided to the + * throttled function. Subsequent calls to the throttled function return the + * result of the last `func` invocation. + * + * **Note:** If `leading` and `trailing` options are `true`, `func` is + * invoked on the trailing edge of the timeout only if the throttled function + * is invoked more than once during the `wait` timeout. + * + * If `wait` is `0` and `leading` is `false`, `func` invocation is deferred + * until to the next tick, similar to `setTimeout` with a timeout of `0`. + * + * See [David Corbacho's article](https://css-tricks.com/debouncing-throttling-explained-examples/) + * for details over the differences between `_.throttle` and `_.debounce`. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Function + * @param {Function} func The function to throttle. + * @param {number} [wait=0] The number of milliseconds to throttle invocations to. + * @param {Object} [options={}] The options object. + * @param {boolean} [options.leading=true] + * Specify invoking on the leading edge of the timeout. + * @param {boolean} [options.trailing=true] + * Specify invoking on the trailing edge of the timeout. + * @returns {Function} Returns the new throttled function. + * @example + * + * // Avoid excessively updating the position while scrolling. + * jQuery(window).on('scroll', _.throttle(updatePosition, 100)); + * + * // Invoke `renewToken` when the click event is fired, but not more than once every 5 minutes. + * var throttled = _.throttle(renewToken, 300000, { 'trailing': false }); + * jQuery(element).on('click', throttled); + * + * // Cancel the trailing throttled invocation. + * jQuery(window).on('popstate', throttled.cancel); + */ + function throttle(func, wait, options) { + var leading = true, + trailing = true; + + if (typeof func != 'function') { + throw new TypeError(FUNC_ERROR_TEXT); + } + if (isObject(options)) { + leading = 'leading' in options ? !!options.leading : leading; + trailing = 'trailing' in options ? !!options.trailing : trailing; + } + return debounce(func, wait, { + 'leading': leading, + 'maxWait': wait, + 'trailing': trailing + }); + } + + /** + * Creates a function that accepts up to one argument, ignoring any + * additional arguments. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Function + * @param {Function} func The function to cap arguments for. + * @returns {Function} Returns the new capped function. + * @example + * + * _.map(['6', '8', '10'], _.unary(parseInt)); + * // => [6, 8, 10] + */ + function unary(func) { + return ary(func, 1); + } + + /** + * Creates a function that provides `value` to `wrapper` as its first + * argument. Any additional arguments provided to the function are appended + * to those provided to the `wrapper`. The wrapper is invoked with the `this` + * binding of the created function. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Function + * @param {*} value The value to wrap. + * @param {Function} [wrapper=identity] The wrapper function. + * @returns {Function} Returns the new function. + * @example + * + * var p = _.wrap(_.escape, function(func, text) { + * return '

' + func(text) + '

'; + * }); + * + * p('fred, barney, & pebbles'); + * // => '

fred, barney, & pebbles

' + */ + function wrap(value, wrapper) { + return partial(castFunction(wrapper), value); + } + + /*------------------------------------------------------------------------*/ + + /** + * Casts `value` as an array if it's not one. + * + * @static + * @memberOf _ + * @since 4.4.0 + * @category Lang + * @param {*} value The value to inspect. + * @returns {Array} Returns the cast array. + * @example + * + * _.castArray(1); + * // => [1] + * + * _.castArray({ 'a': 1 }); + * // => [{ 'a': 1 }] + * + * _.castArray('abc'); + * // => ['abc'] + * + * _.castArray(null); + * // => [null] + * + * _.castArray(undefined); + * // => [undefined] + * + * _.castArray(); + * // => [] + * + * var array = [1, 2, 3]; + * console.log(_.castArray(array) === array); + * // => true + */ + function castArray() { + if (!arguments.length) { + return []; + } + var value = arguments[0]; + return isArray(value) ? value : [value]; + } + + /** + * Creates a shallow clone of `value`. + * + * **Note:** This method is loosely based on the + * [structured clone algorithm](https://mdn.io/Structured_clone_algorithm) + * and supports cloning arrays, array buffers, booleans, date objects, maps, + * numbers, `Object` objects, regexes, sets, strings, symbols, and typed + * arrays. The own enumerable properties of `arguments` objects are cloned + * as plain objects. An empty object is returned for uncloneable values such + * as error objects, functions, DOM nodes, and WeakMaps. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to clone. + * @returns {*} Returns the cloned value. + * @see _.cloneDeep + * @example + * + * var objects = [{ 'a': 1 }, { 'b': 2 }]; + * + * var shallow = _.clone(objects); + * console.log(shallow[0] === objects[0]); + * // => true + */ + function clone(value) { + return baseClone(value, CLONE_SYMBOLS_FLAG); + } + + /** + * This method is like `_.clone` except that it accepts `customizer` which + * is invoked to produce the cloned value. If `customizer` returns `undefined`, + * cloning is handled by the method instead. The `customizer` is invoked with + * up to four arguments; (value [, index|key, object, stack]). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to clone. + * @param {Function} [customizer] The function to customize cloning. + * @returns {*} Returns the cloned value. + * @see _.cloneDeepWith + * @example + * + * function customizer(value) { + * if (_.isElement(value)) { + * return value.cloneNode(false); + * } + * } + * + * var el = _.cloneWith(document.body, customizer); + * + * console.log(el === document.body); + * // => false + * console.log(el.nodeName); + * // => 'BODY' + * console.log(el.childNodes.length); + * // => 0 + */ + function cloneWith(value, customizer) { + customizer = typeof customizer == 'function' ? customizer : undefined; + return baseClone(value, CLONE_SYMBOLS_FLAG, customizer); + } + + /** + * This method is like `_.clone` except that it recursively clones `value`. + * + * @static + * @memberOf _ + * @since 1.0.0 + * @category Lang + * @param {*} value The value to recursively clone. + * @returns {*} Returns the deep cloned value. + * @see _.clone + * @example + * + * var objects = [{ 'a': 1 }, { 'b': 2 }]; + * + * var deep = _.cloneDeep(objects); + * console.log(deep[0] === objects[0]); + * // => false + */ + function cloneDeep(value) { + return baseClone(value, CLONE_DEEP_FLAG | CLONE_SYMBOLS_FLAG); + } + + /** + * This method is like `_.cloneWith` except that it recursively clones `value`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to recursively clone. + * @param {Function} [customizer] The function to customize cloning. + * @returns {*} Returns the deep cloned value. + * @see _.cloneWith + * @example + * + * function customizer(value) { + * if (_.isElement(value)) { + * return value.cloneNode(true); + * } + * } + * + * var el = _.cloneDeepWith(document.body, customizer); + * + * console.log(el === document.body); + * // => false + * console.log(el.nodeName); + * // => 'BODY' + * console.log(el.childNodes.length); + * // => 20 + */ + function cloneDeepWith(value, customizer) { + customizer = typeof customizer == 'function' ? customizer : undefined; + return baseClone(value, CLONE_DEEP_FLAG | CLONE_SYMBOLS_FLAG, customizer); + } + + /** + * Checks if `object` conforms to `source` by invoking the predicate + * properties of `source` with the corresponding property values of `object`. + * + * **Note:** This method is equivalent to `_.conforms` when `source` is + * partially applied. + * + * @static + * @memberOf _ + * @since 4.14.0 + * @category Lang + * @param {Object} object The object to inspect. + * @param {Object} source The object of property predicates to conform to. + * @returns {boolean} Returns `true` if `object` conforms, else `false`. + * @example + * + * var object = { 'a': 1, 'b': 2 }; + * + * _.conformsTo(object, { 'b': function(n) { return n > 1; } }); + * // => true + * + * _.conformsTo(object, { 'b': function(n) { return n > 2; } }); + * // => false + */ + function conformsTo(object, source) { + return source == null || baseConformsTo(object, source, keys(source)); + } + + /** + * Performs a + * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * comparison between two values to determine if they are equivalent. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {boolean} Returns `true` if the values are equivalent, else `false`. + * @example + * + * var object = { 'a': 1 }; + * var other = { 'a': 1 }; + * + * _.eq(object, object); + * // => true + * + * _.eq(object, other); + * // => false + * + * _.eq('a', 'a'); + * // => true + * + * _.eq('a', Object('a')); + * // => false + * + * _.eq(NaN, NaN); + * // => true + */ + function eq(value, other) { + return value === other || (value !== value && other !== other); + } + + /** + * Checks if `value` is greater than `other`. + * + * @static + * @memberOf _ + * @since 3.9.0 + * @category Lang + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {boolean} Returns `true` if `value` is greater than `other`, + * else `false`. + * @see _.lt + * @example + * + * _.gt(3, 1); + * // => true + * + * _.gt(3, 3); + * // => false + * + * _.gt(1, 3); + * // => false + */ + var gt = createRelationalOperation(baseGt); + + /** + * Checks if `value` is greater than or equal to `other`. + * + * @static + * @memberOf _ + * @since 3.9.0 + * @category Lang + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {boolean} Returns `true` if `value` is greater than or equal to + * `other`, else `false`. + * @see _.lte + * @example + * + * _.gte(3, 1); + * // => true + * + * _.gte(3, 3); + * // => true + * + * _.gte(1, 3); + * // => false + */ + var gte = createRelationalOperation(function(value, other) { + return value >= other; + }); + + /** + * Checks if `value` is likely an `arguments` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an `arguments` object, + * else `false`. + * @example + * + * _.isArguments(function() { return arguments; }()); + * // => true + * + * _.isArguments([1, 2, 3]); + * // => false + */ + var isArguments = baseIsArguments(function() { return arguments; }()) ? baseIsArguments : function(value) { + return isObjectLike(value) && hasOwnProperty.call(value, 'callee') && + !propertyIsEnumerable.call(value, 'callee'); + }; + + /** + * Checks if `value` is classified as an `Array` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an array, else `false`. + * @example + * + * _.isArray([1, 2, 3]); + * // => true + * + * _.isArray(document.body.children); + * // => false + * + * _.isArray('abc'); + * // => false + * + * _.isArray(_.noop); + * // => false + */ + var isArray = Array.isArray; + + /** + * Checks if `value` is classified as an `ArrayBuffer` object. + * + * @static + * @memberOf _ + * @since 4.3.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an array buffer, else `false`. + * @example + * + * _.isArrayBuffer(new ArrayBuffer(2)); + * // => true + * + * _.isArrayBuffer(new Array(2)); + * // => false + */ + var isArrayBuffer = nodeIsArrayBuffer ? baseUnary(nodeIsArrayBuffer) : baseIsArrayBuffer; + + /** + * Checks if `value` is array-like. A value is considered array-like if it's + * not a function and has a `value.length` that's an integer greater than or + * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is array-like, else `false`. + * @example + * + * _.isArrayLike([1, 2, 3]); + * // => true + * + * _.isArrayLike(document.body.children); + * // => true + * + * _.isArrayLike('abc'); + * // => true + * + * _.isArrayLike(_.noop); + * // => false + */ + function isArrayLike(value) { + return value != null && isLength(value.length) && !isFunction(value); + } + + /** + * This method is like `_.isArrayLike` except that it also checks if `value` + * is an object. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an array-like object, + * else `false`. + * @example + * + * _.isArrayLikeObject([1, 2, 3]); + * // => true + * + * _.isArrayLikeObject(document.body.children); + * // => true + * + * _.isArrayLikeObject('abc'); + * // => false + * + * _.isArrayLikeObject(_.noop); + * // => false + */ + function isArrayLikeObject(value) { + return isObjectLike(value) && isArrayLike(value); + } + + /** + * Checks if `value` is classified as a boolean primitive or object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a boolean, else `false`. + * @example + * + * _.isBoolean(false); + * // => true + * + * _.isBoolean(null); + * // => false + */ + function isBoolean(value) { + return value === true || value === false || + (isObjectLike(value) && baseGetTag(value) == boolTag); + } + + /** + * Checks if `value` is a buffer. + * + * @static + * @memberOf _ + * @since 4.3.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a buffer, else `false`. + * @example + * + * _.isBuffer(new Buffer(2)); + * // => true + * + * _.isBuffer(new Uint8Array(2)); + * // => false + */ + var isBuffer = nativeIsBuffer || stubFalse; + + /** + * Checks if `value` is classified as a `Date` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a date object, else `false`. + * @example + * + * _.isDate(new Date); + * // => true + * + * _.isDate('Mon April 23 2012'); + * // => false + */ + var isDate = nodeIsDate ? baseUnary(nodeIsDate) : baseIsDate; + + /** + * Checks if `value` is likely a DOM element. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a DOM element, else `false`. + * @example + * + * _.isElement(document.body); + * // => true + * + * _.isElement(''); + * // => false + */ + function isElement(value) { + return isObjectLike(value) && value.nodeType === 1 && !isPlainObject(value); + } + + /** + * Checks if `value` is an empty object, collection, map, or set. + * + * Objects are considered empty if they have no own enumerable string keyed + * properties. + * + * Array-like values such as `arguments` objects, arrays, buffers, strings, or + * jQuery-like collections are considered empty if they have a `length` of `0`. + * Similarly, maps and sets are considered empty if they have a `size` of `0`. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is empty, else `false`. + * @example + * + * _.isEmpty(null); + * // => true + * + * _.isEmpty(true); + * // => true + * + * _.isEmpty(1); + * // => true + * + * _.isEmpty([1, 2, 3]); + * // => false + * + * _.isEmpty({ 'a': 1 }); + * // => false + */ + function isEmpty(value) { + if (value == null) { + return true; + } + if (isArrayLike(value) && + (isArray(value) || typeof value == 'string' || typeof value.splice == 'function' || + isBuffer(value) || isTypedArray(value) || isArguments(value))) { + return !value.length; + } + var tag = getTag(value); + if (tag == mapTag || tag == setTag) { + return !value.size; + } + if (isPrototype(value)) { + return !baseKeys(value).length; + } + for (var key in value) { + if (hasOwnProperty.call(value, key)) { + return false; + } + } + return true; + } + + /** + * Performs a deep comparison between two values to determine if they are + * equivalent. + * + * **Note:** This method supports comparing arrays, array buffers, booleans, + * date objects, error objects, maps, numbers, `Object` objects, regexes, + * sets, strings, symbols, and typed arrays. `Object` objects are compared + * by their own, not inherited, enumerable properties. Functions and DOM + * nodes are compared by strict equality, i.e. `===`. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {boolean} Returns `true` if the values are equivalent, else `false`. + * @example + * + * var object = { 'a': 1 }; + * var other = { 'a': 1 }; + * + * _.isEqual(object, other); + * // => true + * + * object === other; + * // => false + */ + function isEqual(value, other) { + return baseIsEqual(value, other); + } + + /** + * This method is like `_.isEqual` except that it accepts `customizer` which + * is invoked to compare values. If `customizer` returns `undefined`, comparisons + * are handled by the method instead. The `customizer` is invoked with up to + * six arguments: (objValue, othValue [, index|key, object, other, stack]). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @param {Function} [customizer] The function to customize comparisons. + * @returns {boolean} Returns `true` if the values are equivalent, else `false`. + * @example + * + * function isGreeting(value) { + * return /^h(?:i|ello)$/.test(value); + * } + * + * function customizer(objValue, othValue) { + * if (isGreeting(objValue) && isGreeting(othValue)) { + * return true; + * } + * } + * + * var array = ['hello', 'goodbye']; + * var other = ['hi', 'goodbye']; + * + * _.isEqualWith(array, other, customizer); + * // => true + */ + function isEqualWith(value, other, customizer) { + customizer = typeof customizer == 'function' ? customizer : undefined; + var result = customizer ? customizer(value, other) : undefined; + return result === undefined ? baseIsEqual(value, other, undefined, customizer) : !!result; + } + + /** + * Checks if `value` is an `Error`, `EvalError`, `RangeError`, `ReferenceError`, + * `SyntaxError`, `TypeError`, or `URIError` object. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an error object, else `false`. + * @example + * + * _.isError(new Error); + * // => true + * + * _.isError(Error); + * // => false + */ + function isError(value) { + if (!isObjectLike(value)) { + return false; + } + var tag = baseGetTag(value); + return tag == errorTag || tag == domExcTag || + (typeof value.message == 'string' && typeof value.name == 'string' && !isPlainObject(value)); + } + + /** + * Checks if `value` is a finite primitive number. + * + * **Note:** This method is based on + * [`Number.isFinite`](https://mdn.io/Number/isFinite). + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a finite number, else `false`. + * @example + * + * _.isFinite(3); + * // => true + * + * _.isFinite(Number.MIN_VALUE); + * // => true + * + * _.isFinite(Infinity); + * // => false + * + * _.isFinite('3'); + * // => false + */ + function isFinite(value) { + return typeof value == 'number' && nativeIsFinite(value); + } + + /** + * Checks if `value` is classified as a `Function` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a function, else `false`. + * @example + * + * _.isFunction(_); + * // => true + * + * _.isFunction(/abc/); + * // => false + */ + function isFunction(value) { + if (!isObject(value)) { + return false; + } + // The use of `Object#toString` avoids issues with the `typeof` operator + // in Safari 9 which returns 'object' for typed arrays and other constructors. + var tag = baseGetTag(value); + return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag; + } + + /** + * Checks if `value` is an integer. + * + * **Note:** This method is based on + * [`Number.isInteger`](https://mdn.io/Number/isInteger). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an integer, else `false`. + * @example + * + * _.isInteger(3); + * // => true + * + * _.isInteger(Number.MIN_VALUE); + * // => false + * + * _.isInteger(Infinity); + * // => false + * + * _.isInteger('3'); + * // => false + */ + function isInteger(value) { + return typeof value == 'number' && value == toInteger(value); + } + + /** + * Checks if `value` is a valid array-like length. + * + * **Note:** This method is loosely based on + * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a valid length, else `false`. + * @example + * + * _.isLength(3); + * // => true + * + * _.isLength(Number.MIN_VALUE); + * // => false + * + * _.isLength(Infinity); + * // => false + * + * _.isLength('3'); + * // => false + */ + function isLength(value) { + return typeof value == 'number' && + value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER; + } + + /** + * Checks if `value` is the + * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types) + * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an object, else `false`. + * @example + * + * _.isObject({}); + * // => true + * + * _.isObject([1, 2, 3]); + * // => true + * + * _.isObject(_.noop); + * // => true + * + * _.isObject(null); + * // => false + */ + function isObject(value) { + var type = typeof value; + return value != null && (type == 'object' || type == 'function'); + } + + /** + * Checks if `value` is object-like. A value is object-like if it's not `null` + * and has a `typeof` result of "object". + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is object-like, else `false`. + * @example + * + * _.isObjectLike({}); + * // => true + * + * _.isObjectLike([1, 2, 3]); + * // => true + * + * _.isObjectLike(_.noop); + * // => false + * + * _.isObjectLike(null); + * // => false + */ + function isObjectLike(value) { + return value != null && typeof value == 'object'; + } + + /** + * Checks if `value` is classified as a `Map` object. + * + * @static + * @memberOf _ + * @since 4.3.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a map, else `false`. + * @example + * + * _.isMap(new Map); + * // => true + * + * _.isMap(new WeakMap); + * // => false + */ + var isMap = nodeIsMap ? baseUnary(nodeIsMap) : baseIsMap; + + /** + * Performs a partial deep comparison between `object` and `source` to + * determine if `object` contains equivalent property values. + * + * **Note:** This method is equivalent to `_.matches` when `source` is + * partially applied. + * + * Partial comparisons will match empty array and empty object `source` + * values against any array or object value, respectively. See `_.isEqual` + * for a list of supported value comparisons. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Lang + * @param {Object} object The object to inspect. + * @param {Object} source The object of property values to match. + * @returns {boolean} Returns `true` if `object` is a match, else `false`. + * @example + * + * var object = { 'a': 1, 'b': 2 }; + * + * _.isMatch(object, { 'b': 2 }); + * // => true + * + * _.isMatch(object, { 'b': 1 }); + * // => false + */ + function isMatch(object, source) { + return object === source || baseIsMatch(object, source, getMatchData(source)); + } + + /** + * This method is like `_.isMatch` except that it accepts `customizer` which + * is invoked to compare values. If `customizer` returns `undefined`, comparisons + * are handled by the method instead. The `customizer` is invoked with five + * arguments: (objValue, srcValue, index|key, object, source). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {Object} object The object to inspect. + * @param {Object} source The object of property values to match. + * @param {Function} [customizer] The function to customize comparisons. + * @returns {boolean} Returns `true` if `object` is a match, else `false`. + * @example + * + * function isGreeting(value) { + * return /^h(?:i|ello)$/.test(value); + * } + * + * function customizer(objValue, srcValue) { + * if (isGreeting(objValue) && isGreeting(srcValue)) { + * return true; + * } + * } + * + * var object = { 'greeting': 'hello' }; + * var source = { 'greeting': 'hi' }; + * + * _.isMatchWith(object, source, customizer); + * // => true + */ + function isMatchWith(object, source, customizer) { + customizer = typeof customizer == 'function' ? customizer : undefined; + return baseIsMatch(object, source, getMatchData(source), customizer); + } + + /** + * Checks if `value` is `NaN`. + * + * **Note:** This method is based on + * [`Number.isNaN`](https://mdn.io/Number/isNaN) and is not the same as + * global [`isNaN`](https://mdn.io/isNaN) which returns `true` for + * `undefined` and other non-number values. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`. + * @example + * + * _.isNaN(NaN); + * // => true + * + * _.isNaN(new Number(NaN)); + * // => true + * + * isNaN(undefined); + * // => true + * + * _.isNaN(undefined); + * // => false + */ + function isNaN(value) { + // An `NaN` primitive is the only value that is not equal to itself. + // Perform the `toStringTag` check first to avoid errors with some + // ActiveX objects in IE. + return isNumber(value) && value != +value; + } + + /** + * Checks if `value` is a pristine native function. + * + * **Note:** This method can't reliably detect native functions in the presence + * of the core-js package because core-js circumvents this kind of detection. + * Despite multiple requests, the core-js maintainer has made it clear: any + * attempt to fix the detection will be obstructed. As a result, we're left + * with little choice but to throw an error. Unfortunately, this also affects + * packages, like [babel-polyfill](https://www.npmjs.com/package/babel-polyfill), + * which rely on core-js. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a native function, + * else `false`. + * @example + * + * _.isNative(Array.prototype.push); + * // => true + * + * _.isNative(_); + * // => false + */ + function isNative(value) { + if (isMaskable(value)) { + throw new Error(CORE_ERROR_TEXT); + } + return baseIsNative(value); + } + + /** + * Checks if `value` is `null`. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is `null`, else `false`. + * @example + * + * _.isNull(null); + * // => true + * + * _.isNull(void 0); + * // => false + */ + function isNull(value) { + return value === null; + } + + /** + * Checks if `value` is `null` or `undefined`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is nullish, else `false`. + * @example + * + * _.isNil(null); + * // => true + * + * _.isNil(void 0); + * // => true + * + * _.isNil(NaN); + * // => false + */ + function isNil(value) { + return value == null; + } + + /** + * Checks if `value` is classified as a `Number` primitive or object. + * + * **Note:** To exclude `Infinity`, `-Infinity`, and `NaN`, which are + * classified as numbers, use the `_.isFinite` method. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a number, else `false`. + * @example + * + * _.isNumber(3); + * // => true + * + * _.isNumber(Number.MIN_VALUE); + * // => true + * + * _.isNumber(Infinity); + * // => true + * + * _.isNumber('3'); + * // => false + */ + function isNumber(value) { + return typeof value == 'number' || + (isObjectLike(value) && baseGetTag(value) == numberTag); + } + + /** + * Checks if `value` is a plain object, that is, an object created by the + * `Object` constructor or one with a `[[Prototype]]` of `null`. + * + * @static + * @memberOf _ + * @since 0.8.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a plain object, else `false`. + * @example + * + * function Foo() { + * this.a = 1; + * } + * + * _.isPlainObject(new Foo); + * // => false + * + * _.isPlainObject([1, 2, 3]); + * // => false + * + * _.isPlainObject({ 'x': 0, 'y': 0 }); + * // => true + * + * _.isPlainObject(Object.create(null)); + * // => true + */ + function isPlainObject(value) { + if (!isObjectLike(value) || baseGetTag(value) != objectTag) { + return false; + } + var proto = getPrototype(value); + if (proto === null) { + return true; + } + var Ctor = hasOwnProperty.call(proto, 'constructor') && proto.constructor; + return typeof Ctor == 'function' && Ctor instanceof Ctor && + funcToString.call(Ctor) == objectCtorString; + } + + /** + * Checks if `value` is classified as a `RegExp` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a regexp, else `false`. + * @example + * + * _.isRegExp(/abc/); + * // => true + * + * _.isRegExp('/abc/'); + * // => false + */ + var isRegExp = nodeIsRegExp ? baseUnary(nodeIsRegExp) : baseIsRegExp; + + /** + * Checks if `value` is a safe integer. An integer is safe if it's an IEEE-754 + * double precision number which isn't the result of a rounded unsafe integer. + * + * **Note:** This method is based on + * [`Number.isSafeInteger`](https://mdn.io/Number/isSafeInteger). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a safe integer, else `false`. + * @example + * + * _.isSafeInteger(3); + * // => true + * + * _.isSafeInteger(Number.MIN_VALUE); + * // => false + * + * _.isSafeInteger(Infinity); + * // => false + * + * _.isSafeInteger('3'); + * // => false + */ + function isSafeInteger(value) { + return isInteger(value) && value >= -MAX_SAFE_INTEGER && value <= MAX_SAFE_INTEGER; + } + + /** + * Checks if `value` is classified as a `Set` object. + * + * @static + * @memberOf _ + * @since 4.3.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a set, else `false`. + * @example + * + * _.isSet(new Set); + * // => true + * + * _.isSet(new WeakSet); + * // => false + */ + var isSet = nodeIsSet ? baseUnary(nodeIsSet) : baseIsSet; + + /** + * Checks if `value` is classified as a `String` primitive or object. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a string, else `false`. + * @example + * + * _.isString('abc'); + * // => true + * + * _.isString(1); + * // => false + */ + function isString(value) { + return typeof value == 'string' || + (!isArray(value) && isObjectLike(value) && baseGetTag(value) == stringTag); + } + + /** + * Checks if `value` is classified as a `Symbol` primitive or object. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a symbol, else `false`. + * @example + * + * _.isSymbol(Symbol.iterator); + * // => true + * + * _.isSymbol('abc'); + * // => false + */ + function isSymbol(value) { + return typeof value == 'symbol' || + (isObjectLike(value) && baseGetTag(value) == symbolTag); + } + + /** + * Checks if `value` is classified as a typed array. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. + * @example + * + * _.isTypedArray(new Uint8Array); + * // => true + * + * _.isTypedArray([]); + * // => false + */ + var isTypedArray = nodeIsTypedArray ? baseUnary(nodeIsTypedArray) : baseIsTypedArray; + + /** + * Checks if `value` is `undefined`. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is `undefined`, else `false`. + * @example + * + * _.isUndefined(void 0); + * // => true + * + * _.isUndefined(null); + * // => false + */ + function isUndefined(value) { + return value === undefined; + } + + /** + * Checks if `value` is classified as a `WeakMap` object. + * + * @static + * @memberOf _ + * @since 4.3.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a weak map, else `false`. + * @example + * + * _.isWeakMap(new WeakMap); + * // => true + * + * _.isWeakMap(new Map); + * // => false + */ + function isWeakMap(value) { + return isObjectLike(value) && getTag(value) == weakMapTag; + } + + /** + * Checks if `value` is classified as a `WeakSet` object. + * + * @static + * @memberOf _ + * @since 4.3.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a weak set, else `false`. + * @example + * + * _.isWeakSet(new WeakSet); + * // => true + * + * _.isWeakSet(new Set); + * // => false + */ + function isWeakSet(value) { + return isObjectLike(value) && baseGetTag(value) == weakSetTag; + } + + /** + * Checks if `value` is less than `other`. + * + * @static + * @memberOf _ + * @since 3.9.0 + * @category Lang + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {boolean} Returns `true` if `value` is less than `other`, + * else `false`. + * @see _.gt + * @example + * + * _.lt(1, 3); + * // => true + * + * _.lt(3, 3); + * // => false + * + * _.lt(3, 1); + * // => false + */ + var lt = createRelationalOperation(baseLt); + + /** + * Checks if `value` is less than or equal to `other`. + * + * @static + * @memberOf _ + * @since 3.9.0 + * @category Lang + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {boolean} Returns `true` if `value` is less than or equal to + * `other`, else `false`. + * @see _.gte + * @example + * + * _.lte(1, 3); + * // => true + * + * _.lte(3, 3); + * // => true + * + * _.lte(3, 1); + * // => false + */ + var lte = createRelationalOperation(function(value, other) { + return value <= other; + }); + + /** + * Converts `value` to an array. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Lang + * @param {*} value The value to convert. + * @returns {Array} Returns the converted array. + * @example + * + * _.toArray({ 'a': 1, 'b': 2 }); + * // => [1, 2] + * + * _.toArray('abc'); + * // => ['a', 'b', 'c'] + * + * _.toArray(1); + * // => [] + * + * _.toArray(null); + * // => [] + */ + function toArray(value) { + if (!value) { + return []; + } + if (isArrayLike(value)) { + return isString(value) ? stringToArray(value) : copyArray(value); + } + if (symIterator && value[symIterator]) { + return iteratorToArray(value[symIterator]()); + } + var tag = getTag(value), + func = tag == mapTag ? mapToArray : (tag == setTag ? setToArray : values); + + return func(value); + } + + /** + * Converts `value` to a finite number. + * + * @static + * @memberOf _ + * @since 4.12.0 + * @category Lang + * @param {*} value The value to convert. + * @returns {number} Returns the converted number. + * @example + * + * _.toFinite(3.2); + * // => 3.2 + * + * _.toFinite(Number.MIN_VALUE); + * // => 5e-324 + * + * _.toFinite(Infinity); + * // => 1.7976931348623157e+308 + * + * _.toFinite('3.2'); + * // => 3.2 + */ + function toFinite(value) { + if (!value) { + return value === 0 ? value : 0; + } + value = toNumber(value); + if (value === INFINITY || value === -INFINITY) { + var sign = (value < 0 ? -1 : 1); + return sign * MAX_INTEGER; + } + return value === value ? value : 0; + } + + /** + * Converts `value` to an integer. + * + * **Note:** This method is loosely based on + * [`ToInteger`](http://www.ecma-international.org/ecma-262/7.0/#sec-tointeger). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to convert. + * @returns {number} Returns the converted integer. + * @example + * + * _.toInteger(3.2); + * // => 3 + * + * _.toInteger(Number.MIN_VALUE); + * // => 0 + * + * _.toInteger(Infinity); + * // => 1.7976931348623157e+308 + * + * _.toInteger('3.2'); + * // => 3 + */ + function toInteger(value) { + var result = toFinite(value), + remainder = result % 1; + + return result === result ? (remainder ? result - remainder : result) : 0; + } + + /** + * Converts `value` to an integer suitable for use as the length of an + * array-like object. + * + * **Note:** This method is based on + * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to convert. + * @returns {number} Returns the converted integer. + * @example + * + * _.toLength(3.2); + * // => 3 + * + * _.toLength(Number.MIN_VALUE); + * // => 0 + * + * _.toLength(Infinity); + * // => 4294967295 + * + * _.toLength('3.2'); + * // => 3 + */ + function toLength(value) { + return value ? baseClamp(toInteger(value), 0, MAX_ARRAY_LENGTH) : 0; + } + + /** + * Converts `value` to a number. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to process. + * @returns {number} Returns the number. + * @example + * + * _.toNumber(3.2); + * // => 3.2 + * + * _.toNumber(Number.MIN_VALUE); + * // => 5e-324 + * + * _.toNumber(Infinity); + * // => Infinity + * + * _.toNumber('3.2'); + * // => 3.2 + */ + function toNumber(value) { + if (typeof value == 'number') { + return value; + } + if (isSymbol(value)) { + return NAN; + } + if (isObject(value)) { + var other = typeof value.valueOf == 'function' ? value.valueOf() : value; + value = isObject(other) ? (other + '') : other; + } + if (typeof value != 'string') { + return value === 0 ? value : +value; + } + value = baseTrim(value); + var isBinary = reIsBinary.test(value); + return (isBinary || reIsOctal.test(value)) + ? freeParseInt(value.slice(2), isBinary ? 2 : 8) + : (reIsBadHex.test(value) ? NAN : +value); + } + + /** + * Converts `value` to a plain object flattening inherited enumerable string + * keyed properties of `value` to own properties of the plain object. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Lang + * @param {*} value The value to convert. + * @returns {Object} Returns the converted plain object. + * @example + * + * function Foo() { + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.assign({ 'a': 1 }, new Foo); + * // => { 'a': 1, 'b': 2 } + * + * _.assign({ 'a': 1 }, _.toPlainObject(new Foo)); + * // => { 'a': 1, 'b': 2, 'c': 3 } + */ + function toPlainObject(value) { + return copyObject(value, keysIn(value)); + } + + /** + * Converts `value` to a safe integer. A safe integer can be compared and + * represented correctly. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to convert. + * @returns {number} Returns the converted integer. + * @example + * + * _.toSafeInteger(3.2); + * // => 3 + * + * _.toSafeInteger(Number.MIN_VALUE); + * // => 0 + * + * _.toSafeInteger(Infinity); + * // => 9007199254740991 + * + * _.toSafeInteger('3.2'); + * // => 3 + */ + function toSafeInteger(value) { + return value + ? baseClamp(toInteger(value), -MAX_SAFE_INTEGER, MAX_SAFE_INTEGER) + : (value === 0 ? value : 0); + } + + /** + * Converts `value` to a string. An empty string is returned for `null` + * and `undefined` values. The sign of `-0` is preserved. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to convert. + * @returns {string} Returns the converted string. + * @example + * + * _.toString(null); + * // => '' + * + * _.toString(-0); + * // => '-0' + * + * _.toString([1, 2, 3]); + * // => '1,2,3' + */ + function toString(value) { + return value == null ? '' : baseToString(value); + } + + /*------------------------------------------------------------------------*/ + + /** + * Assigns own enumerable string keyed properties of source objects to the + * destination object. Source objects are applied from left to right. + * Subsequent sources overwrite property assignments of previous sources. + * + * **Note:** This method mutates `object` and is loosely based on + * [`Object.assign`](https://mdn.io/Object/assign). + * + * @static + * @memberOf _ + * @since 0.10.0 + * @category Object + * @param {Object} object The destination object. + * @param {...Object} [sources] The source objects. + * @returns {Object} Returns `object`. + * @see _.assignIn + * @example + * + * function Foo() { + * this.a = 1; + * } + * + * function Bar() { + * this.c = 3; + * } + * + * Foo.prototype.b = 2; + * Bar.prototype.d = 4; + * + * _.assign({ 'a': 0 }, new Foo, new Bar); + * // => { 'a': 1, 'c': 3 } + */ + var assign = createAssigner(function(object, source) { + if (isPrototype(source) || isArrayLike(source)) { + copyObject(source, keys(source), object); + return; + } + for (var key in source) { + if (hasOwnProperty.call(source, key)) { + assignValue(object, key, source[key]); + } + } + }); + + /** + * This method is like `_.assign` except that it iterates over own and + * inherited source properties. + * + * **Note:** This method mutates `object`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @alias extend + * @category Object + * @param {Object} object The destination object. + * @param {...Object} [sources] The source objects. + * @returns {Object} Returns `object`. + * @see _.assign + * @example + * + * function Foo() { + * this.a = 1; + * } + * + * function Bar() { + * this.c = 3; + * } + * + * Foo.prototype.b = 2; + * Bar.prototype.d = 4; + * + * _.assignIn({ 'a': 0 }, new Foo, new Bar); + * // => { 'a': 1, 'b': 2, 'c': 3, 'd': 4 } + */ + var assignIn = createAssigner(function(object, source) { + copyObject(source, keysIn(source), object); + }); + + /** + * This method is like `_.assignIn` except that it accepts `customizer` + * which is invoked to produce the assigned values. If `customizer` returns + * `undefined`, assignment is handled by the method instead. The `customizer` + * is invoked with five arguments: (objValue, srcValue, key, object, source). + * + * **Note:** This method mutates `object`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @alias extendWith + * @category Object + * @param {Object} object The destination object. + * @param {...Object} sources The source objects. + * @param {Function} [customizer] The function to customize assigned values. + * @returns {Object} Returns `object`. + * @see _.assignWith + * @example + * + * function customizer(objValue, srcValue) { + * return _.isUndefined(objValue) ? srcValue : objValue; + * } + * + * var defaults = _.partialRight(_.assignInWith, customizer); + * + * defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 }); + * // => { 'a': 1, 'b': 2 } + */ + var assignInWith = createAssigner(function(object, source, srcIndex, customizer) { + copyObject(source, keysIn(source), object, customizer); + }); + + /** + * This method is like `_.assign` except that it accepts `customizer` + * which is invoked to produce the assigned values. If `customizer` returns + * `undefined`, assignment is handled by the method instead. The `customizer` + * is invoked with five arguments: (objValue, srcValue, key, object, source). + * + * **Note:** This method mutates `object`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Object + * @param {Object} object The destination object. + * @param {...Object} sources The source objects. + * @param {Function} [customizer] The function to customize assigned values. + * @returns {Object} Returns `object`. + * @see _.assignInWith + * @example + * + * function customizer(objValue, srcValue) { + * return _.isUndefined(objValue) ? srcValue : objValue; + * } + * + * var defaults = _.partialRight(_.assignWith, customizer); + * + * defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 }); + * // => { 'a': 1, 'b': 2 } + */ + var assignWith = createAssigner(function(object, source, srcIndex, customizer) { + copyObject(source, keys(source), object, customizer); + }); + + /** + * Creates an array of values corresponding to `paths` of `object`. + * + * @static + * @memberOf _ + * @since 1.0.0 + * @category Object + * @param {Object} object The object to iterate over. + * @param {...(string|string[])} [paths] The property paths to pick. + * @returns {Array} Returns the picked values. + * @example + * + * var object = { 'a': [{ 'b': { 'c': 3 } }, 4] }; + * + * _.at(object, ['a[0].b.c', 'a[1]']); + * // => [3, 4] + */ + var at = flatRest(baseAt); + + /** + * Creates an object that inherits from the `prototype` object. If a + * `properties` object is given, its own enumerable string keyed properties + * are assigned to the created object. + * + * @static + * @memberOf _ + * @since 2.3.0 + * @category Object + * @param {Object} prototype The object to inherit from. + * @param {Object} [properties] The properties to assign to the object. + * @returns {Object} Returns the new object. + * @example + * + * function Shape() { + * this.x = 0; + * this.y = 0; + * } + * + * function Circle() { + * Shape.call(this); + * } + * + * Circle.prototype = _.create(Shape.prototype, { + * 'constructor': Circle + * }); + * + * var circle = new Circle; + * circle instanceof Circle; + * // => true + * + * circle instanceof Shape; + * // => true + */ + function create(prototype, properties) { + var result = baseCreate(prototype); + return properties == null ? result : baseAssign(result, properties); + } + + /** + * Assigns own and inherited enumerable string keyed properties of source + * objects to the destination object for all destination properties that + * resolve to `undefined`. Source objects are applied from left to right. + * Once a property is set, additional values of the same property are ignored. + * + * **Note:** This method mutates `object`. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Object + * @param {Object} object The destination object. + * @param {...Object} [sources] The source objects. + * @returns {Object} Returns `object`. + * @see _.defaultsDeep + * @example + * + * _.defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 }); + * // => { 'a': 1, 'b': 2 } + */ + var defaults = baseRest(function(object, sources) { + object = Object(object); + + var index = -1; + var length = sources.length; + var guard = length > 2 ? sources[2] : undefined; + + if (guard && isIterateeCall(sources[0], sources[1], guard)) { + length = 1; + } + + while (++index < length) { + var source = sources[index]; + var props = keysIn(source); + var propsIndex = -1; + var propsLength = props.length; + + while (++propsIndex < propsLength) { + var key = props[propsIndex]; + var value = object[key]; + + if (value === undefined || + (eq(value, objectProto[key]) && !hasOwnProperty.call(object, key))) { + object[key] = source[key]; + } + } + } + + return object; + }); + + /** + * This method is like `_.defaults` except that it recursively assigns + * default properties. + * + * **Note:** This method mutates `object`. + * + * @static + * @memberOf _ + * @since 3.10.0 + * @category Object + * @param {Object} object The destination object. + * @param {...Object} [sources] The source objects. + * @returns {Object} Returns `object`. + * @see _.defaults + * @example + * + * _.defaultsDeep({ 'a': { 'b': 2 } }, { 'a': { 'b': 1, 'c': 3 } }); + * // => { 'a': { 'b': 2, 'c': 3 } } + */ + var defaultsDeep = baseRest(function(args) { + args.push(undefined, customDefaultsMerge); + return apply(mergeWith, undefined, args); + }); + + /** + * This method is like `_.find` except that it returns the key of the first + * element `predicate` returns truthy for instead of the element itself. + * + * @static + * @memberOf _ + * @since 1.1.0 + * @category Object + * @param {Object} object The object to inspect. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @returns {string|undefined} Returns the key of the matched element, + * else `undefined`. + * @example + * + * var users = { + * 'barney': { 'age': 36, 'active': true }, + * 'fred': { 'age': 40, 'active': false }, + * 'pebbles': { 'age': 1, 'active': true } + * }; + * + * _.findKey(users, function(o) { return o.age < 40; }); + * // => 'barney' (iteration order is not guaranteed) + * + * // The `_.matches` iteratee shorthand. + * _.findKey(users, { 'age': 1, 'active': true }); + * // => 'pebbles' + * + * // The `_.matchesProperty` iteratee shorthand. + * _.findKey(users, ['active', false]); + * // => 'fred' + * + * // The `_.property` iteratee shorthand. + * _.findKey(users, 'active'); + * // => 'barney' + */ + function findKey(object, predicate) { + return baseFindKey(object, getIteratee(predicate, 3), baseForOwn); + } + + /** + * This method is like `_.findKey` except that it iterates over elements of + * a collection in the opposite order. + * + * @static + * @memberOf _ + * @since 2.0.0 + * @category Object + * @param {Object} object The object to inspect. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @returns {string|undefined} Returns the key of the matched element, + * else `undefined`. + * @example + * + * var users = { + * 'barney': { 'age': 36, 'active': true }, + * 'fred': { 'age': 40, 'active': false }, + * 'pebbles': { 'age': 1, 'active': true } + * }; + * + * _.findLastKey(users, function(o) { return o.age < 40; }); + * // => returns 'pebbles' assuming `_.findKey` returns 'barney' + * + * // The `_.matches` iteratee shorthand. + * _.findLastKey(users, { 'age': 36, 'active': true }); + * // => 'barney' + * + * // The `_.matchesProperty` iteratee shorthand. + * _.findLastKey(users, ['active', false]); + * // => 'fred' + * + * // The `_.property` iteratee shorthand. + * _.findLastKey(users, 'active'); + * // => 'pebbles' + */ + function findLastKey(object, predicate) { + return baseFindKey(object, getIteratee(predicate, 3), baseForOwnRight); + } + + /** + * Iterates over own and inherited enumerable string keyed properties of an + * object and invokes `iteratee` for each property. The iteratee is invoked + * with three arguments: (value, key, object). Iteratee functions may exit + * iteration early by explicitly returning `false`. + * + * @static + * @memberOf _ + * @since 0.3.0 + * @category Object + * @param {Object} object The object to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @returns {Object} Returns `object`. + * @see _.forInRight + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.forIn(new Foo, function(value, key) { + * console.log(key); + * }); + * // => Logs 'a', 'b', then 'c' (iteration order is not guaranteed). + */ + function forIn(object, iteratee) { + return object == null + ? object + : baseFor(object, getIteratee(iteratee, 3), keysIn); + } + + /** + * This method is like `_.forIn` except that it iterates over properties of + * `object` in the opposite order. + * + * @static + * @memberOf _ + * @since 2.0.0 + * @category Object + * @param {Object} object The object to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @returns {Object} Returns `object`. + * @see _.forIn + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.forInRight(new Foo, function(value, key) { + * console.log(key); + * }); + * // => Logs 'c', 'b', then 'a' assuming `_.forIn` logs 'a', 'b', then 'c'. + */ + function forInRight(object, iteratee) { + return object == null + ? object + : baseForRight(object, getIteratee(iteratee, 3), keysIn); + } + + /** + * Iterates over own enumerable string keyed properties of an object and + * invokes `iteratee` for each property. The iteratee is invoked with three + * arguments: (value, key, object). Iteratee functions may exit iteration + * early by explicitly returning `false`. + * + * @static + * @memberOf _ + * @since 0.3.0 + * @category Object + * @param {Object} object The object to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @returns {Object} Returns `object`. + * @see _.forOwnRight + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.forOwn(new Foo, function(value, key) { + * console.log(key); + * }); + * // => Logs 'a' then 'b' (iteration order is not guaranteed). + */ + function forOwn(object, iteratee) { + return object && baseForOwn(object, getIteratee(iteratee, 3)); + } + + /** + * This method is like `_.forOwn` except that it iterates over properties of + * `object` in the opposite order. + * + * @static + * @memberOf _ + * @since 2.0.0 + * @category Object + * @param {Object} object The object to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @returns {Object} Returns `object`. + * @see _.forOwn + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.forOwnRight(new Foo, function(value, key) { + * console.log(key); + * }); + * // => Logs 'b' then 'a' assuming `_.forOwn` logs 'a' then 'b'. + */ + function forOwnRight(object, iteratee) { + return object && baseForOwnRight(object, getIteratee(iteratee, 3)); + } + + /** + * Creates an array of function property names from own enumerable properties + * of `object`. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Object + * @param {Object} object The object to inspect. + * @returns {Array} Returns the function names. + * @see _.functionsIn + * @example + * + * function Foo() { + * this.a = _.constant('a'); + * this.b = _.constant('b'); + * } + * + * Foo.prototype.c = _.constant('c'); + * + * _.functions(new Foo); + * // => ['a', 'b'] + */ + function functions(object) { + return object == null ? [] : baseFunctions(object, keys(object)); + } + + /** + * Creates an array of function property names from own and inherited + * enumerable properties of `object`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Object + * @param {Object} object The object to inspect. + * @returns {Array} Returns the function names. + * @see _.functions + * @example + * + * function Foo() { + * this.a = _.constant('a'); + * this.b = _.constant('b'); + * } + * + * Foo.prototype.c = _.constant('c'); + * + * _.functionsIn(new Foo); + * // => ['a', 'b', 'c'] + */ + function functionsIn(object) { + return object == null ? [] : baseFunctions(object, keysIn(object)); + } + + /** + * Gets the value at `path` of `object`. If the resolved value is + * `undefined`, the `defaultValue` is returned in its place. + * + * @static + * @memberOf _ + * @since 3.7.0 + * @category Object + * @param {Object} object The object to query. + * @param {Array|string} path The path of the property to get. + * @param {*} [defaultValue] The value returned for `undefined` resolved values. + * @returns {*} Returns the resolved value. + * @example + * + * var object = { 'a': [{ 'b': { 'c': 3 } }] }; + * + * _.get(object, 'a[0].b.c'); + * // => 3 + * + * _.get(object, ['a', '0', 'b', 'c']); + * // => 3 + * + * _.get(object, 'a.b.c', 'default'); + * // => 'default' + */ + function get(object, path, defaultValue) { + var result = object == null ? undefined : baseGet(object, path); + return result === undefined ? defaultValue : result; + } + + /** + * Checks if `path` is a direct property of `object`. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Object + * @param {Object} object The object to query. + * @param {Array|string} path The path to check. + * @returns {boolean} Returns `true` if `path` exists, else `false`. + * @example + * + * var object = { 'a': { 'b': 2 } }; + * var other = _.create({ 'a': _.create({ 'b': 2 }) }); + * + * _.has(object, 'a'); + * // => true + * + * _.has(object, 'a.b'); + * // => true + * + * _.has(object, ['a', 'b']); + * // => true + * + * _.has(other, 'a'); + * // => false + */ + function has(object, path) { + return object != null && hasPath(object, path, baseHas); + } + + /** + * Checks if `path` is a direct or inherited property of `object`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Object + * @param {Object} object The object to query. + * @param {Array|string} path The path to check. + * @returns {boolean} Returns `true` if `path` exists, else `false`. + * @example + * + * var object = _.create({ 'a': _.create({ 'b': 2 }) }); + * + * _.hasIn(object, 'a'); + * // => true + * + * _.hasIn(object, 'a.b'); + * // => true + * + * _.hasIn(object, ['a', 'b']); + * // => true + * + * _.hasIn(object, 'b'); + * // => false + */ + function hasIn(object, path) { + return object != null && hasPath(object, path, baseHasIn); + } + + /** + * Creates an object composed of the inverted keys and values of `object`. + * If `object` contains duplicate values, subsequent values overwrite + * property assignments of previous values. + * + * @static + * @memberOf _ + * @since 0.7.0 + * @category Object + * @param {Object} object The object to invert. + * @returns {Object} Returns the new inverted object. + * @example + * + * var object = { 'a': 1, 'b': 2, 'c': 1 }; + * + * _.invert(object); + * // => { '1': 'c', '2': 'b' } + */ + var invert = createInverter(function(result, value, key) { + if (value != null && + typeof value.toString != 'function') { + value = nativeObjectToString.call(value); + } + + result[value] = key; + }, constant(identity)); + + /** + * This method is like `_.invert` except that the inverted object is generated + * from the results of running each element of `object` thru `iteratee`. The + * corresponding inverted value of each inverted key is an array of keys + * responsible for generating the inverted value. The iteratee is invoked + * with one argument: (value). + * + * @static + * @memberOf _ + * @since 4.1.0 + * @category Object + * @param {Object} object The object to invert. + * @param {Function} [iteratee=_.identity] The iteratee invoked per element. + * @returns {Object} Returns the new inverted object. + * @example + * + * var object = { 'a': 1, 'b': 2, 'c': 1 }; + * + * _.invertBy(object); + * // => { '1': ['a', 'c'], '2': ['b'] } + * + * _.invertBy(object, function(value) { + * return 'group' + value; + * }); + * // => { 'group1': ['a', 'c'], 'group2': ['b'] } + */ + var invertBy = createInverter(function(result, value, key) { + if (value != null && + typeof value.toString != 'function') { + value = nativeObjectToString.call(value); + } + + if (hasOwnProperty.call(result, value)) { + result[value].push(key); + } else { + result[value] = [key]; + } + }, getIteratee); + + /** + * Invokes the method at `path` of `object`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Object + * @param {Object} object The object to query. + * @param {Array|string} path The path of the method to invoke. + * @param {...*} [args] The arguments to invoke the method with. + * @returns {*} Returns the result of the invoked method. + * @example + * + * var object = { 'a': [{ 'b': { 'c': [1, 2, 3, 4] } }] }; + * + * _.invoke(object, 'a[0].b.c.slice', 1, 3); + * // => [2, 3] + */ + var invoke = baseRest(baseInvoke); + + /** + * Creates an array of the own enumerable property names of `object`. + * + * **Note:** Non-object values are coerced to objects. See the + * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) + * for more details. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Object + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names. + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.keys(new Foo); + * // => ['a', 'b'] (iteration order is not guaranteed) + * + * _.keys('hi'); + * // => ['0', '1'] + */ + function keys(object) { + return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object); + } + + /** + * Creates an array of the own and inherited enumerable property names of `object`. + * + * **Note:** Non-object values are coerced to objects. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Object + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names. + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.keysIn(new Foo); + * // => ['a', 'b', 'c'] (iteration order is not guaranteed) + */ + function keysIn(object) { + return isArrayLike(object) ? arrayLikeKeys(object, true) : baseKeysIn(object); + } + + /** + * The opposite of `_.mapValues`; this method creates an object with the + * same values as `object` and keys generated by running each own enumerable + * string keyed property of `object` thru `iteratee`. The iteratee is invoked + * with three arguments: (value, key, object). + * + * @static + * @memberOf _ + * @since 3.8.0 + * @category Object + * @param {Object} object The object to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @returns {Object} Returns the new mapped object. + * @see _.mapValues + * @example + * + * _.mapKeys({ 'a': 1, 'b': 2 }, function(value, key) { + * return key + value; + * }); + * // => { 'a1': 1, 'b2': 2 } + */ + function mapKeys(object, iteratee) { + var result = {}; + iteratee = getIteratee(iteratee, 3); + + baseForOwn(object, function(value, key, object) { + baseAssignValue(result, iteratee(value, key, object), value); + }); + return result; + } + + /** + * Creates an object with the same keys as `object` and values generated + * by running each own enumerable string keyed property of `object` thru + * `iteratee`. The iteratee is invoked with three arguments: + * (value, key, object). + * + * @static + * @memberOf _ + * @since 2.4.0 + * @category Object + * @param {Object} object The object to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @returns {Object} Returns the new mapped object. + * @see _.mapKeys + * @example + * + * var users = { + * 'fred': { 'user': 'fred', 'age': 40 }, + * 'pebbles': { 'user': 'pebbles', 'age': 1 } + * }; + * + * _.mapValues(users, function(o) { return o.age; }); + * // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed) + * + * // The `_.property` iteratee shorthand. + * _.mapValues(users, 'age'); + * // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed) + */ + function mapValues(object, iteratee) { + var result = {}; + iteratee = getIteratee(iteratee, 3); + + baseForOwn(object, function(value, key, object) { + baseAssignValue(result, key, iteratee(value, key, object)); + }); + return result; + } + + /** + * This method is like `_.assign` except that it recursively merges own and + * inherited enumerable string keyed properties of source objects into the + * destination object. Source properties that resolve to `undefined` are + * skipped if a destination value exists. Array and plain object properties + * are merged recursively. Other objects and value types are overridden by + * assignment. Source objects are applied from left to right. Subsequent + * sources overwrite property assignments of previous sources. + * + * **Note:** This method mutates `object`. + * + * @static + * @memberOf _ + * @since 0.5.0 + * @category Object + * @param {Object} object The destination object. + * @param {...Object} [sources] The source objects. + * @returns {Object} Returns `object`. + * @example + * + * var object = { + * 'a': [{ 'b': 2 }, { 'd': 4 }] + * }; + * + * var other = { + * 'a': [{ 'c': 3 }, { 'e': 5 }] + * }; + * + * _.merge(object, other); + * // => { 'a': [{ 'b': 2, 'c': 3 }, { 'd': 4, 'e': 5 }] } + */ + var merge = createAssigner(function(object, source, srcIndex) { + baseMerge(object, source, srcIndex); + }); + + /** + * This method is like `_.merge` except that it accepts `customizer` which + * is invoked to produce the merged values of the destination and source + * properties. If `customizer` returns `undefined`, merging is handled by the + * method instead. The `customizer` is invoked with six arguments: + * (objValue, srcValue, key, object, source, stack). + * + * **Note:** This method mutates `object`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Object + * @param {Object} object The destination object. + * @param {...Object} sources The source objects. + * @param {Function} customizer The function to customize assigned values. + * @returns {Object} Returns `object`. + * @example + * + * function customizer(objValue, srcValue) { + * if (_.isArray(objValue)) { + * return objValue.concat(srcValue); + * } + * } + * + * var object = { 'a': [1], 'b': [2] }; + * var other = { 'a': [3], 'b': [4] }; + * + * _.mergeWith(object, other, customizer); + * // => { 'a': [1, 3], 'b': [2, 4] } + */ + var mergeWith = createAssigner(function(object, source, srcIndex, customizer) { + baseMerge(object, source, srcIndex, customizer); + }); + + /** + * The opposite of `_.pick`; this method creates an object composed of the + * own and inherited enumerable property paths of `object` that are not omitted. + * + * **Note:** This method is considerably slower than `_.pick`. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Object + * @param {Object} object The source object. + * @param {...(string|string[])} [paths] The property paths to omit. + * @returns {Object} Returns the new object. + * @example + * + * var object = { 'a': 1, 'b': '2', 'c': 3 }; + * + * _.omit(object, ['a', 'c']); + * // => { 'b': '2' } + */ + var omit = flatRest(function(object, paths) { + var result = {}; + if (object == null) { + return result; + } + var isDeep = false; + paths = arrayMap(paths, function(path) { + path = castPath(path, object); + isDeep || (isDeep = path.length > 1); + return path; + }); + copyObject(object, getAllKeysIn(object), result); + if (isDeep) { + result = baseClone(result, CLONE_DEEP_FLAG | CLONE_FLAT_FLAG | CLONE_SYMBOLS_FLAG, customOmitClone); + } + var length = paths.length; + while (length--) { + baseUnset(result, paths[length]); + } + return result; + }); + + /** + * The opposite of `_.pickBy`; this method creates an object composed of + * the own and inherited enumerable string keyed properties of `object` that + * `predicate` doesn't return truthy for. The predicate is invoked with two + * arguments: (value, key). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Object + * @param {Object} object The source object. + * @param {Function} [predicate=_.identity] The function invoked per property. + * @returns {Object} Returns the new object. + * @example + * + * var object = { 'a': 1, 'b': '2', 'c': 3 }; + * + * _.omitBy(object, _.isNumber); + * // => { 'b': '2' } + */ + function omitBy(object, predicate) { + return pickBy(object, negate(getIteratee(predicate))); + } + + /** + * Creates an object composed of the picked `object` properties. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Object + * @param {Object} object The source object. + * @param {...(string|string[])} [paths] The property paths to pick. + * @returns {Object} Returns the new object. + * @example + * + * var object = { 'a': 1, 'b': '2', 'c': 3 }; + * + * _.pick(object, ['a', 'c']); + * // => { 'a': 1, 'c': 3 } + */ + var pick = flatRest(function(object, paths) { + return object == null ? {} : basePick(object, paths); + }); + + /** + * Creates an object composed of the `object` properties `predicate` returns + * truthy for. The predicate is invoked with two arguments: (value, key). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Object + * @param {Object} object The source object. + * @param {Function} [predicate=_.identity] The function invoked per property. + * @returns {Object} Returns the new object. + * @example + * + * var object = { 'a': 1, 'b': '2', 'c': 3 }; + * + * _.pickBy(object, _.isNumber); + * // => { 'a': 1, 'c': 3 } + */ + function pickBy(object, predicate) { + if (object == null) { + return {}; + } + var props = arrayMap(getAllKeysIn(object), function(prop) { + return [prop]; + }); + predicate = getIteratee(predicate); + return basePickBy(object, props, function(value, path) { + return predicate(value, path[0]); + }); + } + + /** + * This method is like `_.get` except that if the resolved value is a + * function it's invoked with the `this` binding of its parent object and + * its result is returned. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Object + * @param {Object} object The object to query. + * @param {Array|string} path The path of the property to resolve. + * @param {*} [defaultValue] The value returned for `undefined` resolved values. + * @returns {*} Returns the resolved value. + * @example + * + * var object = { 'a': [{ 'b': { 'c1': 3, 'c2': _.constant(4) } }] }; + * + * _.result(object, 'a[0].b.c1'); + * // => 3 + * + * _.result(object, 'a[0].b.c2'); + * // => 4 + * + * _.result(object, 'a[0].b.c3', 'default'); + * // => 'default' + * + * _.result(object, 'a[0].b.c3', _.constant('default')); + * // => 'default' + */ + function result(object, path, defaultValue) { + path = castPath(path, object); + + var index = -1, + length = path.length; + + // Ensure the loop is entered when path is empty. + if (!length) { + length = 1; + object = undefined; + } + while (++index < length) { + var value = object == null ? undefined : object[toKey(path[index])]; + if (value === undefined) { + index = length; + value = defaultValue; + } + object = isFunction(value) ? value.call(object) : value; + } + return object; + } + + /** + * Sets the value at `path` of `object`. If a portion of `path` doesn't exist, + * it's created. Arrays are created for missing index properties while objects + * are created for all other missing properties. Use `_.setWith` to customize + * `path` creation. + * + * **Note:** This method mutates `object`. + * + * @static + * @memberOf _ + * @since 3.7.0 + * @category Object + * @param {Object} object The object to modify. + * @param {Array|string} path The path of the property to set. + * @param {*} value The value to set. + * @returns {Object} Returns `object`. + * @example + * + * var object = { 'a': [{ 'b': { 'c': 3 } }] }; + * + * _.set(object, 'a[0].b.c', 4); + * console.log(object.a[0].b.c); + * // => 4 + * + * _.set(object, ['x', '0', 'y', 'z'], 5); + * console.log(object.x[0].y.z); + * // => 5 + */ + function set(object, path, value) { + return object == null ? object : baseSet(object, path, value); + } + + /** + * This method is like `_.set` except that it accepts `customizer` which is + * invoked to produce the objects of `path`. If `customizer` returns `undefined` + * path creation is handled by the method instead. The `customizer` is invoked + * with three arguments: (nsValue, key, nsObject). + * + * **Note:** This method mutates `object`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Object + * @param {Object} object The object to modify. + * @param {Array|string} path The path of the property to set. + * @param {*} value The value to set. + * @param {Function} [customizer] The function to customize assigned values. + * @returns {Object} Returns `object`. + * @example + * + * var object = {}; + * + * _.setWith(object, '[0][1]', 'a', Object); + * // => { '0': { '1': 'a' } } + */ + function setWith(object, path, value, customizer) { + customizer = typeof customizer == 'function' ? customizer : undefined; + return object == null ? object : baseSet(object, path, value, customizer); + } + + /** + * Creates an array of own enumerable string keyed-value pairs for `object` + * which can be consumed by `_.fromPairs`. If `object` is a map or set, its + * entries are returned. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @alias entries + * @category Object + * @param {Object} object The object to query. + * @returns {Array} Returns the key-value pairs. + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.toPairs(new Foo); + * // => [['a', 1], ['b', 2]] (iteration order is not guaranteed) + */ + var toPairs = createToPairs(keys); + + /** + * Creates an array of own and inherited enumerable string keyed-value pairs + * for `object` which can be consumed by `_.fromPairs`. If `object` is a map + * or set, its entries are returned. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @alias entriesIn + * @category Object + * @param {Object} object The object to query. + * @returns {Array} Returns the key-value pairs. + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.toPairsIn(new Foo); + * // => [['a', 1], ['b', 2], ['c', 3]] (iteration order is not guaranteed) + */ + var toPairsIn = createToPairs(keysIn); + + /** + * An alternative to `_.reduce`; this method transforms `object` to a new + * `accumulator` object which is the result of running each of its own + * enumerable string keyed properties thru `iteratee`, with each invocation + * potentially mutating the `accumulator` object. If `accumulator` is not + * provided, a new object with the same `[[Prototype]]` will be used. The + * iteratee is invoked with four arguments: (accumulator, value, key, object). + * Iteratee functions may exit iteration early by explicitly returning `false`. + * + * @static + * @memberOf _ + * @since 1.3.0 + * @category Object + * @param {Object} object The object to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @param {*} [accumulator] The custom accumulator value. + * @returns {*} Returns the accumulated value. + * @example + * + * _.transform([2, 3, 4], function(result, n) { + * result.push(n *= n); + * return n % 2 == 0; + * }, []); + * // => [4, 9] + * + * _.transform({ 'a': 1, 'b': 2, 'c': 1 }, function(result, value, key) { + * (result[value] || (result[value] = [])).push(key); + * }, {}); + * // => { '1': ['a', 'c'], '2': ['b'] } + */ + function transform(object, iteratee, accumulator) { + var isArr = isArray(object), + isArrLike = isArr || isBuffer(object) || isTypedArray(object); + + iteratee = getIteratee(iteratee, 4); + if (accumulator == null) { + var Ctor = object && object.constructor; + if (isArrLike) { + accumulator = isArr ? new Ctor : []; + } + else if (isObject(object)) { + accumulator = isFunction(Ctor) ? baseCreate(getPrototype(object)) : {}; + } + else { + accumulator = {}; + } + } + (isArrLike ? arrayEach : baseForOwn)(object, function(value, index, object) { + return iteratee(accumulator, value, index, object); + }); + return accumulator; + } + + /** + * Removes the property at `path` of `object`. + * + * **Note:** This method mutates `object`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Object + * @param {Object} object The object to modify. + * @param {Array|string} path The path of the property to unset. + * @returns {boolean} Returns `true` if the property is deleted, else `false`. + * @example + * + * var object = { 'a': [{ 'b': { 'c': 7 } }] }; + * _.unset(object, 'a[0].b.c'); + * // => true + * + * console.log(object); + * // => { 'a': [{ 'b': {} }] }; + * + * _.unset(object, ['a', '0', 'b', 'c']); + * // => true + * + * console.log(object); + * // => { 'a': [{ 'b': {} }] }; + */ + function unset(object, path) { + return object == null ? true : baseUnset(object, path); + } + + /** + * This method is like `_.set` except that accepts `updater` to produce the + * value to set. Use `_.updateWith` to customize `path` creation. The `updater` + * is invoked with one argument: (value). + * + * **Note:** This method mutates `object`. + * + * @static + * @memberOf _ + * @since 4.6.0 + * @category Object + * @param {Object} object The object to modify. + * @param {Array|string} path The path of the property to set. + * @param {Function} updater The function to produce the updated value. + * @returns {Object} Returns `object`. + * @example + * + * var object = { 'a': [{ 'b': { 'c': 3 } }] }; + * + * _.update(object, 'a[0].b.c', function(n) { return n * n; }); + * console.log(object.a[0].b.c); + * // => 9 + * + * _.update(object, 'x[0].y.z', function(n) { return n ? n + 1 : 0; }); + * console.log(object.x[0].y.z); + * // => 0 + */ + function update(object, path, updater) { + return object == null ? object : baseUpdate(object, path, castFunction(updater)); + } + + /** + * This method is like `_.update` except that it accepts `customizer` which is + * invoked to produce the objects of `path`. If `customizer` returns `undefined` + * path creation is handled by the method instead. The `customizer` is invoked + * with three arguments: (nsValue, key, nsObject). + * + * **Note:** This method mutates `object`. + * + * @static + * @memberOf _ + * @since 4.6.0 + * @category Object + * @param {Object} object The object to modify. + * @param {Array|string} path The path of the property to set. + * @param {Function} updater The function to produce the updated value. + * @param {Function} [customizer] The function to customize assigned values. + * @returns {Object} Returns `object`. + * @example + * + * var object = {}; + * + * _.updateWith(object, '[0][1]', _.constant('a'), Object); + * // => { '0': { '1': 'a' } } + */ + function updateWith(object, path, updater, customizer) { + customizer = typeof customizer == 'function' ? customizer : undefined; + return object == null ? object : baseUpdate(object, path, castFunction(updater), customizer); + } + + /** + * Creates an array of the own enumerable string keyed property values of `object`. + * + * **Note:** Non-object values are coerced to objects. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Object + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property values. + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.values(new Foo); + * // => [1, 2] (iteration order is not guaranteed) + * + * _.values('hi'); + * // => ['h', 'i'] + */ + function values(object) { + return object == null ? [] : baseValues(object, keys(object)); + } + + /** + * Creates an array of the own and inherited enumerable string keyed property + * values of `object`. + * + * **Note:** Non-object values are coerced to objects. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Object + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property values. + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.valuesIn(new Foo); + * // => [1, 2, 3] (iteration order is not guaranteed) + */ + function valuesIn(object) { + return object == null ? [] : baseValues(object, keysIn(object)); + } + + /*------------------------------------------------------------------------*/ + + /** + * Clamps `number` within the inclusive `lower` and `upper` bounds. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Number + * @param {number} number The number to clamp. + * @param {number} [lower] The lower bound. + * @param {number} upper The upper bound. + * @returns {number} Returns the clamped number. + * @example + * + * _.clamp(-10, -5, 5); + * // => -5 + * + * _.clamp(10, -5, 5); + * // => 5 + */ + function clamp(number, lower, upper) { + if (upper === undefined) { + upper = lower; + lower = undefined; + } + if (upper !== undefined) { + upper = toNumber(upper); + upper = upper === upper ? upper : 0; + } + if (lower !== undefined) { + lower = toNumber(lower); + lower = lower === lower ? lower : 0; + } + return baseClamp(toNumber(number), lower, upper); + } + + /** + * Checks if `n` is between `start` and up to, but not including, `end`. If + * `end` is not specified, it's set to `start` with `start` then set to `0`. + * If `start` is greater than `end` the params are swapped to support + * negative ranges. + * + * @static + * @memberOf _ + * @since 3.3.0 + * @category Number + * @param {number} number The number to check. + * @param {number} [start=0] The start of the range. + * @param {number} end The end of the range. + * @returns {boolean} Returns `true` if `number` is in the range, else `false`. + * @see _.range, _.rangeRight + * @example + * + * _.inRange(3, 2, 4); + * // => true + * + * _.inRange(4, 8); + * // => true + * + * _.inRange(4, 2); + * // => false + * + * _.inRange(2, 2); + * // => false + * + * _.inRange(1.2, 2); + * // => true + * + * _.inRange(5.2, 4); + * // => false + * + * _.inRange(-3, -2, -6); + * // => true + */ + function inRange(number, start, end) { + start = toFinite(start); + if (end === undefined) { + end = start; + start = 0; + } else { + end = toFinite(end); + } + number = toNumber(number); + return baseInRange(number, start, end); + } + + /** + * Produces a random number between the inclusive `lower` and `upper` bounds. + * If only one argument is provided a number between `0` and the given number + * is returned. If `floating` is `true`, or either `lower` or `upper` are + * floats, a floating-point number is returned instead of an integer. + * + * **Note:** JavaScript follows the IEEE-754 standard for resolving + * floating-point values which can produce unexpected results. + * + * @static + * @memberOf _ + * @since 0.7.0 + * @category Number + * @param {number} [lower=0] The lower bound. + * @param {number} [upper=1] The upper bound. + * @param {boolean} [floating] Specify returning a floating-point number. + * @returns {number} Returns the random number. + * @example + * + * _.random(0, 5); + * // => an integer between 0 and 5 + * + * _.random(5); + * // => also an integer between 0 and 5 + * + * _.random(5, true); + * // => a floating-point number between 0 and 5 + * + * _.random(1.2, 5.2); + * // => a floating-point number between 1.2 and 5.2 + */ + function random(lower, upper, floating) { + if (floating && typeof floating != 'boolean' && isIterateeCall(lower, upper, floating)) { + upper = floating = undefined; + } + if (floating === undefined) { + if (typeof upper == 'boolean') { + floating = upper; + upper = undefined; + } + else if (typeof lower == 'boolean') { + floating = lower; + lower = undefined; + } + } + if (lower === undefined && upper === undefined) { + lower = 0; + upper = 1; + } + else { + lower = toFinite(lower); + if (upper === undefined) { + upper = lower; + lower = 0; + } else { + upper = toFinite(upper); + } + } + if (lower > upper) { + var temp = lower; + lower = upper; + upper = temp; + } + if (floating || lower % 1 || upper % 1) { + var rand = nativeRandom(); + return nativeMin(lower + (rand * (upper - lower + freeParseFloat('1e-' + ((rand + '').length - 1)))), upper); + } + return baseRandom(lower, upper); + } + + /*------------------------------------------------------------------------*/ + + /** + * Converts `string` to [camel case](https://en.wikipedia.org/wiki/CamelCase). + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category String + * @param {string} [string=''] The string to convert. + * @returns {string} Returns the camel cased string. + * @example + * + * _.camelCase('Foo Bar'); + * // => 'fooBar' + * + * _.camelCase('--foo-bar--'); + * // => 'fooBar' + * + * _.camelCase('__FOO_BAR__'); + * // => 'fooBar' + */ + var camelCase = createCompounder(function(result, word, index) { + word = word.toLowerCase(); + return result + (index ? capitalize(word) : word); + }); + + /** + * Converts the first character of `string` to upper case and the remaining + * to lower case. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category String + * @param {string} [string=''] The string to capitalize. + * @returns {string} Returns the capitalized string. + * @example + * + * _.capitalize('FRED'); + * // => 'Fred' + */ + function capitalize(string) { + return upperFirst(toString(string).toLowerCase()); + } + + /** + * Deburrs `string` by converting + * [Latin-1 Supplement](https://en.wikipedia.org/wiki/Latin-1_Supplement_(Unicode_block)#Character_table) + * and [Latin Extended-A](https://en.wikipedia.org/wiki/Latin_Extended-A) + * letters to basic Latin letters and removing + * [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks). + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category String + * @param {string} [string=''] The string to deburr. + * @returns {string} Returns the deburred string. + * @example + * + * _.deburr('déjà vu'); + * // => 'deja vu' + */ + function deburr(string) { + string = toString(string); + return string && string.replace(reLatin, deburrLetter).replace(reComboMark, ''); + } + + /** + * Checks if `string` ends with the given target string. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category String + * @param {string} [string=''] The string to inspect. + * @param {string} [target] The string to search for. + * @param {number} [position=string.length] The position to search up to. + * @returns {boolean} Returns `true` if `string` ends with `target`, + * else `false`. + * @example + * + * _.endsWith('abc', 'c'); + * // => true + * + * _.endsWith('abc', 'b'); + * // => false + * + * _.endsWith('abc', 'b', 2); + * // => true + */ + function endsWith(string, target, position) { + string = toString(string); + target = baseToString(target); + + var length = string.length; + position = position === undefined + ? length + : baseClamp(toInteger(position), 0, length); + + var end = position; + position -= target.length; + return position >= 0 && string.slice(position, end) == target; + } + + /** + * Converts the characters "&", "<", ">", '"', and "'" in `string` to their + * corresponding HTML entities. + * + * **Note:** No other characters are escaped. To escape additional + * characters use a third-party library like [_he_](https://mths.be/he). + * + * Though the ">" character is escaped for symmetry, characters like + * ">" and "/" don't need escaping in HTML and have no special meaning + * unless they're part of a tag or unquoted attribute value. See + * [Mathias Bynens's article](https://mathiasbynens.be/notes/ambiguous-ampersands) + * (under "semi-related fun fact") for more details. + * + * When working with HTML you should always + * [quote attribute values](http://wonko.com/post/html-escaping) to reduce + * XSS vectors. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category String + * @param {string} [string=''] The string to escape. + * @returns {string} Returns the escaped string. + * @example + * + * _.escape('fred, barney, & pebbles'); + * // => 'fred, barney, & pebbles' + */ + function escape(string) { + string = toString(string); + return (string && reHasUnescapedHtml.test(string)) + ? string.replace(reUnescapedHtml, escapeHtmlChar) + : string; + } + + /** + * Escapes the `RegExp` special characters "^", "$", "\", ".", "*", "+", + * "?", "(", ")", "[", "]", "{", "}", and "|" in `string`. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category String + * @param {string} [string=''] The string to escape. + * @returns {string} Returns the escaped string. + * @example + * + * _.escapeRegExp('[lodash](https://lodash.com/)'); + * // => '\[lodash\]\(https://lodash\.com/\)' + */ + function escapeRegExp(string) { + string = toString(string); + return (string && reHasRegExpChar.test(string)) + ? string.replace(reRegExpChar, '\\$&') + : string; + } + + /** + * Converts `string` to + * [kebab case](https://en.wikipedia.org/wiki/Letter_case#Special_case_styles). + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category String + * @param {string} [string=''] The string to convert. + * @returns {string} Returns the kebab cased string. + * @example + * + * _.kebabCase('Foo Bar'); + * // => 'foo-bar' + * + * _.kebabCase('fooBar'); + * // => 'foo-bar' + * + * _.kebabCase('__FOO_BAR__'); + * // => 'foo-bar' + */ + var kebabCase = createCompounder(function(result, word, index) { + return result + (index ? '-' : '') + word.toLowerCase(); + }); + + /** + * Converts `string`, as space separated words, to lower case. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category String + * @param {string} [string=''] The string to convert. + * @returns {string} Returns the lower cased string. + * @example + * + * _.lowerCase('--Foo-Bar--'); + * // => 'foo bar' + * + * _.lowerCase('fooBar'); + * // => 'foo bar' + * + * _.lowerCase('__FOO_BAR__'); + * // => 'foo bar' + */ + var lowerCase = createCompounder(function(result, word, index) { + return result + (index ? ' ' : '') + word.toLowerCase(); + }); + + /** + * Converts the first character of `string` to lower case. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category String + * @param {string} [string=''] The string to convert. + * @returns {string} Returns the converted string. + * @example + * + * _.lowerFirst('Fred'); + * // => 'fred' + * + * _.lowerFirst('FRED'); + * // => 'fRED' + */ + var lowerFirst = createCaseFirst('toLowerCase'); + + /** + * Pads `string` on the left and right sides if it's shorter than `length`. + * Padding characters are truncated if they can't be evenly divided by `length`. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category String + * @param {string} [string=''] The string to pad. + * @param {number} [length=0] The padding length. + * @param {string} [chars=' '] The string used as padding. + * @returns {string} Returns the padded string. + * @example + * + * _.pad('abc', 8); + * // => ' abc ' + * + * _.pad('abc', 8, '_-'); + * // => '_-abc_-_' + * + * _.pad('abc', 3); + * // => 'abc' + */ + function pad(string, length, chars) { + string = toString(string); + length = toInteger(length); + + var strLength = length ? stringSize(string) : 0; + if (!length || strLength >= length) { + return string; + } + var mid = (length - strLength) / 2; + return ( + createPadding(nativeFloor(mid), chars) + + string + + createPadding(nativeCeil(mid), chars) + ); + } + + /** + * Pads `string` on the right side if it's shorter than `length`. Padding + * characters are truncated if they exceed `length`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category String + * @param {string} [string=''] The string to pad. + * @param {number} [length=0] The padding length. + * @param {string} [chars=' '] The string used as padding. + * @returns {string} Returns the padded string. + * @example + * + * _.padEnd('abc', 6); + * // => 'abc ' + * + * _.padEnd('abc', 6, '_-'); + * // => 'abc_-_' + * + * _.padEnd('abc', 3); + * // => 'abc' + */ + function padEnd(string, length, chars) { + string = toString(string); + length = toInteger(length); + + var strLength = length ? stringSize(string) : 0; + return (length && strLength < length) + ? (string + createPadding(length - strLength, chars)) + : string; + } + + /** + * Pads `string` on the left side if it's shorter than `length`. Padding + * characters are truncated if they exceed `length`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category String + * @param {string} [string=''] The string to pad. + * @param {number} [length=0] The padding length. + * @param {string} [chars=' '] The string used as padding. + * @returns {string} Returns the padded string. + * @example + * + * _.padStart('abc', 6); + * // => ' abc' + * + * _.padStart('abc', 6, '_-'); + * // => '_-_abc' + * + * _.padStart('abc', 3); + * // => 'abc' + */ + function padStart(string, length, chars) { + string = toString(string); + length = toInteger(length); + + var strLength = length ? stringSize(string) : 0; + return (length && strLength < length) + ? (createPadding(length - strLength, chars) + string) + : string; + } + + /** + * Converts `string` to an integer of the specified radix. If `radix` is + * `undefined` or `0`, a `radix` of `10` is used unless `value` is a + * hexadecimal, in which case a `radix` of `16` is used. + * + * **Note:** This method aligns with the + * [ES5 implementation](https://es5.github.io/#x15.1.2.2) of `parseInt`. + * + * @static + * @memberOf _ + * @since 1.1.0 + * @category String + * @param {string} string The string to convert. + * @param {number} [radix=10] The radix to interpret `value` by. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {number} Returns the converted integer. + * @example + * + * _.parseInt('08'); + * // => 8 + * + * _.map(['6', '08', '10'], _.parseInt); + * // => [6, 8, 10] + */ + function parseInt(string, radix, guard) { + if (guard || radix == null) { + radix = 0; + } else if (radix) { + radix = +radix; + } + return nativeParseInt(toString(string).replace(reTrimStart, ''), radix || 0); + } + + /** + * Repeats the given string `n` times. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category String + * @param {string} [string=''] The string to repeat. + * @param {number} [n=1] The number of times to repeat the string. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {string} Returns the repeated string. + * @example + * + * _.repeat('*', 3); + * // => '***' + * + * _.repeat('abc', 2); + * // => 'abcabc' + * + * _.repeat('abc', 0); + * // => '' + */ + function repeat(string, n, guard) { + if ((guard ? isIterateeCall(string, n, guard) : n === undefined)) { + n = 1; + } else { + n = toInteger(n); + } + return baseRepeat(toString(string), n); + } + + /** + * Replaces matches for `pattern` in `string` with `replacement`. + * + * **Note:** This method is based on + * [`String#replace`](https://mdn.io/String/replace). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category String + * @param {string} [string=''] The string to modify. + * @param {RegExp|string} pattern The pattern to replace. + * @param {Function|string} replacement The match replacement. + * @returns {string} Returns the modified string. + * @example + * + * _.replace('Hi Fred', 'Fred', 'Barney'); + * // => 'Hi Barney' + */ + function replace() { + var args = arguments, + string = toString(args[0]); + + return args.length < 3 ? string : string.replace(args[1], args[2]); + } + + /** + * Converts `string` to + * [snake case](https://en.wikipedia.org/wiki/Snake_case). + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category String + * @param {string} [string=''] The string to convert. + * @returns {string} Returns the snake cased string. + * @example + * + * _.snakeCase('Foo Bar'); + * // => 'foo_bar' + * + * _.snakeCase('fooBar'); + * // => 'foo_bar' + * + * _.snakeCase('--FOO-BAR--'); + * // => 'foo_bar' + */ + var snakeCase = createCompounder(function(result, word, index) { + return result + (index ? '_' : '') + word.toLowerCase(); + }); + + /** + * Splits `string` by `separator`. + * + * **Note:** This method is based on + * [`String#split`](https://mdn.io/String/split). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category String + * @param {string} [string=''] The string to split. + * @param {RegExp|string} separator The separator pattern to split by. + * @param {number} [limit] The length to truncate results to. + * @returns {Array} Returns the string segments. + * @example + * + * _.split('a-b-c', '-', 2); + * // => ['a', 'b'] + */ + function split(string, separator, limit) { + if (limit && typeof limit != 'number' && isIterateeCall(string, separator, limit)) { + separator = limit = undefined; + } + limit = limit === undefined ? MAX_ARRAY_LENGTH : limit >>> 0; + if (!limit) { + return []; + } + string = toString(string); + if (string && ( + typeof separator == 'string' || + (separator != null && !isRegExp(separator)) + )) { + separator = baseToString(separator); + if (!separator && hasUnicode(string)) { + return castSlice(stringToArray(string), 0, limit); + } + } + return string.split(separator, limit); + } + + /** + * Converts `string` to + * [start case](https://en.wikipedia.org/wiki/Letter_case#Stylistic_or_specialised_usage). + * + * @static + * @memberOf _ + * @since 3.1.0 + * @category String + * @param {string} [string=''] The string to convert. + * @returns {string} Returns the start cased string. + * @example + * + * _.startCase('--foo-bar--'); + * // => 'Foo Bar' + * + * _.startCase('fooBar'); + * // => 'Foo Bar' + * + * _.startCase('__FOO_BAR__'); + * // => 'FOO BAR' + */ + var startCase = createCompounder(function(result, word, index) { + return result + (index ? ' ' : '') + upperFirst(word); + }); + + /** + * Checks if `string` starts with the given target string. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category String + * @param {string} [string=''] The string to inspect. + * @param {string} [target] The string to search for. + * @param {number} [position=0] The position to search from. + * @returns {boolean} Returns `true` if `string` starts with `target`, + * else `false`. + * @example + * + * _.startsWith('abc', 'a'); + * // => true + * + * _.startsWith('abc', 'b'); + * // => false + * + * _.startsWith('abc', 'b', 1); + * // => true + */ + function startsWith(string, target, position) { + string = toString(string); + position = position == null + ? 0 + : baseClamp(toInteger(position), 0, string.length); + + target = baseToString(target); + return string.slice(position, position + target.length) == target; + } + + /** + * Creates a compiled template function that can interpolate data properties + * in "interpolate" delimiters, HTML-escape interpolated data properties in + * "escape" delimiters, and execute JavaScript in "evaluate" delimiters. Data + * properties may be accessed as free variables in the template. If a setting + * object is given, it takes precedence over `_.templateSettings` values. + * + * **Note:** In the development build `_.template` utilizes + * [sourceURLs](http://www.html5rocks.com/en/tutorials/developertools/sourcemaps/#toc-sourceurl) + * for easier debugging. + * + * For more information on precompiling templates see + * [lodash's custom builds documentation](https://lodash.com/custom-builds). + * + * For more information on Chrome extension sandboxes see + * [Chrome's extensions documentation](https://developer.chrome.com/extensions/sandboxingEval). + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category String + * @param {string} [string=''] The template string. + * @param {Object} [options={}] The options object. + * @param {RegExp} [options.escape=_.templateSettings.escape] + * The HTML "escape" delimiter. + * @param {RegExp} [options.evaluate=_.templateSettings.evaluate] + * The "evaluate" delimiter. + * @param {Object} [options.imports=_.templateSettings.imports] + * An object to import into the template as free variables. + * @param {RegExp} [options.interpolate=_.templateSettings.interpolate] + * The "interpolate" delimiter. + * @param {string} [options.sourceURL='lodash.templateSources[n]'] + * The sourceURL of the compiled template. + * @param {string} [options.variable='obj'] + * The data object variable name. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {Function} Returns the compiled template function. + * @example + * + * // Use the "interpolate" delimiter to create a compiled template. + * var compiled = _.template('hello <%= user %>!'); + * compiled({ 'user': 'fred' }); + * // => 'hello fred!' + * + * // Use the HTML "escape" delimiter to escape data property values. + * var compiled = _.template('<%- value %>'); + * compiled({ 'value': '