file_path stringlengths 3 280 | file_language stringclasses 66
values | content stringlengths 1 1.04M | repo_name stringlengths 5 92 | repo_stars int64 0 154k | repo_description stringlengths 0 402 | repo_primary_language stringclasses 108
values | developer_username stringlengths 1 25 | developer_name stringlengths 0 30 | developer_company stringlengths 0 82 |
|---|---|---|---|---|---|---|---|---|---|
crates/swc_ecma_minifier/tests/fixture/issues/9030/output.js | JavaScript | var FRUITS_MANGO = "mango", getMangoLabel = (label)=>label[FRUITS_MANGO];
export default ((name)=>{
// Breaks with switch case
if (name === FRUITS_MANGO) return getMangoLabel;
// Works with if else
// if (name === FRUITS.MANGO) {
// return getMangoLabel;
// }
});
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_minifier/tests/fixture/issues/9148/input.js | JavaScript | function foo() {
const obj = {
clear: function () {
console.log('clear')
},
start: function () {
const _this = this;
setTimeout(function () {
_this.clear();
});
}
};
return () => obj.start()
};
export default foo() | willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_minifier/tests/fixture/issues/9148/output.js | JavaScript | export default (function() {
const obj = {
clear: function() {
console.log('clear');
},
start: function() {
const _this = this;
setTimeout(function() {
_this.clear();
});
}
};
return ()=>obj.start();
})();
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_minifier/tests/fixture/issues/9176/input.js | JavaScript | "use strict";
const k = (function () {
switch (-0) {
case 0:
console.log("hi");
break;
default:
throw 0;
}
})();
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_minifier/tests/fixture/issues/9176/output.js | JavaScript | "use strict";
console.log("hi");
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_minifier/tests/fixture/issues/9186/1/input.js | JavaScript | o = {
foo() {
return val;
},
s: "test",
};
console.log(o.foo().length);
o = {
foo(val = this.s) {
return val;
},
s: "test",
};
console.log(o.foo().length);
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_minifier/tests/fixture/issues/9186/1/output.js | JavaScript | console.log((o = {
foo: ()=>val,
s: "test"
}).foo().length), console.log((o = {
foo (val1 = this.s) {
return val1;
},
s: "test"
}).foo().length);
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_minifier/tests/fixture/issues/9186/2/input.js | JavaScript | console.log(
(function () {
while (true) {
console.log(123);
}
})()
);
console.log(
(function (a = this.a) {
while (true) {
console.log(123);
}
})()
);
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_minifier/tests/fixture/issues/9186/2/output.js | JavaScript | console.log((()=>{
while(true){
console.log(123);
}
})());
console.log(function(a = this.a) {
while(true){
console.log(123);
}
}());
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_minifier/tests/fixture/issues/9263/input.js | JavaScript | "use strict";
const k = (function () {
var x = 42;
for (var x in [4242]) break;
return x;
})();
export { k }; | willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_minifier/tests/fixture/issues/9263/output.js | JavaScript | "use strict";
const k = function() {
for(var x in [
4242
])break;
return 42;
}();
export { k };
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_minifier/tests/fixture/issues/9453/input.js | JavaScript | "use strict";
class x {}
const y = x;
const z = class {};
console.log(typeof x);
console.log(typeof y);
console.log(typeof z);
console.log(typeof class {});
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_minifier/tests/fixture/issues/9453/output.js | JavaScript | "use strict";
console.log("function"), console.log("function"), console.log("function"), console.log("function");
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_minifier/tests/fixture/issues/9459/input.js | JavaScript |
export default function Component() {
const [state, setState] = /*#__PURE__*/ useState();
const { a, b = 'b' } = /*#__PURE__*/ call();
} | willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_minifier/tests/fixture/issues/9459/output.js | JavaScript | export default function Component() {}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_minifier/tests/fixture/issues/9466/input.js | JavaScript | "use strict";
let k = function () {
function x() { }
class y { }
for (x of ['']);
for (y in ['']);
}(); | willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_minifier/tests/fixture/issues/9466/output.js | JavaScript | "use strict";
let k = function() {
function x() {}
class y {
}
for (x of [
''
]);
for(y in [
''
]);
}();
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_minifier/tests/fixture/issues/9468/input.js | JavaScript | function func1(arg1, arg2) {
return getX(arg1) + arg2
}
function getX(x) {
const v = document.getElementById('eid').getAttribute(x)
return v
}
console.log(func1(7, getX('data-x')))
console.log(func1(7, getX('data-y')))
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_minifier/tests/fixture/issues/9468/output.js | JavaScript | var t, e;
function getX(t) {
return document.getElementById('eid').getAttribute(t);
}
console.log((t = getX('data-x'), getX(7) + t)), console.log((e = getX('data-y'), getX(7) + e));
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_minifier/tests/fixture/issues/9500/input.js | JavaScript | let foo = 1;
const obj = {
get 1() {
// same with get "1"()
foo = 2;
return 40;
},
};
obj["1"]; // same with obj[1]
console.log(foo);
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_minifier/tests/fixture/issues/9500/output.js | JavaScript | let foo = 1;
({
get 1 () {
return(// same with get "1"()
foo = 2, 40);
}
})["1"], console.log(foo);
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_minifier/tests/fixture/issues/9504/input.js | JavaScript | export function panUpdate(e) {
if (!moveDirectionExpected) {
panStart = false;
return;
}
caf(rafIndex);
if (panStart) { rafIndex = raf(function () { panUpdate(e); }); }
if (moveDirectionExpected === '?') { moveDirectionExpected = getMoveDirectionExpected(); }
if (moveDirectionExpected) {
if (!preventScroll && isTouchEvent(e)) { preventScroll = true; }
try {
if (e.type) { events.emit(isTouchEvent(e) ? 'touchMove' : 'dragMove', info(e)); }
} catch (err) { }
var x = translateInit,
dist = getDist(lastPosition, initPosition);
if (!horizontal || fixedWidth || autoWidth) {
// Relevant lines below
x += dist;
x += 'px';
} else {
var percentageX = TRANSFORM ? dist * items * 100 / ((viewport + gutter) * slideCountNew) : dist * 100 / (viewport + gutter);
x += percentageX;
x += '%';
}
container.style[transformAttr] = transformPrefix + x + transformPostfix;
}
} | willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_minifier/tests/fixture/issues/9504/output.js | JavaScript | export function panUpdate(e) {
if (!moveDirectionExpected) {
panStart = !1;
return;
}
if (caf(rafIndex), panStart && (rafIndex = raf(function() {
panUpdate(e);
})), '?' === moveDirectionExpected && (moveDirectionExpected = getMoveDirectionExpected()), moveDirectionExpected) {
!preventScroll && isTouchEvent(e) && (preventScroll = !0);
try {
e.type && events.emit(isTouchEvent(e) ? 'touchMove' : 'dragMove', info(e));
} catch (err) {}
var x = translateInit, dist = getDist(lastPosition, initPosition);
!horizontal || fixedWidth || autoWidth ? (// Relevant lines below
x += dist, x += 'px') : (x += TRANSFORM ? dist * items * 100 / ((viewport + gutter) * slideCountNew) : 100 * dist / (viewport + gutter), x += '%'), container.style[transformAttr] = transformPrefix + x + transformPostfix;
}
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_minifier/tests/fixture/issues/9619/input.js | JavaScript | var a = (() => {
switch ("production") {
case "production":
return "expected";
default:
return "unexpected1";
}
switch ("production") {
case "production":
return "unexpected2";
default:
return "unexpected3";
}
})();
console.log(a);
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_minifier/tests/fixture/issues/9619/output.js | JavaScript | var a = (()=>"expected")();
console.log(a);
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_minifier/tests/fixture/issues/9628/input.js | JavaScript | const getString = () => {
switch ("apple") {
case "apple":
return "1";
case "banana":
return "2";
}
return "3";
};
console.log(getString());
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_minifier/tests/fixture/issues/9628/output.js | JavaScript | console.log("1");
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_minifier/tests/fixture/issues/9650/input.js | JavaScript | export function logVariables(
var1,
var2,
var3,
var4,
var5,
var6,
var7,
var8,
var9,
var10,
var11,
var12,
var13,
var14,
var15,
var16,
var17,
var18,
var19,
var20,
var21,
var22,
var23,
var24,
var25,
var26,
var27,
var28,
var29,
var30,
var101,
var201,
var301,
var401,
var501,
var601,
var701,
var801,
var901,
var1001,
var1101,
var1201,
var1301,
var1401,
var1501,
var1601,
var1701,
var1801,
var1901,
var2001,
var2101,
var2201,
var2301,
var2401,
var2501,
var2601,
var2701,
var2801,
var2901,
var3001
) {
console.log(
var1,
var2,
var3,
var4,
var5,
var6,
var7,
var8,
var9,
var10,
var11,
var12,
var13,
var14,
var15,
var16,
var17,
var18,
var19,
var20,
var21,
var22,
var23,
var24,
var25,
var26,
var27,
var28,
var29,
var30
);
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_minifier/tests/fixture/issues/9650/output.js | JavaScript | export function logVariables(o, l, e, n, a, c, g, i, r, s, t, b, f, p, u, x, V, d, h, j, k, m, q, v, w, y, z, A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, W, X, Y, Z, _, oo, ol, oe, on, oa, oc, og) {
console.log(o, l, e, n, a, c, g, i, r, s, t, b, f, p, u, x, V, d, h, j, k, m, q, v, w, y, z, A, B, C);
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_minifier/tests/fixture/issues/9739/input.js | JavaScript | const arr = ['a', 'b'];
[arr[0], arr[1]] = [arr[1], arr[0]]; | willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_minifier/tests/fixture/issues/9739/output.js | JavaScript | const arr = [
'a',
'b'
];
[arr[0], arr[1]] = [
'b',
'a'
];
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_minifier/tests/fixture/issues/9757/input.js | JavaScript | export default function A() {
console?.log?.(123);
console?.log?.apply(console, arguments);
console?.a.b?.c(console, arguments);
console?.any();
console?.warn();
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_minifier/tests/fixture/issues/9757/output.js | JavaScript | export default function A() {}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_minifier/tests/fixture/issues/9785/input.js | JavaScript | function dist_index_es_P(e) {
try {
t = JSON.stringify(e);
} catch (r) {
t = String(e);
}
for (var r = 0, o = 0; o < t.length; o++) {
r += 1;
}
console.log(r);
return r;
}
dist_index_es_P("aa");
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_minifier/tests/fixture/issues/9785/output.js | JavaScript | !function(e) {
try {
t = JSON.stringify("aa");
} catch (r) {
t = String("aa");
}
for(var r = 0, o = 0; o < t.length; o++)r += 1;
console.log(r);
}(0);
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_minifier/tests/fixture/issues/9823/1-class/input.js | JavaScript | (() => {
"use strict";
class Element { }
class PointElement extends Element {
static id = 'point';
constructor(cfg) {
super();
}
}
// var chart_elements = /*#__PURE__*/ Object.freeze({
// PointElement: PointElement
// });
var chart_elements = /*#__PURE__*/(null && (Object.freeze({
PointElement: PointElement
})));
const registerables = null && ([
chart_elements,
chart_plugins,
]);
console.log('Done 1')
})()
; | willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_minifier/tests/fixture/issues/9823/1-class/output.js | JavaScript | console.log('Done 1');
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_minifier/tests/fixture/issues/9823/2-class-extends/input.js | JavaScript | (() => {
"use strict";
class Element { }
// var chart_elements = /*#__PURE__*/ Object.freeze({
// PointElement: PointElement
// });
var chart_elements = /*#__PURE__*/(null && (Object.freeze({
Element: Element
})));
const registerables = null && ([
chart_elements,
chart_plugins
]);
console.log('Done 2')
})()
; | willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_minifier/tests/fixture/issues/9823/2-class-extends/output.js | JavaScript | console.log('Done 2');
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_minifier/tests/fixture/issues/9823/3/input.js | JavaScript | (function () {
function foo() {
}
console.log('Done')
})() | willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_minifier/tests/fixture/issues/9823/3/output.js | JavaScript | console.log('Done');
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_minifier/tests/fixture/issues/9922/1/input.js | JavaScript | switch (0) {
default:
x: break;
console.log(1);
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_minifier/tests/fixture/issues/9922/2/input.js | JavaScript | switch (g()) {
case 1:
y: break;
console.log(2);
default:
x: break;
console.log(1);
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_minifier/tests/fixture/issues/9922/2/output.js | JavaScript | g();
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_minifier/tests/fixture/issues/buble/1/input.js | JavaScript | export default function thrower() {
throw new Error(
`Failed to recognize value \`${value}\` for property ` +
`\`${property}\`.`
);
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_minifier/tests/fixture/issues/buble/1/output.js | JavaScript | export default function thrower() {
throw Error(`Failed to recognize value \`${value}\` for property \`${property}\`.`);
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_minifier/tests/fixture/issues/d3-color/1/input.js | JavaScript | import define, { extend } from "./define.js";
import { Color, rgbConvert, Rgb, darker, brighter } from "./color.js";
import { deg2rad, rad2deg } from "./math.js";
var A = -0.14861,
B = +1.78277,
C = -0.29227,
D = -0.90649,
E = +1.97294,
ED = E * D,
EB = E * B,
BC_DA = B * C - D * A;
function cubehelixConvert(o) {
if (o instanceof Cubehelix) return new Cubehelix(o.h, o.s, o.l, o.opacity);
if (!(o instanceof Rgb)) o = rgbConvert(o);
var r = o.r / 255,
g = o.g / 255,
b = o.b / 255,
l = (BC_DA * b + ED * r - EB * g) / (BC_DA + ED - EB),
bl = b - l,
k = (E * (g - l) - C * bl) / D,
s = Math.sqrt(k * k + bl * bl) / (E * l * (1 - l)), // NaN if l=0 or l=1
h = s ? Math.atan2(k, bl) * rad2deg - 120 : NaN;
return new Cubehelix(h < 0 ? h + 360 : h, s, l, o.opacity);
}
export default function cubehelix(h, s, l, opacity) {
return arguments.length === 1
? cubehelixConvert(h)
: new Cubehelix(h, s, l, opacity == null ? 1 : opacity);
}
export function Cubehelix(h, s, l, opacity) {
this.h = +h;
this.s = +s;
this.l = +l;
this.opacity = +opacity;
}
define(
Cubehelix,
cubehelix,
extend(Color, {
brighter: function (k) {
k = k == null ? brighter : Math.pow(brighter, k);
return new Cubehelix(this.h, this.s, this.l * k, this.opacity);
},
darker: function (k) {
k = k == null ? darker : Math.pow(darker, k);
return new Cubehelix(this.h, this.s, this.l * k, this.opacity);
},
rgb: function () {
var h = isNaN(this.h) ? 0 : (this.h + 120) * deg2rad,
l = +this.l,
a = isNaN(this.s) ? 0 : this.s * l * (1 - l),
cosh = Math.cos(h),
sinh = Math.sin(h);
return new Rgb(
255 * (l + a * (A * cosh + B * sinh)),
255 * (l + a * (C * cosh + D * sinh)),
255 * (l + a * (E * cosh)),
this.opacity
);
},
})
);
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_minifier/tests/fixture/issues/d3-color/1/output.js | JavaScript | import define, { extend } from "./define.js";
import { Color, rgbConvert, Rgb, darker, brighter } from "./color.js";
import { deg2rad, rad2deg } from "./math.js";
var BC_DA = -1.78277 * 0.29227 - 0.1347134789;
export default function cubehelix(h, s, l, opacity) {
return 1 == arguments.length ? function(o) {
if (o instanceof Cubehelix) return new Cubehelix(o.h, o.s, o.l, o.opacity);
o instanceof Rgb || (o = rgbConvert(o));
var r = o.r / 255, g = o.g / 255, b = o.b / 255, l = (BC_DA * b + -1.7884503806 * r - 3.5172982438 * g) / (BC_DA + -1.7884503806 - 3.5172982438), bl = b - l, k = -((1.97294 * (g - l) - -0.29227 * bl) / 0.90649), s = Math.sqrt(k * k + bl * bl) / (1.97294 * l * (1 - l)), h = s ? Math.atan2(k, bl) * rad2deg - 120 : NaN;
return new Cubehelix(h < 0 ? h + 360 : h, s, l, o.opacity);
}(h) : new Cubehelix(h, s, l, null == opacity ? 1 : opacity);
}
export function Cubehelix(h, s, l, opacity) {
this.h = +h, this.s = +s, this.l = +l, this.opacity = +opacity;
}
define(Cubehelix, cubehelix, extend(Color, {
brighter: function(k) {
return k = null == k ? brighter : Math.pow(brighter, k), new Cubehelix(this.h, this.s, this.l * k, this.opacity);
},
darker: function(k) {
return k = null == k ? darker : Math.pow(darker, k), new Cubehelix(this.h, this.s, this.l * k, this.opacity);
},
rgb: function() {
var h = isNaN(this.h) ? 0 : (this.h + 120) * deg2rad, l = +this.l, a = isNaN(this.s) ? 0 : this.s * l * (1 - l), cosh = Math.cos(h), sinh = Math.sin(h);
return new Rgb(255 * (l + a * (-0.14861 * cosh + 1.78277 * sinh)), 255 * (l + a * (-0.29227 * cosh + -0.90649 * sinh)), 255 * (l + 1.97294 * cosh * a), this.opacity);
}
}));
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_minifier/tests/fixture/issues/d3-time-format/1/input.js | JavaScript | import {
timeDay,
timeSunday,
timeMonday,
timeThursday,
timeYear,
utcDay,
utcSunday,
utcMonday,
utcThursday,
utcYear,
} from "d3-time";
function localDate(d) {
if (0 <= d.y && d.y < 100) {
var date = new Date(-1, d.m, d.d, d.H, d.M, d.S, d.L);
date.setFullYear(d.y);
return date;
}
return new Date(d.y, d.m, d.d, d.H, d.M, d.S, d.L);
}
function utcDate(d) {
if (0 <= d.y && d.y < 100) {
var date = new Date(Date.UTC(-1, d.m, d.d, d.H, d.M, d.S, d.L));
date.setUTCFullYear(d.y);
return date;
}
return new Date(Date.UTC(d.y, d.m, d.d, d.H, d.M, d.S, d.L));
}
function newDate(y, m, d) {
return { y: y, m: m, d: d, H: 0, M: 0, S: 0, L: 0 };
}
export default function formatLocale(locale) {
var locale_dateTime = locale.dateTime,
locale_date = locale.date,
locale_time = locale.time,
locale_periods = locale.periods,
locale_weekdays = locale.days,
locale_shortWeekdays = locale.shortDays,
locale_months = locale.months,
locale_shortMonths = locale.shortMonths;
var periodRe = formatRe(locale_periods),
periodLookup = formatLookup(locale_periods),
weekdayRe = formatRe(locale_weekdays),
weekdayLookup = formatLookup(locale_weekdays),
shortWeekdayRe = formatRe(locale_shortWeekdays),
shortWeekdayLookup = formatLookup(locale_shortWeekdays),
monthRe = formatRe(locale_months),
monthLookup = formatLookup(locale_months),
shortMonthRe = formatRe(locale_shortMonths),
shortMonthLookup = formatLookup(locale_shortMonths);
var formats = {
a: formatShortWeekday,
A: formatWeekday,
b: formatShortMonth,
B: formatMonth,
c: null,
d: formatDayOfMonth,
e: formatDayOfMonth,
f: formatMicroseconds,
g: formatYearISO,
G: formatFullYearISO,
H: formatHour24,
I: formatHour12,
j: formatDayOfYear,
L: formatMilliseconds,
m: formatMonthNumber,
M: formatMinutes,
p: formatPeriod,
q: formatQuarter,
Q: formatUnixTimestamp,
s: formatUnixTimestampSeconds,
S: formatSeconds,
u: formatWeekdayNumberMonday,
U: formatWeekNumberSunday,
V: formatWeekNumberISO,
w: formatWeekdayNumberSunday,
W: formatWeekNumberMonday,
x: null,
X: null,
y: formatYear,
Y: formatFullYear,
Z: formatZone,
"%": formatLiteralPercent,
};
var utcFormats = {
a: formatUTCShortWeekday,
A: formatUTCWeekday,
b: formatUTCShortMonth,
B: formatUTCMonth,
c: null,
d: formatUTCDayOfMonth,
e: formatUTCDayOfMonth,
f: formatUTCMicroseconds,
g: formatUTCYearISO,
G: formatUTCFullYearISO,
H: formatUTCHour24,
I: formatUTCHour12,
j: formatUTCDayOfYear,
L: formatUTCMilliseconds,
m: formatUTCMonthNumber,
M: formatUTCMinutes,
p: formatUTCPeriod,
q: formatUTCQuarter,
Q: formatUnixTimestamp,
s: formatUnixTimestampSeconds,
S: formatUTCSeconds,
u: formatUTCWeekdayNumberMonday,
U: formatUTCWeekNumberSunday,
V: formatUTCWeekNumberISO,
w: formatUTCWeekdayNumberSunday,
W: formatUTCWeekNumberMonday,
x: null,
X: null,
y: formatUTCYear,
Y: formatUTCFullYear,
Z: formatUTCZone,
"%": formatLiteralPercent,
};
var parses = {
a: parseShortWeekday,
A: parseWeekday,
b: parseShortMonth,
B: parseMonth,
c: parseLocaleDateTime,
d: parseDayOfMonth,
e: parseDayOfMonth,
f: parseMicroseconds,
g: parseYear,
G: parseFullYear,
H: parseHour24,
I: parseHour24,
j: parseDayOfYear,
L: parseMilliseconds,
m: parseMonthNumber,
M: parseMinutes,
p: parsePeriod,
q: parseQuarter,
Q: parseUnixTimestamp,
s: parseUnixTimestampSeconds,
S: parseSeconds,
u: parseWeekdayNumberMonday,
U: parseWeekNumberSunday,
V: parseWeekNumberISO,
w: parseWeekdayNumberSunday,
W: parseWeekNumberMonday,
x: parseLocaleDate,
X: parseLocaleTime,
y: parseYear,
Y: parseFullYear,
Z: parseZone,
"%": parseLiteralPercent,
};
// These recursive directive definitions must be deferred.
formats.x = newFormat(locale_date, formats);
formats.X = newFormat(locale_time, formats);
formats.c = newFormat(locale_dateTime, formats);
utcFormats.x = newFormat(locale_date, utcFormats);
utcFormats.X = newFormat(locale_time, utcFormats);
utcFormats.c = newFormat(locale_dateTime, utcFormats);
function newFormat(specifier, formats) {
return function (date) {
var string = [],
i = -1,
j = 0,
n = specifier.length,
c,
pad,
format;
if (!(date instanceof Date)) date = new Date(+date);
while (++i < n) {
if (specifier.charCodeAt(i) === 37) {
string.push(specifier.slice(j, i));
if ((pad = pads[(c = specifier.charAt(++i))]) != null)
c = specifier.charAt(++i);
else pad = c === "e" ? " " : "0";
if ((format = formats[c])) c = format(date, pad);
string.push(c);
j = i + 1;
}
}
string.push(specifier.slice(j, i));
return string.join("");
};
}
function newParse(specifier, Z) {
return function (string) {
var d = newDate(1900, undefined, 1),
i = parseSpecifier(d, specifier, (string += ""), 0),
week,
day;
if (i != string.length) return null;
// If a UNIX timestamp is specified, return it.
if ("Q" in d) return new Date(d.Q);
if ("s" in d) return new Date(d.s * 1000 + ("L" in d ? d.L : 0));
// If this is utcParse, never use the local timezone.
if (Z && !("Z" in d)) d.Z = 0;
// The am-pm flag is 0 for AM, and 1 for PM.
if ("p" in d) d.H = (d.H % 12) + d.p * 12;
// If the month was not specified, inherit from the quarter.
if (d.m === undefined) d.m = "q" in d ? d.q : 0;
// Convert day-of-week and week-of-year to day-of-year.
if ("V" in d) {
if (d.V < 1 || d.V > 53) return null;
if (!("w" in d)) d.w = 1;
if ("Z" in d) {
(week = utcDate(newDate(d.y, 0, 1))),
(day = week.getUTCDay());
week =
day > 4 || day === 0
? utcMonday.ceil(week)
: utcMonday(week);
week = utcDay.offset(week, (d.V - 1) * 7);
d.y = week.getUTCFullYear();
d.m = week.getUTCMonth();
d.d = week.getUTCDate() + ((d.w + 6) % 7);
} else {
(week = localDate(newDate(d.y, 0, 1))),
(day = week.getDay());
week =
day > 4 || day === 0
? timeMonday.ceil(week)
: timeMonday(week);
week = timeDay.offset(week, (d.V - 1) * 7);
d.y = week.getFullYear();
d.m = week.getMonth();
d.d = week.getDate() + ((d.w + 6) % 7);
}
} else if ("W" in d || "U" in d) {
if (!("w" in d)) d.w = "u" in d ? d.u % 7 : "W" in d ? 1 : 0;
day =
"Z" in d
? utcDate(newDate(d.y, 0, 1)).getUTCDay()
: localDate(newDate(d.y, 0, 1)).getDay();
d.m = 0;
d.d =
"W" in d
? ((d.w + 6) % 7) + d.W * 7 - ((day + 5) % 7)
: d.w + d.U * 7 - ((day + 6) % 7);
}
// If a time zone is specified, all fields are interpreted as UTC and then
// offset according to the specified time zone.
if ("Z" in d) {
d.H += (d.Z / 100) | 0;
d.M += d.Z % 100;
return utcDate(d);
}
// Otherwise, all fields are in local time.
return localDate(d);
};
}
function parseSpecifier(d, specifier, string, j) {
var i = 0,
n = specifier.length,
m = string.length,
c,
parse;
while (i < n) {
if (j >= m) return -1;
c = specifier.charCodeAt(i++);
if (c === 37) {
c = specifier.charAt(i++);
parse = parses[c in pads ? specifier.charAt(i++) : c];
if (!parse || (j = parse(d, string, j)) < 0) return -1;
} else if (c != string.charCodeAt(j++)) {
return -1;
}
}
return j;
}
function parsePeriod(d, string, i) {
var n = periodRe.exec(string.slice(i));
return n
? ((d.p = periodLookup.get(n[0].toLowerCase())), i + n[0].length)
: -1;
}
function parseShortWeekday(d, string, i) {
var n = shortWeekdayRe.exec(string.slice(i));
return n
? ((d.w = shortWeekdayLookup.get(n[0].toLowerCase())),
i + n[0].length)
: -1;
}
function parseWeekday(d, string, i) {
var n = weekdayRe.exec(string.slice(i));
return n
? ((d.w = weekdayLookup.get(n[0].toLowerCase())), i + n[0].length)
: -1;
}
function parseShortMonth(d, string, i) {
var n = shortMonthRe.exec(string.slice(i));
return n
? ((d.m = shortMonthLookup.get(n[0].toLowerCase())),
i + n[0].length)
: -1;
}
function parseMonth(d, string, i) {
var n = monthRe.exec(string.slice(i));
return n
? ((d.m = monthLookup.get(n[0].toLowerCase())), i + n[0].length)
: -1;
}
function parseLocaleDateTime(d, string, i) {
return parseSpecifier(d, locale_dateTime, string, i);
}
function parseLocaleDate(d, string, i) {
return parseSpecifier(d, locale_date, string, i);
}
function parseLocaleTime(d, string, i) {
return parseSpecifier(d, locale_time, string, i);
}
function formatShortWeekday(d) {
return locale_shortWeekdays[d.getDay()];
}
function formatWeekday(d) {
return locale_weekdays[d.getDay()];
}
function formatShortMonth(d) {
return locale_shortMonths[d.getMonth()];
}
function formatMonth(d) {
return locale_months[d.getMonth()];
}
function formatPeriod(d) {
return locale_periods[+(d.getHours() >= 12)];
}
function formatQuarter(d) {
return 1 + ~~(d.getMonth() / 3);
}
function formatUTCShortWeekday(d) {
return locale_shortWeekdays[d.getUTCDay()];
}
function formatUTCWeekday(d) {
return locale_weekdays[d.getUTCDay()];
}
function formatUTCShortMonth(d) {
return locale_shortMonths[d.getUTCMonth()];
}
function formatUTCMonth(d) {
return locale_months[d.getUTCMonth()];
}
function formatUTCPeriod(d) {
return locale_periods[+(d.getUTCHours() >= 12)];
}
function formatUTCQuarter(d) {
return 1 + ~~(d.getUTCMonth() / 3);
}
return {
format: function (specifier) {
var f = newFormat((specifier += ""), formats);
f.toString = function () {
return specifier;
};
return f;
},
parse: function (specifier) {
var p = newParse((specifier += ""), false);
p.toString = function () {
return specifier;
};
return p;
},
utcFormat: function (specifier) {
var f = newFormat((specifier += ""), utcFormats);
f.toString = function () {
return specifier;
};
return f;
},
utcParse: function (specifier) {
var p = newParse((specifier += ""), true);
p.toString = function () {
return specifier;
};
return p;
},
};
}
var pads = { "-": "", _: " ", 0: "0" },
numberRe = /^\s*\d+/, // note: ignores next directive
percentRe = /^%/,
requoteRe = /[\\^$*+?|[\]().{}]/g;
function pad(value, fill, width) {
var sign = value < 0 ? "-" : "",
string = (sign ? -value : value) + "",
length = string.length;
return (
sign +
(length < width
? new Array(width - length + 1).join(fill) + string
: string)
);
}
function requote(s) {
return s.replace(requoteRe, "\\$&");
}
function formatRe(names) {
return new RegExp("^(?:" + names.map(requote).join("|") + ")", "i");
}
function formatLookup(names) {
return new Map(names.map((name, i) => [name.toLowerCase(), i]));
}
function parseWeekdayNumberSunday(d, string, i) {
var n = numberRe.exec(string.slice(i, i + 1));
return n ? ((d.w = +n[0]), i + n[0].length) : -1;
}
function parseWeekdayNumberMonday(d, string, i) {
var n = numberRe.exec(string.slice(i, i + 1));
return n ? ((d.u = +n[0]), i + n[0].length) : -1;
}
function parseWeekNumberSunday(d, string, i) {
var n = numberRe.exec(string.slice(i, i + 2));
return n ? ((d.U = +n[0]), i + n[0].length) : -1;
}
function parseWeekNumberISO(d, string, i) {
var n = numberRe.exec(string.slice(i, i + 2));
return n ? ((d.V = +n[0]), i + n[0].length) : -1;
}
function parseWeekNumberMonday(d, string, i) {
var n = numberRe.exec(string.slice(i, i + 2));
return n ? ((d.W = +n[0]), i + n[0].length) : -1;
}
function parseFullYear(d, string, i) {
var n = numberRe.exec(string.slice(i, i + 4));
return n ? ((d.y = +n[0]), i + n[0].length) : -1;
}
function parseYear(d, string, i) {
var n = numberRe.exec(string.slice(i, i + 2));
return n
? ((d.y = +n[0] + (+n[0] > 68 ? 1900 : 2000)), i + n[0].length)
: -1;
}
function parseZone(d, string, i) {
var n = /^(Z)|([+-]\d\d)(?::?(\d\d))?/.exec(string.slice(i, i + 6));
return n
? ((d.Z = n[1] ? 0 : -(n[2] + (n[3] || "00"))), i + n[0].length)
: -1;
}
function parseQuarter(d, string, i) {
var n = numberRe.exec(string.slice(i, i + 1));
return n ? ((d.q = n[0] * 3 - 3), i + n[0].length) : -1;
}
function parseMonthNumber(d, string, i) {
var n = numberRe.exec(string.slice(i, i + 2));
return n ? ((d.m = n[0] - 1), i + n[0].length) : -1;
}
function parseDayOfMonth(d, string, i) {
var n = numberRe.exec(string.slice(i, i + 2));
return n ? ((d.d = +n[0]), i + n[0].length) : -1;
}
function parseDayOfYear(d, string, i) {
var n = numberRe.exec(string.slice(i, i + 3));
return n ? ((d.m = 0), (d.d = +n[0]), i + n[0].length) : -1;
}
function parseHour24(d, string, i) {
var n = numberRe.exec(string.slice(i, i + 2));
return n ? ((d.H = +n[0]), i + n[0].length) : -1;
}
function parseMinutes(d, string, i) {
var n = numberRe.exec(string.slice(i, i + 2));
return n ? ((d.M = +n[0]), i + n[0].length) : -1;
}
function parseSeconds(d, string, i) {
var n = numberRe.exec(string.slice(i, i + 2));
return n ? ((d.S = +n[0]), i + n[0].length) : -1;
}
function parseMilliseconds(d, string, i) {
var n = numberRe.exec(string.slice(i, i + 3));
return n ? ((d.L = +n[0]), i + n[0].length) : -1;
}
function parseMicroseconds(d, string, i) {
var n = numberRe.exec(string.slice(i, i + 6));
return n ? ((d.L = Math.floor(n[0] / 1000)), i + n[0].length) : -1;
}
function parseLiteralPercent(d, string, i) {
var n = percentRe.exec(string.slice(i, i + 1));
return n ? i + n[0].length : -1;
}
function parseUnixTimestamp(d, string, i) {
var n = numberRe.exec(string.slice(i));
return n ? ((d.Q = +n[0]), i + n[0].length) : -1;
}
function parseUnixTimestampSeconds(d, string, i) {
var n = numberRe.exec(string.slice(i));
return n ? ((d.s = +n[0]), i + n[0].length) : -1;
}
function formatDayOfMonth(d, p) {
return pad(d.getDate(), p, 2);
}
function formatHour24(d, p) {
return pad(d.getHours(), p, 2);
}
function formatHour12(d, p) {
return pad(d.getHours() % 12 || 12, p, 2);
}
function formatDayOfYear(d, p) {
return pad(1 + timeDay.count(timeYear(d), d), p, 3);
}
function formatMilliseconds(d, p) {
return pad(d.getMilliseconds(), p, 3);
}
function formatMicroseconds(d, p) {
return formatMilliseconds(d, p) + "000";
}
function formatMonthNumber(d, p) {
return pad(d.getMonth() + 1, p, 2);
}
function formatMinutes(d, p) {
return pad(d.getMinutes(), p, 2);
}
function formatSeconds(d, p) {
return pad(d.getSeconds(), p, 2);
}
function formatWeekdayNumberMonday(d) {
var day = d.getDay();
return day === 0 ? 7 : day;
}
function formatWeekNumberSunday(d, p) {
return pad(timeSunday.count(timeYear(d) - 1, d), p, 2);
}
function dISO(d) {
var day = d.getDay();
return day >= 4 || day === 0 ? timeThursday(d) : timeThursday.ceil(d);
}
function formatWeekNumberISO(d, p) {
d = dISO(d);
return pad(
timeThursday.count(timeYear(d), d) + (timeYear(d).getDay() === 4),
p,
2
);
}
function formatWeekdayNumberSunday(d) {
return d.getDay();
}
function formatWeekNumberMonday(d, p) {
return pad(timeMonday.count(timeYear(d) - 1, d), p, 2);
}
function formatYear(d, p) {
return pad(d.getFullYear() % 100, p, 2);
}
function formatYearISO(d, p) {
d = dISO(d);
return pad(d.getFullYear() % 100, p, 2);
}
function formatFullYear(d, p) {
return pad(d.getFullYear() % 10000, p, 4);
}
function formatFullYearISO(d, p) {
var day = d.getDay();
d = day >= 4 || day === 0 ? timeThursday(d) : timeThursday.ceil(d);
return pad(d.getFullYear() % 10000, p, 4);
}
function formatZone(d) {
var z = d.getTimezoneOffset();
return (
(z > 0 ? "-" : ((z *= -1), "+")) +
pad((z / 60) | 0, "0", 2) +
pad(z % 60, "0", 2)
);
}
function formatUTCDayOfMonth(d, p) {
return pad(d.getUTCDate(), p, 2);
}
function formatUTCHour24(d, p) {
return pad(d.getUTCHours(), p, 2);
}
function formatUTCHour12(d, p) {
return pad(d.getUTCHours() % 12 || 12, p, 2);
}
function formatUTCDayOfYear(d, p) {
return pad(1 + utcDay.count(utcYear(d), d), p, 3);
}
function formatUTCMilliseconds(d, p) {
return pad(d.getUTCMilliseconds(), p, 3);
}
function formatUTCMicroseconds(d, p) {
return formatUTCMilliseconds(d, p) + "000";
}
function formatUTCMonthNumber(d, p) {
return pad(d.getUTCMonth() + 1, p, 2);
}
function formatUTCMinutes(d, p) {
return pad(d.getUTCMinutes(), p, 2);
}
function formatUTCSeconds(d, p) {
return pad(d.getUTCSeconds(), p, 2);
}
function formatUTCWeekdayNumberMonday(d) {
var dow = d.getUTCDay();
return dow === 0 ? 7 : dow;
}
function formatUTCWeekNumberSunday(d, p) {
return pad(utcSunday.count(utcYear(d) - 1, d), p, 2);
}
function UTCdISO(d) {
var day = d.getUTCDay();
return day >= 4 || day === 0 ? utcThursday(d) : utcThursday.ceil(d);
}
function formatUTCWeekNumberISO(d, p) {
d = UTCdISO(d);
return pad(
utcThursday.count(utcYear(d), d) + (utcYear(d).getUTCDay() === 4),
p,
2
);
}
function formatUTCWeekdayNumberSunday(d) {
return d.getUTCDay();
}
function formatUTCWeekNumberMonday(d, p) {
return pad(utcMonday.count(utcYear(d) - 1, d), p, 2);
}
function formatUTCYear(d, p) {
return pad(d.getUTCFullYear() % 100, p, 2);
}
function formatUTCYearISO(d, p) {
d = UTCdISO(d);
return pad(d.getUTCFullYear() % 100, p, 2);
}
function formatUTCFullYear(d, p) {
return pad(d.getUTCFullYear() % 10000, p, 4);
}
function formatUTCFullYearISO(d, p) {
var day = d.getUTCDay();
d = day >= 4 || day === 0 ? utcThursday(d) : utcThursday.ceil(d);
return pad(d.getUTCFullYear() % 10000, p, 4);
}
function formatUTCZone() {
return "+0000";
}
function formatLiteralPercent() {
return "%";
}
function formatUnixTimestamp(d) {
return +d;
}
function formatUnixTimestampSeconds(d) {
return Math.floor(+d / 1000);
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_minifier/tests/fixture/issues/d3-time-format/1/output.js | JavaScript | import { timeDay, timeSunday, timeMonday, timeThursday, timeYear, utcDay, utcSunday, utcMonday, utcThursday, utcYear } from "d3-time";
function localDate(d) {
if (0 <= d.y && d.y < 100) {
var date = new Date(-1, d.m, d.d, d.H, d.M, d.S, d.L);
return date.setFullYear(d.y), date;
}
return new Date(d.y, d.m, d.d, d.H, d.M, d.S, d.L);
}
function utcDate(d) {
if (0 <= d.y && d.y < 100) {
var date = new Date(Date.UTC(-1, d.m, d.d, d.H, d.M, d.S, d.L));
return date.setUTCFullYear(d.y), date;
}
return new Date(Date.UTC(d.y, d.m, d.d, d.H, d.M, d.S, d.L));
}
function newDate(y, m, d) {
return {
y: y,
m: m,
d: d,
H: 0,
M: 0,
S: 0,
L: 0
};
}
export default function formatLocale(locale) {
var locale_dateTime = locale.dateTime, locale_date = locale.date, locale_time = locale.time, locale_periods = locale.periods, locale_weekdays = locale.days, locale_shortWeekdays = locale.shortDays, locale_months = locale.months, locale_shortMonths = locale.shortMonths, periodRe = formatRe(locale_periods), periodLookup = formatLookup(locale_periods), weekdayRe = formatRe(locale_weekdays), weekdayLookup = formatLookup(locale_weekdays), shortWeekdayRe = formatRe(locale_shortWeekdays), shortWeekdayLookup = formatLookup(locale_shortWeekdays), monthRe = formatRe(locale_months), monthLookup = formatLookup(locale_months), shortMonthRe = formatRe(locale_shortMonths), shortMonthLookup = formatLookup(locale_shortMonths), formats = {
a: function(d) {
return locale_shortWeekdays[d.getDay()];
},
A: function(d) {
return locale_weekdays[d.getDay()];
},
b: function(d) {
return locale_shortMonths[d.getMonth()];
},
B: function(d) {
return locale_months[d.getMonth()];
},
c: null,
d: formatDayOfMonth,
e: formatDayOfMonth,
f: formatMicroseconds,
g: formatYearISO,
G: formatFullYearISO,
H: formatHour24,
I: formatHour12,
j: formatDayOfYear,
L: formatMilliseconds,
m: formatMonthNumber,
M: formatMinutes,
p: function(d) {
return locale_periods[+(d.getHours() >= 12)];
},
q: function(d) {
return 1 + ~~(d.getMonth() / 3);
},
Q: formatUnixTimestamp,
s: formatUnixTimestampSeconds,
S: formatSeconds,
u: formatWeekdayNumberMonday,
U: formatWeekNumberSunday,
V: formatWeekNumberISO,
w: formatWeekdayNumberSunday,
W: formatWeekNumberMonday,
x: null,
X: null,
y: formatYear,
Y: formatFullYear,
Z: formatZone,
"%": formatLiteralPercent
}, utcFormats = {
a: function(d) {
return locale_shortWeekdays[d.getUTCDay()];
},
A: function(d) {
return locale_weekdays[d.getUTCDay()];
},
b: function(d) {
return locale_shortMonths[d.getUTCMonth()];
},
B: function(d) {
return locale_months[d.getUTCMonth()];
},
c: null,
d: formatUTCDayOfMonth,
e: formatUTCDayOfMonth,
f: formatUTCMicroseconds,
g: formatUTCYearISO,
G: formatUTCFullYearISO,
H: formatUTCHour24,
I: formatUTCHour12,
j: formatUTCDayOfYear,
L: formatUTCMilliseconds,
m: formatUTCMonthNumber,
M: formatUTCMinutes,
p: function(d) {
return locale_periods[+(d.getUTCHours() >= 12)];
},
q: function(d) {
return 1 + ~~(d.getUTCMonth() / 3);
},
Q: formatUnixTimestamp,
s: formatUnixTimestampSeconds,
S: formatUTCSeconds,
u: formatUTCWeekdayNumberMonday,
U: formatUTCWeekNumberSunday,
V: formatUTCWeekNumberISO,
w: formatUTCWeekdayNumberSunday,
W: formatUTCWeekNumberMonday,
x: null,
X: null,
y: formatUTCYear,
Y: formatUTCFullYear,
Z: formatUTCZone,
"%": formatLiteralPercent
}, parses = {
a: function(d, string, i) {
var n = shortWeekdayRe.exec(string.slice(i));
return n ? (d.w = shortWeekdayLookup.get(n[0].toLowerCase()), i + n[0].length) : -1;
},
A: function(d, string, i) {
var n = weekdayRe.exec(string.slice(i));
return n ? (d.w = weekdayLookup.get(n[0].toLowerCase()), i + n[0].length) : -1;
},
b: function(d, string, i) {
var n = shortMonthRe.exec(string.slice(i));
return n ? (d.m = shortMonthLookup.get(n[0].toLowerCase()), i + n[0].length) : -1;
},
B: function(d, string, i) {
var n = monthRe.exec(string.slice(i));
return n ? (d.m = monthLookup.get(n[0].toLowerCase()), i + n[0].length) : -1;
},
c: function(d, string, i) {
return parseSpecifier(d, locale_dateTime, string, i);
},
d: parseDayOfMonth,
e: parseDayOfMonth,
f: parseMicroseconds,
g: parseYear,
G: parseFullYear,
H: parseHour24,
I: parseHour24,
j: parseDayOfYear,
L: parseMilliseconds,
m: parseMonthNumber,
M: parseMinutes,
p: function(d, string, i) {
var n = periodRe.exec(string.slice(i));
return n ? (d.p = periodLookup.get(n[0].toLowerCase()), i + n[0].length) : -1;
},
q: parseQuarter,
Q: parseUnixTimestamp,
s: parseUnixTimestampSeconds,
S: parseSeconds,
u: parseWeekdayNumberMonday,
U: parseWeekNumberSunday,
V: parseWeekNumberISO,
w: parseWeekdayNumberSunday,
W: parseWeekNumberMonday,
x: function(d, string, i) {
return parseSpecifier(d, locale_date, string, i);
},
X: function(d, string, i) {
return parseSpecifier(d, locale_time, string, i);
},
y: parseYear,
Y: parseFullYear,
Z: parseZone,
"%": parseLiteralPercent
};
function newFormat(specifier, formats) {
return function(date) {
var c, pad, format, string = [], i = -1, j = 0, n = specifier.length;
for(date instanceof Date || (date = new Date(+date)); ++i < n;)37 === specifier.charCodeAt(i) && (string.push(specifier.slice(j, i)), null != (pad = pads[c = specifier.charAt(++i)]) ? c = specifier.charAt(++i) : pad = "e" === c ? " " : "0", (format = formats[c]) && (c = format(date, pad)), string.push(c), j = i + 1);
return string.push(specifier.slice(j, i)), string.join("");
};
}
function newParse(specifier, Z) {
return function(string) {
var week, day, d = newDate(1900, void 0, 1);
if (parseSpecifier(d, specifier, string += "", 0) != string.length) return null;
// If a UNIX timestamp is specified, return it.
if ("Q" in d) return new Date(d.Q);
if ("s" in d) return new Date(1000 * d.s + ("L" in d ? d.L : 0));
// Convert day-of-week and week-of-year to day-of-year.
if (!Z || "Z" in d || (d.Z = 0), "p" in d && (d.H = d.H % 12 + 12 * d.p), void 0 === d.m && (d.m = "q" in d ? d.q : 0), "V" in d) {
if (d.V < 1 || d.V > 53) return null;
"w" in d || (d.w = 1), "Z" in d ? (week = (day = (week = utcDate(newDate(d.y, 0, 1))).getUTCDay()) > 4 || 0 === day ? utcMonday.ceil(week) : utcMonday(week), week = utcDay.offset(week, (d.V - 1) * 7), d.y = week.getUTCFullYear(), d.m = week.getUTCMonth(), d.d = week.getUTCDate() + (d.w + 6) % 7) : (week = (day = (week = localDate(newDate(d.y, 0, 1))).getDay()) > 4 || 0 === day ? timeMonday.ceil(week) : timeMonday(week), week = timeDay.offset(week, (d.V - 1) * 7), d.y = week.getFullYear(), d.m = week.getMonth(), d.d = week.getDate() + (d.w + 6) % 7);
} else ("W" in d || "U" in d) && ("w" in d || (d.w = "u" in d ? d.u % 7 : +("W" in d)), day = "Z" in d ? utcDate(newDate(d.y, 0, 1)).getUTCDay() : localDate(newDate(d.y, 0, 1)).getDay(), d.m = 0, d.d = "W" in d ? (d.w + 6) % 7 + 7 * d.W - (day + 5) % 7 : d.w + 7 * d.U - (day + 6) % 7);
return(// If a time zone is specified, all fields are interpreted as UTC and then
// offset according to the specified time zone.
"Z" in d ? (d.H += d.Z / 100 | 0, d.M += d.Z % 100, utcDate(d)) : localDate(d));
};
}
function parseSpecifier(d, specifier, string, j) {
for(var c, parse, i = 0, n = specifier.length, m = string.length; i < n;){
if (j >= m) return -1;
if (37 === (c = specifier.charCodeAt(i++))) {
if (!(parse = parses[(c = specifier.charAt(i++)) in pads ? specifier.charAt(i++) : c]) || (j = parse(d, string, j)) < 0) return -1;
} else if (c != string.charCodeAt(j++)) return -1;
}
return j;
}
return(// These recursive directive definitions must be deferred.
formats.x = newFormat(locale_date, formats), formats.X = newFormat(locale_time, formats), formats.c = newFormat(locale_dateTime, formats), utcFormats.x = newFormat(locale_date, utcFormats), utcFormats.X = newFormat(locale_time, utcFormats), utcFormats.c = newFormat(locale_dateTime, utcFormats), {
format: function(specifier) {
var f = newFormat(specifier += "", formats);
return f.toString = function() {
return specifier;
}, f;
},
parse: function(specifier) {
var p = newParse(specifier += "", !1);
return p.toString = function() {
return specifier;
}, p;
},
utcFormat: function(specifier) {
var f = newFormat(specifier += "", utcFormats);
return f.toString = function() {
return specifier;
}, f;
},
utcParse: function(specifier) {
var p = newParse(specifier += "", !0);
return p.toString = function() {
return specifier;
}, p;
}
});
}
var pads = {
"-": "",
_: " ",
0: "0"
}, numberRe = /^\s*\d+/, percentRe = /^%/, requoteRe = /[\\^$*+?|[\]().{}]/g;
function pad(value, fill, width) {
var sign = value < 0 ? "-" : "", string = (sign ? -value : value) + "", length = string.length;
return sign + (length < width ? Array(width - length + 1).join(fill) + string : string);
}
function requote(s) {
return s.replace(requoteRe, "\\$&");
}
function formatRe(names) {
return RegExp("^(?:" + names.map(requote).join("|") + ")", "i");
}
function formatLookup(names) {
return new Map(names.map((name, i)=>[
name.toLowerCase(),
i
]));
}
function parseWeekdayNumberSunday(d, string, i) {
var n = numberRe.exec(string.slice(i, i + 1));
return n ? (d.w = +n[0], i + n[0].length) : -1;
}
function parseWeekdayNumberMonday(d, string, i) {
var n = numberRe.exec(string.slice(i, i + 1));
return n ? (d.u = +n[0], i + n[0].length) : -1;
}
function parseWeekNumberSunday(d, string, i) {
var n = numberRe.exec(string.slice(i, i + 2));
return n ? (d.U = +n[0], i + n[0].length) : -1;
}
function parseWeekNumberISO(d, string, i) {
var n = numberRe.exec(string.slice(i, i + 2));
return n ? (d.V = +n[0], i + n[0].length) : -1;
}
function parseWeekNumberMonday(d, string, i) {
var n = numberRe.exec(string.slice(i, i + 2));
return n ? (d.W = +n[0], i + n[0].length) : -1;
}
function parseFullYear(d, string, i) {
var n = numberRe.exec(string.slice(i, i + 4));
return n ? (d.y = +n[0], i + n[0].length) : -1;
}
function parseYear(d, string, i) {
var n = numberRe.exec(string.slice(i, i + 2));
return n ? (d.y = +n[0] + (+n[0] > 68 ? 1900 : 2000), i + n[0].length) : -1;
}
function parseZone(d, string, i) {
var n = /^(Z)|([+-]\d\d)(?::?(\d\d))?/.exec(string.slice(i, i + 6));
return n ? (d.Z = n[1] ? 0 : -(n[2] + (n[3] || "00")), i + n[0].length) : -1;
}
function parseQuarter(d, string, i) {
var n = numberRe.exec(string.slice(i, i + 1));
return n ? (d.q = 3 * n[0] - 3, i + n[0].length) : -1;
}
function parseMonthNumber(d, string, i) {
var n = numberRe.exec(string.slice(i, i + 2));
return n ? (d.m = n[0] - 1, i + n[0].length) : -1;
}
function parseDayOfMonth(d, string, i) {
var n = numberRe.exec(string.slice(i, i + 2));
return n ? (d.d = +n[0], i + n[0].length) : -1;
}
function parseDayOfYear(d, string, i) {
var n = numberRe.exec(string.slice(i, i + 3));
return n ? (d.m = 0, d.d = +n[0], i + n[0].length) : -1;
}
function parseHour24(d, string, i) {
var n = numberRe.exec(string.slice(i, i + 2));
return n ? (d.H = +n[0], i + n[0].length) : -1;
}
function parseMinutes(d, string, i) {
var n = numberRe.exec(string.slice(i, i + 2));
return n ? (d.M = +n[0], i + n[0].length) : -1;
}
function parseSeconds(d, string, i) {
var n = numberRe.exec(string.slice(i, i + 2));
return n ? (d.S = +n[0], i + n[0].length) : -1;
}
function parseMilliseconds(d, string, i) {
var n = numberRe.exec(string.slice(i, i + 3));
return n ? (d.L = +n[0], i + n[0].length) : -1;
}
function parseMicroseconds(d, string, i) {
var n = numberRe.exec(string.slice(i, i + 6));
return n ? (d.L = Math.floor(n[0] / 1000), i + n[0].length) : -1;
}
function parseLiteralPercent(d, string, i) {
var n = percentRe.exec(string.slice(i, i + 1));
return n ? i + n[0].length : -1;
}
function parseUnixTimestamp(d, string, i) {
var n = numberRe.exec(string.slice(i));
return n ? (d.Q = +n[0], i + n[0].length) : -1;
}
function parseUnixTimestampSeconds(d, string, i) {
var n = numberRe.exec(string.slice(i));
return n ? (d.s = +n[0], i + n[0].length) : -1;
}
function formatDayOfMonth(d, p) {
return pad(d.getDate(), p, 2);
}
function formatHour24(d, p) {
return pad(d.getHours(), p, 2);
}
function formatHour12(d, p) {
return pad(d.getHours() % 12 || 12, p, 2);
}
function formatDayOfYear(d, p) {
return pad(1 + timeDay.count(timeYear(d), d), p, 3);
}
function formatMilliseconds(d, p) {
return pad(d.getMilliseconds(), p, 3);
}
function formatMicroseconds(d, p) {
return formatMilliseconds(d, p) + "000";
}
function formatMonthNumber(d, p) {
return pad(d.getMonth() + 1, p, 2);
}
function formatMinutes(d, p) {
return pad(d.getMinutes(), p, 2);
}
function formatSeconds(d, p) {
return pad(d.getSeconds(), p, 2);
}
function formatWeekdayNumberMonday(d) {
var day = d.getDay();
return 0 === day ? 7 : day;
}
function formatWeekNumberSunday(d, p) {
return pad(timeSunday.count(timeYear(d) - 1, d), p, 2);
}
function dISO(d) {
var day = d.getDay();
return day >= 4 || 0 === day ? timeThursday(d) : timeThursday.ceil(d);
}
function formatWeekNumberISO(d, p) {
return d = dISO(d), pad(timeThursday.count(timeYear(d), d) + (4 === timeYear(d).getDay()), p, 2);
}
function formatWeekdayNumberSunday(d) {
return d.getDay();
}
function formatWeekNumberMonday(d, p) {
return pad(timeMonday.count(timeYear(d) - 1, d), p, 2);
}
function formatYear(d, p) {
return pad(d.getFullYear() % 100, p, 2);
}
function formatYearISO(d, p) {
return pad((d = dISO(d)).getFullYear() % 100, p, 2);
}
function formatFullYear(d, p) {
return pad(d.getFullYear() % 10000, p, 4);
}
function formatFullYearISO(d, p) {
var day = d.getDay();
return pad((d = day >= 4 || 0 === day ? timeThursday(d) : timeThursday.ceil(d)).getFullYear() % 10000, p, 4);
}
function formatZone(d) {
var z = d.getTimezoneOffset();
return (z > 0 ? "-" : (z *= -1, "+")) + pad(z / 60 | 0, "0", 2) + pad(z % 60, "0", 2);
}
function formatUTCDayOfMonth(d, p) {
return pad(d.getUTCDate(), p, 2);
}
function formatUTCHour24(d, p) {
return pad(d.getUTCHours(), p, 2);
}
function formatUTCHour12(d, p) {
return pad(d.getUTCHours() % 12 || 12, p, 2);
}
function formatUTCDayOfYear(d, p) {
return pad(1 + utcDay.count(utcYear(d), d), p, 3);
}
function formatUTCMilliseconds(d, p) {
return pad(d.getUTCMilliseconds(), p, 3);
}
function formatUTCMicroseconds(d, p) {
return formatUTCMilliseconds(d, p) + "000";
}
function formatUTCMonthNumber(d, p) {
return pad(d.getUTCMonth() + 1, p, 2);
}
function formatUTCMinutes(d, p) {
return pad(d.getUTCMinutes(), p, 2);
}
function formatUTCSeconds(d, p) {
return pad(d.getUTCSeconds(), p, 2);
}
function formatUTCWeekdayNumberMonday(d) {
var dow = d.getUTCDay();
return 0 === dow ? 7 : dow;
}
function formatUTCWeekNumberSunday(d, p) {
return pad(utcSunday.count(utcYear(d) - 1, d), p, 2);
}
function UTCdISO(d) {
var day = d.getUTCDay();
return day >= 4 || 0 === day ? utcThursday(d) : utcThursday.ceil(d);
}
function formatUTCWeekNumberISO(d, p) {
return d = UTCdISO(d), pad(utcThursday.count(utcYear(d), d) + (4 === utcYear(d).getUTCDay()), p, 2);
}
function formatUTCWeekdayNumberSunday(d) {
return d.getUTCDay();
}
function formatUTCWeekNumberMonday(d, p) {
return pad(utcMonday.count(utcYear(d) - 1, d), p, 2);
}
function formatUTCYear(d, p) {
return pad(d.getUTCFullYear() % 100, p, 2);
}
function formatUTCYearISO(d, p) {
return pad((d = UTCdISO(d)).getUTCFullYear() % 100, p, 2);
}
function formatUTCFullYear(d, p) {
return pad(d.getUTCFullYear() % 10000, p, 4);
}
function formatUTCFullYearISO(d, p) {
var day = d.getUTCDay();
return pad((d = day >= 4 || 0 === day ? utcThursday(d) : utcThursday.ceil(d)).getUTCFullYear() % 10000, p, 4);
}
function formatUTCZone() {
return "+0000";
}
function formatLiteralPercent() {
return "%";
}
function formatUnixTimestamp(d) {
return +d;
}
function formatUnixTimestampSeconds(d) {
return Math.floor(+d / 1000);
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_minifier/tests/fixture/issues/d3-time-format/3/input.js | JavaScript | (self["webpackChunk_N_E"] = self["webpackChunk_N_E"] || []).push([
[6945],
{
/***/ 2728: /***/ function (
__unused_webpack_module,
__webpack_exports__,
__webpack_require__
) {
"use strict";
// EXPORTS
__webpack_require__.d(__webpack_exports__, {
Z: function () {
return /* binding */ createTimeScale;
},
});
// UNUSED EXPORTS: updateTimeScale
// EXTERNAL MODULE: ../node_modules/d3-array/src/bisector.js
var bisector = __webpack_require__(24852);
// EXTERNAL MODULE: ../node_modules/d3-array/src/ticks.js
var src_ticks = __webpack_require__(73002); // CONCATENATED MODULE: ../node_modules/d3-time/src/duration.js
const durationSecond = 1000;
const durationMinute = durationSecond * 60;
const durationHour = durationMinute * 60;
const durationDay = durationHour * 24;
const durationWeek = durationDay * 7;
const durationMonth = durationDay * 30;
const durationYear = durationDay * 365; // CONCATENATED MODULE: ../node_modules/d3-time/src/interval.js
var t0 = new Date(),
t1 = new Date();
function newInterval(floori, offseti, count, field) {
function interval(date) {
return (
floori(
(date =
arguments.length === 0
? new Date()
: new Date(+date))
),
date
);
}
interval.floor = function (date) {
return floori((date = new Date(+date))), date;
};
interval.ceil = function (date) {
return (
floori((date = new Date(date - 1))),
offseti(date, 1),
floori(date),
date
);
};
interval.round = function (date) {
var d0 = interval(date),
d1 = interval.ceil(date);
return date - d0 < d1 - date ? d0 : d1;
};
interval.offset = function (date, step) {
return (
offseti(
(date = new Date(+date)),
step == null ? 1 : Math.floor(step)
),
date
);
};
interval.range = function (start, stop, step) {
var range = [],
previous;
start = interval.ceil(start);
step = step == null ? 1 : Math.floor(step);
if (!(start < stop) || !(step > 0)) return range; // also handles Invalid Date
do
range.push((previous = new Date(+start))),
offseti(start, step),
floori(start);
while (previous < start && start < stop);
return range;
};
interval.filter = function (test) {
return newInterval(
function (date) {
if (date >= date)
while ((floori(date), !test(date)))
date.setTime(date - 1);
},
function (date, step) {
if (date >= date) {
if (step < 0)
while (++step <= 0) {
while (
(offseti(date, -1), !test(date))
) {} // eslint-disable-line no-empty
}
else
while (--step >= 0) {
while (
(offseti(date, +1), !test(date))
) {} // eslint-disable-line no-empty
}
}
}
);
};
if (count) {
interval.count = function (start, end) {
t0.setTime(+start), t1.setTime(+end);
floori(t0), floori(t1);
return Math.floor(count(t0, t1));
};
interval.every = function (step) {
step = Math.floor(step);
return !isFinite(step) || !(step > 0)
? null
: !(step > 1)
? interval
: interval.filter(
field
? function (d) {
return field(d) % step === 0;
}
: function (d) {
return (
interval.count(0, d) % step ===
0
);
}
);
};
}
return interval;
} // CONCATENATED MODULE: ../node_modules/d3-time/src/millisecond.js
var millisecond = newInterval(
function () {
// noop
},
function (date, step) {
date.setTime(+date + step);
},
function (start, end) {
return end - start;
}
);
// An optimized implementation for this simple case.
millisecond.every = function (k) {
k = Math.floor(k);
if (!isFinite(k) || !(k > 0)) return null;
if (!(k > 1)) return millisecond;
return newInterval(
function (date) {
date.setTime(Math.floor(date / k) * k);
},
function (date, step) {
date.setTime(+date + step * k);
},
function (start, end) {
return (end - start) / k;
}
);
};
/* harmony default export */ var src_millisecond = millisecond;
var milliseconds = millisecond.range; // CONCATENATED MODULE: ../node_modules/d3-time/src/second.js
var second = newInterval(
function (date) {
date.setTime(date - date.getMilliseconds());
},
function (date, step) {
date.setTime(+date + step * durationSecond);
},
function (start, end) {
return (end - start) / durationSecond;
},
function (date) {
return date.getUTCSeconds();
}
);
/* harmony default export */ var src_second = second;
var seconds = second.range; // CONCATENATED MODULE: ../node_modules/d3-time/src/minute.js
var minute = newInterval(
function (date) {
date.setTime(
date -
date.getMilliseconds() -
date.getSeconds() * durationSecond
);
},
function (date, step) {
date.setTime(+date + step * durationMinute);
},
function (start, end) {
return (end - start) / durationMinute;
},
function (date) {
return date.getMinutes();
}
);
/* harmony default export */ var src_minute = minute;
var minutes = minute.range; // CONCATENATED MODULE: ../node_modules/d3-time/src/hour.js
var hour = newInterval(
function (date) {
date.setTime(
date -
date.getMilliseconds() -
date.getSeconds() * durationSecond -
date.getMinutes() * durationMinute
);
},
function (date, step) {
date.setTime(+date + step * durationHour);
},
function (start, end) {
return (end - start) / durationHour;
},
function (date) {
return date.getHours();
}
);
/* harmony default export */ var src_hour = hour;
var hours = hour.range; // CONCATENATED MODULE: ../node_modules/d3-time/src/day.js
var day = newInterval(
(date) => date.setHours(0, 0, 0, 0),
(date, step) => date.setDate(date.getDate() + step),
(start, end) =>
(end -
start -
(end.getTimezoneOffset() - start.getTimezoneOffset()) *
durationMinute) /
durationDay,
(date) => date.getDate() - 1
);
/* harmony default export */ var src_day = day;
var days = day.range; // CONCATENATED MODULE: ../node_modules/d3-time/src/week.js
function weekday(i) {
return newInterval(
function (date) {
date.setDate(
date.getDate() - ((date.getDay() + 7 - i) % 7)
);
date.setHours(0, 0, 0, 0);
},
function (date, step) {
date.setDate(date.getDate() + step * 7);
},
function (start, end) {
return (
(end -
start -
(end.getTimezoneOffset() -
start.getTimezoneOffset()) *
durationMinute) /
durationWeek
);
}
);
}
var sunday = weekday(0);
var monday = weekday(1);
var tuesday = weekday(2);
var wednesday = weekday(3);
var thursday = weekday(4);
var friday = weekday(5);
var saturday = weekday(6);
var sundays = sunday.range;
var mondays = monday.range;
var tuesdays = tuesday.range;
var wednesdays = wednesday.range;
var thursdays = thursday.range;
var fridays = friday.range;
var saturdays = saturday.range; // CONCATENATED MODULE: ../node_modules/d3-time/src/month.js
var month = newInterval(
function (date) {
date.setDate(1);
date.setHours(0, 0, 0, 0);
},
function (date, step) {
date.setMonth(date.getMonth() + step);
},
function (start, end) {
return (
end.getMonth() -
start.getMonth() +
(end.getFullYear() - start.getFullYear()) * 12
);
},
function (date) {
return date.getMonth();
}
);
/* harmony default export */ var src_month = month;
var months = month.range; // CONCATENATED MODULE: ../node_modules/d3-time/src/year.js
var year = newInterval(
function (date) {
date.setMonth(0, 1);
date.setHours(0, 0, 0, 0);
},
function (date, step) {
date.setFullYear(date.getFullYear() + step);
},
function (start, end) {
return end.getFullYear() - start.getFullYear();
},
function (date) {
return date.getFullYear();
}
);
// An optimized implementation for this simple case.
year.every = function (k) {
return !isFinite((k = Math.floor(k))) || !(k > 0)
? null
: newInterval(
function (date) {
date.setFullYear(
Math.floor(date.getFullYear() / k) * k
);
date.setMonth(0, 1);
date.setHours(0, 0, 0, 0);
},
function (date, step) {
date.setFullYear(date.getFullYear() + step * k);
}
);
};
/* harmony default export */ var src_year = year;
var years = year.range; // CONCATENATED MODULE: ../node_modules/d3-time/src/utcMinute.js
var utcMinute = newInterval(
function (date) {
date.setUTCSeconds(0, 0);
},
function (date, step) {
date.setTime(+date + step * durationMinute);
},
function (start, end) {
return (end - start) / durationMinute;
},
function (date) {
return date.getUTCMinutes();
}
);
/* harmony default export */ var src_utcMinute = utcMinute;
var utcMinutes = utcMinute.range; // CONCATENATED MODULE: ../node_modules/d3-time/src/utcHour.js
var utcHour = newInterval(
function (date) {
date.setUTCMinutes(0, 0, 0);
},
function (date, step) {
date.setTime(+date + step * durationHour);
},
function (start, end) {
return (end - start) / durationHour;
},
function (date) {
return date.getUTCHours();
}
);
/* harmony default export */ var src_utcHour = utcHour;
var utcHours = utcHour.range; // CONCATENATED MODULE: ../node_modules/d3-time/src/utcDay.js
var utcDay = newInterval(
function (date) {
date.setUTCHours(0, 0, 0, 0);
},
function (date, step) {
date.setUTCDate(date.getUTCDate() + step);
},
function (start, end) {
return (end - start) / durationDay;
},
function (date) {
return date.getUTCDate() - 1;
}
);
/* harmony default export */ var src_utcDay = utcDay;
var utcDays = utcDay.range; // CONCATENATED MODULE: ../node_modules/d3-time/src/utcWeek.js
function utcWeekday(i) {
return newInterval(
function (date) {
date.setUTCDate(
date.getUTCDate() - ((date.getUTCDay() + 7 - i) % 7)
);
date.setUTCHours(0, 0, 0, 0);
},
function (date, step) {
date.setUTCDate(date.getUTCDate() + step * 7);
},
function (start, end) {
return (end - start) / durationWeek;
}
);
}
var utcSunday = utcWeekday(0);
var utcMonday = utcWeekday(1);
var utcTuesday = utcWeekday(2);
var utcWednesday = utcWeekday(3);
var utcThursday = utcWeekday(4);
var utcFriday = utcWeekday(5);
var utcSaturday = utcWeekday(6);
var utcSundays = utcSunday.range;
var utcMondays = utcMonday.range;
var utcTuesdays = utcTuesday.range;
var utcWednesdays = utcWednesday.range;
var utcThursdays = utcThursday.range;
var utcFridays = utcFriday.range;
var utcSaturdays = utcSaturday.range; // CONCATENATED MODULE: ../node_modules/d3-time/src/utcMonth.js
var utcMonth = newInterval(
function (date) {
date.setUTCDate(1);
date.setUTCHours(0, 0, 0, 0);
},
function (date, step) {
date.setUTCMonth(date.getUTCMonth() + step);
},
function (start, end) {
return (
end.getUTCMonth() -
start.getUTCMonth() +
(end.getUTCFullYear() - start.getUTCFullYear()) * 12
);
},
function (date) {
return date.getUTCMonth();
}
);
/* harmony default export */ var src_utcMonth = utcMonth;
var utcMonths = utcMonth.range; // CONCATENATED MODULE: ../node_modules/d3-time/src/utcYear.js
var utcYear = newInterval(
function (date) {
date.setUTCMonth(0, 1);
date.setUTCHours(0, 0, 0, 0);
},
function (date, step) {
date.setUTCFullYear(date.getUTCFullYear() + step);
},
function (start, end) {
return end.getUTCFullYear() - start.getUTCFullYear();
},
function (date) {
return date.getUTCFullYear();
}
);
// An optimized implementation for this simple case.
utcYear.every = function (k) {
return !isFinite((k = Math.floor(k))) || !(k > 0)
? null
: newInterval(
function (date) {
date.setUTCFullYear(
Math.floor(date.getUTCFullYear() / k) * k
);
date.setUTCMonth(0, 1);
date.setUTCHours(0, 0, 0, 0);
},
function (date, step) {
date.setUTCFullYear(
date.getUTCFullYear() + step * k
);
}
);
};
/* harmony default export */ var src_utcYear = utcYear;
var utcYears = utcYear.range; // CONCATENATED MODULE: ../node_modules/d3-time/src/ticks.js
function ticker(year, month, week, day, hour, minute) {
const tickIntervals = [
[src_second, 1, durationSecond],
[src_second, 5, 5 * durationSecond],
[src_second, 15, 15 * durationSecond],
[src_second, 30, 30 * durationSecond],
[minute, 1, durationMinute],
[minute, 5, 5 * durationMinute],
[minute, 15, 15 * durationMinute],
[minute, 30, 30 * durationMinute],
[hour, 1, durationHour],
[hour, 3, 3 * durationHour],
[hour, 6, 6 * durationHour],
[hour, 12, 12 * durationHour],
[day, 1, durationDay],
[day, 2, 2 * durationDay],
[week, 1, durationWeek],
[month, 1, durationMonth],
[month, 3, 3 * durationMonth],
[year, 1, durationYear],
];
function ticks(start, stop, count) {
const reverse = stop < start;
if (reverse) [start, stop] = [stop, start];
const interval =
count && typeof count.range === "function"
? count
: tickInterval(start, stop, count);
const ticks = interval
? interval.range(start, +stop + 1)
: []; // inclusive stop
return reverse ? ticks.reverse() : ticks;
}
function tickInterval(start, stop, count) {
const target = Math.abs(stop - start) / count;
const i = (0, bisector /* default */.Z)(
([, , step]) => step
).right(tickIntervals, target);
if (i === tickIntervals.length)
return year.every(
(0, src_ticks /* tickStep */.ly)(
start / durationYear,
stop / durationYear,
count
)
);
if (i === 0)
return src_millisecond.every(
Math.max(
(0, src_ticks /* tickStep */.ly)(
start,
stop,
count
),
1
)
);
const [t, step] =
tickIntervals[
target / tickIntervals[i - 1][2] <
tickIntervals[i][2] / target
? i - 1
: i
];
return t.every(step);
}
return [ticks, tickInterval];
}
const [utcTicks, utcTickInterval] = ticker(
src_utcYear,
src_utcMonth,
utcSunday,
src_utcDay,
src_utcHour,
src_utcMinute
);
const [timeTicks, timeTickInterval] = ticker(
src_year,
src_month,
sunday,
src_day,
src_hour,
src_minute
); // CONCATENATED MODULE: ../node_modules/d3-time-format/src/locale.js
function localDate(d) {
if (0 <= d.y && d.y < 100) {
var date = new Date(-1, d.m, d.d, d.H, d.M, d.S, d.L);
date.setFullYear(d.y);
return date;
}
return new Date(d.y, d.m, d.d, d.H, d.M, d.S, d.L);
}
function utcDate(d) {
if (0 <= d.y && d.y < 100) {
var date = new Date(
Date.UTC(-1, d.m, d.d, d.H, d.M, d.S, d.L)
);
date.setUTCFullYear(d.y);
return date;
}
return new Date(Date.UTC(d.y, d.m, d.d, d.H, d.M, d.S, d.L));
}
function newDate(y, m, d) {
return { y: y, m: m, d: d, H: 0, M: 0, S: 0, L: 0 };
}
function formatLocale(locale) {
var locale_dateTime = locale.dateTime,
locale_date = locale.date,
locale_time = locale.time,
locale_periods = locale.periods,
locale_weekdays = locale.days,
locale_shortWeekdays = locale.shortDays,
locale_months = locale.months,
locale_shortMonths = locale.shortMonths;
var periodRe = formatRe(locale_periods),
periodLookup = formatLookup(locale_periods),
weekdayRe = formatRe(locale_weekdays),
weekdayLookup = formatLookup(locale_weekdays),
shortWeekdayRe = formatRe(locale_shortWeekdays),
shortWeekdayLookup = formatLookup(locale_shortWeekdays),
monthRe = formatRe(locale_months),
monthLookup = formatLookup(locale_months),
shortMonthRe = formatRe(locale_shortMonths),
shortMonthLookup = formatLookup(locale_shortMonths);
var formats = {
a: formatShortWeekday,
A: formatWeekday,
b: formatShortMonth,
B: formatMonth,
c: null,
d: formatDayOfMonth,
e: formatDayOfMonth,
f: formatMicroseconds,
g: formatYearISO,
G: formatFullYearISO,
H: formatHour24,
I: formatHour12,
j: formatDayOfYear,
L: formatMilliseconds,
m: formatMonthNumber,
M: formatMinutes,
p: formatPeriod,
q: formatQuarter,
Q: formatUnixTimestamp,
s: formatUnixTimestampSeconds,
S: formatSeconds,
u: formatWeekdayNumberMonday,
U: formatWeekNumberSunday,
V: formatWeekNumberISO,
w: formatWeekdayNumberSunday,
W: formatWeekNumberMonday,
x: null,
X: null,
y: formatYear,
Y: formatFullYear,
Z: formatZone,
"%": formatLiteralPercent,
};
var utcFormats = {
a: formatUTCShortWeekday,
A: formatUTCWeekday,
b: formatUTCShortMonth,
B: formatUTCMonth,
c: null,
d: formatUTCDayOfMonth,
e: formatUTCDayOfMonth,
f: formatUTCMicroseconds,
g: formatUTCYearISO,
G: formatUTCFullYearISO,
H: formatUTCHour24,
I: formatUTCHour12,
j: formatUTCDayOfYear,
L: formatUTCMilliseconds,
m: formatUTCMonthNumber,
M: formatUTCMinutes,
p: formatUTCPeriod,
q: formatUTCQuarter,
Q: formatUnixTimestamp,
s: formatUnixTimestampSeconds,
S: formatUTCSeconds,
u: formatUTCWeekdayNumberMonday,
U: formatUTCWeekNumberSunday,
V: formatUTCWeekNumberISO,
w: formatUTCWeekdayNumberSunday,
W: formatUTCWeekNumberMonday,
x: null,
X: null,
y: formatUTCYear,
Y: formatUTCFullYear,
Z: formatUTCZone,
"%": formatLiteralPercent,
};
var parses = {
a: parseShortWeekday,
A: parseWeekday,
b: parseShortMonth,
B: parseMonth,
c: parseLocaleDateTime,
d: parseDayOfMonth,
e: parseDayOfMonth,
f: parseMicroseconds,
g: parseYear,
G: parseFullYear,
H: parseHour24,
I: parseHour24,
j: parseDayOfYear,
L: parseMilliseconds,
m: parseMonthNumber,
M: parseMinutes,
p: parsePeriod,
q: parseQuarter,
Q: parseUnixTimestamp,
s: parseUnixTimestampSeconds,
S: parseSeconds,
u: parseWeekdayNumberMonday,
U: parseWeekNumberSunday,
V: parseWeekNumberISO,
w: parseWeekdayNumberSunday,
W: parseWeekNumberMonday,
x: parseLocaleDate,
X: parseLocaleTime,
y: parseYear,
Y: parseFullYear,
Z: parseZone,
"%": parseLiteralPercent,
};
// These recursive directive definitions must be deferred.
formats.x = newFormat(locale_date, formats);
formats.X = newFormat(locale_time, formats);
formats.c = newFormat(locale_dateTime, formats);
utcFormats.x = newFormat(locale_date, utcFormats);
utcFormats.X = newFormat(locale_time, utcFormats);
utcFormats.c = newFormat(locale_dateTime, utcFormats);
function newFormat(specifier, formats) {
return function (date) {
var string = [],
i = -1,
j = 0,
n = specifier.length,
c,
pad,
format;
if (!(date instanceof Date)) date = new Date(+date);
while (++i < n) {
if (specifier.charCodeAt(i) === 37) {
string.push(specifier.slice(j, i));
if (
(pad = pads[(c = specifier.charAt(++i))]) !=
null
)
c = specifier.charAt(++i);
else pad = c === "e" ? " " : "0";
if ((format = formats[c]))
c = format(date, pad);
string.push(c);
j = i + 1;
}
}
string.push(specifier.slice(j, i));
return string.join("");
};
}
function newParse(specifier, Z) {
return function (string) {
var d = newDate(1900, undefined, 1),
i = parseSpecifier(d, specifier, (string += ""), 0),
week,
day;
if (i != string.length) return null;
// If a UNIX timestamp is specified, return it.
if ("Q" in d) return new Date(d.Q);
if ("s" in d)
return new Date(d.s * 1000 + ("L" in d ? d.L : 0));
// If this is utcParse, never use the local timezone.
if (Z && !("Z" in d)) d.Z = 0;
// The am-pm flag is 0 for AM, and 1 for PM.
if ("p" in d) d.H = (d.H % 12) + d.p * 12;
// If the month was not specified, inherit from the quarter.
if (d.m === undefined) d.m = "q" in d ? d.q : 0;
// Convert day-of-week and week-of-year to day-of-year.
if ("V" in d) {
if (d.V < 1 || d.V > 53) return null;
if (!("w" in d)) d.w = 1;
if ("Z" in d) {
(week = utcDate(newDate(d.y, 0, 1))),
(day = week.getUTCDay());
week =
day > 4 || day === 0
? utcMonday.ceil(week)
: utcMonday(week);
week = src_utcDay.offset(week, (d.V - 1) * 7);
d.y = week.getUTCFullYear();
d.m = week.getUTCMonth();
d.d = week.getUTCDate() + ((d.w + 6) % 7);
} else {
(week = localDate(newDate(d.y, 0, 1))),
(day = week.getDay());
week =
day > 4 || day === 0
? monday.ceil(week)
: monday(week);
week = src_day.offset(week, (d.V - 1) * 7);
d.y = week.getFullYear();
d.m = week.getMonth();
d.d = week.getDate() + ((d.w + 6) % 7);
}
} else if ("W" in d || "U" in d) {
if (!("w" in d))
d.w = "u" in d ? d.u % 7 : "W" in d ? 1 : 0;
day =
"Z" in d
? utcDate(newDate(d.y, 0, 1)).getUTCDay()
: localDate(newDate(d.y, 0, 1)).getDay();
d.m = 0;
d.d =
"W" in d
? ((d.w + 6) % 7) +
d.W * 7 -
((day + 5) % 7)
: d.w + d.U * 7 - ((day + 6) % 7);
}
// If a time zone is specified, all fields are interpreted as UTC and then
// offset according to the specified time zone.
if ("Z" in d) {
d.H += (d.Z / 100) | 0;
d.M += d.Z % 100;
return utcDate(d);
}
// Otherwise, all fields are in local time.
return localDate(d);
};
}
function parseSpecifier(d, specifier, string, j) {
var i = 0,
n = specifier.length,
m = string.length,
c,
parse;
while (i < n) {
if (j >= m) return -1;
c = specifier.charCodeAt(i++);
if (c === 37) {
c = specifier.charAt(i++);
parse =
parses[c in pads ? specifier.charAt(i++) : c];
if (!parse || (j = parse(d, string, j)) < 0)
return -1;
} else if (c != string.charCodeAt(j++)) {
return -1;
}
}
return j;
}
function parsePeriod(d, string, i) {
var n = periodRe.exec(string.slice(i));
return n
? ((d.p = periodLookup.get(n[0].toLowerCase())),
i + n[0].length)
: -1;
}
function parseShortWeekday(d, string, i) {
var n = shortWeekdayRe.exec(string.slice(i));
return n
? ((d.w = shortWeekdayLookup.get(n[0].toLowerCase())),
i + n[0].length)
: -1;
}
function parseWeekday(d, string, i) {
var n = weekdayRe.exec(string.slice(i));
return n
? ((d.w = weekdayLookup.get(n[0].toLowerCase())),
i + n[0].length)
: -1;
}
function parseShortMonth(d, string, i) {
var n = shortMonthRe.exec(string.slice(i));
return n
? ((d.m = shortMonthLookup.get(n[0].toLowerCase())),
i + n[0].length)
: -1;
}
function parseMonth(d, string, i) {
var n = monthRe.exec(string.slice(i));
return n
? ((d.m = monthLookup.get(n[0].toLowerCase())),
i + n[0].length)
: -1;
}
function parseLocaleDateTime(d, string, i) {
return parseSpecifier(d, locale_dateTime, string, i);
}
function parseLocaleDate(d, string, i) {
return parseSpecifier(d, locale_date, string, i);
}
function parseLocaleTime(d, string, i) {
return parseSpecifier(d, locale_time, string, i);
}
function formatShortWeekday(d) {
return locale_shortWeekdays[d.getDay()];
}
function formatWeekday(d) {
return locale_weekdays[d.getDay()];
}
function formatShortMonth(d) {
return locale_shortMonths[d.getMonth()];
}
function formatMonth(d) {
return locale_months[d.getMonth()];
}
function formatPeriod(d) {
return locale_periods[+(d.getHours() >= 12)];
}
function formatQuarter(d) {
return 1 + ~~(d.getMonth() / 3);
}
function formatUTCShortWeekday(d) {
return locale_shortWeekdays[d.getUTCDay()];
}
function formatUTCWeekday(d) {
return locale_weekdays[d.getUTCDay()];
}
function formatUTCShortMonth(d) {
return locale_shortMonths[d.getUTCMonth()];
}
function formatUTCMonth(d) {
return locale_months[d.getUTCMonth()];
}
function formatUTCPeriod(d) {
return locale_periods[+(d.getUTCHours() >= 12)];
}
function formatUTCQuarter(d) {
return 1 + ~~(d.getUTCMonth() / 3);
}
return {
format: function (specifier) {
var f = newFormat((specifier += ""), formats);
f.toString = function () {
return specifier;
};
return f;
},
parse: function (specifier) {
var p = newParse((specifier += ""), false);
p.toString = function () {
return specifier;
};
return p;
},
utcFormat: function (specifier) {
var f = newFormat((specifier += ""), utcFormats);
f.toString = function () {
return specifier;
};
return f;
},
utcParse: function (specifier) {
var p = newParse((specifier += ""), true);
p.toString = function () {
return specifier;
};
return p;
},
};
}
var pads = { "-": "", _: " ", 0: "0" },
numberRe = /^\s*\d+/, // note: ignores next directive
percentRe = /^%/,
requoteRe = /[\\^$*+?|[\]().{}]/g;
function pad(value, fill, width) {
var sign = value < 0 ? "-" : "",
string = (sign ? -value : value) + "",
length = string.length;
return (
sign +
(length < width
? new Array(width - length + 1).join(fill) + string
: string)
);
}
function requote(s) {
return s.replace(requoteRe, "\\$&");
}
function formatRe(names) {
return new RegExp(
"^(?:" + names.map(requote).join("|") + ")",
"i"
);
}
function formatLookup(names) {
return new Map(names.map((name, i) => [name.toLowerCase(), i]));
}
function parseWeekdayNumberSunday(d, string, i) {
var n = numberRe.exec(string.slice(i, i + 1));
return n ? ((d.w = +n[0]), i + n[0].length) : -1;
}
function parseWeekdayNumberMonday(d, string, i) {
var n = numberRe.exec(string.slice(i, i + 1));
return n ? ((d.u = +n[0]), i + n[0].length) : -1;
}
function parseWeekNumberSunday(d, string, i) {
var n = numberRe.exec(string.slice(i, i + 2));
return n ? ((d.U = +n[0]), i + n[0].length) : -1;
}
function parseWeekNumberISO(d, string, i) {
var n = numberRe.exec(string.slice(i, i + 2));
return n ? ((d.V = +n[0]), i + n[0].length) : -1;
}
function parseWeekNumberMonday(d, string, i) {
var n = numberRe.exec(string.slice(i, i + 2));
return n ? ((d.W = +n[0]), i + n[0].length) : -1;
}
function parseFullYear(d, string, i) {
var n = numberRe.exec(string.slice(i, i + 4));
return n ? ((d.y = +n[0]), i + n[0].length) : -1;
}
function parseYear(d, string, i) {
var n = numberRe.exec(string.slice(i, i + 2));
return n
? ((d.y = +n[0] + (+n[0] > 68 ? 1900 : 2000)),
i + n[0].length)
: -1;
}
function parseZone(d, string, i) {
var n = /^(Z)|([+-]\d\d)(?::?(\d\d))?/.exec(
string.slice(i, i + 6)
);
return n
? ((d.Z = n[1] ? 0 : -(n[2] + (n[3] || "00"))),
i + n[0].length)
: -1;
}
function parseQuarter(d, string, i) {
var n = numberRe.exec(string.slice(i, i + 1));
return n ? ((d.q = n[0] * 3 - 3), i + n[0].length) : -1;
}
function parseMonthNumber(d, string, i) {
var n = numberRe.exec(string.slice(i, i + 2));
return n ? ((d.m = n[0] - 1), i + n[0].length) : -1;
}
function parseDayOfMonth(d, string, i) {
var n = numberRe.exec(string.slice(i, i + 2));
return n ? ((d.d = +n[0]), i + n[0].length) : -1;
}
function parseDayOfYear(d, string, i) {
var n = numberRe.exec(string.slice(i, i + 3));
return n ? ((d.m = 0), (d.d = +n[0]), i + n[0].length) : -1;
}
function parseHour24(d, string, i) {
var n = numberRe.exec(string.slice(i, i + 2));
return n ? ((d.H = +n[0]), i + n[0].length) : -1;
}
function parseMinutes(d, string, i) {
var n = numberRe.exec(string.slice(i, i + 2));
return n ? ((d.M = +n[0]), i + n[0].length) : -1;
}
function parseSeconds(d, string, i) {
var n = numberRe.exec(string.slice(i, i + 2));
return n ? ((d.S = +n[0]), i + n[0].length) : -1;
}
function parseMilliseconds(d, string, i) {
var n = numberRe.exec(string.slice(i, i + 3));
return n ? ((d.L = +n[0]), i + n[0].length) : -1;
}
function parseMicroseconds(d, string, i) {
var n = numberRe.exec(string.slice(i, i + 6));
return n
? ((d.L = Math.floor(n[0] / 1000)), i + n[0].length)
: -1;
}
function parseLiteralPercent(d, string, i) {
var n = percentRe.exec(string.slice(i, i + 1));
return n ? i + n[0].length : -1;
}
function parseUnixTimestamp(d, string, i) {
var n = numberRe.exec(string.slice(i));
return n ? ((d.Q = +n[0]), i + n[0].length) : -1;
}
function parseUnixTimestampSeconds(d, string, i) {
var n = numberRe.exec(string.slice(i));
return n ? ((d.s = +n[0]), i + n[0].length) : -1;
}
function formatDayOfMonth(d, p) {
return pad(d.getDate(), p, 2);
}
function formatHour24(d, p) {
return pad(d.getHours(), p, 2);
}
function formatHour12(d, p) {
return pad(d.getHours() % 12 || 12, p, 2);
}
function formatDayOfYear(d, p) {
return pad(1 + src_day.count(src_year(d), d), p, 3);
}
function formatMilliseconds(d, p) {
return pad(d.getMilliseconds(), p, 3);
}
function formatMicroseconds(d, p) {
return formatMilliseconds(d, p) + "000";
}
function formatMonthNumber(d, p) {
return pad(d.getMonth() + 1, p, 2);
}
function formatMinutes(d, p) {
return pad(d.getMinutes(), p, 2);
}
function formatSeconds(d, p) {
return pad(d.getSeconds(), p, 2);
}
function formatWeekdayNumberMonday(d) {
var day = d.getDay();
return day === 0 ? 7 : day;
}
function formatWeekNumberSunday(d, p) {
return pad(sunday.count(src_year(d) - 1, d), p, 2);
}
function dISO(d) {
var day = d.getDay();
return day >= 4 || day === 0 ? thursday(d) : thursday.ceil(d);
}
function formatWeekNumberISO(d, p) {
d = dISO(d);
return pad(
thursday.count(src_year(d), d) +
(src_year(d).getDay() === 4),
p,
2
);
}
function formatWeekdayNumberSunday(d) {
return d.getDay();
}
function formatWeekNumberMonday(d, p) {
return pad(monday.count(src_year(d) - 1, d), p, 2);
}
function formatYear(d, p) {
return pad(d.getFullYear() % 100, p, 2);
}
function formatYearISO(d, p) {
d = dISO(d);
return pad(d.getFullYear() % 100, p, 2);
}
function formatFullYear(d, p) {
return pad(d.getFullYear() % 10000, p, 4);
}
function formatFullYearISO(d, p) {
var day = d.getDay();
d = day >= 4 || day === 0 ? thursday(d) : thursday.ceil(d);
return pad(d.getFullYear() % 10000, p, 4);
}
function formatZone(d) {
var z = d.getTimezoneOffset();
return (
(z > 0 ? "-" : ((z *= -1), "+")) +
pad((z / 60) | 0, "0", 2) +
pad(z % 60, "0", 2)
);
}
function formatUTCDayOfMonth(d, p) {
return pad(d.getUTCDate(), p, 2);
}
function formatUTCHour24(d, p) {
return pad(d.getUTCHours(), p, 2);
}
function formatUTCHour12(d, p) {
return pad(d.getUTCHours() % 12 || 12, p, 2);
}
function formatUTCDayOfYear(d, p) {
return pad(1 + src_utcDay.count(src_utcYear(d), d), p, 3);
}
function formatUTCMilliseconds(d, p) {
return pad(d.getUTCMilliseconds(), p, 3);
}
function formatUTCMicroseconds(d, p) {
return formatUTCMilliseconds(d, p) + "000";
}
function formatUTCMonthNumber(d, p) {
return pad(d.getUTCMonth() + 1, p, 2);
}
function formatUTCMinutes(d, p) {
return pad(d.getUTCMinutes(), p, 2);
}
function formatUTCSeconds(d, p) {
return pad(d.getUTCSeconds(), p, 2);
}
function formatUTCWeekdayNumberMonday(d) {
var dow = d.getUTCDay();
return dow === 0 ? 7 : dow;
}
function formatUTCWeekNumberSunday(d, p) {
return pad(utcSunday.count(src_utcYear(d) - 1, d), p, 2);
}
function UTCdISO(d) {
var day = d.getUTCDay();
return day >= 4 || day === 0
? utcThursday(d)
: utcThursday.ceil(d);
}
function formatUTCWeekNumberISO(d, p) {
d = UTCdISO(d);
return pad(
utcThursday.count(src_utcYear(d), d) +
(src_utcYear(d).getUTCDay() === 4),
p,
2
);
}
function formatUTCWeekdayNumberSunday(d) {
return d.getUTCDay();
}
function formatUTCWeekNumberMonday(d, p) {
return pad(utcMonday.count(src_utcYear(d) - 1, d), p, 2);
}
function formatUTCYear(d, p) {
return pad(d.getUTCFullYear() % 100, p, 2);
}
function formatUTCYearISO(d, p) {
d = UTCdISO(d);
return pad(d.getUTCFullYear() % 100, p, 2);
}
function formatUTCFullYear(d, p) {
return pad(d.getUTCFullYear() % 10000, p, 4);
}
function formatUTCFullYearISO(d, p) {
var day = d.getUTCDay();
d =
day >= 4 || day === 0
? utcThursday(d)
: utcThursday.ceil(d);
return pad(d.getUTCFullYear() % 10000, p, 4);
}
function formatUTCZone() {
return "+0000";
}
function formatLiteralPercent() {
return "%";
}
function formatUnixTimestamp(d) {
return +d;
}
function formatUnixTimestampSeconds(d) {
return Math.floor(+d / 1000);
} // CONCATENATED MODULE: ../node_modules/d3-time-format/src/defaultLocale.js
var locale;
var timeFormat;
var timeParse;
var utcFormat;
var utcParse;
defaultLocale({
dateTime: "%x, %X",
date: "%-m/%-d/%Y",
time: "%-I:%M:%S %p",
periods: ["AM", "PM"],
days: [
"Sunday",
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday",
],
shortDays: ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"],
months: [
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December",
],
shortMonths: [
"Jan",
"Feb",
"Mar",
"Apr",
"May",
"Jun",
"Jul",
"Aug",
"Sep",
"Oct",
"Nov",
"Dec",
],
});
function defaultLocale(definition) {
locale = formatLocale(definition);
timeFormat = locale.format;
timeParse = locale.parse;
utcFormat = locale.utcFormat;
utcParse = locale.utcParse;
return locale;
}
// EXTERNAL MODULE: ../node_modules/d3-scale/src/continuous.js + 19 modules
var continuous = __webpack_require__(73516);
// EXTERNAL MODULE: ../node_modules/d3-scale/src/init.js
var init = __webpack_require__(42287); // CONCATENATED MODULE: ../node_modules/d3-scale/src/nice.js
function nice(domain, interval) {
domain = domain.slice();
var i0 = 0,
i1 = domain.length - 1,
x0 = domain[i0],
x1 = domain[i1],
t;
if (x1 < x0) {
(t = i0), (i0 = i1), (i1 = t);
(t = x0), (x0 = x1), (x1 = t);
}
domain[i0] = interval.floor(x0);
domain[i1] = interval.ceil(x1);
return domain;
} // CONCATENATED MODULE: ../node_modules/d3-scale/src/time.js
function date(t) {
return new Date(t);
}
function number(t) {
return t instanceof Date ? +t : +new Date(+t);
}
/***/
},
},
]);
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_minifier/tests/fixture/issues/d3-time-format/3/output.js | JavaScript | (self.webpackChunk_N_E = self.webpackChunk_N_E || []).push([
[
6945
],
{
/***/ 2728: /***/ function(__unused_webpack_module, __webpack_exports__, __webpack_require__) {
"use strict";
// EXPORTS
__webpack_require__.d(__webpack_exports__, {
Z: function() {
return /* binding */ createTimeScale;
}
});
// UNUSED EXPORTS: updateTimeScale
// EXTERNAL MODULE: ../node_modules/d3-array/src/bisector.js
var locale, bisector = __webpack_require__(24852), src_ticks = __webpack_require__(73002), t0 = new Date(), t1 = new Date();
function newInterval(floori, offseti, count, field) {
function interval(date) {
return floori(date = 0 == arguments.length ? new Date() : new Date(+date)), date;
}
return interval.floor = function(date) {
return floori(date = new Date(+date)), date;
}, interval.ceil = function(date) {
return floori(date = new Date(date - 1)), offseti(date, 1), floori(date), date;
}, interval.round = function(date) {
var d0 = interval(date), d1 = interval.ceil(date);
return date - d0 < d1 - date ? d0 : d1;
}, interval.offset = function(date, step) {
return offseti(date = new Date(+date), null == step ? 1 : Math.floor(step)), date;
}, interval.range = function(start, stop, step) {
var previous, range = [];
if (start = interval.ceil(start), step = null == step ? 1 : Math.floor(step), !(start < stop) || !(step > 0)) return range; // also handles Invalid Date
do range.push(previous = new Date(+start)), offseti(start, step), floori(start);
while (previous < start && start < stop)
return range;
}, interval.filter = function(test) {
return newInterval(function(date) {
if (date >= date) for(; floori(date), !test(date);)date.setTime(date - 1);
}, function(date, step) {
if (date >= date) {
if (step < 0) for(; ++step <= 0;)for(; offseti(date, -1), !test(date););
// eslint-disable-line no-empty
else for(; --step >= 0;)for(; offseti(date, 1), !test(date););
// eslint-disable-line no-empty
}
});
}, count && (interval.count = function(start, end) {
return t0.setTime(+start), t1.setTime(+end), floori(t0), floori(t1), Math.floor(count(t0, t1));
}, interval.every = function(step) {
return isFinite(step = Math.floor(step)) && step > 0 ? step > 1 ? interval.filter(field ? function(d) {
return field(d) % step == 0;
} : function(d) {
return interval.count(0, d) % step == 0;
}) : interval : null;
}), interval;
} // CONCATENATED MODULE: ../node_modules/d3-time/src/millisecond.js
var millisecond = newInterval(function() {
// noop
}, function(date, step) {
date.setTime(+date + step);
}, function(start, end) {
return end - start;
});
// An optimized implementation for this simple case.
millisecond.every = function(k) {
return isFinite(k = Math.floor(k)) && k > 0 ? k > 1 ? newInterval(function(date) {
date.setTime(Math.floor(date / k) * k);
}, function(date, step) {
date.setTime(+date + step * k);
}, function(start, end) {
return (end - start) / k;
}) : millisecond : null;
}, millisecond.range;
var second = newInterval(function(date) {
date.setTime(date - date.getMilliseconds());
}, function(date, step) {
date.setTime(+date + 1000 * step);
}, function(start, end) {
return (end - start) / 1000;
}, function(date) {
return date.getUTCSeconds();
});
second.range;
var minute = newInterval(function(date) {
date.setTime(date - date.getMilliseconds() - 1000 * date.getSeconds());
}, function(date, step) {
date.setTime(+date + 60000 * step);
}, function(start, end) {
return (end - start) / 60000;
}, function(date) {
return date.getMinutes();
});
minute.range;
var hour = newInterval(function(date) {
date.setTime(date - date.getMilliseconds() - 1000 * date.getSeconds() - 60000 * date.getMinutes());
}, function(date, step) {
date.setTime(+date + 3600000 * step);
}, function(start, end) {
return (end - start) / 3600000;
}, function(date) {
return date.getHours();
});
hour.range;
var day = newInterval((date)=>date.setHours(0, 0, 0, 0), (date, step)=>date.setDate(date.getDate() + step), (start, end)=>(end - start - (end.getTimezoneOffset() - start.getTimezoneOffset()) * 60000) / 86400000, (date)=>date.getDate() - 1);
function weekday(i) {
return newInterval(function(date) {
date.setDate(date.getDate() - (date.getDay() + 7 - i) % 7), date.setHours(0, 0, 0, 0);
}, function(date, step) {
date.setDate(date.getDate() + 7 * step);
}, function(start, end) {
return (end - start - (end.getTimezoneOffset() - start.getTimezoneOffset()) * 60000) / 604800000;
});
}
day.range;
var sunday = weekday(0), monday = weekday(1), tuesday = weekday(2), wednesday = weekday(3), thursday = weekday(4), friday = weekday(5), saturday = weekday(6);
sunday.range, monday.range, tuesday.range, wednesday.range, thursday.range, friday.range, saturday.range;
var month = newInterval(function(date) {
date.setDate(1), date.setHours(0, 0, 0, 0);
}, function(date, step) {
date.setMonth(date.getMonth() + step);
}, function(start, end) {
return end.getMonth() - start.getMonth() + (end.getFullYear() - start.getFullYear()) * 12;
}, function(date) {
return date.getMonth();
});
month.range;
var year = newInterval(function(date) {
date.setMonth(0, 1), date.setHours(0, 0, 0, 0);
}, function(date, step) {
date.setFullYear(date.getFullYear() + step);
}, function(start, end) {
return end.getFullYear() - start.getFullYear();
}, function(date) {
return date.getFullYear();
});
// An optimized implementation for this simple case.
year.every = function(k) {
return isFinite(k = Math.floor(k)) && k > 0 ? newInterval(function(date) {
date.setFullYear(Math.floor(date.getFullYear() / k) * k), date.setMonth(0, 1), date.setHours(0, 0, 0, 0);
}, function(date, step) {
date.setFullYear(date.getFullYear() + step * k);
}) : null;
}, year.range;
var utcMinute = newInterval(function(date) {
date.setUTCSeconds(0, 0);
}, function(date, step) {
date.setTime(+date + 60000 * step);
}, function(start, end) {
return (end - start) / 60000;
}, function(date) {
return date.getUTCMinutes();
});
utcMinute.range;
var utcHour = newInterval(function(date) {
date.setUTCMinutes(0, 0, 0);
}, function(date, step) {
date.setTime(+date + 3600000 * step);
}, function(start, end) {
return (end - start) / 3600000;
}, function(date) {
return date.getUTCHours();
});
utcHour.range;
var utcDay = newInterval(function(date) {
date.setUTCHours(0, 0, 0, 0);
}, function(date, step) {
date.setUTCDate(date.getUTCDate() + step);
}, function(start, end) {
return (end - start) / 86400000;
}, function(date) {
return date.getUTCDate() - 1;
});
function utcWeekday(i) {
return newInterval(function(date) {
date.setUTCDate(date.getUTCDate() - (date.getUTCDay() + 7 - i) % 7), date.setUTCHours(0, 0, 0, 0);
}, function(date, step) {
date.setUTCDate(date.getUTCDate() + 7 * step);
}, function(start, end) {
return (end - start) / 604800000;
});
}
utcDay.range;
var utcSunday = utcWeekday(0), utcMonday = utcWeekday(1), utcTuesday = utcWeekday(2), utcWednesday = utcWeekday(3), utcThursday = utcWeekday(4), utcFriday = utcWeekday(5), utcSaturday = utcWeekday(6);
utcSunday.range, utcMonday.range, utcTuesday.range, utcWednesday.range, utcThursday.range, utcFriday.range, utcSaturday.range;
var utcMonth = newInterval(function(date) {
date.setUTCDate(1), date.setUTCHours(0, 0, 0, 0);
}, function(date, step) {
date.setUTCMonth(date.getUTCMonth() + step);
}, function(start, end) {
return end.getUTCMonth() - start.getUTCMonth() + (end.getUTCFullYear() - start.getUTCFullYear()) * 12;
}, function(date) {
return date.getUTCMonth();
});
utcMonth.range;
var utcYear = newInterval(function(date) {
date.setUTCMonth(0, 1), date.setUTCHours(0, 0, 0, 0);
}, function(date, step) {
date.setUTCFullYear(date.getUTCFullYear() + step);
}, function(start, end) {
return end.getUTCFullYear() - start.getUTCFullYear();
}, function(date) {
return date.getUTCFullYear();
});
function ticker(year, month, week, day, hour, minute) {
const tickIntervals = [
[
second,
1,
1000
],
[
second,
5,
5000
],
[
second,
15,
15000
],
[
second,
30,
30000
],
[
minute,
1,
60000
],
[
minute,
5,
300000
],
[
minute,
15,
900000
],
[
minute,
30,
1800000
],
[
hour,
1,
3600000
],
[
hour,
3,
10800000
],
[
hour,
6,
21600000
],
[
hour,
12,
43200000
],
[
day,
1,
86400000
],
[
day,
2,
172800000
],
[
week,
1,
604800000
],
[
month,
1,
2592000000
],
[
month,
3,
7776000000
],
[
year,
1,
31536000000
]
];
function tickInterval(start, stop, count) {
const target = Math.abs(stop - start) / count, i = (0, bisector /* default */ .Z)(([, , step])=>step).right(tickIntervals, target);
if (i === tickIntervals.length) return year.every((0, src_ticks /* tickStep */ .ly)(start / 31536000000, stop / 31536000000, count));
if (0 === i) return millisecond.every(Math.max((0, src_ticks /* tickStep */ .ly)(start, stop, count), 1));
const [t, step] = tickIntervals[target / tickIntervals[i - 1][2] < tickIntervals[i][2] / target ? i - 1 : i];
return t.every(step);
}
return [
function(start, stop, count) {
const reverse = stop < start;
reverse && ([start, stop] = [
stop,
start
]);
const interval = count && "function" == typeof count.range ? count : tickInterval(start, stop, count), ticks = interval ? interval.range(start, +stop + 1) : [];
return reverse ? ticks.reverse() : ticks;
},
tickInterval
];
}
// An optimized implementation for this simple case.
utcYear.every = function(k) {
return isFinite(k = Math.floor(k)) && k > 0 ? newInterval(function(date) {
date.setUTCFullYear(Math.floor(date.getUTCFullYear() / k) * k), date.setUTCMonth(0, 1), date.setUTCHours(0, 0, 0, 0);
}, function(date, step) {
date.setUTCFullYear(date.getUTCFullYear() + step * k);
}) : null;
}, utcYear.range;
const [utcTicks, utcTickInterval] = ticker(utcYear, utcMonth, utcSunday, utcDay, utcHour, utcMinute), [timeTicks, timeTickInterval] = ticker(year, month, sunday, day, hour, minute);
function localDate(d) {
if (0 <= d.y && d.y < 100) {
var date = new Date(-1, d.m, d.d, d.H, d.M, d.S, d.L);
return date.setFullYear(d.y), date;
}
return new Date(d.y, d.m, d.d, d.H, d.M, d.S, d.L);
}
function utcDate(d) {
if (0 <= d.y && d.y < 100) {
var date = new Date(Date.UTC(-1, d.m, d.d, d.H, d.M, d.S, d.L));
return date.setUTCFullYear(d.y), date;
}
return new Date(Date.UTC(d.y, d.m, d.d, d.H, d.M, d.S, d.L));
}
function newDate(y, m, d) {
return {
y: y,
m: m,
d: d,
H: 0,
M: 0,
S: 0,
L: 0
};
}
var pads = {
"-": "",
_: " ",
0: "0"
}, numberRe = /^\s*\d+/, percentRe = /^%/, requoteRe = /[\\^$*+?|[\]().{}]/g;
function pad(value, fill, width) {
var sign = value < 0 ? "-" : "", string = (sign ? -value : value) + "", length = string.length;
return sign + (length < width ? Array(width - length + 1).join(fill) + string : string);
}
function requote(s) {
return s.replace(requoteRe, "\\$&");
}
function formatRe(names) {
return RegExp("^(?:" + names.map(requote).join("|") + ")", "i");
}
function formatLookup(names) {
return new Map(names.map((name, i)=>[
name.toLowerCase(),
i
]));
}
function parseWeekdayNumberSunday(d, string, i) {
var n = numberRe.exec(string.slice(i, i + 1));
return n ? (d.w = +n[0], i + n[0].length) : -1;
}
function parseWeekdayNumberMonday(d, string, i) {
var n = numberRe.exec(string.slice(i, i + 1));
return n ? (d.u = +n[0], i + n[0].length) : -1;
}
function parseWeekNumberSunday(d, string, i) {
var n = numberRe.exec(string.slice(i, i + 2));
return n ? (d.U = +n[0], i + n[0].length) : -1;
}
function parseWeekNumberISO(d, string, i) {
var n = numberRe.exec(string.slice(i, i + 2));
return n ? (d.V = +n[0], i + n[0].length) : -1;
}
function parseWeekNumberMonday(d, string, i) {
var n = numberRe.exec(string.slice(i, i + 2));
return n ? (d.W = +n[0], i + n[0].length) : -1;
}
function parseFullYear(d, string, i) {
var n = numberRe.exec(string.slice(i, i + 4));
return n ? (d.y = +n[0], i + n[0].length) : -1;
}
function parseYear(d, string, i) {
var n = numberRe.exec(string.slice(i, i + 2));
return n ? (d.y = +n[0] + (+n[0] > 68 ? 1900 : 2000), i + n[0].length) : -1;
}
function parseZone(d, string, i) {
var n = /^(Z)|([+-]\d\d)(?::?(\d\d))?/.exec(string.slice(i, i + 6));
return n ? (d.Z = n[1] ? 0 : -(n[2] + (n[3] || "00")), i + n[0].length) : -1;
}
function parseQuarter(d, string, i) {
var n = numberRe.exec(string.slice(i, i + 1));
return n ? (d.q = 3 * n[0] - 3, i + n[0].length) : -1;
}
function parseMonthNumber(d, string, i) {
var n = numberRe.exec(string.slice(i, i + 2));
return n ? (d.m = n[0] - 1, i + n[0].length) : -1;
}
function parseDayOfMonth(d, string, i) {
var n = numberRe.exec(string.slice(i, i + 2));
return n ? (d.d = +n[0], i + n[0].length) : -1;
}
function parseDayOfYear(d, string, i) {
var n = numberRe.exec(string.slice(i, i + 3));
return n ? (d.m = 0, d.d = +n[0], i + n[0].length) : -1;
}
function parseHour24(d, string, i) {
var n = numberRe.exec(string.slice(i, i + 2));
return n ? (d.H = +n[0], i + n[0].length) : -1;
}
function parseMinutes(d, string, i) {
var n = numberRe.exec(string.slice(i, i + 2));
return n ? (d.M = +n[0], i + n[0].length) : -1;
}
function parseSeconds(d, string, i) {
var n = numberRe.exec(string.slice(i, i + 2));
return n ? (d.S = +n[0], i + n[0].length) : -1;
}
function parseMilliseconds(d, string, i) {
var n = numberRe.exec(string.slice(i, i + 3));
return n ? (d.L = +n[0], i + n[0].length) : -1;
}
function parseMicroseconds(d, string, i) {
var n = numberRe.exec(string.slice(i, i + 6));
return n ? (d.L = Math.floor(n[0] / 1000), i + n[0].length) : -1;
}
function parseLiteralPercent(d, string, i) {
var n = percentRe.exec(string.slice(i, i + 1));
return n ? i + n[0].length : -1;
}
function parseUnixTimestamp(d, string, i) {
var n = numberRe.exec(string.slice(i));
return n ? (d.Q = +n[0], i + n[0].length) : -1;
}
function parseUnixTimestampSeconds(d, string, i) {
var n = numberRe.exec(string.slice(i));
return n ? (d.s = +n[0], i + n[0].length) : -1;
}
function formatDayOfMonth(d, p) {
return pad(d.getDate(), p, 2);
}
function formatHour24(d, p) {
return pad(d.getHours(), p, 2);
}
function formatHour12(d, p) {
return pad(d.getHours() % 12 || 12, p, 2);
}
function formatDayOfYear(d, p) {
return pad(1 + day.count(year(d), d), p, 3);
}
function formatMilliseconds(d, p) {
return pad(d.getMilliseconds(), p, 3);
}
function formatMicroseconds(d, p) {
return formatMilliseconds(d, p) + "000";
}
function formatMonthNumber(d, p) {
return pad(d.getMonth() + 1, p, 2);
}
function formatMinutes(d, p) {
return pad(d.getMinutes(), p, 2);
}
function formatSeconds(d, p) {
return pad(d.getSeconds(), p, 2);
}
function formatWeekdayNumberMonday(d) {
var day = d.getDay();
return 0 === day ? 7 : day;
}
function formatWeekNumberSunday(d, p) {
return pad(sunday.count(year(d) - 1, d), p, 2);
}
function dISO(d) {
var day = d.getDay();
return day >= 4 || 0 === day ? thursday(d) : thursday.ceil(d);
}
function formatWeekNumberISO(d, p) {
return d = dISO(d), pad(thursday.count(year(d), d) + (4 === year(d).getDay()), p, 2);
}
function formatWeekdayNumberSunday(d) {
return d.getDay();
}
function formatWeekNumberMonday(d, p) {
return pad(monday.count(year(d) - 1, d), p, 2);
}
function formatYear(d, p) {
return pad(d.getFullYear() % 100, p, 2);
}
function formatYearISO(d, p) {
return pad((d = dISO(d)).getFullYear() % 100, p, 2);
}
function formatFullYear(d, p) {
return pad(d.getFullYear() % 10000, p, 4);
}
function formatFullYearISO(d, p) {
var day = d.getDay();
return pad((d = day >= 4 || 0 === day ? thursday(d) : thursday.ceil(d)).getFullYear() % 10000, p, 4);
}
function formatZone(d) {
var z = d.getTimezoneOffset();
return (z > 0 ? "-" : (z *= -1, "+")) + pad(z / 60 | 0, "0", 2) + pad(z % 60, "0", 2);
}
function formatUTCDayOfMonth(d, p) {
return pad(d.getUTCDate(), p, 2);
}
function formatUTCHour24(d, p) {
return pad(d.getUTCHours(), p, 2);
}
function formatUTCHour12(d, p) {
return pad(d.getUTCHours() % 12 || 12, p, 2);
}
function formatUTCDayOfYear(d, p) {
return pad(1 + utcDay.count(utcYear(d), d), p, 3);
}
function formatUTCMilliseconds(d, p) {
return pad(d.getUTCMilliseconds(), p, 3);
}
function formatUTCMicroseconds(d, p) {
return formatUTCMilliseconds(d, p) + "000";
}
function formatUTCMonthNumber(d, p) {
return pad(d.getUTCMonth() + 1, p, 2);
}
function formatUTCMinutes(d, p) {
return pad(d.getUTCMinutes(), p, 2);
}
function formatUTCSeconds(d, p) {
return pad(d.getUTCSeconds(), p, 2);
}
function formatUTCWeekdayNumberMonday(d) {
var dow = d.getUTCDay();
return 0 === dow ? 7 : dow;
}
function formatUTCWeekNumberSunday(d, p) {
return pad(utcSunday.count(utcYear(d) - 1, d), p, 2);
}
function UTCdISO(d) {
var day = d.getUTCDay();
return day >= 4 || 0 === day ? utcThursday(d) : utcThursday.ceil(d);
}
function formatUTCWeekNumberISO(d, p) {
return d = UTCdISO(d), pad(utcThursday.count(utcYear(d), d) + (4 === utcYear(d).getUTCDay()), p, 2);
}
function formatUTCWeekdayNumberSunday(d) {
return d.getUTCDay();
}
function formatUTCWeekNumberMonday(d, p) {
return pad(utcMonday.count(utcYear(d) - 1, d), p, 2);
}
function formatUTCYear(d, p) {
return pad(d.getUTCFullYear() % 100, p, 2);
}
function formatUTCYearISO(d, p) {
return pad((d = UTCdISO(d)).getUTCFullYear() % 100, p, 2);
}
function formatUTCFullYear(d, p) {
return pad(d.getUTCFullYear() % 10000, p, 4);
}
function formatUTCFullYearISO(d, p) {
var day = d.getUTCDay();
return pad((d = day >= 4 || 0 === day ? utcThursday(d) : utcThursday.ceil(d)).getUTCFullYear() % 10000, p, 4);
}
function formatUTCZone() {
return "+0000";
}
function formatLiteralPercent() {
return "%";
}
function formatUnixTimestamp(d) {
return +d;
}
function formatUnixTimestampSeconds(d) {
return Math.floor(+d / 1000);
} // CONCATENATED MODULE: ../node_modules/d3-time-format/src/defaultLocale.js
(locale = function(locale) {
var locale_dateTime = locale.dateTime, locale_date = locale.date, locale_time = locale.time, locale_periods = locale.periods, locale_weekdays = locale.days, locale_shortWeekdays = locale.shortDays, locale_months = locale.months, locale_shortMonths = locale.shortMonths, periodRe = formatRe(locale_periods), periodLookup = formatLookup(locale_periods), weekdayRe = formatRe(locale_weekdays), weekdayLookup = formatLookup(locale_weekdays), shortWeekdayRe = formatRe(locale_shortWeekdays), shortWeekdayLookup = formatLookup(locale_shortWeekdays), monthRe = formatRe(locale_months), monthLookup = formatLookup(locale_months), shortMonthRe = formatRe(locale_shortMonths), shortMonthLookup = formatLookup(locale_shortMonths), formats = {
a: function(d) {
return locale_shortWeekdays[d.getDay()];
},
A: function(d) {
return locale_weekdays[d.getDay()];
},
b: function(d) {
return locale_shortMonths[d.getMonth()];
},
B: function(d) {
return locale_months[d.getMonth()];
},
c: null,
d: formatDayOfMonth,
e: formatDayOfMonth,
f: formatMicroseconds,
g: formatYearISO,
G: formatFullYearISO,
H: formatHour24,
I: formatHour12,
j: formatDayOfYear,
L: formatMilliseconds,
m: formatMonthNumber,
M: formatMinutes,
p: function(d) {
return locale_periods[+(d.getHours() >= 12)];
},
q: function(d) {
return 1 + ~~(d.getMonth() / 3);
},
Q: formatUnixTimestamp,
s: formatUnixTimestampSeconds,
S: formatSeconds,
u: formatWeekdayNumberMonday,
U: formatWeekNumberSunday,
V: formatWeekNumberISO,
w: formatWeekdayNumberSunday,
W: formatWeekNumberMonday,
x: null,
X: null,
y: formatYear,
Y: formatFullYear,
Z: formatZone,
"%": formatLiteralPercent
}, utcFormats = {
a: function(d) {
return locale_shortWeekdays[d.getUTCDay()];
},
A: function(d) {
return locale_weekdays[d.getUTCDay()];
},
b: function(d) {
return locale_shortMonths[d.getUTCMonth()];
},
B: function(d) {
return locale_months[d.getUTCMonth()];
},
c: null,
d: formatUTCDayOfMonth,
e: formatUTCDayOfMonth,
f: formatUTCMicroseconds,
g: formatUTCYearISO,
G: formatUTCFullYearISO,
H: formatUTCHour24,
I: formatUTCHour12,
j: formatUTCDayOfYear,
L: formatUTCMilliseconds,
m: formatUTCMonthNumber,
M: formatUTCMinutes,
p: function(d) {
return locale_periods[+(d.getUTCHours() >= 12)];
},
q: function(d) {
return 1 + ~~(d.getUTCMonth() / 3);
},
Q: formatUnixTimestamp,
s: formatUnixTimestampSeconds,
S: formatUTCSeconds,
u: formatUTCWeekdayNumberMonday,
U: formatUTCWeekNumberSunday,
V: formatUTCWeekNumberISO,
w: formatUTCWeekdayNumberSunday,
W: formatUTCWeekNumberMonday,
x: null,
X: null,
y: formatUTCYear,
Y: formatUTCFullYear,
Z: formatUTCZone,
"%": formatLiteralPercent
}, parses = {
a: function(d, string, i) {
var n = shortWeekdayRe.exec(string.slice(i));
return n ? (d.w = shortWeekdayLookup.get(n[0].toLowerCase()), i + n[0].length) : -1;
},
A: function(d, string, i) {
var n = weekdayRe.exec(string.slice(i));
return n ? (d.w = weekdayLookup.get(n[0].toLowerCase()), i + n[0].length) : -1;
},
b: function(d, string, i) {
var n = shortMonthRe.exec(string.slice(i));
return n ? (d.m = shortMonthLookup.get(n[0].toLowerCase()), i + n[0].length) : -1;
},
B: function(d, string, i) {
var n = monthRe.exec(string.slice(i));
return n ? (d.m = monthLookup.get(n[0].toLowerCase()), i + n[0].length) : -1;
},
c: function(d, string, i) {
return parseSpecifier(d, locale_dateTime, string, i);
},
d: parseDayOfMonth,
e: parseDayOfMonth,
f: parseMicroseconds,
g: parseYear,
G: parseFullYear,
H: parseHour24,
I: parseHour24,
j: parseDayOfYear,
L: parseMilliseconds,
m: parseMonthNumber,
M: parseMinutes,
p: function(d, string, i) {
var n = periodRe.exec(string.slice(i));
return n ? (d.p = periodLookup.get(n[0].toLowerCase()), i + n[0].length) : -1;
},
q: parseQuarter,
Q: parseUnixTimestamp,
s: parseUnixTimestampSeconds,
S: parseSeconds,
u: parseWeekdayNumberMonday,
U: parseWeekNumberSunday,
V: parseWeekNumberISO,
w: parseWeekdayNumberSunday,
W: parseWeekNumberMonday,
x: function(d, string, i) {
return parseSpecifier(d, locale_date, string, i);
},
X: function(d, string, i) {
return parseSpecifier(d, locale_time, string, i);
},
y: parseYear,
Y: parseFullYear,
Z: parseZone,
"%": parseLiteralPercent
};
function newFormat(specifier, formats) {
return function(date) {
var c, pad, format, string = [], i = -1, j = 0, n = specifier.length;
for(date instanceof Date || (date = new Date(+date)); ++i < n;)37 === specifier.charCodeAt(i) && (string.push(specifier.slice(j, i)), null != (pad = pads[c = specifier.charAt(++i)]) ? c = specifier.charAt(++i) : pad = "e" === c ? " " : "0", (format = formats[c]) && (c = format(date, pad)), string.push(c), j = i + 1);
return string.push(specifier.slice(j, i)), string.join("");
};
}
function newParse(specifier, Z) {
return function(string) {
var week, day1, d = newDate(1900, void 0, 1);
if (parseSpecifier(d, specifier, string += "", 0) != string.length) return null;
// If a UNIX timestamp is specified, return it.
if ("Q" in d) return new Date(d.Q);
if ("s" in d) return new Date(1000 * d.s + ("L" in d ? d.L : 0));
// Convert day-of-week and week-of-year to day-of-year.
if (!Z || "Z" in d || (d.Z = 0), "p" in d && (d.H = d.H % 12 + 12 * d.p), void 0 === d.m && (d.m = "q" in d ? d.q : 0), "V" in d) {
if (d.V < 1 || d.V > 53) return null;
"w" in d || (d.w = 1), "Z" in d ? (week = (day1 = (week = utcDate(newDate(d.y, 0, 1))).getUTCDay()) > 4 || 0 === day1 ? utcMonday.ceil(week) : utcMonday(week), week = utcDay.offset(week, (d.V - 1) * 7), d.y = week.getUTCFullYear(), d.m = week.getUTCMonth(), d.d = week.getUTCDate() + (d.w + 6) % 7) : (week = (day1 = (week = localDate(newDate(d.y, 0, 1))).getDay()) > 4 || 0 === day1 ? monday.ceil(week) : monday(week), week = day.offset(week, (d.V - 1) * 7), d.y = week.getFullYear(), d.m = week.getMonth(), d.d = week.getDate() + (d.w + 6) % 7);
} else ("W" in d || "U" in d) && ("w" in d || (d.w = "u" in d ? d.u % 7 : +("W" in d)), day1 = "Z" in d ? utcDate(newDate(d.y, 0, 1)).getUTCDay() : localDate(newDate(d.y, 0, 1)).getDay(), d.m = 0, d.d = "W" in d ? (d.w + 6) % 7 + 7 * d.W - (day1 + 5) % 7 : d.w + 7 * d.U - (day1 + 6) % 7);
return(// If a time zone is specified, all fields are interpreted as UTC and then
// offset according to the specified time zone.
"Z" in d ? (d.H += d.Z / 100 | 0, d.M += d.Z % 100, utcDate(d)) : localDate(d));
};
}
function parseSpecifier(d, specifier, string, j) {
for(var c, parse, i = 0, n = specifier.length, m = string.length; i < n;){
if (j >= m) return -1;
if (37 === (c = specifier.charCodeAt(i++))) {
if (!(parse = parses[(c = specifier.charAt(i++)) in pads ? specifier.charAt(i++) : c]) || (j = parse(d, string, j)) < 0) return -1;
} else if (c != string.charCodeAt(j++)) return -1;
}
return j;
}
return(// These recursive directive definitions must be deferred.
formats.x = newFormat(locale_date, formats), formats.X = newFormat(locale_time, formats), formats.c = newFormat(locale_dateTime, formats), utcFormats.x = newFormat(locale_date, utcFormats), utcFormats.X = newFormat(locale_time, utcFormats), utcFormats.c = newFormat(locale_dateTime, utcFormats), {
format: function(specifier) {
var f = newFormat(specifier += "", formats);
return f.toString = function() {
return specifier;
}, f;
},
parse: function(specifier) {
var p = newParse(specifier += "", !1);
return p.toString = function() {
return specifier;
}, p;
},
utcFormat: function(specifier) {
var f = newFormat(specifier += "", utcFormats);
return f.toString = function() {
return specifier;
}, f;
},
utcParse: function(specifier) {
var p = newParse(specifier += "", !0);
return p.toString = function() {
return specifier;
}, p;
}
});
}({
dateTime: "%x, %X",
date: "%-m/%-d/%Y",
time: "%-I:%M:%S %p",
periods: [
"AM",
"PM"
],
days: [
"Sunday",
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday"
],
shortDays: [
"Sun",
"Mon",
"Tue",
"Wed",
"Thu",
"Fri",
"Sat"
],
months: [
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December"
],
shortMonths: [
"Jan",
"Feb",
"Mar",
"Apr",
"May",
"Jun",
"Jul",
"Aug",
"Sep",
"Oct",
"Nov",
"Dec"
]
})).format, locale.parse, locale.utcFormat, locale.utcParse, __webpack_require__(73516), __webpack_require__(42287);
/***/ }
}
]);
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_minifier/tests/fixture/issues/emotion/react/1/input.js | JavaScript | (self["webpackChunk_N_E"] = self["webpackChunk_N_E"] || []).push([
[111],
{
/***/
2781:
/***/
function (
__unused_webpack_module,
__webpack_exports__,
__webpack_require__
) {
"use strict";
// EXPORTS
__webpack_require__.d(__webpack_exports__, {
xB: function () {
return /* binding */ Global;
},
});
// UNUSED EXPORTS: CacheProvider, ClassNames, ThemeContext, ThemeProvider, __unsafe_useEmotionCache, createElement, css, jsx, keyframes, useTheme, withEmotionCache, withTheme
// EXTERNAL MODULE: ./node_modules/react/index.js
var react = __webpack_require__(7294); // CONCATENATED MODULE: ./node_modules/@emotion/sheet/dist/emotion-sheet.browser.esm.js
/*
Based off glamor's StyleSheet, thanks Sunil ❤️
high performance StyleSheet for css-in-js systems
- uses multiple style tags behind the scenes for millions of rules
- uses `insertRule` for appending in production for *much* faster performance
// usage
import { StyleSheet } from '@emotion/sheet'
let styleSheet = new StyleSheet({ key: '', container: document.head })
styleSheet.insert('#box { border: 1px solid red; }')
- appends a css rule into the stylesheet
styleSheet.flush()
- empties the stylesheet of all its contents
*/
// $FlowFixMe
function sheetForTag(tag) {
if (tag.sheet) {
// $FlowFixMe
return tag.sheet;
} // this weirdness brought to you by firefox
/* istanbul ignore next */
for (var i = 0; i < document.styleSheets.length; i++) {
if (document.styleSheets[i].ownerNode === tag) {
// $FlowFixMe
return document.styleSheets[i];
}
}
}
function createStyleElement(options) {
var tag = document.createElement("style");
tag.setAttribute("data-emotion", options.key);
if (options.nonce !== undefined) {
tag.setAttribute("nonce", options.nonce);
}
tag.appendChild(document.createTextNode(""));
tag.setAttribute("data-s", "");
return tag;
}
var StyleSheet = /*#__PURE__*/ (function () {
function StyleSheet(options) {
var _this = this;
this._insertTag = function (tag) {
var before;
if (_this.tags.length === 0) {
before = _this.prepend
? _this.container.firstChild
: _this.before;
} else {
before =
_this.tags[_this.tags.length - 1]
.nextSibling;
}
_this.container.insertBefore(tag, before);
_this.tags.push(tag);
};
this.isSpeedy =
options.speedy === undefined
? "production" === "production"
: options.speedy;
this.tags = [];
this.ctr = 0;
this.nonce = options.nonce; // key is the value of the data-emotion attribute, it's used to identify different sheets
this.key = options.key;
this.container = options.container;
this.prepend = options.prepend;
this.before = null;
}
var _proto = StyleSheet.prototype;
_proto.hydrate = function hydrate(nodes) {
nodes.forEach(this._insertTag);
};
_proto.insert = function insert(rule) {
// the max length is how many rules we have per style tag, it's 65000 in speedy mode
// it's 1 in dev because we insert source maps that map a single rule to a location
// and you can only have one source map per style tag
if (this.ctr % (this.isSpeedy ? 65000 : 1) === 0) {
this._insertTag(createStyleElement(this));
}
var tag = this.tags[this.tags.length - 1];
if (false) {
var isImportRule;
}
if (this.isSpeedy) {
var sheet = sheetForTag(tag);
try {
// this is the ultrafast version, works across browsers
// the big drawback is that the css won't be editable in devtools
sheet.insertRule(rule, sheet.cssRules.length);
} catch (e) {
if (false) {
}
}
} else {
tag.appendChild(document.createTextNode(rule));
}
this.ctr++;
};
_proto.flush = function flush() {
// $FlowFixMe
this.tags.forEach(function (tag) {
return (
tag.parentNode &&
tag.parentNode.removeChild(tag)
);
});
this.tags = [];
this.ctr = 0;
if (false) {
}
};
return StyleSheet;
})(); // CONCATENATED MODULE: ./node_modules/@emotion/cache/node_modules/stylis/src/Utility.js
/**
* @param {number}
* @return {number}
*/
var abs = Math.abs;
/**
* @param {number}
* @return {string}
*/
var Utility_from = String.fromCharCode;
/**
* @param {string} value
* @param {number} length
* @return {number}
*/
function hash(value, length) {
return (
(((((((length << 2) ^ Utility_charat(value, 0)) << 2) ^
Utility_charat(value, 1)) <<
2) ^
Utility_charat(value, 2)) <<
2) ^
Utility_charat(value, 3)
);
}
/**
* @param {string} value
* @return {string}
*/
function trim(value) {
return value.trim();
}
/**
* @param {string} value
* @param {RegExp} pattern
* @return {string?}
*/
function match(value, pattern) {
return (value = pattern.exec(value)) ? value[0] : value;
}
/**
* @param {string} value
* @param {(string|RegExp)} pattern
* @param {string} replacement
* @return {string}
*/
function replace(value, pattern, replacement) {
return value.replace(pattern, replacement);
}
/**
* @param {string} value
* @param {string} value
* @return {number}
*/
function indexof(value, search) {
return value.indexOf(search);
}
/**
* @param {string} value
* @param {number} index
* @return {number}
*/
function Utility_charat(value, index) {
return value.charCodeAt(index) | 0;
}
/**
* @param {string} value
* @param {number} begin
* @param {number} end
* @return {string}
*/
function Utility_substr(value, begin, end) {
return value.slice(begin, end);
}
/**
* @param {string} value
* @return {number}
*/
function Utility_strlen(value) {
return value.length;
}
/**
* @param {any[]} value
* @return {number}
*/
function Utility_sizeof(value) {
return value.length;
}
/**
* @param {any} value
* @param {any[]} array
* @return {any}
*/
function Utility_append(value, array) {
return array.push(value), value;
}
/**
* @param {string[]} array
* @param {function} callback
* @return {string}
*/
function Utility_combine(array, callback) {
return array.map(callback).join("");
} // CONCATENATED MODULE: ./node_modules/@emotion/cache/node_modules/stylis/src/Tokenizer.js
var line = 1;
var column = 1;
var Tokenizer_length = 0;
var position = 0;
var character = 0;
var characters = "";
/**
* @param {string} value
* @param {object} root
* @param {object?} parent
* @param {string} type
* @param {string[]} props
* @param {object[]} children
* @param {number} length
*/
function node(
value,
root,
parent,
type,
props,
children,
length
) {
return {
value: value,
root: root,
parent: parent,
type: type,
props: props,
children: children,
line: line,
column: column,
length: length,
return: "",
};
}
/**
* @param {string} value
* @param {object} root
* @param {string} type
*/
function copy(value, root, type) {
return node(
value,
root.root,
root.parent,
type,
root.props,
root.children,
0
);
}
/**
* @return {number}
*/
function Tokenizer_char() {
return character;
}
/**
* @return {number}
*/
function prev() {
character =
position > 0
? Utility_charat(characters, --position)
: 0;
if ((column--, character === 10)) (column = 1), line--;
return character;
}
/**
* @return {number}
*/
function next() {
character =
position < Tokenizer_length
? Utility_charat(characters, position++)
: 0;
if ((column++, character === 10)) (column = 1), line++;
return character;
}
/**
* @return {number}
*/
function peek() {
return Utility_charat(characters, position);
}
/**
* @return {number}
*/
function caret() {
return position;
}
/**
* @param {number} begin
* @param {number} end
* @return {string}
*/
function slice(begin, end) {
return Utility_substr(characters, begin, end);
}
/**
* @param {number} type
* @return {number}
*/
function token(type) {
switch (type) {
// \0 \t \n \r \s whitespace token
case 0:
case 9:
case 10:
case 13:
case 32:
return 5;
// ! + , / > @ ~ isolate token
case 33:
case 43:
case 44:
case 47:
case 62:
case 64:
case 126:
// ; { } breakpoint token
case 59:
case 123:
case 125:
return 4;
// : accompanied token
case 58:
return 3;
// " ' ( [ opening delimit token
case 34:
case 39:
case 40:
case 91:
return 2;
// ) ] closing delimit token
case 41:
case 93:
return 1;
}
return 0;
}
/**
* @param {string} value
* @return {any[]}
*/
function alloc(value) {
return (
(line = column = 1),
(Tokenizer_length = Utility_strlen(
(characters = value)
)),
(position = 0),
[]
);
}
/**
* @param {any} value
* @return {any}
*/
function dealloc(value) {
return (characters = ""), value;
}
/**
* @param {number} type
* @return {string}
*/
function delimit(type) {
return trim(
slice(
position - 1,
delimiter(
type === 91
? type + 2
: type === 40
? type + 1
: type
)
)
);
}
/**
* @param {string} value
* @return {string[]}
*/
function Tokenizer_tokenize(value) {
return dealloc(tokenizer(alloc(value)));
}
/**
* @param {number} type
* @return {string}
*/
function whitespace(type) {
while ((character = peek()))
if (character < 33) next();
else break;
return token(type) > 2 || token(character) > 3 ? "" : " ";
}
/**
* @param {string[]} children
* @return {string[]}
*/
function tokenizer(children) {
while (next())
switch (token(character)) {
case 0:
append(identifier(position - 1), children);
break;
case 2:
append(delimit(character), children);
break;
default:
append(from(character), children);
}
return children;
}
/**
* @param {number} index
* @param {number} count
* @return {string}
*/
function escaping(index, count) {
while (--count && next())
// not 0-9 A-F a-f
if (
character < 48 ||
character > 102 ||
(character > 57 && character < 65) ||
(character > 70 && character < 97)
)
break;
return slice(
index,
caret() + (count < 6 && peek() == 32 && next() == 32)
);
}
/**
* @param {number} type
* @return {number}
*/
function delimiter(type) {
while (next())
switch (character) {
// ] ) " '
case type:
return position;
// " '
case 34:
case 39:
return delimiter(
type === 34 || type === 39
? type
: character
);
// (
case 40:
if (type === 41) delimiter(type);
break;
// \
case 92:
next();
break;
}
return position;
}
/**
* @param {number} type
* @param {number} index
* @return {number}
*/
function commenter(type, index) {
while (next())
// //
if (type + character === 47 + 10) break;
// /*
else if (type + character === 42 + 42 && peek() === 47)
break;
return (
"/*" +
slice(index, position - 1) +
"*" +
Utility_from(type === 47 ? type : next())
);
}
/**
* @param {number} index
* @return {string}
*/
function identifier(index) {
while (!token(peek())) next();
return slice(index, position);
} // CONCATENATED MODULE: ./node_modules/@emotion/cache/node_modules/stylis/src/Enum.js
var MS = "-ms-";
var MOZ = "-moz-";
var WEBKIT = "-webkit-";
var COMMENT = "comm";
var Enum_RULESET = "rule";
var DECLARATION = "decl";
var PAGE = "@page";
var MEDIA = "@media";
var IMPORT = "@import";
var CHARSET = "@charset";
var VIEWPORT = "@viewport";
var SUPPORTS = "@supports";
var DOCUMENT = "@document";
var NAMESPACE = "@namespace";
var KEYFRAMES = "@keyframes";
var FONT_FACE = "@font-face";
var COUNTER_STYLE = "@counter-style";
var FONT_FEATURE_VALUES = "@font-feature-values"; // CONCATENATED MODULE: ./node_modules/@emotion/cache/node_modules/stylis/src/Serializer.js
/**
* @param {object[]} children
* @param {function} callback
* @return {string}
*/
function serialize(children, callback) {
var output = "";
var length = Utility_sizeof(children);
for (var i = 0; i < length; i++)
output +=
callback(children[i], i, children, callback) || "";
return output;
}
/**
* @param {object} element
* @param {number} index
* @param {object[]} children
* @param {function} callback
* @return {string}
*/
function stringify(element, index, children, callback) {
switch (element.type) {
case IMPORT:
case DECLARATION:
return (element.return =
element.return || element.value);
case COMMENT:
return "";
case Enum_RULESET:
element.value = element.props.join(",");
}
return Utility_strlen(
(children = serialize(element.children, callback))
)
? (element.return =
element.value + "{" + children + "}")
: "";
} // CONCATENATED MODULE: ./node_modules/@emotion/cache/node_modules/stylis/src/Prefixer.js
/**
* @param {string} value
* @param {number} length
* @return {string}
*/
function prefix(value, length) {
switch (hash(value, length)) {
// color-adjust
case 5103:
return WEBKIT + "print-" + value + value;
// animation, animation-(delay|direction|duration|fill-mode|iteration-count|name|play-state|timing-function)
case 5737:
case 4201:
case 3177:
case 3433:
case 1641:
case 4457:
case 2921:
// text-decoration, filter, clip-path, backface-visibility, column, box-decoration-break
case 5572:
case 6356:
case 5844:
case 3191:
case 6645:
case 3005:
// mask, mask-image, mask-(mode|clip|size), mask-(repeat|origin), mask-position, mask-composite,
case 6391:
case 5879:
case 5623:
case 6135:
case 4599:
case 4855:
// background-clip, columns, column-(count|fill|gap|rule|rule-color|rule-style|rule-width|span|width)
case 4215:
case 6389:
case 5109:
case 5365:
case 5621:
case 3829:
return WEBKIT + value + value;
// appearance, user-select, transform, hyphens, text-size-adjust
case 5349:
case 4246:
case 4810:
case 6968:
case 2756:
return (
WEBKIT +
value +
MOZ +
value +
MS +
value +
value
);
// flex, flex-direction
case 6828:
case 4268:
return WEBKIT + value + MS + value + value;
// order
case 6165:
return (
WEBKIT + value + MS + "flex-" + value + value
);
// align-items
case 5187:
return (
WEBKIT +
value +
replace(
value,
/(\w+).+(:[^]+)/,
WEBKIT + "box-$1$2" + MS + "flex-$1$2"
) +
value
);
// align-self
case 5443:
return (
WEBKIT +
value +
MS +
"flex-item-" +
replace(value, /flex-|-self/, "") +
value
);
// align-content
case 4675:
return (
WEBKIT +
value +
MS +
"flex-line-pack" +
replace(
value,
/align-content|flex-|-self/,
""
) +
value
);
// flex-shrink
case 5548:
return (
WEBKIT +
value +
MS +
replace(value, "shrink", "negative") +
value
);
// flex-basis
case 5292:
return (
WEBKIT +
value +
MS +
replace(value, "basis", "preferred-size") +
value
);
// flex-grow
case 6060:
return (
WEBKIT +
"box-" +
replace(value, "-grow", "") +
WEBKIT +
value +
MS +
replace(value, "grow", "positive") +
value
);
// transition
case 4554:
return (
WEBKIT +
replace(
value,
/([^-])(transform)/g,
"$1" + WEBKIT + "$2"
) +
value
);
// cursor
case 6187:
return (
replace(
replace(
replace(
value,
/(zoom-|grab)/,
WEBKIT + "$1"
),
/(image-set)/,
WEBKIT + "$1"
),
value,
""
) + value
);
// background, background-image
case 5495:
case 3959:
return replace(
value,
/(image-set\([^]*)/,
WEBKIT + "$1" + "$`$1"
);
// justify-content
case 4968:
return (
replace(
replace(
value,
/(.+:)(flex-)?(.*)/,
WEBKIT +
"box-pack:$3" +
MS +
"flex-pack:$3"
),
/s.+-b[^;]+/,
"justify"
) +
WEBKIT +
value +
value
);
// (margin|padding)-inline-(start|end)
case 4095:
case 3583:
case 4068:
case 2532:
return (
replace(
value,
/(.+)-inline(.+)/,
WEBKIT + "$1$2"
) + value
);
// (min|max)?(width|height|inline-size|block-size)
case 8116:
case 7059:
case 5753:
case 5535:
case 5445:
case 5701:
case 4933:
case 4677:
case 5533:
case 5789:
case 5021:
case 4765:
// stretch, max-content, min-content, fill-available
if (Utility_strlen(value) - 1 - length > 6)
switch (Utility_charat(value, length + 1)) {
// (m)ax-content, (m)in-content
case 109:
// -
if (
Utility_charat(
value,
length + 4
) !== 45
)
break;
// (f)ill-available, (f)it-content
case 102:
return (
replace(
value,
/(.+:)(.+)-([^]+)/,
"$1" +
WEBKIT +
"$2-$3" +
"$1" +
MOZ +
(Utility_charat(
value,
length + 3
) == 108
? "$3"
: "$2-$3")
) + value
);
// (s)tretch
case 115:
return ~indexof(value, "stretch")
? prefix(
replace(
value,
"stretch",
"fill-available"
),
length
) + value
: value;
}
break;
// position: sticky
case 4949:
// (s)ticky?
if (Utility_charat(value, length + 1) !== 115)
break;
// display: (flex|inline-flex)
case 6444:
switch (
Utility_charat(
value,
Utility_strlen(value) -
3 -
(~indexof(value, "!important") && 10)
)
) {
// stic(k)y
case 107:
return (
replace(value, ":", ":" + WEBKIT) +
value
);
// (inline-)?fl(e)x
case 101:
return (
replace(
value,
/(.+:)([^;!]+)(;|!.+)?/,
"$1" +
WEBKIT +
(Utility_charat(value, 14) ===
45
? "inline-"
: "") +
"box$3" +
"$1" +
WEBKIT +
"$2$3" +
"$1" +
MS +
"$2box$3"
) + value
);
}
break;
// writing-mode
case 5936:
switch (Utility_charat(value, length + 11)) {
// vertical-l(r)
case 114:
return (
WEBKIT +
value +
MS +
replace(
value,
/[svh]\w+-[tblr]{2}/,
"tb"
) +
value
);
// vertical-r(l)
case 108:
return (
WEBKIT +
value +
MS +
replace(
value,
/[svh]\w+-[tblr]{2}/,
"tb-rl"
) +
value
);
// horizontal(-)tb
case 45:
return (
WEBKIT +
value +
MS +
replace(
value,
/[svh]\w+-[tblr]{2}/,
"lr"
) +
value
);
}
return WEBKIT + value + MS + value + value;
}
return value;
} // CONCATENATED MODULE: ./node_modules/@emotion/cache/node_modules/stylis/src/Middleware.js
/**
* @param {function[]} collection
* @return {function}
*/
function middleware(collection) {
var length = Utility_sizeof(collection);
return function (element, index, children, callback) {
var output = "";
for (var i = 0; i < length; i++)
output +=
collection[i](
element,
index,
children,
callback
) || "";
return output;
};
}
/**
* @param {function} callback
* @return {function}
*/
function rulesheet(callback) {
return function (element) {
if (!element.root)
if ((element = element.return)) callback(element);
};
}
/**
* @param {object} element
* @param {number} index
* @param {object[]} children
* @param {function} callback
*/
function prefixer(element, index, children, callback) {
if (!element.return)
switch (element.type) {
case DECLARATION:
element.return = prefix(
element.value,
element.length
);
break;
case KEYFRAMES:
return serialize(
[
copy(
replace(
element.value,
"@",
"@" + WEBKIT
),
element,
""
),
],
callback
);
case Enum_RULESET:
if (element.length)
return Utility_combine(
element.props,
function (value) {
switch (
match(
value,
/(::plac\w+|:read-\w+)/
)
) {
// :read-(only|write)
case ":read-only":
case ":read-write":
return serialize(
[
copy(
replace(
value,
/:(read-\w+)/,
":" +
MOZ +
"$1"
),
element,
""
),
],
callback
);
// :placeholder
case "::placeholder":
return serialize(
[
copy(
replace(
value,
/:(plac\w+)/,
":" +
WEBKIT +
"input-$1"
),
element,
""
),
copy(
replace(
value,
/:(plac\w+)/,
":" +
MOZ +
"$1"
),
element,
""
),
copy(
replace(
value,
/:(plac\w+)/,
MS +
"input-$1"
),
element,
""
),
],
callback
);
}
return "";
}
);
}
}
/**
* @param {object} element
* @param {number} index
* @param {object[]} children
*/
function namespace(element) {
switch (element.type) {
case RULESET:
element.props = element.props.map(function (value) {
return combine(
tokenize(value),
function (value, index, children) {
switch (charat(value, 0)) {
// \f
case 12:
return substr(
value,
1,
strlen(value)
);
// \0 ( + > ~
case 0:
case 40:
case 43:
case 62:
case 126:
return value;
// :
case 58:
if (
children[++index] ===
"global"
)
(children[index] = ""),
(children[++index] =
"\f" +
substr(
children[index],
(index = 1),
-1
));
// \s
case 32:
return index === 1 ? "" : value;
default:
switch (index) {
case 0:
element = value;
return sizeof(
children
) > 1
? ""
: value;
case (index =
sizeof(children) - 1):
case 2:
return index === 2
? value +
element +
element
: value + element;
default:
return value;
}
}
}
);
});
}
} // CONCATENATED MODULE: ./node_modules/@emotion/cache/node_modules/stylis/src/Parser.js
/**
* @param {string} value
* @return {object[]}
*/
function compile(value) {
return dealloc(
parse(
"",
null,
null,
null,
[""],
(value = alloc(value)),
0,
[0],
value
)
);
}
/**
* @param {string} value
* @param {object} root
* @param {object?} parent
* @param {string[]} rule
* @param {string[]} rules
* @param {string[]} rulesets
* @param {number[]} pseudo
* @param {number[]} points
* @param {string[]} declarations
* @return {object}
*/
function parse(
value,
root,
parent,
rule,
rules,
rulesets,
pseudo,
points,
declarations
) {
var index = 0;
var offset = 0;
var length = pseudo;
var atrule = 0;
var property = 0;
var previous = 0;
var variable = 1;
var scanning = 1;
var ampersand = 1;
var character = 0;
var type = "";
var props = rules;
var children = rulesets;
var reference = rule;
var characters = type;
while (scanning)
switch (
((previous = character), (character = next()))
) {
// " ' [ (
case 34:
case 39:
case 91:
case 40:
characters += delimit(character);
break;
// \t \n \r \s
case 9:
case 10:
case 13:
case 32:
characters += whitespace(previous);
break;
// \
case 92:
characters += escaping(caret() - 1, 7);
continue;
// /
case 47:
switch (peek()) {
case 42:
case 47:
Utility_append(
comment(
commenter(next(), caret()),
root,
parent
),
declarations
);
break;
default:
characters += "/";
}
break;
// {
case 123 * variable:
points[index++] =
Utility_strlen(characters) * ampersand;
// } ; \0
case 125 * variable:
case 59:
case 0:
switch (character) {
// \0 }
case 0:
case 125:
scanning = 0;
// ;
case 59 + offset:
if (
property > 0 &&
Utility_strlen(characters) - length
)
Utility_append(
property > 32
? declaration(
characters + ";",
rule,
parent,
length - 1
)
: declaration(
replace(
characters,
" ",
""
) + ";",
rule,
parent,
length - 2
),
declarations
);
break;
// @ ;
case 59:
characters += ";";
// { rule/at-rule
default:
Utility_append(
(reference = ruleset(
characters,
root,
parent,
index,
offset,
rules,
points,
type,
(props = []),
(children = []),
length
)),
rulesets
);
if (character === 123)
if (offset === 0)
parse(
characters,
root,
reference,
reference,
props,
rulesets,
length,
points,
children
);
else
switch (atrule) {
// d m s
case 100:
case 109:
case 115:
parse(
value,
reference,
reference,
rule &&
Utility_append(
ruleset(
value,
reference,
reference,
0,
0,
rules,
points,
type,
rules,
(props =
[]),
length
),
children
),
rules,
children,
length,
points,
rule
? props
: children
);
break;
default:
parse(
characters,
reference,
reference,
reference,
[""],
children,
length,
points,
children
);
}
}
(index = offset = property = 0),
(variable = ampersand = 1),
(type = characters = ""),
(length = pseudo);
break;
// :
case 58:
(length = 1 + Utility_strlen(characters)),
(property = previous);
default:
if (variable < 1)
if (character == 123) --variable;
else if (
character == 125 &&
variable++ == 0 &&
prev() == 125
)
continue;
switch (
((characters += Utility_from(character)),
character * variable)
) {
// &
case 38:
ampersand =
offset > 0
? 1
: ((characters += "\f"), -1);
break;
// ,
case 44:
(points[index++] =
(Utility_strlen(characters) - 1) *
ampersand),
(ampersand = 1);
break;
// @
case 64:
// -
if (peek() === 45)
characters += delimit(next());
(atrule = peek()),
(offset = Utility_strlen(
(type = characters +=
identifier(caret()))
)),
character++;
break;
// -
case 45:
if (
previous === 45 &&
Utility_strlen(characters) == 2
)
variable = 0;
}
}
return rulesets;
}
/**
* @param {string} value
* @param {object} root
* @param {object?} parent
* @param {number} index
* @param {number} offset
* @param {string[]} rules
* @param {number[]} points
* @param {string} type
* @param {string[]} props
* @param {string[]} children
* @param {number} length
* @return {object}
*/
function ruleset(
value,
root,
parent,
index,
offset,
rules,
points,
type,
props,
children,
length
) {
var post = offset - 1;
var rule = offset === 0 ? rules : [""];
var size = Utility_sizeof(rule);
for (var i = 0, j = 0, k = 0; i < index; ++i)
for (
var x = 0,
y = Utility_substr(
value,
post + 1,
(post = abs((j = points[i])))
),
z = value;
x < size;
++x
)
if (
(z = trim(
j > 0
? rule[x] + " " + y
: replace(y, /&\f/g, rule[x])
))
)
props[k++] = z;
return node(
value,
root,
parent,
offset === 0 ? Enum_RULESET : type,
props,
children,
length
);
}
/**
* @param {number} value
* @param {object} root
* @param {object?} parent
* @return {object}
*/
function comment(value, root, parent) {
return node(
value,
root,
parent,
COMMENT,
Utility_from(Tokenizer_char()),
Utility_substr(value, 2, -2),
0
);
}
/**
* @param {string} value
* @param {object} root
* @param {object?} parent
* @param {number} length
* @return {object}
*/
function declaration(value, root, parent, length) {
return node(
value,
root,
parent,
DECLARATION,
Utility_substr(value, 0, length),
Utility_substr(value, length + 1, -1),
length
);
} // CONCATENATED MODULE: ./node_modules/@emotion/cache/dist/emotion-cache.browser.esm.js
var last = function last(arr) {
return arr.length ? arr[arr.length - 1] : null;
}; // based on https://github.com/thysultan/stylis.js/blob/e6843c373ebcbbfade25ebcc23f540ed8508da0a/src/Tokenizer.js#L239-L244
var identifierWithPointTracking =
function identifierWithPointTracking(begin, points, index) {
var previous = 0;
var character = 0;
while (true) {
previous = character;
character = peek(); // &\f
if (previous === 38 && character === 12) {
points[index] = 1;
}
if (token(character)) {
break;
}
next();
}
return slice(begin, position);
};
var toRules = function toRules(parsed, points) {
// pretend we've started with a comma
var index = -1;
var character = 44;
do {
switch (token(character)) {
case 0:
// &\f
if (character === 38 && peek() === 12) {
// this is not 100% correct, we don't account for literal sequences here - like for example quoted strings
// stylis inserts \f after & to know when & where it should replace this sequence with the context selector
// and when it should just concatenate the outer and inner selectors
// it's very unlikely for this sequence to actually appear in a different context, so we just leverage this fact here
points[index] = 1;
}
parsed[index] += identifierWithPointTracking(
position - 1,
points,
index
);
break;
case 2:
parsed[index] += delimit(character);
break;
case 4:
// comma
if (character === 44) {
// colon
parsed[++index] =
peek() === 58 ? "&\f" : "";
points[index] = parsed[index].length;
break;
}
// fallthrough
default:
parsed[index] += Utility_from(character);
}
} while ((character = next()));
return parsed;
};
var getRules = function getRules(value, points) {
return dealloc(toRules(alloc(value), points));
}; // WeakSet would be more appropriate, but only WeakMap is supported in IE11
var fixedElements = /* #__PURE__ */ new WeakMap();
var compat = function compat(element) {
if (
element.type !== "rule" ||
!element.parent || // .length indicates if this rule contains pseudo or not
!element.length
) {
return;
}
var value = element.value,
parent = element.parent;
var isImplicitRule =
element.column === parent.column &&
element.line === parent.line;
while (parent.type !== "rule") {
parent = parent.parent;
if (!parent) return;
} // short-circuit for the simplest case
if (
element.props.length === 1 &&
value.charCodeAt(0) !== 58 &&
/* colon */
!fixedElements.get(parent)
) {
return;
} // if this is an implicitly inserted rule (the one eagerly inserted at the each new nested level)
// then the props has already been manipulated beforehand as they that array is shared between it and its "rule parent"
if (isImplicitRule) {
return;
}
fixedElements.set(element, true);
var points = [];
var rules = getRules(value, points);
var parentRules = parent.props;
for (var i = 0, k = 0; i < rules.length; i++) {
for (var j = 0; j < parentRules.length; j++, k++) {
element.props[k] = points[i]
? rules[i].replace(/&\f/g, parentRules[j])
: parentRules[j] + " " + rules[i];
}
}
};
var removeLabel = function removeLabel(element) {
if (element.type === "decl") {
var value = element.value;
if (
// charcode for l
value.charCodeAt(0) === 108 && // charcode for b
value.charCodeAt(2) === 98
) {
// this ignores label
element["return"] = "";
element.value = "";
}
}
};
var ignoreFlag =
"emotion-disable-server-rendering-unsafe-selector-warning-please-do-not-use-this-the-warning-exists-for-a-reason";
var isIgnoringComment = function isIgnoringComment(element) {
return (
!!element &&
element.type === "comm" &&
element.children.indexOf(ignoreFlag) > -1
);
};
var createUnsafeSelectorsAlarm =
function createUnsafeSelectorsAlarm(cache) {
return function (element, index, children) {
if (element.type !== "rule") return;
var unsafePseudoClasses = element.value.match(
/(:first|:nth|:nth-last)-child/g
);
if (unsafePseudoClasses && cache.compat !== true) {
var prevElement =
index > 0 ? children[index - 1] : null;
if (
prevElement &&
isIgnoringComment(
last(prevElement.children)
)
) {
return;
}
unsafePseudoClasses.forEach(function (
unsafePseudoClass
) {
console.error(
'The pseudo class "' +
unsafePseudoClass +
'" is potentially unsafe when doing server-side rendering. Try changing it to "' +
unsafePseudoClass.split(
"-child"
)[0] +
'-of-type".'
);
});
}
};
};
var isImportRule = function isImportRule(element) {
return (
element.type.charCodeAt(1) === 105 &&
element.type.charCodeAt(0) === 64
);
};
var isPrependedWithRegularRules =
function isPrependedWithRegularRules(index, children) {
for (var i = index - 1; i >= 0; i--) {
if (!isImportRule(children[i])) {
return true;
}
}
return false;
}; // use this to remove incorrect elements from further processing
// so they don't get handed to the `sheet` (or anything else)
// as that could potentially lead to additional logs which in turn could be overhelming to the user
var nullifyElement = function nullifyElement(element) {
element.type = "";
element.value = "";
element["return"] = "";
element.children = "";
element.props = "";
};
var incorrectImportAlarm = function incorrectImportAlarm(
element,
index,
children
) {
if (!isImportRule(element)) {
return;
}
if (element.parent) {
console.error(
"`@import` rules can't be nested inside other rules. Please move it to the top level and put it before regular rules. Keep in mind that they can only be used within global styles."
);
nullifyElement(element);
} else if (isPrependedWithRegularRules(index, children)) {
console.error(
"`@import` rules can't be after other rules. Please put your `@import` rules before your other rules."
);
nullifyElement(element);
}
};
var defaultStylisPlugins = [prefixer];
var createCache = function createCache(options) {
var key = options.key;
if (false) {
}
if (key === "css") {
var ssrStyles = document.querySelectorAll(
"style[data-emotion]:not([data-s])"
); // get SSRed styles out of the way of React's hydration
// document.head is a safe place to move them to(though note document.head is not necessarily the last place they will be)
// note this very very intentionally targets all style elements regardless of the key to ensure
// that creating a cache works inside of render of a React component
Array.prototype.forEach.call(
ssrStyles,
function (node) {
// we want to only move elements which have a space in the data-emotion attribute value
// because that indicates that it is an Emotion 11 server-side rendered style elements
// while we will already ignore Emotion 11 client-side inserted styles because of the :not([data-s]) part in the selector
// Emotion 10 client-side inserted styles did not have data-s (but importantly did not have a space in their data-emotion attributes)
// so checking for the space ensures that loading Emotion 11 after Emotion 10 has inserted some styles
// will not result in the Emotion 10 styles being destroyed
var dataEmotionAttribute =
node.getAttribute("data-emotion");
if (dataEmotionAttribute.indexOf(" ") === -1) {
return;
}
document.head.appendChild(node);
node.setAttribute("data-s", "");
}
);
}
var stylisPlugins =
options.stylisPlugins || defaultStylisPlugins;
if (false) {
}
var inserted = {}; // $FlowFixMe
var container;
var nodesToHydrate = [];
{
container = options.container || document.head;
Array.prototype.forEach.call(
// this means we will ignore elements which don't have a space in them which
// means that the style elements we're looking at are only Emotion 11 server-rendered style elements
document.querySelectorAll(
'style[data-emotion^="' + key + ' "]'
),
function (node) {
var attrib = node
.getAttribute("data-emotion")
.split(" "); // $FlowFixMe
for (var i = 1; i < attrib.length; i++) {
inserted[attrib[i]] = true;
}
nodesToHydrate.push(node);
}
);
}
var _insert;
var omnipresentPlugins = [compat, removeLabel];
if (false) {
}
{
var currentSheet;
var finalizingPlugins = [
stringify,
false
? 0
: rulesheet(function (rule) {
currentSheet.insert(rule);
}),
];
var serializer = middleware(
omnipresentPlugins.concat(
stylisPlugins,
finalizingPlugins
)
);
var stylis = function stylis(styles) {
return serialize(compile(styles), serializer);
};
_insert = function insert(
selector,
serialized,
sheet,
shouldCache
) {
currentSheet = sheet;
if (false) {
}
stylis(
selector
? selector + "{" + serialized.styles + "}"
: serialized.styles
);
if (shouldCache) {
cache.inserted[serialized.name] = true;
}
};
}
var cache = {
key: key,
sheet: new StyleSheet({
key: key,
container: container,
nonce: options.nonce,
speedy: options.speedy,
prepend: options.prepend,
}),
nonce: options.nonce,
inserted: inserted,
registered: {},
insert: _insert,
};
cache.sheet.hydrate(nodesToHydrate);
return cache;
};
/* harmony default export */
var emotion_cache_browser_esm = createCache; // CONCATENATED MODULE: ./node_modules/@emotion/hash/dist/hash.browser.esm.js
/* eslint-disable */
// Inspired by https://github.com/garycourt/murmurhash-js
// Ported from https://github.com/aappleby/smhasher/blob/61a0530f28277f2e850bfc39600ce61d02b518de/src/MurmurHash2.cpp#L37-L86
function murmur2(str) {
// 'm' and 'r' are mixing constants generated offline.
// They're not really 'magic', they just happen to work well.
// const m = 0x5bd1e995;
// const r = 24;
// Initialize the hash
var h = 0; // Mix 4 bytes at a time into the hash
var k,
i = 0,
len = str.length;
for (; len >= 4; ++i, len -= 4) {
k =
(str.charCodeAt(i) & 0xff) |
((str.charCodeAt(++i) & 0xff) << 8) |
((str.charCodeAt(++i) & 0xff) << 16) |
((str.charCodeAt(++i) & 0xff) << 24);
k =
/* Math.imul(k, m): */
(k & 0xffff) * 0x5bd1e995 +
(((k >>> 16) * 0xe995) << 16);
k ^=
/* k >>> r: */
k >>> 24;
h =
/* Math.imul(k, m): */
((k & 0xffff) * 0x5bd1e995 +
(((k >>> 16) * 0xe995) << 16)) ^
/* Math.imul(h, m): */
((h & 0xffff) * 0x5bd1e995 +
(((h >>> 16) * 0xe995) << 16));
} // Handle the last few bytes of the input array
switch (len) {
case 3:
h ^= (str.charCodeAt(i + 2) & 0xff) << 16;
case 2:
h ^= (str.charCodeAt(i + 1) & 0xff) << 8;
case 1:
h ^= str.charCodeAt(i) & 0xff;
h =
/* Math.imul(h, m): */
(h & 0xffff) * 0x5bd1e995 +
(((h >>> 16) * 0xe995) << 16);
} // Do a few final mixes of the hash to ensure the last few
// bytes are well-incorporated.
h ^= h >>> 13;
h =
/* Math.imul(h, m): */
(h & 0xffff) * 0x5bd1e995 +
(((h >>> 16) * 0xe995) << 16);
return ((h ^ (h >>> 15)) >>> 0).toString(36);
}
/* harmony default export */
var hash_browser_esm = murmur2; // CONCATENATED MODULE: ./node_modules/@emotion/unitless/dist/unitless.browser.esm.js
var unitlessKeys = {
animationIterationCount: 1,
borderImageOutset: 1,
borderImageSlice: 1,
borderImageWidth: 1,
boxFlex: 1,
boxFlexGroup: 1,
boxOrdinalGroup: 1,
columnCount: 1,
columns: 1,
flex: 1,
flexGrow: 1,
flexPositive: 1,
flexShrink: 1,
flexNegative: 1,
flexOrder: 1,
gridRow: 1,
gridRowEnd: 1,
gridRowSpan: 1,
gridRowStart: 1,
gridColumn: 1,
gridColumnEnd: 1,
gridColumnSpan: 1,
gridColumnStart: 1,
msGridRow: 1,
msGridRowSpan: 1,
msGridColumn: 1,
msGridColumnSpan: 1,
fontWeight: 1,
lineHeight: 1,
opacity: 1,
order: 1,
orphans: 1,
tabSize: 1,
widows: 1,
zIndex: 1,
zoom: 1,
WebkitLineClamp: 1,
// SVG-related properties
fillOpacity: 1,
floodOpacity: 1,
stopOpacity: 1,
strokeDasharray: 1,
strokeDashoffset: 1,
strokeMiterlimit: 1,
strokeOpacity: 1,
strokeWidth: 1,
};
/* harmony default export */
var unitless_browser_esm = unitlessKeys; // CONCATENATED MODULE: ./node_modules/@emotion/memoize/dist/emotion-memoize.browser.esm.js
function memoize(fn) {
var cache = Object.create(null);
return function (arg) {
if (cache[arg] === undefined) cache[arg] = fn(arg);
return cache[arg];
};
}
/* harmony default export */
var emotion_memoize_browser_esm = memoize; // CONCATENATED MODULE: ./node_modules/@emotion/serialize/dist/emotion-serialize.browser.esm.js
var ILLEGAL_ESCAPE_SEQUENCE_ERROR =
"You have illegal escape sequence in your template literal, most likely inside content's property value.\nBecause you write your CSS inside a JavaScript string you actually have to do double escaping, so for example \"content: '\\00d7';\" should become \"content: '\\\\00d7';\".\nYou can read more about this here:\nhttps://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals#ES2018_revision_of_illegal_escape_sequences";
var UNDEFINED_AS_OBJECT_KEY_ERROR =
"You have passed in falsy value as style object's key (can happen when in example you pass unexported component as computed key).";
var hyphenateRegex = /[A-Z]|^ms/g;
var animationRegex = /_EMO_([^_]+?)_([^]*?)_EMO_/g;
var isCustomProperty = function isCustomProperty(property) {
return property.charCodeAt(1) === 45;
};
var isProcessableValue = function isProcessableValue(value) {
return value != null && typeof value !== "boolean";
};
var processStyleName =
/* #__PURE__ */ emotion_memoize_browser_esm(function (
styleName
) {
return isCustomProperty(styleName)
? styleName
: styleName
.replace(hyphenateRegex, "-$&")
.toLowerCase();
});
var processStyleValue = function processStyleValue(key, value) {
switch (key) {
case "animation":
case "animationName": {
if (typeof value === "string") {
return value.replace(
animationRegex,
function (match, p1, p2) {
cursor = {
name: p1,
styles: p2,
next: cursor,
};
return p1;
}
);
}
}
}
if (
unitless_browser_esm[key] !== 1 &&
!isCustomProperty(key) &&
typeof value === "number" &&
value !== 0
) {
return value + "px";
}
return value;
};
if (false) {
var hyphenatedCache,
hyphenPattern,
msPattern,
oldProcessStyleValue,
contentValues,
contentValuePattern;
}
function handleInterpolation(
mergedProps,
registered,
interpolation
) {
if (interpolation == null) {
return "";
}
if (interpolation.__emotion_styles !== undefined) {
if (false) {
}
return interpolation;
}
switch (typeof interpolation) {
case "boolean": {
return "";
}
case "object": {
if (interpolation.anim === 1) {
cursor = {
name: interpolation.name,
styles: interpolation.styles,
next: cursor,
};
return interpolation.name;
}
if (interpolation.styles !== undefined) {
var next = interpolation.next;
if (next !== undefined) {
// not the most efficient thing ever but this is a pretty rare case
// and there will be very few iterations of this generally
while (next !== undefined) {
cursor = {
name: next.name,
styles: next.styles,
next: cursor,
};
next = next.next;
}
}
var styles = interpolation.styles + ";";
if (false) {
}
return styles;
}
return createStringFromObject(
mergedProps,
registered,
interpolation
);
}
case "function": {
if (mergedProps !== undefined) {
var previousCursor = cursor;
var result = interpolation(mergedProps);
cursor = previousCursor;
return handleInterpolation(
mergedProps,
registered,
result
);
} else if (false) {
}
break;
}
case "string":
if (false) {
var replaced, matched;
}
break;
} // finalize string values (regular strings and functions interpolated into css calls)
if (registered == null) {
return interpolation;
}
var cached = registered[interpolation];
return cached !== undefined ? cached : interpolation;
}
function createStringFromObject(mergedProps, registered, obj) {
var string = "";
if (Array.isArray(obj)) {
for (var i = 0; i < obj.length; i++) {
string +=
handleInterpolation(
mergedProps,
registered,
obj[i]
) + ";";
}
} else {
for (var _key in obj) {
var value = obj[_key];
if (typeof value !== "object") {
if (
registered != null &&
registered[value] !== undefined
) {
string +=
_key + "{" + registered[value] + "}";
} else if (isProcessableValue(value)) {
string +=
processStyleName(_key) +
":" +
processStyleValue(_key, value) +
";";
}
} else {
if (
_key === "NO_COMPONENT_SELECTOR" &&
"production" !== "production"
) {
}
if (
Array.isArray(value) &&
typeof value[0] === "string" &&
(registered == null ||
registered[value[0]] === undefined)
) {
for (var _i = 0; _i < value.length; _i++) {
if (isProcessableValue(value[_i])) {
string +=
processStyleName(_key) +
":" +
processStyleValue(
_key,
value[_i]
) +
";";
}
}
} else {
var interpolated = handleInterpolation(
mergedProps,
registered,
value
);
switch (_key) {
case "animation":
case "animationName": {
string +=
processStyleName(_key) +
":" +
interpolated +
";";
break;
}
default: {
if (false) {
}
string +=
_key + "{" + interpolated + "}";
}
}
}
}
}
}
return string;
}
var labelPattern = /label:\s*([^\s;\n{]+)\s*(;|$)/g;
var sourceMapPattern;
if (false) {
} // this is the cursor for keyframes
// keyframes are stored on the SerializedStyles object as a linked list
var cursor;
var emotion_serialize_browser_esm_serializeStyles =
function serializeStyles(args, registered, mergedProps) {
if (
args.length === 1 &&
typeof args[0] === "object" &&
args[0] !== null &&
args[0].styles !== undefined
) {
return args[0];
}
var stringMode = true;
var styles = "";
cursor = undefined;
var strings = args[0];
if (strings == null || strings.raw === undefined) {
stringMode = false;
styles += handleInterpolation(
mergedProps,
registered,
strings
);
} else {
if (false) {
}
styles += strings[0];
} // we start at 1 since we've already handled the first arg
for (var i = 1; i < args.length; i++) {
styles += handleInterpolation(
mergedProps,
registered,
args[i]
);
if (stringMode) {
if (false) {
}
styles += strings[i];
}
}
var sourceMap;
if (false) {
} // using a global regex with .exec is stateful so lastIndex has to be reset each time
labelPattern.lastIndex = 0;
var identifierName = "";
var match; // https://esbench.com/bench/5b809c2cf2949800a0f61fb5
while ((match = labelPattern.exec(styles)) !== null) {
identifierName +=
"-" + // $FlowFixMe we know it's not null
match[1];
}
var name = hash_browser_esm(styles) + identifierName;
if (false) {
}
return {
name: name,
styles: styles,
next: cursor,
};
}; // CONCATENATED MODULE: ./node_modules/@emotion/react/dist/emotion-element-99289b21.browser.esm.js
var emotion_element_99289b21_browser_esm_hasOwnProperty =
Object.prototype.hasOwnProperty;
var EmotionCacheContext = /* #__PURE__ */ (0,
react.createContext)(
// we're doing this to avoid preconstruct's dead code elimination in this one case
// because this module is primarily intended for the browser and node
// but it's also required in react native and similar environments sometimes
// and we could have a special build just for that
// but this is much easier and the native packages
// might use a different theme context in the future anyway
typeof HTMLElement !== "undefined"
? /* #__PURE__ */ emotion_cache_browser_esm({
key: "css",
})
: null
);
if (false) {
}
var CacheProvider = EmotionCacheContext.Provider;
var __unsafe_useEmotionCache = function useEmotionCache() {
return useContext(EmotionCacheContext);
};
var emotion_element_99289b21_browser_esm_withEmotionCache =
function withEmotionCache(func) {
// $FlowFixMe
return /*#__PURE__*/ (0, react.forwardRef)(function (
props,
ref
) {
// the cache will never be null in the browser
var cache = (0, react.useContext)(
EmotionCacheContext
);
return func(props, cache, ref);
});
};
var emotion_element_99289b21_browser_esm_ThemeContext =
/* #__PURE__ */ (0, react.createContext)({});
if (false) {
}
var useTheme = function useTheme() {
return useContext(
emotion_element_99289b21_browser_esm_ThemeContext
);
};
var getTheme = function getTheme(outerTheme, theme) {
if (typeof theme === "function") {
var mergedTheme = theme(outerTheme);
if (false) {
}
return mergedTheme;
}
if (false) {
}
return _extends({}, outerTheme, theme);
};
var createCacheWithTheme =
/* #__PURE__ */ /* unused pure expression or super */ null &&
weakMemoize(function (outerTheme) {
return weakMemoize(function (theme) {
return getTheme(outerTheme, theme);
});
});
var ThemeProvider = function ThemeProvider(props) {
var theme = useContext(
emotion_element_99289b21_browser_esm_ThemeContext
);
if (props.theme !== theme) {
theme = createCacheWithTheme(theme)(props.theme);
}
return /*#__PURE__*/ createElement(
emotion_element_99289b21_browser_esm_ThemeContext.Provider,
{
value: theme,
},
props.children
);
};
function withTheme(Component) {
var componentName =
Component.displayName || Component.name || "Component";
var render = function render(props, ref) {
var theme = useContext(
emotion_element_99289b21_browser_esm_ThemeContext
);
return /*#__PURE__*/ createElement(
Component,
_extends(
{
theme: theme,
ref: ref,
},
props
)
);
}; // $FlowFixMe
var WithTheme = /*#__PURE__*/ forwardRef(render);
WithTheme.displayName = "WithTheme(" + componentName + ")";
return hoistNonReactStatics(WithTheme, Component);
}
// thus we only need to replace what is a valid character for JS, but not for CSS
var sanitizeIdentifier = function sanitizeIdentifier(
identifier
) {
return identifier.replace(/\$/g, "-");
};
var typePropName = "__EMOTION_TYPE_PLEASE_DO_NOT_USE__";
var labelPropName = "__EMOTION_LABEL_PLEASE_DO_NOT_USE__";
var emotion_element_99289b21_browser_esm_createEmotionProps =
function createEmotionProps(type, props) {
if (false) {
}
var newProps = {};
for (var key in props) {
if (
emotion_element_99289b21_browser_esm_hasOwnProperty.call(
props,
key
)
) {
newProps[key] = props[key];
}
}
newProps[typePropName] = type;
if (false) {
var match, error;
}
return newProps;
};
var emotion_element_99289b21_browser_esm_Emotion =
/* #__PURE__ */ /* unused pure expression or super */ null &&
emotion_element_99289b21_browser_esm_withEmotionCache(
function (props, cache, ref) {
var cssProp = props.css; // so that using `css` from `emotion` and passing the result to the css prop works
// not passing the registered cache to serializeStyles because it would
// make certain babel optimisations not possible
if (
typeof cssProp === "string" &&
cache.registered[cssProp] !== undefined
) {
cssProp = cache.registered[cssProp];
}
var type = props[typePropName];
var registeredStyles = [cssProp];
var className = "";
if (typeof props.className === "string") {
className = getRegisteredStyles(
cache.registered,
registeredStyles,
props.className
);
} else if (props.className != null) {
className = props.className + " ";
}
var serialized = serializeStyles(
registeredStyles,
undefined,
useContext(
emotion_element_99289b21_browser_esm_ThemeContext
)
);
if (false) {
var labelFromStack;
}
var rules = insertStyles(
cache,
serialized,
typeof type === "string"
);
className += cache.key + "-" + serialized.name;
var newProps = {};
for (var key in props) {
if (
emotion_element_99289b21_browser_esm_hasOwnProperty.call(
props,
key
) &&
key !== "css" &&
key !== typePropName &&
(true || 0)
) {
newProps[key] = props[key];
}
}
newProps.ref = ref;
newProps.className = className;
var ele = /*#__PURE__*/ createElement(
type,
newProps
);
return ele;
}
);
if (false) {
}
// EXTERNAL MODULE: ./node_modules/hoist-non-react-statics/dist/hoist-non-react-statics.cjs.js
var hoist_non_react_statics_cjs = __webpack_require__(8679); // CONCATENATED MODULE: ./node_modules/@emotion/utils/dist/emotion-utils.browser.esm.js
var isBrowser = "object" !== "undefined";
function emotion_utils_browser_esm_getRegisteredStyles(
registered,
registeredStyles,
classNames
) {
var rawClassName = "";
classNames.split(" ").forEach(function (className) {
if (registered[className] !== undefined) {
registeredStyles.push(registered[className] + ";");
} else {
rawClassName += className + " ";
}
});
return rawClassName;
}
var emotion_utils_browser_esm_insertStyles =
function insertStyles(cache, serialized, isStringTag) {
var className = cache.key + "-" + serialized.name;
if (
// we only need to add the styles to the registered cache if the
// class name could be used further down
// the tree but if it's a string tag, we know it won't
// so we don't have to add it to registered cache.
// this improves memory usage since we can avoid storing the whole style string
(isStringTag === false || // we need to always store it if we're in compat mode and
// in node since emotion-server relies on whether a style is in
// the registered cache to know whether a style is global or not
// also, note that this check will be dead code eliminated in the browser
isBrowser === false) &&
cache.registered[className] === undefined
) {
cache.registered[className] = serialized.styles;
}
if (cache.inserted[serialized.name] === undefined) {
var current = serialized;
do {
var maybeStyles = cache.insert(
serialized === current
? "." + className
: "",
current,
cache.sheet,
true
);
current = current.next;
} while (current !== undefined);
}
}; // CONCATENATED MODULE: ./node_modules/@emotion/react/dist/emotion-react.browser.esm.js
var pkg = {
name: "@emotion/react",
version: "11.5.0",
main: "dist/emotion-react.cjs.js",
module: "dist/emotion-react.esm.js",
browser: {
"./dist/emotion-react.cjs.js":
"./dist/emotion-react.browser.cjs.js",
"./dist/emotion-react.esm.js":
"./dist/emotion-react.browser.esm.js",
},
types: "types/index.d.ts",
files: [
"src",
"dist",
"jsx-runtime",
"jsx-dev-runtime",
"isolated-hoist-non-react-statics-do-not-use-this-in-your-code",
"types/*.d.ts",
"macro.js",
"macro.d.ts",
"macro.js.flow",
],
sideEffects: false,
author: "mitchellhamilton <mitchell@mitchellhamilton.me>",
license: "MIT",
scripts: {
"test:typescript": "dtslint types",
},
dependencies: {
"@babel/runtime": "^7.13.10",
"@emotion/cache": "^11.5.0",
"@emotion/serialize": "^1.0.2",
"@emotion/sheet": "^1.0.3",
"@emotion/utils": "^1.0.0",
"@emotion/weak-memoize": "^0.2.5",
"hoist-non-react-statics": "^3.3.1",
},
peerDependencies: {
"@babel/core": "^7.0.0",
react: ">=16.8.0",
},
peerDependenciesMeta: {
"@babel/core": {
optional: true,
},
"@types/react": {
optional: true,
},
},
devDependencies: {
"@babel/core": "^7.13.10",
"@emotion/css": "11.5.0",
"@emotion/css-prettifier": "1.0.0",
"@emotion/server": "11.4.0",
"@emotion/styled": "11.3.0",
"@types/react": "^16.9.11",
dtslint: "^0.3.0",
"html-tag-names": "^1.1.2",
react: "16.14.0",
"svg-tag-names": "^1.1.1",
},
repository:
"https://github.com/emotion-js/emotion/tree/main/packages/react",
publishConfig: {
access: "public",
},
"umd:main": "dist/emotion-react.umd.min.js",
preconstruct: {
entrypoints: [
"./index.js",
"./jsx-runtime.js",
"./jsx-dev-runtime.js",
"./isolated-hoist-non-react-statics-do-not-use-this-in-your-code.js",
],
umdName: "emotionReact",
},
};
var jsx = function jsx(type, props) {
var args = arguments;
if (props == null || !hasOwnProperty.call(props, "css")) {
// $FlowFixMe
return createElement.apply(undefined, args);
}
var argsLength = args.length;
var createElementArgArray = new Array(argsLength);
createElementArgArray[0] = Emotion;
createElementArgArray[1] = createEmotionProps(type, props);
for (var i = 2; i < argsLength; i++) {
createElementArgArray[i] = args[i];
} // $FlowFixMe
return createElement.apply(null, createElementArgArray);
};
var warnedAboutCssPropForGlobal = false; // maintain place over rerenders.
// initial render from browser, insertBefore context.sheet.tags[0] or if a style hasn't been inserted there yet, appendChild
// initial client-side render from SSR, use place of hydrating tag
var Global =
/* #__PURE__ */ emotion_element_99289b21_browser_esm_withEmotionCache(
function (props, cache) {
if (false) {
}
var styles = props.styles;
var serialized =
emotion_serialize_browser_esm_serializeStyles(
[styles],
undefined,
(0, react.useContext)(
emotion_element_99289b21_browser_esm_ThemeContext
)
);
// but it is based on a constant that will never change at runtime
// it's effectively like having two implementations and switching them out
// so it's not actually breaking anything
var sheetRef = (0, react.useRef)();
(0, react.useLayoutEffect)(
function () {
var key = cache.key + "-global";
var sheet = new StyleSheet({
key: key,
nonce: cache.sheet.nonce,
container: cache.sheet.container,
speedy: cache.sheet.isSpeedy,
});
var rehydrating = false; // $FlowFixMe
var node = document.querySelector(
'style[data-emotion="' +
key +
" " +
serialized.name +
'"]'
);
if (cache.sheet.tags.length) {
sheet.before = cache.sheet.tags[0];
}
if (node !== null) {
rehydrating = true; // clear the hash so this node won't be recognizable as rehydratable by other <Global/>s
node.setAttribute("data-emotion", key);
sheet.hydrate([node]);
}
sheetRef.current = [sheet, rehydrating];
return function () {
sheet.flush();
};
},
[cache]
);
(0, react.useLayoutEffect)(
function () {
var sheetRefCurrent = sheetRef.current;
var sheet = sheetRefCurrent[0],
rehydrating = sheetRefCurrent[1];
if (rehydrating) {
sheetRefCurrent[1] = false;
return;
}
if (serialized.next !== undefined) {
// insert keyframes
emotion_utils_browser_esm_insertStyles(
cache,
serialized.next,
true
);
}
if (sheet.tags.length) {
// if this doesn't exist then it will be null so the style element will be appended
var element =
sheet.tags[sheet.tags.length - 1]
.nextElementSibling;
sheet.before = element;
sheet.flush();
}
cache.insert("", serialized, sheet, false);
},
[cache, serialized.name]
);
return null;
}
);
if (false) {
}
function css() {
for (
var _len = arguments.length,
args = new Array(_len),
_key = 0;
_key < _len;
_key++
) {
args[_key] = arguments[_key];
}
return serializeStyles(args);
}
var keyframes = function keyframes() {
var insertable = css.apply(void 0, arguments);
var name = "animation-" + insertable.name; // $FlowFixMe
return {
name: name,
styles:
"@keyframes " +
name +
"{" +
insertable.styles +
"}",
anim: 1,
toString: function toString() {
return (
"_EMO_" +
this.name +
"_" +
this.styles +
"_EMO_"
);
},
};
};
var classnames = function classnames(args) {
var len = args.length;
var i = 0;
var cls = "";
for (; i < len; i++) {
var arg = args[i];
if (arg == null) continue;
var toAdd = void 0;
switch (typeof arg) {
case "boolean":
break;
case "object": {
if (Array.isArray(arg)) {
toAdd = classnames(arg);
} else {
if (false) {
}
toAdd = "";
for (var k in arg) {
if (arg[k] && k) {
toAdd && (toAdd += " ");
toAdd += k;
}
}
}
break;
}
default: {
toAdd = arg;
}
}
if (toAdd) {
cls && (cls += " ");
cls += toAdd;
}
}
return cls;
};
function merge(registered, css, className) {
var registeredStyles = [];
var rawClassName = getRegisteredStyles(
registered,
registeredStyles,
className
);
if (registeredStyles.length < 2) {
return className;
}
return rawClassName + css(registeredStyles);
}
var ClassNames =
/* #__PURE__ */ /* unused pure expression or super */ null &&
withEmotionCache(function (props, cache) {
var hasRendered = false;
var css = function css() {
if (hasRendered && "production" !== "production") {
}
for (
var _len = arguments.length,
args = new Array(_len),
_key = 0;
_key < _len;
_key++
) {
args[_key] = arguments[_key];
}
var serialized = serializeStyles(
args,
cache.registered
);
{
insertStyles(cache, serialized, false);
}
return cache.key + "-" + serialized.name;
};
var cx = function cx() {
if (hasRendered && "production" !== "production") {
}
for (
var _len2 = arguments.length,
args = new Array(_len2),
_key2 = 0;
_key2 < _len2;
_key2++
) {
args[_key2] = arguments[_key2];
}
return merge(
cache.registered,
css,
classnames(args)
);
};
var content = {
css: css,
cx: cx,
theme: useContext(ThemeContext),
};
var ele = props.children(content);
hasRendered = true;
return ele;
});
if (false) {
}
if (false) {
var globalKey,
globalContext,
isJest,
emotion_react_browser_esm_isBrowser;
}
/***/
},
/***/
8679:
/***/
function (module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var reactIs = __webpack_require__(9864);
/**
* Copyright 2015, Yahoo! Inc.
* Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms.
*/
var REACT_STATICS = {
childContextTypes: true,
contextType: true,
contextTypes: true,
defaultProps: true,
displayName: true,
getDefaultProps: true,
getDerivedStateFromError: true,
getDerivedStateFromProps: true,
mixins: true,
propTypes: true,
type: true,
};
var KNOWN_STATICS = {
name: true,
length: true,
prototype: true,
caller: true,
callee: true,
arguments: true,
arity: true,
};
var FORWARD_REF_STATICS = {
$$typeof: true,
render: true,
defaultProps: true,
displayName: true,
propTypes: true,
};
var MEMO_STATICS = {
$$typeof: true,
compare: true,
defaultProps: true,
displayName: true,
propTypes: true,
type: true,
};
var TYPE_STATICS = {};
TYPE_STATICS[reactIs.ForwardRef] = FORWARD_REF_STATICS;
TYPE_STATICS[reactIs.Memo] = MEMO_STATICS;
function getStatics(component) {
// React v16.11 and below
if (reactIs.isMemo(component)) {
return MEMO_STATICS;
} // React v16.12 and above
return TYPE_STATICS[component["$$typeof"]] || REACT_STATICS;
}
var defineProperty = Object.defineProperty;
var getOwnPropertyNames = Object.getOwnPropertyNames;
var getOwnPropertySymbols = Object.getOwnPropertySymbols;
var getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;
var getPrototypeOf = Object.getPrototypeOf;
var objectPrototype = Object.prototype;
function hoistNonReactStatics(
targetComponent,
sourceComponent,
blacklist
) {
if (typeof sourceComponent !== "string") {
// don't hoist over string (html) components
if (objectPrototype) {
var inheritedComponent =
getPrototypeOf(sourceComponent);
if (
inheritedComponent &&
inheritedComponent !== objectPrototype
) {
hoistNonReactStatics(
targetComponent,
inheritedComponent,
blacklist
);
}
}
var keys = getOwnPropertyNames(sourceComponent);
if (getOwnPropertySymbols) {
keys = keys.concat(
getOwnPropertySymbols(sourceComponent)
);
}
var targetStatics = getStatics(targetComponent);
var sourceStatics = getStatics(sourceComponent);
for (var i = 0; i < keys.length; ++i) {
var key = keys[i];
if (
!KNOWN_STATICS[key] &&
!(blacklist && blacklist[key]) &&
!(sourceStatics && sourceStatics[key]) &&
!(targetStatics && targetStatics[key])
) {
var descriptor = getOwnPropertyDescriptor(
sourceComponent,
key
);
try {
// Avoid failures from read-only properties
defineProperty(
targetComponent,
key,
descriptor
);
} catch (e) {}
}
}
}
return targetComponent;
}
module.exports = hoistNonReactStatics;
/***/
},
/***/
8418:
/***/
function (__unused_webpack_module, exports, __webpack_require__) {
"use strict";
var __webpack_unused_export__;
function _arrayWithHoles(arr) {
if (Array.isArray(arr)) return arr;
}
function _iterableToArrayLimit(arr, i) {
var _arr = [];
var _n = true;
var _d = false;
var _e = undefined;
try {
for (
var _i = arr[Symbol.iterator](), _s;
!(_n = (_s = _i.next()).done);
_n = true
) {
_arr.push(_s.value);
if (i && _arr.length === i) break;
}
} catch (err) {
_d = true;
_e = err;
} finally {
try {
if (!_n && _i["return"] != null) _i["return"]();
} finally {
if (_d) throw _e;
}
}
return _arr;
}
function _nonIterableRest() {
throw new TypeError(
"Invalid attempt to destructure non-iterable instance"
);
}
function _slicedToArray(arr, i) {
return (
_arrayWithHoles(arr) ||
_iterableToArrayLimit(arr, i) ||
_nonIterableRest()
);
}
var _typeof = function (obj) {
return obj &&
typeof Symbol !== "undefined" &&
obj.constructor === Symbol
? "symbol"
: typeof obj;
};
__webpack_unused_export__ = {
value: true,
};
exports["default"] = void 0;
var _react = _interopRequireDefault(__webpack_require__(7294));
var _router = __webpack_require__(6273);
var _router1 = __webpack_require__(387);
var _useIntersection = __webpack_require__(7190);
function _interopRequireDefault(obj) {
return obj && obj.__esModule
? obj
: {
default: obj,
};
}
var prefetched = {};
function prefetch(router, href, as, options) {
if (false || !router) return;
if (!(0, _router).isLocalURL(href)) return;
// Prefetch the JSON page if asked (only in the client)
// We need to handle a prefetch error here since we may be
// loading with priority which can reject but we don't
// want to force navigation since this is only a prefetch
router.prefetch(href, as, options).catch(function (err) {
if (false) {
}
});
var curLocale =
options && typeof options.locale !== "undefined"
? options.locale
: router && router.locale;
// Join on an invalid URI character
prefetched[
href + "%" + as + (curLocale ? "%" + curLocale : "")
] = true;
}
function isModifiedEvent(event) {
var target = event.currentTarget.target;
return (
(target && target !== "_self") ||
event.metaKey ||
event.ctrlKey ||
event.shiftKey ||
event.altKey ||
(event.nativeEvent && event.nativeEvent.which === 2)
);
}
function linkClicked(
e,
router,
href,
as,
replace,
shallow,
scroll,
locale
) {
var nodeName = e.currentTarget.nodeName;
if (
nodeName === "A" &&
(isModifiedEvent(e) || !(0, _router).isLocalURL(href))
) {
// ignore click for browser’s default behavior
return;
}
e.preventDefault();
// avoid scroll for urls with anchor refs
if (scroll == null && as.indexOf("#") >= 0) {
scroll = false;
}
// replace state instead of push if prop is present
router[replace ? "replace" : "push"](href, as, {
shallow: shallow,
locale: locale,
scroll: scroll,
});
}
function Link(props) {
if (false) {
var hasWarned,
optionalProps,
optionalPropsGuard,
requiredProps,
requiredPropsGuard,
createPropError;
}
var p = props.prefetch !== false;
var router = (0, _router1).useRouter();
var ref2 = _react.default.useMemo(
function () {
var ref = _slicedToArray(
(0, _router).resolveHref(
router,
props.href,
true
),
2
),
resolvedHref = ref[0],
resolvedAs = ref[1];
return {
href: resolvedHref,
as: props.as
? (0, _router).resolveHref(
router,
props.as
)
: resolvedAs || resolvedHref,
};
},
[router, props.href, props.as]
),
href = ref2.href,
as = ref2.as;
var children = props.children,
replace = props.replace,
shallow = props.shallow,
scroll = props.scroll,
locale = props.locale;
// Deprecated. Warning shown by propType check. If the children provided is a string (<Link>example</Link>) we wrap it in an <a> tag
if (typeof children === "string") {
children = /*#__PURE__*/ _react.default.createElement(
"a",
null,
children
);
}
// This will return the first child, if multiple are provided it will throw an error
var child;
if (false) {
} else {
child = _react.default.Children.only(children);
}
var childRef =
child && typeof child === "object" && child.ref;
var ref1 = _slicedToArray(
(0, _useIntersection).useIntersection({
rootMargin: "200px",
}),
2
),
setIntersectionRef = ref1[0],
isVisible = ref1[1];
var setRef = _react.default.useCallback(
function (el) {
setIntersectionRef(el);
if (childRef) {
if (typeof childRef === "function")
childRef(el);
else if (typeof childRef === "object") {
childRef.current = el;
}
}
},
[childRef, setIntersectionRef]
);
_react.default.useEffect(
function () {
var shouldPrefetch =
isVisible && p && (0, _router).isLocalURL(href);
var curLocale =
typeof locale !== "undefined"
? locale
: router && router.locale;
var isPrefetched =
prefetched[
href +
"%" +
as +
(curLocale ? "%" + curLocale : "")
];
if (shouldPrefetch && !isPrefetched) {
prefetch(router, href, as, {
locale: curLocale,
});
}
},
[as, href, isVisible, locale, p, router]
);
var childProps = {
ref: setRef,
onClick: function (e) {
if (
child.props &&
typeof child.props.onClick === "function"
) {
child.props.onClick(e);
}
if (!e.defaultPrevented) {
linkClicked(
e,
router,
href,
as,
replace,
shallow,
scroll,
locale
);
}
},
};
childProps.onMouseEnter = function (e) {
if (!(0, _router).isLocalURL(href)) return;
if (
child.props &&
typeof child.props.onMouseEnter === "function"
) {
child.props.onMouseEnter(e);
}
prefetch(router, href, as, {
priority: true,
});
};
// If child is an <a> tag and doesn't have a href attribute, or if the 'passHref' property is
// defined, we specify the current 'href', so that repetition is not needed by the user
if (
props.passHref ||
(child.type === "a" && !("href" in child.props))
) {
var curLocale1 =
typeof locale !== "undefined"
? locale
: router && router.locale;
// we only render domain locales if we are currently on a domain locale
// so that locale links are still visitable in development/preview envs
var localeDomain =
router &&
router.isLocaleDomain &&
(0, _router).getDomainLocale(
as,
curLocale1,
router && router.locales,
router && router.domainLocales
);
childProps.href =
localeDomain ||
(0, _router).addBasePath(
(0, _router).addLocale(
as,
curLocale1,
router && router.defaultLocale
)
);
}
return /*#__PURE__*/ _react.default.cloneElement(
child,
childProps
);
}
var _default = Link;
exports["default"] = _default; //# sourceMappingURL=link.js.map
/***/
},
/***/
7190:
/***/
function (__unused_webpack_module, exports, __webpack_require__) {
"use strict";
function _arrayWithHoles(arr) {
if (Array.isArray(arr)) return arr;
}
function _iterableToArrayLimit(arr, i) {
var _arr = [];
var _n = true;
var _d = false;
var _e = undefined;
try {
for (
var _i = arr[Symbol.iterator](), _s;
!(_n = (_s = _i.next()).done);
_n = true
) {
_arr.push(_s.value);
if (i && _arr.length === i) break;
}
} catch (err) {
_d = true;
_e = err;
} finally {
try {
if (!_n && _i["return"] != null) _i["return"]();
} finally {
if (_d) throw _e;
}
}
return _arr;
}
function _nonIterableRest() {
throw new TypeError(
"Invalid attempt to destructure non-iterable instance"
);
}
function _slicedToArray(arr, i) {
return (
_arrayWithHoles(arr) ||
_iterableToArrayLimit(arr, i) ||
_nonIterableRest()
);
}
Object.defineProperty(exports, "__esModule", {
value: true,
});
exports.useIntersection = useIntersection;
var _react = __webpack_require__(7294);
var _requestIdleCallback = __webpack_require__(9311);
var hasIntersectionObserver =
typeof IntersectionObserver !== "undefined";
function useIntersection(param) {
var rootMargin = param.rootMargin,
disabled = param.disabled;
var isDisabled = disabled || !hasIntersectionObserver;
var unobserve = (0, _react).useRef();
var ref = _slicedToArray((0, _react).useState(false), 2),
visible = ref[0],
setVisible = ref[1];
var setRef = (0, _react).useCallback(
function (el) {
if (unobserve.current) {
unobserve.current();
unobserve.current = undefined;
}
if (isDisabled || visible) return;
if (el && el.tagName) {
unobserve.current = observe(
el,
function (isVisible) {
return (
isVisible && setVisible(isVisible)
);
},
{
rootMargin: rootMargin,
}
);
}
},
[isDisabled, rootMargin, visible]
);
(0, _react).useEffect(
function () {
if (!hasIntersectionObserver) {
if (!visible) {
var idleCallback = (0,
_requestIdleCallback).requestIdleCallback(
function () {
return setVisible(true);
}
);
return function () {
return (0,
_requestIdleCallback).cancelIdleCallback(
idleCallback
);
};
}
}
},
[visible]
);
return [setRef, visible];
}
function observe(element, callback, options) {
var ref = createObserver(options),
id = ref.id,
observer = ref.observer,
elements = ref.elements;
elements.set(element, callback);
observer.observe(element);
return function unobserve() {
elements.delete(element);
observer.unobserve(element);
// Destroy observer when there's nothing left to watch:
if (elements.size === 0) {
observer.disconnect();
observers.delete(id);
}
};
}
var observers = new Map();
function createObserver(options) {
var id = options.rootMargin || "";
var instance = observers.get(id);
if (instance) {
return instance;
}
var elements = new Map();
var observer = new IntersectionObserver(function (entries) {
entries.forEach(function (entry) {
var callback = elements.get(entry.target);
var isVisible =
entry.isIntersecting ||
entry.intersectionRatio > 0;
if (callback && isVisible) {
callback(isVisible);
}
});
}, options);
observers.set(
id,
(instance = {
id: id,
observer: observer,
elements: elements,
})
);
return instance;
} //# sourceMappingURL=use-intersection.js.map
/***/
},
/***/
9008:
/***/
function (module, __unused_webpack_exports, __webpack_require__) {
module.exports = __webpack_require__(5443);
/***/
},
/***/
1664:
/***/
function (module, __unused_webpack_exports, __webpack_require__) {
module.exports = __webpack_require__(8418);
/***/
},
/***/
9921:
/***/
function (__unused_webpack_module, exports) {
"use strict";
/** @license React v16.13.1
* react-is.production.min.js
*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
var b = "function" === typeof Symbol && Symbol.for,
c = b ? Symbol.for("react.element") : 60103,
d = b ? Symbol.for("react.portal") : 60106,
e = b ? Symbol.for("react.fragment") : 60107,
f = b ? Symbol.for("react.strict_mode") : 60108,
g = b ? Symbol.for("react.profiler") : 60114,
h = b ? Symbol.for("react.provider") : 60109,
k = b ? Symbol.for("react.context") : 60110,
l = b ? Symbol.for("react.async_mode") : 60111,
m = b ? Symbol.for("react.concurrent_mode") : 60111,
n = b ? Symbol.for("react.forward_ref") : 60112,
p = b ? Symbol.for("react.suspense") : 60113,
q = b ? Symbol.for("react.suspense_list") : 60120,
r = b ? Symbol.for("react.memo") : 60115,
t = b ? Symbol.for("react.lazy") : 60116,
v = b ? Symbol.for("react.block") : 60121,
w = b ? Symbol.for("react.fundamental") : 60117,
x = b ? Symbol.for("react.responder") : 60118,
y = b ? Symbol.for("react.scope") : 60119;
function z(a) {
if ("object" === typeof a && null !== a) {
var u = a.$$typeof;
switch (u) {
case c:
switch (((a = a.type), a)) {
case l:
case m:
case e:
case g:
case f:
case p:
return a;
default:
switch (((a = a && a.$$typeof), a)) {
case k:
case n:
case t:
case r:
case h:
return a;
default:
return u;
}
}
case d:
return u;
}
}
}
function A(a) {
return z(a) === m;
}
exports.AsyncMode = l;
exports.ConcurrentMode = m;
exports.ContextConsumer = k;
exports.ContextProvider = h;
exports.Element = c;
exports.ForwardRef = n;
exports.Fragment = e;
exports.Lazy = t;
exports.Memo = r;
exports.Portal = d;
exports.Profiler = g;
exports.StrictMode = f;
exports.Suspense = p;
exports.isAsyncMode = function (a) {
return A(a) || z(a) === l;
};
exports.isConcurrentMode = A;
exports.isContextConsumer = function (a) {
return z(a) === k;
};
exports.isContextProvider = function (a) {
return z(a) === h;
};
exports.isElement = function (a) {
return (
"object" === typeof a && null !== a && a.$$typeof === c
);
};
exports.isForwardRef = function (a) {
return z(a) === n;
};
exports.isFragment = function (a) {
return z(a) === e;
};
exports.isLazy = function (a) {
return z(a) === t;
};
exports.isMemo = function (a) {
return z(a) === r;
};
exports.isPortal = function (a) {
return z(a) === d;
};
exports.isProfiler = function (a) {
return z(a) === g;
};
exports.isStrictMode = function (a) {
return z(a) === f;
};
exports.isSuspense = function (a) {
return z(a) === p;
};
exports.isValidElementType = function (a) {
return (
"string" === typeof a ||
"function" === typeof a ||
a === e ||
a === m ||
a === g ||
a === f ||
a === p ||
a === q ||
("object" === typeof a &&
null !== a &&
(a.$$typeof === t ||
a.$$typeof === r ||
a.$$typeof === h ||
a.$$typeof === k ||
a.$$typeof === n ||
a.$$typeof === w ||
a.$$typeof === x ||
a.$$typeof === y ||
a.$$typeof === v))
);
};
exports.typeOf = z;
/***/
},
/***/
9864:
/***/
function (module, __unused_webpack_exports, __webpack_require__) {
"use strict";
if (true) {
module.exports = __webpack_require__(9921);
} else {
}
/***/
},
},
]);
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_minifier/tests/fixture/issues/emotion/react/1/output.js | JavaScript | (self.webpackChunk_N_E = self.webpackChunk_N_E || []).push([
[
111
],
{
/***/ 2781: /***/ function(__unused_webpack_module, __webpack_exports__, __webpack_require__) {
"use strict";
// EXPORTS
__webpack_require__.d(__webpack_exports__, {
xB: function() {
return /* binding */ Global;
}
});
// UNUSED EXPORTS: CacheProvider, ClassNames, ThemeContext, ThemeProvider, __unsafe_useEmotionCache, createElement, css, jsx, keyframes, useTheme, withEmotionCache, withTheme
// EXTERNAL MODULE: ./node_modules/react/index.js
var cache, func, cursor, react = __webpack_require__(7294), StyleSheet = /*#__PURE__*/ function() {
function StyleSheet(options) {
var _this = this;
this._insertTag = function(tag) {
var before;
before = 0 === _this.tags.length ? _this.prepend ? _this.container.firstChild : _this.before : _this.tags[_this.tags.length - 1].nextSibling, _this.container.insertBefore(tag, before), _this.tags.push(tag);
}, this.isSpeedy = void 0 === options.speedy || options.speedy, this.tags = [], this.ctr = 0, this.nonce = options.nonce, this.key = options.key, this.container = options.container, this.prepend = options.prepend, this.before = null;
}
var _proto = StyleSheet.prototype;
return _proto.hydrate = function(nodes) {
nodes.forEach(this._insertTag);
}, _proto.insert = function(rule) {
// the max length is how many rules we have per style tag, it's 65000 in speedy mode
// it's 1 in dev because we insert source maps that map a single rule to a location
// and you can only have one source map per style tag
if (this.ctr % (this.isSpeedy ? 65000 : 1) == 0) {
var tag;
this._insertTag(((tag = document.createElement("style")).setAttribute("data-emotion", this.key), void 0 !== this.nonce && tag.setAttribute("nonce", this.nonce), tag.appendChild(document.createTextNode("")), tag.setAttribute("data-s", ""), tag));
}
var tag1 = this.tags[this.tags.length - 1];
if (this.isSpeedy) {
var sheet = /*
Based off glamor's StyleSheet, thanks Sunil ❤️
high performance StyleSheet for css-in-js systems
- uses multiple style tags behind the scenes for millions of rules
- uses `insertRule` for appending in production for *much* faster performance
// usage
import { StyleSheet } from '@emotion/sheet'
let styleSheet = new StyleSheet({ key: '', container: document.head })
styleSheet.insert('#box { border: 1px solid red; }')
- appends a css rule into the stylesheet
styleSheet.flush()
- empties the stylesheet of all its contents
*/ // $FlowFixMe
function(tag) {
if (tag.sheet) // $FlowFixMe
return tag.sheet;
// this weirdness brought to you by firefox
/* istanbul ignore next */ for(var i = 0; i < document.styleSheets.length; i++)if (document.styleSheets[i].ownerNode === tag) // $FlowFixMe
return document.styleSheets[i];
}(tag1);
try {
// this is the ultrafast version, works across browsers
// the big drawback is that the css won't be editable in devtools
sheet.insertRule(rule, sheet.cssRules.length);
} catch (e) {}
} else tag1.appendChild(document.createTextNode(rule));
this.ctr++;
}, _proto.flush = function() {
// $FlowFixMe
this.tags.forEach(function(tag) {
return tag.parentNode && tag.parentNode.removeChild(tag);
}), this.tags = [], this.ctr = 0;
}, StyleSheet;
}(), abs = Math.abs, Utility_from = String.fromCharCode; // CONCATENATED MODULE: ./node_modules/@emotion/sheet/dist/emotion-sheet.browser.esm.js
/**
* @param {string} value
* @param {(string|RegExp)} pattern
* @param {string} replacement
* @return {string}
*/ function replace(value, pattern, replacement) {
return value.replace(pattern, replacement);
}
/**
* @param {string} value
* @param {number} index
* @return {number}
*/ function Utility_charat(value, index) {
return 0 | value.charCodeAt(index);
}
/**
* @param {string} value
* @param {number} begin
* @param {number} end
* @return {string}
*/ function Utility_substr(value, begin, end) {
return value.slice(begin, end);
}
/**
* @param {string} value
* @return {number}
*/ function Utility_strlen(value) {
return value.length;
}
/**
* @param {any} value
* @param {any[]} array
* @return {any}
*/ function Utility_append(value, array) {
return array.push(value), value;
}
var line = 1, column = 1, Tokenizer_length = 0, position = 0, character = 0, characters = "";
/**
* @param {string} value
* @param {object} root
* @param {object?} parent
* @param {string} type
* @param {string[]} props
* @param {object[]} children
* @param {number} length
*/ function node(value, root, parent, type, props, children, length) {
return {
value: value,
root: root,
parent: parent,
type: type,
props: props,
children: children,
line: line,
column: column,
length: length,
return: ""
};
}
/**
* @param {string} value
* @param {object} root
* @param {string} type
*/ function copy(value, root, type) {
return node(value, root.root, root.parent, type, root.props, root.children, 0);
}
/**
* @return {number}
*/ function next() {
return character = position < Tokenizer_length ? Utility_charat(characters, position++) : 0, column++, 10 === character && (column = 1, line++), character;
}
/**
* @return {number}
*/ function peek() {
return Utility_charat(characters, position);
}
/**
* @param {number} type
* @return {number}
*/ function token(type) {
switch(type){
// \0 \t \n \r \s whitespace token
case 0:
case 9:
case 10:
case 13:
case 32:
return 5;
// ! + , / > @ ~ isolate token
case 33:
case 43:
case 44:
case 47:
case 62:
case 64:
case 126:
// ; { } breakpoint token
case 59:
case 123:
case 125:
return 4;
// : accompanied token
case 58:
return 3;
// " ' ( [ opening delimit token
case 34:
case 39:
case 40:
case 91:
return 2;
// ) ] closing delimit token
case 41:
case 93:
return 1;
}
return 0;
}
/**
* @param {string} value
* @return {any[]}
*/ function alloc(value) {
return line = column = 1, Tokenizer_length = Utility_strlen(characters = value), position = 0, [];
}
/**
* @param {number} type
* @return {string}
*/ function delimit(type) {
var begin, end;
return (begin = position - 1, end = /**
* @param {number} type
* @return {number}
*/ function delimiter(type) {
for(; next();)switch(character){
// ] ) " '
case type:
return position;
// " '
case 34:
case 39:
return delimiter(34 === type || 39 === type ? type : character);
// (
case 40:
41 === type && delimiter(type);
break;
// \
case 92:
next();
}
return position;
}(91 === type ? type + 2 : 40 === type ? type + 1 : type), Utility_substr(characters, begin, end)).trim();
}
var MS = "-ms-", MOZ = "-moz-", WEBKIT = "-webkit-", COMMENT = "comm", Enum_RULESET = "rule", DECLARATION = "decl";
/**
* @param {object[]} children
* @param {function} callback
* @return {string}
*/ function serialize(children, callback) {
for(var output = "", length = children.length, i = 0; i < length; i++)output += callback(children[i], i, children, callback) || "";
return output;
}
/**
* @param {object} element
* @param {number} index
* @param {object[]} children
* @param {function} callback
* @return {string}
*/ function stringify(element, index, children, callback) {
switch(element.type){
case "@import":
case DECLARATION:
return element.return = element.return || element.value;
case COMMENT:
return "";
case Enum_RULESET:
element.value = element.props.join(",");
}
return Utility_strlen(children = serialize(element.children, callback)) ? element.return = element.value + "{" + children + "}" : "";
} // CONCATENATED MODULE: ./node_modules/@emotion/cache/node_modules/stylis/src/Prefixer.js
/**
* @param {string} value
* @param {object} root
* @param {object?} parent
* @param {number} index
* @param {number} offset
* @param {string[]} rules
* @param {number[]} points
* @param {string} type
* @param {string[]} props
* @param {string[]} children
* @param {number} length
* @return {object}
*/ function ruleset(value, root, parent, index, offset, rules, points, type, props, children, length) {
for(var post = offset - 1, rule = 0 === offset ? rules : [
""
], size = rule.length, i = 0, j = 0, k = 0; i < index; ++i)for(var x = 0, y = Utility_substr(value, post + 1, post = abs(j = points[i])), z = value; x < size; ++x)(z = (j > 0 ? rule[x] + " " + y : replace(y, /&\f/g, rule[x])).trim()) && (props[k++] = z);
return node(value, root, parent, 0 === offset ? Enum_RULESET : type, props, children, length);
}
/**
* @param {string} value
* @param {object} root
* @param {object?} parent
* @param {number} length
* @return {object}
*/ function declaration(value, root, parent, length) {
return node(value, root, parent, DECLARATION, Utility_substr(value, 0, length), Utility_substr(value, length + 1, -1), length);
} // CONCATENATED MODULE: ./node_modules/@emotion/cache/dist/emotion-cache.browser.esm.js
var identifierWithPointTracking = function(begin, points, index) {
for(var previous = 0, character = 0; previous = character, character = peek(), 38 === previous && 12 === character && (points[index] = 1), !token(character);)next();
return Utility_substr(characters, begin, position);
}, toRules = function(parsed, points) {
// pretend we've started with a comma
var index = -1, character = 44;
do switch(token(character)){
case 0:
38 === character && 12 === peek() && // this is not 100% correct, we don't account for literal sequences here - like for example quoted strings
// stylis inserts \f after & to know when & where it should replace this sequence with the context selector
// and when it should just concatenate the outer and inner selectors
// it's very unlikely for this sequence to actually appear in a different context, so we just leverage this fact here
(points[index] = 1), parsed[index] += identifierWithPointTracking(position - 1, points, index);
break;
case 2:
parsed[index] += delimit(character);
break;
case 4:
// comma
if (44 === character) {
// colon
parsed[++index] = 58 === peek() ? "&\f" : "", points[index] = parsed[index].length;
break;
}
// fallthrough
default:
parsed[index] += Utility_from(character);
}
while (character = next())
return parsed;
}, getRules = function(value, points) {
var value1;
return value1 = toRules(alloc(value), points), characters = "", value1;
}, fixedElements = /* #__PURE__ */ new WeakMap(), compat = function(element) {
if ("rule" === element.type && element.parent && element.length) {
for(var value = element.value, parent = element.parent, isImplicitRule = element.column === parent.column && element.line === parent.line; "rule" !== parent.type;)if (!(parent = parent.parent)) return;
// short-circuit for the simplest case
if ((1 !== element.props.length || 58 === value.charCodeAt(0) || fixedElements.get(parent)) && !isImplicitRule) {
fixedElements.set(element, !0);
for(var points = [], rules = getRules(value, points), parentRules = parent.props, i = 0, k = 0; i < rules.length; i++)for(var j = 0; j < parentRules.length; j++, k++)element.props[k] = points[i] ? rules[i].replace(/&\f/g, parentRules[j]) : parentRules[j] + " " + rules[i];
} // if this is an implicitly inserted rule (the one eagerly inserted at the each new nested level)
}
}, removeLabel = function(element) {
if ("decl" === element.type) {
var value = element.value;
108 === // charcode for l
value.charCodeAt(0) && // charcode for b
98 === value.charCodeAt(2) && (// this ignores label
element.return = "", element.value = "");
}
}, defaultStylisPlugins = [
/**
* @param {object} element
* @param {number} index
* @param {object[]} children
* @param {function} callback
*/ function(element, index, children, callback) {
if (!element.return) switch(element.type){
case DECLARATION:
element.return = /**
* @param {string} value
* @param {number} length
* @return {string}
*/ function prefix(value, length) {
switch((((length << 2 ^ Utility_charat(value, 0)) << 2 ^ Utility_charat(value, 1)) << 2 ^ Utility_charat(value, 2)) << 2 ^ Utility_charat(value, 3)){
// color-adjust
case 5103:
return WEBKIT + "print-" + value + value;
// animation, animation-(delay|direction|duration|fill-mode|iteration-count|name|play-state|timing-function)
case 5737:
case 4201:
case 3177:
case 3433:
case 1641:
case 4457:
case 2921:
// text-decoration, filter, clip-path, backface-visibility, column, box-decoration-break
case 5572:
case 6356:
case 5844:
case 3191:
case 6645:
case 3005:
// mask, mask-image, mask-(mode|clip|size), mask-(repeat|origin), mask-position, mask-composite,
case 6391:
case 5879:
case 5623:
case 6135:
case 4599:
case 4855:
// background-clip, columns, column-(count|fill|gap|rule|rule-color|rule-style|rule-width|span|width)
case 4215:
case 6389:
case 5109:
case 5365:
case 5621:
case 3829:
return WEBKIT + value + value;
// appearance, user-select, transform, hyphens, text-size-adjust
case 5349:
case 4246:
case 4810:
case 6968:
case 2756:
return WEBKIT + value + MOZ + value + MS + value + value;
// flex, flex-direction
case 6828:
case 4268:
return WEBKIT + value + MS + value + value;
// order
case 6165:
return WEBKIT + value + MS + "flex-" + value + value;
// align-items
case 5187:
return WEBKIT + value + replace(value, /(\w+).+(:[^]+)/, WEBKIT + "box-$1$2" + MS + "flex-$1$2") + value;
// align-self
case 5443:
return WEBKIT + value + MS + "flex-item-" + replace(value, /flex-|-self/, "") + value;
// align-content
case 4675:
return WEBKIT + value + MS + "flex-line-pack" + replace(value, /align-content|flex-|-self/, "") + value;
// flex-shrink
case 5548:
return WEBKIT + value + MS + replace(value, "shrink", "negative") + value;
// flex-basis
case 5292:
return WEBKIT + value + MS + replace(value, "basis", "preferred-size") + value;
// flex-grow
case 6060:
return WEBKIT + "box-" + replace(value, "-grow", "") + WEBKIT + value + MS + replace(value, "grow", "positive") + value;
// transition
case 4554:
return WEBKIT + replace(value, /([^-])(transform)/g, "$1" + WEBKIT + "$2") + value;
// cursor
case 6187:
return replace(replace(replace(value, /(zoom-|grab)/, WEBKIT + "$1"), /(image-set)/, WEBKIT + "$1"), value, "") + value;
// background, background-image
case 5495:
case 3959:
return replace(value, /(image-set\([^]*)/, WEBKIT + "$1$`$1");
// justify-content
case 4968:
return replace(replace(value, /(.+:)(flex-)?(.*)/, WEBKIT + "box-pack:$3" + MS + "flex-pack:$3"), /s.+-b[^;]+/, "justify") + WEBKIT + value + value;
// (margin|padding)-inline-(start|end)
case 4095:
case 3583:
case 4068:
case 2532:
return replace(value, /(.+)-inline(.+)/, WEBKIT + "$1$2") + value;
// (min|max)?(width|height|inline-size|block-size)
case 8116:
case 7059:
case 5753:
case 5535:
case 5445:
case 5701:
case 4933:
case 4677:
case 5533:
case 5789:
case 5021:
case 4765:
// stretch, max-content, min-content, fill-available
if (Utility_strlen(value) - 1 - length > 6) switch(Utility_charat(value, length + 1)){
// (m)ax-content, (m)in-content
case 109:
// -
if (45 !== Utility_charat(value, length + 4)) break;
// (f)ill-available, (f)it-content
case 102:
return replace(value, /(.+:)(.+)-([^]+)/, "$1" + WEBKIT + "$2-$3$1" + MOZ + (108 == Utility_charat(value, length + 3) ? "$3" : "$2-$3")) + value;
// (s)tretch
case 115:
return ~value.indexOf("stretch") ? prefix(replace(value, "stretch", "fill-available"), length) + value : value;
}
break;
// position: sticky
case 4949:
// (s)ticky?
if (115 !== Utility_charat(value, length + 1)) break;
// display: (flex|inline-flex)
case 6444:
switch(Utility_charat(value, Utility_strlen(value) - 3 - (~value.indexOf("!important") && 10))){
// stic(k)y
case 107:
return replace(value, ":", ":" + WEBKIT) + value;
// (inline-)?fl(e)x
case 101:
return replace(value, /(.+:)([^;!]+)(;|!.+)?/, "$1" + WEBKIT + (45 === Utility_charat(value, 14) ? "inline-" : "") + "box$3$1" + WEBKIT + "$2$3$1" + MS + "$2box$3") + value;
}
break;
// writing-mode
case 5936:
switch(Utility_charat(value, length + 11)){
// vertical-l(r)
case 114:
return WEBKIT + value + MS + replace(value, /[svh]\w+-[tblr]{2}/, "tb") + value;
// vertical-r(l)
case 108:
return WEBKIT + value + MS + replace(value, /[svh]\w+-[tblr]{2}/, "tb-rl") + value;
// horizontal(-)tb
case 45:
return WEBKIT + value + MS + replace(value, /[svh]\w+-[tblr]{2}/, "lr") + value;
}
return WEBKIT + value + MS + value + value;
}
return value;
} // CONCATENATED MODULE: ./node_modules/@emotion/cache/node_modules/stylis/src/Middleware.js
(element.value, element.length);
break;
case "@keyframes":
return serialize([
copy(replace(element.value, "@", "@" + WEBKIT), element, "")
], callback);
case Enum_RULESET:
if (element.length) return element.props.map(function(value) {
var value1;
switch(value1 = value, (value1 = /(::plac\w+|:read-\w+)/.exec(value1)) ? value1[0] : value1){
// :read-(only|write)
case ":read-only":
case ":read-write":
return serialize([
copy(replace(value, /:(read-\w+)/, ":" + MOZ + "$1"), element, "")
], callback);
// :placeholder
case "::placeholder":
return serialize([
copy(replace(value, /:(plac\w+)/, ":" + WEBKIT + "input-$1"), element, ""),
copy(replace(value, /:(plac\w+)/, ":" + MOZ + "$1"), element, ""),
copy(replace(value, /:(plac\w+)/, MS + "input-$1"), element, "")
], callback);
}
return "";
}).join("");
}
}
], hash_browser_esm = /* eslint-disable */ // Inspired by https://github.com/garycourt/murmurhash-js
// Ported from https://github.com/aappleby/smhasher/blob/61a0530f28277f2e850bfc39600ce61d02b518de/src/MurmurHash2.cpp#L37-L86
function(str) {
for(// 'm' and 'r' are mixing constants generated offline.
// They're not really 'magic', they just happen to work well.
// const m = 0x5bd1e995;
// const r = 24;
// Initialize the hash
var k, h = 0, i = 0, len = str.length; len >= 4; ++i, len -= 4)k = /* Math.imul(k, m): */ (0xffff & (k = 0xff & str.charCodeAt(i) | (0xff & str.charCodeAt(++i)) << 8 | (0xff & str.charCodeAt(++i)) << 16 | (0xff & str.charCodeAt(++i)) << 24)) * 0x5bd1e995 + ((k >>> 16) * 0xe995 << 16), k ^= /* k >>> r: */ k >>> 24, h = (0xffff & k) * 0x5bd1e995 + ((k >>> 16) * 0xe995 << 16) ^ /* Math.imul(h, m): */ (0xffff & h) * 0x5bd1e995 + ((h >>> 16) * 0xe995 << 16);
// Handle the last few bytes of the input array
switch(len){
case 3:
h ^= (0xff & str.charCodeAt(i + 2)) << 16;
case 2:
h ^= (0xff & str.charCodeAt(i + 1)) << 8;
case 1:
h ^= 0xff & str.charCodeAt(i), h = /* Math.imul(h, m): */ (0xffff & h) * 0x5bd1e995 + ((h >>> 16) * 0xe995 << 16);
} // Do a few final mixes of the hash to ensure the last few
return(// bytes are well-incorporated.
h ^= h >>> 13, (((h = /* Math.imul(h, m): */ (0xffff & h) * 0x5bd1e995 + ((h >>> 16) * 0xe995 << 16)) ^ h >>> 15) >>> 0).toString(36));
}, unitless_browser_esm = {
animationIterationCount: 1,
borderImageOutset: 1,
borderImageSlice: 1,
borderImageWidth: 1,
boxFlex: 1,
boxFlexGroup: 1,
boxOrdinalGroup: 1,
columnCount: 1,
columns: 1,
flex: 1,
flexGrow: 1,
flexPositive: 1,
flexShrink: 1,
flexNegative: 1,
flexOrder: 1,
gridRow: 1,
gridRowEnd: 1,
gridRowSpan: 1,
gridRowStart: 1,
gridColumn: 1,
gridColumnEnd: 1,
gridColumnSpan: 1,
gridColumnStart: 1,
msGridRow: 1,
msGridRowSpan: 1,
msGridColumn: 1,
msGridColumnSpan: 1,
fontWeight: 1,
lineHeight: 1,
opacity: 1,
order: 1,
orphans: 1,
tabSize: 1,
widows: 1,
zIndex: 1,
zoom: 1,
WebkitLineClamp: 1,
// SVG-related properties
fillOpacity: 1,
floodOpacity: 1,
stopOpacity: 1,
strokeDasharray: 1,
strokeDashoffset: 1,
strokeMiterlimit: 1,
strokeOpacity: 1,
strokeWidth: 1
}, hyphenateRegex = /[A-Z]|^ms/g, animationRegex = /_EMO_([^_]+?)_([^]*?)_EMO_/g, isCustomProperty = function(property) {
return 45 === property.charCodeAt(1);
}, isProcessableValue = function(value) {
return null != value && "boolean" != typeof value;
}, processStyleName = (cache = Object.create(null), function(arg) {
return void 0 === cache[arg] && (cache[arg] = isCustomProperty(arg) ? arg : arg.replace(hyphenateRegex, "-$&").toLowerCase()), cache[arg];
}), processStyleValue = function(key, value) {
switch(key){
case "animation":
case "animationName":
if ("string" == typeof value) return value.replace(animationRegex, function(match, p1, p2) {
return cursor = {
name: p1,
styles: p2,
next: cursor
}, p1;
});
}
return 1 === unitless_browser_esm[key] || isCustomProperty(key) || "number" != typeof value || 0 === value ? value : value + "px";
};
function handleInterpolation(mergedProps, registered, interpolation) {
if (null == interpolation) return "";
if (void 0 !== interpolation.__emotion_styles) return interpolation;
switch(typeof interpolation){
case "boolean":
return "";
case "object":
if (1 === interpolation.anim) return cursor = {
name: interpolation.name,
styles: interpolation.styles,
next: cursor
}, interpolation.name;
if (void 0 !== interpolation.styles) {
var next = interpolation.next;
if (void 0 !== next) // not the most efficient thing ever but this is a pretty rare case
// and there will be very few iterations of this generally
for(; void 0 !== next;)cursor = {
name: next.name,
styles: next.styles,
next: cursor
}, next = next.next;
return interpolation.styles + ";";
}
return function(mergedProps, registered, obj) {
var string = "";
if (Array.isArray(obj)) for(var i = 0; i < obj.length; i++)string += handleInterpolation(mergedProps, registered, obj[i]) + ";";
else for(var _key in obj){
var value = obj[_key];
if ("object" != typeof value) null != registered && void 0 !== registered[value] ? string += _key + "{" + registered[value] + "}" : isProcessableValue(value) && (string += processStyleName(_key) + ":" + processStyleValue(_key, value) + ";");
else if (Array.isArray(value) && "string" == typeof value[0] && (null == registered || void 0 === registered[value[0]])) for(var _i = 0; _i < value.length; _i++)isProcessableValue(value[_i]) && (string += processStyleName(_key) + ":" + processStyleValue(_key, value[_i]) + ";");
else {
var interpolated = handleInterpolation(mergedProps, registered, value);
switch(_key){
case "animation":
case "animationName":
string += processStyleName(_key) + ":" + interpolated + ";";
break;
default:
string += _key + "{" + interpolated + "}";
}
}
}
return string;
}(mergedProps, registered, interpolation);
case "function":
if (void 0 !== mergedProps) {
var previousCursor = cursor, result = interpolation(mergedProps);
return cursor = previousCursor, handleInterpolation(mergedProps, registered, result);
}
} // finalize string values (regular strings and functions interpolated into css calls)
if (null == registered) return interpolation;
var cached = registered[interpolation];
return void 0 !== cached ? cached : interpolation;
}
var labelPattern = /label:\s*([^\s;\n{]+)\s*(;|$)/g, emotion_serialize_browser_esm_serializeStyles = function(args, registered, mergedProps) {
if (1 === args.length && "object" == typeof args[0] && null !== args[0] && void 0 !== args[0].styles) return args[0];
var match, stringMode = !0, styles = "";
cursor = void 0;
var strings = args[0];
null == strings || void 0 === strings.raw ? (stringMode = !1, styles += handleInterpolation(mergedProps, registered, strings)) : styles += strings[0]; // we start at 1 since we've already handled the first arg
for(var i = 1; i < args.length; i++)styles += handleInterpolation(mergedProps, registered, args[i]), stringMode && (styles += strings[i]);
labelPattern.lastIndex = 0;
for(var identifierName = ""; null !== (match = labelPattern.exec(styles));)identifierName += "-" + // $FlowFixMe we know it's not null
match[1];
return {
name: hash_browser_esm(styles) + identifierName,
styles: styles,
next: cursor
};
};
Object.prototype.hasOwnProperty;
var EmotionCacheContext = /* #__PURE__ */ (0, react.createContext)(// we're doing this to avoid preconstruct's dead code elimination in this one case
// because this module is primarily intended for the browser and node
// but it's also required in react native and similar environments sometimes
// and we could have a special build just for that
// but this is much easier and the native packages
// might use a different theme context in the future anyway
"undefined" != typeof HTMLElement ? /* #__PURE__ */ function(options) {
var collection, length, callback, container, currentSheet, key = options.key;
if ("css" === key) {
var ssrStyles = document.querySelectorAll("style[data-emotion]:not([data-s])"); // get SSRed styles out of the way of React's hydration
// document.head is a safe place to move them to(though note document.head is not necessarily the last place they will be)
// note this very very intentionally targets all style elements regardless of the key to ensure
// that creating a cache works inside of render of a React component
Array.prototype.forEach.call(ssrStyles, function(node) {
-1 !== node.getAttribute("data-emotion").indexOf(" ") && (document.head.appendChild(node), node.setAttribute("data-s", ""));
});
}
var stylisPlugins = options.stylisPlugins || defaultStylisPlugins, inserted = {}, nodesToHydrate = [];
container = options.container || document.head, Array.prototype.forEach.call(// this means we will ignore elements which don't have a space in them which
// means that the style elements we're looking at are only Emotion 11 server-rendered style elements
document.querySelectorAll('style[data-emotion^="' + key + ' "]'), function(node) {
for(var attrib = node.getAttribute("data-emotion").split(" "), i = 1; i < attrib.length; i++)inserted[attrib[i]] = !0;
nodesToHydrate.push(node);
});
var serializer = (length = (collection = [
compat,
removeLabel
].concat(stylisPlugins, [
stringify,
(callback = function(rule) {
currentSheet.insert(rule);
}, function(element) {
!element.root && (element = element.return) && callback(element);
})
])).length, function(element, index, children, callback) {
for(var output = "", i = 0; i < length; i++)output += collection[i](element, index, children, callback) || "";
return output;
}), stylis = function(styles) {
var value, value1;
return serialize((value1 = /**
* @param {string} value
* @param {object} root
* @param {object?} parent
* @param {string[]} rule
* @param {string[]} rules
* @param {string[]} rulesets
* @param {number[]} pseudo
* @param {number[]} points
* @param {string[]} declarations
* @return {object}
*/ function parse(value, root, parent, rule, rules, rulesets, pseudo, points, declarations) {
for(var value1, index = 0, offset = 0, length = pseudo, atrule = 0, property = 0, previous = 0, variable = 1, scanning = 1, ampersand = 1, character1 = 0, type = "", props = rules, children = rulesets, reference = rule, characters1 = type; scanning;)switch(previous = character1, character1 = next()){
// " ' [ (
case 34:
case 39:
case 91:
case 40:
characters1 += delimit(character1);
break;
// \t \n \r \s
case 9:
case 10:
case 13:
case 32:
characters1 += /**
* @param {number} type
* @return {string}
*/ function(type) {
for(; character = peek();)if (character < 33) next();
else break;
return token(type) > 2 || token(character) > 3 ? "" : " ";
}(previous);
break;
// \
case 92:
characters1 += /**
* @param {number} index
* @param {number} count
* @return {string}
*/ function(index, count) {
for(var end; --count && next() && !(character < 48) && !(character > 102) && (!(character > 57) || !(character < 65)) && (!(character > 70) || !(character < 97)););
return end = position + (count < 6 && 32 == peek() && 32 == next()), Utility_substr(characters, index, end);
}(position - 1, 7);
continue;
// /
case 47:
switch(peek()){
case 42:
case 47:
Utility_append(node(value1 = /**
* @param {number} type
* @param {number} index
* @return {number}
*/ function(type, index) {
for(; next();)// //
if (type + character === 57) break;
else if (type + character === 84 && 47 === peek()) break;
return "/*" + Utility_substr(characters, index, position - 1) + "*" + Utility_from(47 === type ? type : next());
}(next(), position), root, parent, COMMENT, Utility_from(character), Utility_substr(value1, 2, -2), 0), declarations);
break;
default:
characters1 += "/";
}
break;
// {
case 123 * variable:
points[index++] = Utility_strlen(characters1) * ampersand;
// } ; \0
case 125 * variable:
case 59:
case 0:
switch(character1){
// \0 }
case 0:
case 125:
scanning = 0;
// ;
case 59 + offset:
property > 0 && Utility_strlen(characters1) - length && Utility_append(property > 32 ? declaration(characters1 + ";", rule, parent, length - 1) : declaration(replace(characters1, " ", "") + ";", rule, parent, length - 2), declarations);
break;
// @ ;
case 59:
characters1 += ";";
// { rule/at-rule
default:
if (Utility_append(reference = ruleset(characters1, root, parent, index, offset, rules, points, type, props = [], children = [], length), rulesets), 123 === character1) {
if (0 === offset) parse(characters1, root, reference, reference, props, rulesets, length, points, children);
else switch(atrule){
// d m s
case 100:
case 109:
case 115:
parse(value, reference, reference, rule && Utility_append(ruleset(value, reference, reference, 0, 0, rules, points, type, rules, props = [], length), children), rules, children, length, points, rule ? props : children);
break;
default:
parse(characters1, reference, reference, reference, [
""
], children, length, points, children);
}
}
}
index = offset = property = 0, variable = ampersand = 1, type = characters1 = "", length = pseudo;
break;
// :
case 58:
length = 1 + Utility_strlen(characters1), property = previous;
default:
if (variable < 1) {
if (123 == character1) --variable;
else if (125 == character1 && 0 == variable++ && 125 == (character = position > 0 ? Utility_charat(characters, --position) : 0, column--, 10 === character && (column = 1, line--), character)) continue;
}
switch(characters1 += Utility_from(character1), character1 * variable){
// &
case 38:
ampersand = offset > 0 ? 1 : (characters1 += "\f", -1);
break;
// ,
case 44:
points[index++] = (Utility_strlen(characters1) - 1) * ampersand, ampersand = 1;
break;
// @
case 64:
45 === peek() && (characters1 += delimit(next())), atrule = peek(), offset = Utility_strlen(type = characters1 += /**
* @param {number} index
* @return {string}
*/ function(index) {
for(; !token(peek());)next();
return Utility_substr(characters, index, position);
} // CONCATENATED MODULE: ./node_modules/@emotion/cache/node_modules/stylis/src/Enum.js
(position)), character1++;
break;
// -
case 45:
45 === previous && 2 == Utility_strlen(characters1) && (variable = 0);
}
}
return rulesets;
}("", null, null, null, [
""
], value = alloc(value = styles), 0, [
0
], value), characters = "", value1), serializer);
}, cache = {
key: key,
sheet: new StyleSheet({
key: key,
container: container,
nonce: options.nonce,
speedy: options.speedy,
prepend: options.prepend
}),
nonce: options.nonce,
inserted: inserted,
registered: {},
insert: function(selector, serialized, sheet, shouldCache) {
currentSheet = sheet, stylis(selector ? selector + "{" + serialized.styles + "}" : serialized.styles), shouldCache && (cache.inserted[serialized.name] = !0);
}
};
return cache.sheet.hydrate(nodesToHydrate), cache;
}({
key: "css"
}) : null);
EmotionCacheContext.Provider;
var emotion_element_99289b21_browser_esm_ThemeContext = /* #__PURE__ */ (0, react.createContext)({});
// EXTERNAL MODULE: ./node_modules/hoist-non-react-statics/dist/hoist-non-react-statics.cjs.js
__webpack_require__(8679); // CONCATENATED MODULE: ./node_modules/@emotion/utils/dist/emotion-utils.browser.esm.js
var emotion_utils_browser_esm_insertStyles = function(cache, serialized, isStringTag) {
var className = cache.key + "-" + serialized.name;
if (!1 === // we only need to add the styles to the registered cache if the
// class name could be used further down
// the tree but if it's a string tag, we know it won't
// so we don't have to add it to registered cache.
// this improves memory usage since we can avoid storing the whole style string
isStringTag && void 0 === cache.registered[className] && (cache.registered[className] = serialized.styles), void 0 === cache.inserted[serialized.name]) {
var current = serialized;
do cache.insert(serialized === current ? "." + className : "", current, cache.sheet, !0), current = current.next;
while (void 0 !== current)
}
}, Global = (func = function(props, cache) {
var serialized = emotion_serialize_browser_esm_serializeStyles([
props.styles
], void 0, (0, react.useContext)(emotion_element_99289b21_browser_esm_ThemeContext)), sheetRef = (0, react.useRef)();
return (0, react.useLayoutEffect)(function() {
var key = cache.key + "-global", sheet = new StyleSheet({
key: key,
nonce: cache.sheet.nonce,
container: cache.sheet.container,
speedy: cache.sheet.isSpeedy
}), rehydrating = !1, node = document.querySelector('style[data-emotion="' + key + " " + serialized.name + '"]');
return cache.sheet.tags.length && (sheet.before = cache.sheet.tags[0]), null !== node && (rehydrating = !0, node.setAttribute("data-emotion", key), sheet.hydrate([
node
])), sheetRef.current = [
sheet,
rehydrating
], function() {
sheet.flush();
};
}, [
cache
]), (0, react.useLayoutEffect)(function() {
var sheetRefCurrent = sheetRef.current, sheet = sheetRefCurrent[0];
if (sheetRefCurrent[1]) {
sheetRefCurrent[1] = !1;
return;
}
if (void 0 !== serialized.next && // insert keyframes
emotion_utils_browser_esm_insertStyles(cache, serialized.next, !0), sheet.tags.length) {
// if this doesn't exist then it will be null so the style element will be appended
var element = sheet.tags[sheet.tags.length - 1].nextElementSibling;
sheet.before = element, sheet.flush();
}
cache.insert("", serialized, sheet, !1);
}, [
cache,
serialized.name
]), null;
}, /*#__PURE__*/ (0, react.forwardRef)(function(props, ref) {
return func(props, (0, react.useContext)(EmotionCacheContext), ref);
})); // CONCATENATED MODULE: ./node_modules/@emotion/react/dist/emotion-react.browser.esm.js
/***/ },
/***/ 8679: /***/ function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var reactIs = __webpack_require__(9864), REACT_STATICS = {
childContextTypes: !0,
contextType: !0,
contextTypes: !0,
defaultProps: !0,
displayName: !0,
getDefaultProps: !0,
getDerivedStateFromError: !0,
getDerivedStateFromProps: !0,
mixins: !0,
propTypes: !0,
type: !0
}, KNOWN_STATICS = {
name: !0,
length: !0,
prototype: !0,
caller: !0,
callee: !0,
arguments: !0,
arity: !0
}, MEMO_STATICS = {
$$typeof: !0,
compare: !0,
defaultProps: !0,
displayName: !0,
propTypes: !0,
type: !0
}, TYPE_STATICS = {};
function getStatics(component) {
return(// React v16.11 and below
reactIs.isMemo(component) ? MEMO_STATICS : TYPE_STATICS[component.$$typeof] || REACT_STATICS // React v16.12 and above
);
}
TYPE_STATICS[reactIs.ForwardRef] = {
$$typeof: !0,
render: !0,
defaultProps: !0,
displayName: !0,
propTypes: !0
}, TYPE_STATICS[reactIs.Memo] = MEMO_STATICS;
var defineProperty = Object.defineProperty, getOwnPropertyNames = Object.getOwnPropertyNames, getOwnPropertySymbols = Object.getOwnPropertySymbols, getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor, getPrototypeOf = Object.getPrototypeOf, objectPrototype = Object.prototype;
module.exports = function hoistNonReactStatics(targetComponent, sourceComponent, blacklist) {
if ("string" != typeof sourceComponent) {
// don't hoist over string (html) components
if (objectPrototype) {
var inheritedComponent = getPrototypeOf(sourceComponent);
inheritedComponent && inheritedComponent !== objectPrototype && hoistNonReactStatics(targetComponent, inheritedComponent, blacklist);
}
var keys = getOwnPropertyNames(sourceComponent);
getOwnPropertySymbols && (keys = keys.concat(getOwnPropertySymbols(sourceComponent)));
for(var targetStatics = getStatics(targetComponent), sourceStatics = getStatics(sourceComponent), i = 0; i < keys.length; ++i){
var key = keys[i];
if (!KNOWN_STATICS[key] && !(blacklist && blacklist[key]) && !(sourceStatics && sourceStatics[key]) && !(targetStatics && targetStatics[key])) {
var descriptor = getOwnPropertyDescriptor(sourceComponent, key);
try {
// Avoid failures from read-only properties
defineProperty(targetComponent, key, descriptor);
} catch (e) {}
}
}
}
return targetComponent;
};
/***/ },
/***/ 8418: /***/ function(__unused_webpack_module, exports, __webpack_require__) {
"use strict";
function _slicedToArray(arr, i) {
return function(arr) {
if (Array.isArray(arr)) return arr;
}(arr) || function(arr, i) {
var _arr = [], _n = !0, _d = !1, _e = void 0;
try {
for(var _s, _i = arr[Symbol.iterator](); !(_n = (_s = _i.next()).done) && (_arr.push(_s.value), !i || _arr.length !== i); _n = !0);
} catch (err) {
_d = !0, _e = err;
} finally{
try {
_n || null == _i.return || _i.return();
} finally{
if (_d) throw _e;
}
}
return _arr;
}(arr, i) || function() {
throw TypeError("Invalid attempt to destructure non-iterable instance");
}();
}
exports.default = void 0;
var obj, _react = (obj = __webpack_require__(7294)) && obj.__esModule ? obj : {
default: obj
}, _router = __webpack_require__(6273), _router1 = __webpack_require__(387), _useIntersection = __webpack_require__(7190), prefetched = {};
function prefetch(router, href, as, options) {
if (router && _router.isLocalURL(href)) {
// Prefetch the JSON page if asked (only in the client)
// We need to handle a prefetch error here since we may be
// loading with priority which can reject but we don't
// want to force navigation since this is only a prefetch
router.prefetch(href, as, options).catch(function(err) {});
var curLocale = options && void 0 !== options.locale ? options.locale : router && router.locale;
// Join on an invalid URI character
prefetched[href + "%" + as + (curLocale ? "%" + curLocale : "")] = !0;
}
}
exports.default = function(props) {
var child, p = !1 !== props.prefetch, router = _router1.useRouter(), ref2 = _react.default.useMemo(function() {
var ref = _slicedToArray(_router.resolveHref(router, props.href, !0), 2), resolvedHref = ref[0], resolvedAs = ref[1];
return {
href: resolvedHref,
as: props.as ? _router.resolveHref(router, props.as) : resolvedAs || resolvedHref
};
}, [
router,
props.href,
props.as
]), href = ref2.href, as = ref2.as, children = props.children, replace = props.replace, shallow = props.shallow, scroll = props.scroll, locale = props.locale;
"string" == typeof children && (children = /*#__PURE__*/ _react.default.createElement("a", null, children));
var childRef = (child = _react.default.Children.only(children)) && "object" == typeof child && child.ref, ref1 = _slicedToArray(_useIntersection.useIntersection({
rootMargin: "200px"
}), 2), setIntersectionRef = ref1[0], isVisible = ref1[1], setRef = _react.default.useCallback(function(el) {
setIntersectionRef(el), childRef && ("function" == typeof childRef ? childRef(el) : "object" == typeof childRef && (childRef.current = el));
}, [
childRef,
setIntersectionRef
]);
_react.default.useEffect(function() {
var shouldPrefetch = isVisible && p && _router.isLocalURL(href), curLocale = void 0 !== locale ? locale : router && router.locale, isPrefetched = prefetched[href + "%" + as + (curLocale ? "%" + curLocale : "")];
shouldPrefetch && !isPrefetched && prefetch(router, href, as, {
locale: curLocale
});
}, [
as,
href,
isVisible,
locale,
p,
router
]);
var childProps = {
ref: setRef,
onClick: function(e) {
var scroll1, target;
child.props && "function" == typeof child.props.onClick && child.props.onClick(e), e.defaultPrevented || (scroll1 = scroll, ("A" !== e.currentTarget.nodeName || (!(target = e.currentTarget.target) || "_self" === target) && !e.metaKey && !e.ctrlKey && !e.shiftKey && !e.altKey && (!e.nativeEvent || 2 !== e.nativeEvent.which) && _router.isLocalURL(href)) && (e.preventDefault(), null == scroll1 && as.indexOf("#") >= 0 && (scroll1 = !1), // replace state instead of push if prop is present
router[replace ? "replace" : "push"](href, as, {
shallow: shallow,
locale: locale,
scroll: scroll1
})));
}
};
// If child is an <a> tag and doesn't have a href attribute, or if the 'passHref' property is
// defined, we specify the current 'href', so that repetition is not needed by the user
if (childProps.onMouseEnter = function(e) {
_router.isLocalURL(href) && (child.props && "function" == typeof child.props.onMouseEnter && child.props.onMouseEnter(e), prefetch(router, href, as, {
priority: !0
}));
}, props.passHref || "a" === child.type && !("href" in child.props)) {
var curLocale1 = void 0 !== locale ? locale : router && router.locale;
childProps.href = router && router.isLocaleDomain && _router.getDomainLocale(as, curLocale1, router && router.locales, router && router.domainLocales) || _router.addBasePath(_router.addLocale(as, curLocale1, router && router.defaultLocale));
}
return /*#__PURE__*/ _react.default.cloneElement(child, childProps);
};
/***/ },
/***/ 7190: /***/ function(__unused_webpack_module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: !0
}), exports.useIntersection = function(param) {
var arr, rootMargin = param.rootMargin, isDisabled = param.disabled || !hasIntersectionObserver, unobserve = _react.useRef(), ref = function(arr) {
if (Array.isArray(arr)) return arr;
}(arr = _react.useState(!1)) || function(arr, i) {
var _arr = [], _n = !0, _d = !1, _e = void 0;
try {
for(var _s, _i = arr[Symbol.iterator](); !(_n = (_s = _i.next()).done) && (_arr.push(_s.value), 2 !== _arr.length); _n = !0);
} catch (err) {
_d = !0, _e = err;
} finally{
try {
_n || null == _i.return || _i.return();
} finally{
if (_d) throw _e;
}
}
return _arr;
}(arr, 0) || function() {
throw TypeError("Invalid attempt to destructure non-iterable instance");
}(), visible = ref[0], setVisible = ref[1], setRef = _react.useCallback(function(el) {
var ref, id, observer, elements;
unobserve.current && (unobserve.current(), unobserve.current = void 0), !isDisabled && !visible && el && el.tagName && (id = (ref = function(options) {
var id = options.rootMargin || "", instance = observers.get(id);
if (instance) return instance;
var elements = new Map(), observer = new IntersectionObserver(function(entries) {
entries.forEach(function(entry) {
var callback = elements.get(entry.target), isVisible = entry.isIntersecting || entry.intersectionRatio > 0;
callback && isVisible && callback(isVisible);
});
}, options);
return observers.set(id, instance = {
id: id,
observer: observer,
elements: elements
}), instance;
} //# sourceMappingURL=use-intersection.js.map
({
rootMargin: rootMargin
})).id, observer = ref.observer, (elements = ref.elements).set(el, function(isVisible) {
return isVisible && setVisible(isVisible);
}), observer.observe(el), unobserve.current = function() {
elements.delete(el), observer.unobserve(el), 0 === elements.size && (observer.disconnect(), observers.delete(id));
});
}, [
isDisabled,
rootMargin,
visible
]);
return _react.useEffect(function() {
if (!hasIntersectionObserver && !visible) {
var idleCallback = _requestIdleCallback.requestIdleCallback(function() {
return setVisible(!0);
});
return function() {
return _requestIdleCallback.cancelIdleCallback(idleCallback);
};
}
}, [
visible
]), [
setRef,
visible
];
};
var _react = __webpack_require__(7294), _requestIdleCallback = __webpack_require__(9311), hasIntersectionObserver = "undefined" != typeof IntersectionObserver, observers = new Map();
/***/ },
/***/ 9008: /***/ function(module, __unused_webpack_exports, __webpack_require__) {
module.exports = __webpack_require__(5443);
/***/ },
/***/ 1664: /***/ function(module, __unused_webpack_exports, __webpack_require__) {
module.exports = __webpack_require__(8418);
/***/ },
/***/ 9921: /***/ function(__unused_webpack_module, exports) {
"use strict";
/** @license React v16.13.1
* react-is.production.min.js
*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/ var b = "function" == typeof Symbol && Symbol.for, c = b ? Symbol.for("react.element") : 60103, d = b ? Symbol.for("react.portal") : 60106, e = b ? Symbol.for("react.fragment") : 60107, f = b ? Symbol.for("react.strict_mode") : 60108, g = b ? Symbol.for("react.profiler") : 60114, h = b ? Symbol.for("react.provider") : 60109, k = b ? Symbol.for("react.context") : 60110, l = b ? Symbol.for("react.async_mode") : 60111, m = b ? Symbol.for("react.concurrent_mode") : 60111, n = b ? Symbol.for("react.forward_ref") : 60112, p = b ? Symbol.for("react.suspense") : 60113, q = b ? Symbol.for("react.suspense_list") : 60120, r = b ? Symbol.for("react.memo") : 60115, t = b ? Symbol.for("react.lazy") : 60116, v = b ? Symbol.for("react.block") : 60121, w = b ? Symbol.for("react.fundamental") : 60117, x = b ? Symbol.for("react.responder") : 60118, y = b ? Symbol.for("react.scope") : 60119;
function z(a) {
if ("object" == typeof a && null !== a) {
var u = a.$$typeof;
switch(u){
case c:
switch(a = a.type){
case l:
case m:
case e:
case g:
case f:
case p:
return a;
default:
switch(a = a && a.$$typeof){
case k:
case n:
case t:
case r:
case h:
return a;
default:
return u;
}
}
case d:
return u;
}
}
}
function A(a) {
return z(a) === m;
}
exports.AsyncMode = l, exports.ConcurrentMode = m, exports.ContextConsumer = k, exports.ContextProvider = h, exports.Element = c, exports.ForwardRef = n, exports.Fragment = e, exports.Lazy = t, exports.Memo = r, exports.Portal = d, exports.Profiler = g, exports.StrictMode = f, exports.Suspense = p, exports.isAsyncMode = function(a) {
return A(a) || z(a) === l;
}, exports.isConcurrentMode = A, exports.isContextConsumer = function(a) {
return z(a) === k;
}, exports.isContextProvider = function(a) {
return z(a) === h;
}, exports.isElement = function(a) {
return "object" == typeof a && null !== a && a.$$typeof === c;
}, exports.isForwardRef = function(a) {
return z(a) === n;
}, exports.isFragment = function(a) {
return z(a) === e;
}, exports.isLazy = function(a) {
return z(a) === t;
}, exports.isMemo = function(a) {
return z(a) === r;
}, exports.isPortal = function(a) {
return z(a) === d;
}, exports.isProfiler = function(a) {
return z(a) === g;
}, exports.isStrictMode = function(a) {
return z(a) === f;
}, exports.isSuspense = function(a) {
return z(a) === p;
}, exports.isValidElementType = function(a) {
return "string" == typeof a || "function" == typeof a || a === e || a === m || a === g || a === f || a === p || a === q || "object" == typeof a && null !== a && (a.$$typeof === t || a.$$typeof === r || a.$$typeof === h || a.$$typeof === k || a.$$typeof === n || a.$$typeof === w || a.$$typeof === x || a.$$typeof === y || a.$$typeof === v);
}, exports.typeOf = z;
/***/ },
/***/ 9864: /***/ function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
module.exports = __webpack_require__(9921);
/***/ }
}
]);
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_minifier/tests/fixture/issues/emotion/react/2/input.js | JavaScript | /* harmony default export */
var emotion_memoize_browser_esm = memoize;
var hyphenateRegex = /[A-Z]|^ms/g;
var animationRegex = /_EMO_([^_]+?)_([^]*?)_EMO_/g;
var unitlessKeys = {
animationIterationCount: 1,
borderImageOutset: 1,
borderImageSlice: 1,
borderImageWidth: 1,
boxFlex: 1,
boxFlexGroup: 1,
boxOrdinalGroup: 1,
columnCount: 1,
columns: 1,
flex: 1,
flexGrow: 1,
flexPositive: 1,
flexShrink: 1,
flexNegative: 1,
flexOrder: 1,
gridRow: 1,
gridRowEnd: 1,
gridRowSpan: 1,
gridRowStart: 1,
gridColumn: 1,
gridColumnEnd: 1,
gridColumnSpan: 1,
gridColumnStart: 1,
msGridRow: 1,
msGridRowSpan: 1,
msGridColumn: 1,
msGridColumnSpan: 1,
fontWeight: 1,
lineHeight: 1,
opacity: 1,
order: 1,
orphans: 1,
tabSize: 1,
widows: 1,
zIndex: 1,
zoom: 1,
WebkitLineClamp: 1,
// SVG-related properties
fillOpacity: 1,
floodOpacity: 1,
stopOpacity: 1,
strokeDasharray: 1,
strokeDashoffset: 1,
strokeMiterlimit: 1,
strokeOpacity: 1,
strokeWidth: 1,
};
var unitless_browser_esm = unitlessKeys;
var isCustomProperty = function isCustomProperty(property) {
return property.charCodeAt(1) === 45;
};
var labelPattern = /label:\s*([^\s;\n{]+)\s*(;|$)/g;
var cursor;
var hash_browser_esm = murmur2;
function handleInterpolation(mergedProps, registered, interpolation) {
if (interpolation == null) {
return "";
}
if (interpolation.__emotion_styles !== undefined) {
if (false) {
}
return interpolation;
}
switch (typeof interpolation) {
case "boolean": {
return "";
}
case "object": {
if (interpolation.anim === 1) {
cursor = {
name: interpolation.name,
styles: interpolation.styles,
next: cursor,
};
return interpolation.name;
}
if (interpolation.styles !== undefined) {
var next = interpolation.next;
if (next !== undefined) {
// not the most efficient thing ever but this is a pretty rare case
// and there will be very few iterations of this generally
while (next !== undefined) {
cursor = {
name: next.name,
styles: next.styles,
next: cursor,
};
next = next.next;
}
}
var styles = interpolation.styles + ";";
if (false) {
}
return styles;
}
return createStringFromObject(
mergedProps,
registered,
interpolation
);
}
case "function": {
if (mergedProps !== undefined) {
var previousCursor = cursor;
var result = interpolation(mergedProps);
cursor = previousCursor;
return handleInterpolation(mergedProps, registered, result);
} else if (false) {
}
break;
}
case "string":
if (false) {
var replaced, matched;
}
break;
} // finalize string values (regular strings and functions interpolated into css calls)
if (registered == null) {
return interpolation;
}
var cached = registered[interpolation];
return cached !== undefined ? cached : interpolation;
}
export function serializeStyles(args, registered, mergedProps) {
if (
args.length === 1 &&
typeof args[0] === "object" &&
args[0] !== null &&
args[0].styles !== undefined
) {
return args[0];
}
var stringMode = true;
var styles = "";
cursor = undefined;
var strings = args[0];
if (strings == null || strings.raw === undefined) {
stringMode = false;
styles += handleInterpolation(mergedProps, registered, strings);
} else {
if (false) {
}
styles += strings[0];
} // we start at 1 since we've already handled the first arg
for (var i = 1; i < args.length; i++) {
styles += handleInterpolation(mergedProps, registered, args[i]);
if (stringMode) {
if (false) {
}
styles += strings[i];
}
}
var sourceMap;
if (false) {
} // using a global regex with .exec is stateful so lastIndex has to be reset each time
labelPattern.lastIndex = 0;
var identifierName = "";
var match; // https://esbench.com/bench/5b809c2cf2949800a0f61fb5
while ((match = labelPattern.exec(styles)) !== null) {
identifierName +=
"-" + // $FlowFixMe we know it's not null
match[1];
}
var name = hash_browser_esm(styles) + identifierName;
if (false) {
}
return {
name: name,
styles: styles,
next: cursor,
};
}
function createStringFromObject(mergedProps, registered, obj) {
var string = "";
if (Array.isArray(obj)) {
for (var i = 0; i < obj.length; i++) {
string +=
handleInterpolation(mergedProps, registered, obj[i]) + ";";
}
} else {
for (var _key in obj) {
var value = obj[_key];
if (typeof value !== "object") {
if (registered != null && registered[value] !== undefined) {
string += _key + "{" + registered[value] + "}";
} else if (isProcessableValue(value)) {
string +=
processStyleName(_key) +
":" +
processStyleValue(_key, value) +
";";
}
} else {
if (
_key === "NO_COMPONENT_SELECTOR" &&
"production" !== "production"
) {
}
if (
Array.isArray(value) &&
typeof value[0] === "string" &&
(registered == null || registered[value[0]] === undefined)
) {
for (var _i = 0; _i < value.length; _i++) {
if (isProcessableValue(value[_i])) {
string +=
processStyleName(_key) +
":" +
processStyleValue(_key, value[_i]) +
";";
}
}
} else {
var interpolated = handleInterpolation(
mergedProps,
registered,
value
);
switch (_key) {
case "animation":
case "animationName": {
string +=
processStyleName(_key) +
":" +
interpolated +
";";
break;
}
default: {
if (false) {
}
string += _key + "{" + interpolated + "}";
}
}
}
}
}
}
return string;
}
function murmur2(str) {
// 'm' and 'r' are mixing constants generated offline.
// They're not really 'magic', they just happen to work well.
// const m = 0x5bd1e995;
// const r = 24;
// Initialize the hash
var h = 0; // Mix 4 bytes at a time into the hash
var k,
i = 0,
len = str.length;
for (; len >= 4; ++i, len -= 4) {
k =
(str.charCodeAt(i) & 0xff) |
((str.charCodeAt(++i) & 0xff) << 8) |
((str.charCodeAt(++i) & 0xff) << 16) |
((str.charCodeAt(++i) & 0xff) << 24);
k =
/* Math.imul(k, m): */
(k & 0xffff) * 0x5bd1e995 + (((k >>> 16) * 0xe995) << 16);
k ^=
/* k >>> r: */
k >>> 24;
h =
/* Math.imul(k, m): */
((k & 0xffff) * 0x5bd1e995 + (((k >>> 16) * 0xe995) << 16)) ^
/* Math.imul(h, m): */
((h & 0xffff) * 0x5bd1e995 + (((h >>> 16) * 0xe995) << 16));
} // Handle the last few bytes of the input array
switch (len) {
case 3:
h ^= (str.charCodeAt(i + 2) & 0xff) << 16;
case 2:
h ^= (str.charCodeAt(i + 1) & 0xff) << 8;
case 1:
h ^= str.charCodeAt(i) & 0xff;
h =
/* Math.imul(h, m): */
(h & 0xffff) * 0x5bd1e995 + (((h >>> 16) * 0xe995) << 16);
} // Do a few final mixes of the hash to ensure the last few
// bytes are well-incorporated.
h ^= h >>> 13;
h =
/* Math.imul(h, m): */
(h & 0xffff) * 0x5bd1e995 + (((h >>> 16) * 0xe995) << 16);
return ((h ^ (h >>> 15)) >>> 0).toString(36);
}
function isProcessableValue(value) {
return value != null && typeof value !== "boolean";
}
var processStyleName = /* #__PURE__ */ emotion_memoize_browser_esm(function (
styleName
) {
return isCustomProperty(styleName)
? styleName
: styleName.replace(hyphenateRegex, "-$&").toLowerCase();
});
var processStyleValue = function processStyleValue(key, value) {
switch (key) {
case "animation":
case "animationName": {
if (typeof value === "string") {
return value.replace(animationRegex, function (match, p1, p2) {
cursor = {
name: p1,
styles: p2,
next: cursor,
};
return p1;
});
}
}
}
if (
unitless_browser_esm[key] !== 1 &&
!isCustomProperty(key) &&
typeof value === "number" &&
value !== 0
) {
return value + "px";
}
return value;
};
function memoize(fn) {
var cache = Object.create(null);
return function (arg) {
if (cache[arg] === undefined) cache[arg] = fn(arg);
return cache[arg];
};
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_minifier/tests/fixture/issues/emotion/react/2/output.js | JavaScript | /* harmony default export */ var cache, cursor, hyphenateRegex = /[A-Z]|^ms/g, animationRegex = /_EMO_([^_]+?)_([^]*?)_EMO_/g, unitless_browser_esm = {
animationIterationCount: 1,
borderImageOutset: 1,
borderImageSlice: 1,
borderImageWidth: 1,
boxFlex: 1,
boxFlexGroup: 1,
boxOrdinalGroup: 1,
columnCount: 1,
columns: 1,
flex: 1,
flexGrow: 1,
flexPositive: 1,
flexShrink: 1,
flexNegative: 1,
flexOrder: 1,
gridRow: 1,
gridRowEnd: 1,
gridRowSpan: 1,
gridRowStart: 1,
gridColumn: 1,
gridColumnEnd: 1,
gridColumnSpan: 1,
gridColumnStart: 1,
msGridRow: 1,
msGridRowSpan: 1,
msGridColumn: 1,
msGridColumnSpan: 1,
fontWeight: 1,
lineHeight: 1,
opacity: 1,
order: 1,
orphans: 1,
tabSize: 1,
widows: 1,
zIndex: 1,
zoom: 1,
WebkitLineClamp: 1,
// SVG-related properties
fillOpacity: 1,
floodOpacity: 1,
stopOpacity: 1,
strokeDasharray: 1,
strokeDashoffset: 1,
strokeMiterlimit: 1,
strokeOpacity: 1,
strokeWidth: 1
}, isCustomProperty = function(property) {
return 45 === property.charCodeAt(1);
}, labelPattern = /label:\s*([^\s;\n{]+)\s*(;|$)/g;
function handleInterpolation(mergedProps, registered, interpolation) {
if (null == interpolation) return "";
if (void 0 !== interpolation.__emotion_styles) return interpolation;
switch(typeof interpolation){
case "boolean":
return "";
case "object":
if (1 === interpolation.anim) return cursor = {
name: interpolation.name,
styles: interpolation.styles,
next: cursor
}, interpolation.name;
if (void 0 !== interpolation.styles) {
var next = interpolation.next;
if (void 0 !== next) // not the most efficient thing ever but this is a pretty rare case
// and there will be very few iterations of this generally
for(; void 0 !== next;)cursor = {
name: next.name,
styles: next.styles,
next: cursor
}, next = next.next;
return interpolation.styles + ";";
}
return function(mergedProps, registered, obj) {
var string = "";
if (Array.isArray(obj)) for(var i = 0; i < obj.length; i++)string += handleInterpolation(mergedProps, registered, obj[i]) + ";";
else for(var _key in obj){
var value = obj[_key];
if ("object" != typeof value) null != registered && void 0 !== registered[value] ? string += _key + "{" + registered[value] + "}" : isProcessableValue(value) && (string += processStyleName(_key) + ":" + processStyleValue(_key, value) + ";");
else if (Array.isArray(value) && "string" == typeof value[0] && (null == registered || void 0 === registered[value[0]])) for(var _i = 0; _i < value.length; _i++)isProcessableValue(value[_i]) && (string += processStyleName(_key) + ":" + processStyleValue(_key, value[_i]) + ";");
else {
var interpolated = handleInterpolation(mergedProps, registered, value);
switch(_key){
case "animation":
case "animationName":
string += processStyleName(_key) + ":" + interpolated + ";";
break;
default:
string += _key + "{" + interpolated + "}";
}
}
}
return string;
}(mergedProps, registered, interpolation);
case "function":
if (void 0 !== mergedProps) {
var previousCursor = cursor, result = interpolation(mergedProps);
return cursor = previousCursor, handleInterpolation(mergedProps, registered, result);
}
} // finalize string values (regular strings and functions interpolated into css calls)
if (null == registered) return interpolation;
var cached = registered[interpolation];
return void 0 !== cached ? cached : interpolation;
}
export function serializeStyles(args, registered, mergedProps) {
if (1 === args.length && "object" == typeof args[0] && null !== args[0] && void 0 !== args[0].styles) return args[0];
var match, stringMode = !0, styles = "";
cursor = void 0;
var strings = args[0];
null == strings || void 0 === strings.raw ? (stringMode = !1, styles += handleInterpolation(mergedProps, registered, strings)) : styles += strings[0]; // we start at 1 since we've already handled the first arg
for(var i = 1; i < args.length; i++)styles += handleInterpolation(mergedProps, registered, args[i]), stringMode && (styles += strings[i]);
labelPattern.lastIndex = 0;
for(var identifierName = ""; null !== (match = labelPattern.exec(styles));)identifierName += "-" + // $FlowFixMe we know it's not null
match[1];
return {
name: function(str) {
for(// 'm' and 'r' are mixing constants generated offline.
// They're not really 'magic', they just happen to work well.
// const m = 0x5bd1e995;
// const r = 24;
// Initialize the hash
var k, h = 0, i = 0, len = str.length; len >= 4; ++i, len -= 4)k = /* Math.imul(k, m): */ (0xffff & (k = 0xff & str.charCodeAt(i) | (0xff & str.charCodeAt(++i)) << 8 | (0xff & str.charCodeAt(++i)) << 16 | (0xff & str.charCodeAt(++i)) << 24)) * 0x5bd1e995 + ((k >>> 16) * 0xe995 << 16), k ^= /* k >>> r: */ k >>> 24, h = (0xffff & k) * 0x5bd1e995 + ((k >>> 16) * 0xe995 << 16) ^ /* Math.imul(h, m): */ (0xffff & h) * 0x5bd1e995 + ((h >>> 16) * 0xe995 << 16);
// Handle the last few bytes of the input array
switch(len){
case 3:
h ^= (0xff & str.charCodeAt(i + 2)) << 16;
case 2:
h ^= (0xff & str.charCodeAt(i + 1)) << 8;
case 1:
h ^= 0xff & str.charCodeAt(i), h = /* Math.imul(h, m): */ (0xffff & h) * 0x5bd1e995 + ((h >>> 16) * 0xe995 << 16);
} // Do a few final mixes of the hash to ensure the last few
return(// bytes are well-incorporated.
h ^= h >>> 13, (((h = /* Math.imul(h, m): */ (0xffff & h) * 0x5bd1e995 + ((h >>> 16) * 0xe995 << 16)) ^ h >>> 15) >>> 0).toString(36));
}(styles) + identifierName,
styles: styles,
next: cursor
};
}
function isProcessableValue(value) {
return null != value && "boolean" != typeof value;
}
var processStyleName = (cache = Object.create(null), function(arg) {
return void 0 === cache[arg] && (cache[arg] = isCustomProperty(arg) ? arg : arg.replace(hyphenateRegex, "-$&").toLowerCase()), cache[arg];
}), processStyleValue = function(key, value) {
switch(key){
case "animation":
case "animationName":
if ("string" == typeof value) return value.replace(animationRegex, function(match, p1, p2) {
return cursor = {
name: p1,
styles: p2,
next: cursor
}, p1;
});
}
return 1 === unitless_browser_esm[key] || isCustomProperty(key) || "number" != typeof value || 0 === value ? value : value + "px";
};
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_minifier/tests/fixture/issues/export/1/input.js | JavaScript | function _defineProperty(obj, key, value) {
return key in obj ? Object.defineProperty(obj, key, {
value: value,
enumerable: !0,
configurable: !0,
writable: !0
}) : obj[key] = value, obj;
}
var _obj;
export var DML_Statements = (_defineProperty(_obj = {}, PrivilegeType.DML_SELECT, "Select"), _defineProperty(_obj, PrivilegeType.DML_SELECT_SEQUENCE, "Select Sequence"), _defineProperty(_obj, PrivilegeType.DML_DELETE, "Delete"), _defineProperty(_obj, PrivilegeType.DML_INSERT, "Insert"), _defineProperty(_obj, PrivilegeType.DML_UPDATE, "Update"), _defineProperty(_obj, PrivilegeType.DML_MERGE_INTO, "Merge into"), _obj);
var _obj1;
export var DCL_Statements = (_defineProperty(_obj1 = {}, PrivilegeType.DCL_GRANT, "Grant"), _defineProperty(_obj1, PrivilegeType.DCL_REVOKE, "Revoke"), _defineProperty(_obj1, PrivilegeType.DCL_COMMIT, "Commit"), _defineProperty(_obj1, PrivilegeType.DCL_ROLLBACK, "Rollback"), _obj1);
var _obj2;
export var DDL_Statements = (_defineProperty(_obj2 = {}, PrivilegeType.DDL_DROP, "Drop"), _defineProperty(_obj2, PrivilegeType.DDL_ALTER, "Alter"), _defineProperty(_obj2, PrivilegeType.DDL_CREATE, "Create"), _defineProperty(_obj2, PrivilegeType.DDL_RENAME, "Rename"), _defineProperty(_obj2, PrivilegeType.DDL_TRUNCATE, "Truncate"), _obj2);
var _obj3;
export var ETC_Statements = (_defineProperty(_obj3 = {}, PrivilegeType.ETC_BEGIN, "Begin"), _defineProperty(_obj3, PrivilegeType.ETC_EXECUTE, "Execute"), _defineProperty(_obj3, PrivilegeType.ETC_EXPLAIN, "Explain"), _defineProperty(_obj3, PrivilegeType.ETC_OTHERS, "Etc."), _obj3);
export var AWS_REGION = [
{
value: "ap-northeast-2",
text: "Asia Pacific (Seoul)"
},
{
value: "ap-northeast-3",
text: "Asia Pacific (Osaka-Local)"
},
{
value: "ap-southeast-1",
text: "Asia Pacific (Singapore)"
},
{
value: "ap-southeast-2",
text: "Asia Pacific (Sydney)"
},
{
value: "ap-northeast-1",
text: "Asia Pacific (Tokyo)"
},
{
value: "ap-east-1",
text: "Asia Pacific (Hong Kong)"
},
{
value: "ap-south-1",
text: "Asia Pacific (Mumbai)"
},
{
value: "us-east-2",
text: "US East (Ohio)"
},
{
value: "us-east-1",
text: "US East (N. Virginia)"
},
{
value: "us-west-1",
text: "US West (N. California)"
},
{
value: "us-west-2",
text: "US West (Oregon)"
},
{
value: "af-south-1",
text: "Africa (Cape Town)"
},
{
value: "ca-central-1",
text: "Canada (Central)"
},
{
value: "cn-north-1",
text: "China (Beijing)"
},
{
value: "cn-northwest-1",
text: "China (Ningxia)"
},
{
value: "eu-central-1",
text: "Europe (Frankfurt)"
},
{
value: "eu-west-1",
text: "Europe (Ireland)"
},
{
value: "eu-west-2",
text: "Europe (London)"
},
{
value: "eu-south-1",
text: "Europe (Milan)"
},
{
value: "eu-west-3",
text: "Europe (Paris)"
},
{
value: "eu-north-1",
text: "Europe (Stockholm)"
},
{
value: "me-south-1",
text: "Middle East (Bahrain)"
},
{
value: "sa-east-1",
text: "South America (S\xe3o Paulo)"
},
];
var _obj4;
export var NotificationChannelTypes = (_defineProperty(_obj4 = {}, NotificationServiceType.HTTP, "HTTP"), _defineProperty(_obj4, NotificationServiceType.AGIT, "Agit"), _defineProperty(_obj4, NotificationServiceType.SLACK, "Slack"), _defineProperty(_obj4, NotificationServiceType.KAKAOWORK, "Kakaowork"), _obj4);
var _obj5;
export var AlertActionGroup = (_defineProperty(_obj5 = {}, ActionTypeGroup.APPROVAL, "New Request"), _defineProperty(_obj5, ActionTypeGroup.DATABASE_AUTHENTICATION, "DB Connection Attempt"), _defineProperty(_obj5, ActionTypeGroup.EXCEL_EXPORT, "Data Export"), _defineProperty(_obj5, ActionTypeGroup.SQL_EXECUTION_PREVENTED, "Prevented SQL Execution"), _defineProperty(_obj5, ActionTypeGroup.SENSITIVE_DATA, "Sensitive Data Access"), _defineProperty(_obj5, ActionTypeGroup.SQL_EXECUTION, "SQL Execution"), _obj5);
var _obj6;
export var AUDIT_ACTION_TYPE = (_defineProperty(_obj6 = {}, AuditActionType.CONNECTION, "Connection"), _defineProperty(_obj6, AuditActionType.SQL_EXECUTION, "SQL Execution"), _defineProperty(_obj6, AuditActionType.EXPORT_DATA, "Export Data"), _defineProperty(_obj6, AuditActionType.IMPORT_DATA, "Import Data"), _defineProperty(_obj6, AuditActionType.EXPORT_SCHEMA, "Export Schema"), _defineProperty(_obj6, AuditActionType.IMPORT_SCHEMA, "Import Schema"), _defineProperty(_obj6, AuditActionType.COPY_CLIPBOARD, "Copy Clipboard"), _obj6);
var _obj7;
export var ROLE_HISTORY_MODE_TYPE = (_defineProperty(_obj7 = {}, RoleHistoryModeType.USER_ADD, "User Added"), _defineProperty(_obj7, RoleHistoryModeType.USER_MOD, "User Modified"), _defineProperty(_obj7, RoleHistoryModeType.USER_REMOVE, "User Removed"), _defineProperty(_obj7, RoleHistoryModeType.GROUP_ADD, "Group Added"), _defineProperty(_obj7, RoleHistoryModeType.GROUP_MOD, "Group Modified"), _defineProperty(_obj7, RoleHistoryModeType.GROUP_REMOVE, "Group Removed"), _defineProperty(_obj7, RoleHistoryModeType.ROLE_GRANTED, "Role Granted"), _defineProperty(_obj7, RoleHistoryModeType.ROLE_REVOKED, "Role Revoked"), _defineProperty(_obj7, RoleHistoryModeType.ACL_ADD, "Access Control Granted"), _defineProperty(_obj7, RoleHistoryModeType.ACL_MOD, "Access Control Updated"), _defineProperty(_obj7, RoleHistoryModeType.ACL_REMOVE, "Access Control Revoked"), _defineProperty(_obj7, RoleHistoryModeType.ACL_EXPIRED, "Access Control Expired"), _obj7);
var _obj8;
export var HISTORY_ACTION_TYPE = (_defineProperty(_obj8 = {}, HistoryActionType.CONNECT, "Connect"), _defineProperty(_obj8, HistoryActionType.DISCONNECT, "Disconnect"), _defineProperty(_obj8, HistoryActionType.LOGIN, "User Login"), _defineProperty(_obj8, HistoryActionType.LOGOUT, "User Logout"), _defineProperty(_obj8, HistoryActionType.LOCKED, "Account Locked"), _defineProperty(_obj8, HistoryActionType.EXPIRED, "Account Expired"), _defineProperty(_obj8, HistoryActionType.LOCKED_MANUALLY, "Account Locked Manually"), _defineProperty(_obj8, HistoryActionType.UNLOCK, "Account Unlocked"), _obj8);
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_minifier/tests/fixture/issues/export/1/output.js | JavaScript | var _obj, _obj1, _obj2, _obj3, _obj4, _obj5, _obj6, _obj7, _obj8;
function _defineProperty(obj, key, value) {
return key in obj ? Object.defineProperty(obj, key, {
value: value,
enumerable: !0,
configurable: !0,
writable: !0
}) : obj[key] = value, obj;
}
export var DML_Statements = (_defineProperty(_obj = {}, PrivilegeType.DML_SELECT, "Select"), _defineProperty(_obj, PrivilegeType.DML_SELECT_SEQUENCE, "Select Sequence"), _defineProperty(_obj, PrivilegeType.DML_DELETE, "Delete"), _defineProperty(_obj, PrivilegeType.DML_INSERT, "Insert"), _defineProperty(_obj, PrivilegeType.DML_UPDATE, "Update"), _defineProperty(_obj, PrivilegeType.DML_MERGE_INTO, "Merge into"), _obj);
export var DCL_Statements = (_defineProperty(_obj1 = {}, PrivilegeType.DCL_GRANT, "Grant"), _defineProperty(_obj1, PrivilegeType.DCL_REVOKE, "Revoke"), _defineProperty(_obj1, PrivilegeType.DCL_COMMIT, "Commit"), _defineProperty(_obj1, PrivilegeType.DCL_ROLLBACK, "Rollback"), _obj1);
export var DDL_Statements = (_defineProperty(_obj2 = {}, PrivilegeType.DDL_DROP, "Drop"), _defineProperty(_obj2, PrivilegeType.DDL_ALTER, "Alter"), _defineProperty(_obj2, PrivilegeType.DDL_CREATE, "Create"), _defineProperty(_obj2, PrivilegeType.DDL_RENAME, "Rename"), _defineProperty(_obj2, PrivilegeType.DDL_TRUNCATE, "Truncate"), _obj2);
export var ETC_Statements = (_defineProperty(_obj3 = {}, PrivilegeType.ETC_BEGIN, "Begin"), _defineProperty(_obj3, PrivilegeType.ETC_EXECUTE, "Execute"), _defineProperty(_obj3, PrivilegeType.ETC_EXPLAIN, "Explain"), _defineProperty(_obj3, PrivilegeType.ETC_OTHERS, "Etc."), _obj3);
export var AWS_REGION = [
{
value: "ap-northeast-2",
text: "Asia Pacific (Seoul)"
},
{
value: "ap-northeast-3",
text: "Asia Pacific (Osaka-Local)"
},
{
value: "ap-southeast-1",
text: "Asia Pacific (Singapore)"
},
{
value: "ap-southeast-2",
text: "Asia Pacific (Sydney)"
},
{
value: "ap-northeast-1",
text: "Asia Pacific (Tokyo)"
},
{
value: "ap-east-1",
text: "Asia Pacific (Hong Kong)"
},
{
value: "ap-south-1",
text: "Asia Pacific (Mumbai)"
},
{
value: "us-east-2",
text: "US East (Ohio)"
},
{
value: "us-east-1",
text: "US East (N. Virginia)"
},
{
value: "us-west-1",
text: "US West (N. California)"
},
{
value: "us-west-2",
text: "US West (Oregon)"
},
{
value: "af-south-1",
text: "Africa (Cape Town)"
},
{
value: "ca-central-1",
text: "Canada (Central)"
},
{
value: "cn-north-1",
text: "China (Beijing)"
},
{
value: "cn-northwest-1",
text: "China (Ningxia)"
},
{
value: "eu-central-1",
text: "Europe (Frankfurt)"
},
{
value: "eu-west-1",
text: "Europe (Ireland)"
},
{
value: "eu-west-2",
text: "Europe (London)"
},
{
value: "eu-south-1",
text: "Europe (Milan)"
},
{
value: "eu-west-3",
text: "Europe (Paris)"
},
{
value: "eu-north-1",
text: "Europe (Stockholm)"
},
{
value: "me-south-1",
text: "Middle East (Bahrain)"
},
{
value: "sa-east-1",
text: "South America (S\xe3o Paulo)"
}
];
export var NotificationChannelTypes = (_defineProperty(_obj4 = {}, NotificationServiceType.HTTP, "HTTP"), _defineProperty(_obj4, NotificationServiceType.AGIT, "Agit"), _defineProperty(_obj4, NotificationServiceType.SLACK, "Slack"), _defineProperty(_obj4, NotificationServiceType.KAKAOWORK, "Kakaowork"), _obj4);
export var AlertActionGroup = (_defineProperty(_obj5 = {}, ActionTypeGroup.APPROVAL, "New Request"), _defineProperty(_obj5, ActionTypeGroup.DATABASE_AUTHENTICATION, "DB Connection Attempt"), _defineProperty(_obj5, ActionTypeGroup.EXCEL_EXPORT, "Data Export"), _defineProperty(_obj5, ActionTypeGroup.SQL_EXECUTION_PREVENTED, "Prevented SQL Execution"), _defineProperty(_obj5, ActionTypeGroup.SENSITIVE_DATA, "Sensitive Data Access"), _defineProperty(_obj5, ActionTypeGroup.SQL_EXECUTION, "SQL Execution"), _obj5);
export var AUDIT_ACTION_TYPE = (_defineProperty(_obj6 = {}, AuditActionType.CONNECTION, "Connection"), _defineProperty(_obj6, AuditActionType.SQL_EXECUTION, "SQL Execution"), _defineProperty(_obj6, AuditActionType.EXPORT_DATA, "Export Data"), _defineProperty(_obj6, AuditActionType.IMPORT_DATA, "Import Data"), _defineProperty(_obj6, AuditActionType.EXPORT_SCHEMA, "Export Schema"), _defineProperty(_obj6, AuditActionType.IMPORT_SCHEMA, "Import Schema"), _defineProperty(_obj6, AuditActionType.COPY_CLIPBOARD, "Copy Clipboard"), _obj6);
export var ROLE_HISTORY_MODE_TYPE = (_defineProperty(_obj7 = {}, RoleHistoryModeType.USER_ADD, "User Added"), _defineProperty(_obj7, RoleHistoryModeType.USER_MOD, "User Modified"), _defineProperty(_obj7, RoleHistoryModeType.USER_REMOVE, "User Removed"), _defineProperty(_obj7, RoleHistoryModeType.GROUP_ADD, "Group Added"), _defineProperty(_obj7, RoleHistoryModeType.GROUP_MOD, "Group Modified"), _defineProperty(_obj7, RoleHistoryModeType.GROUP_REMOVE, "Group Removed"), _defineProperty(_obj7, RoleHistoryModeType.ROLE_GRANTED, "Role Granted"), _defineProperty(_obj7, RoleHistoryModeType.ROLE_REVOKED, "Role Revoked"), _defineProperty(_obj7, RoleHistoryModeType.ACL_ADD, "Access Control Granted"), _defineProperty(_obj7, RoleHistoryModeType.ACL_MOD, "Access Control Updated"), _defineProperty(_obj7, RoleHistoryModeType.ACL_REMOVE, "Access Control Revoked"), _defineProperty(_obj7, RoleHistoryModeType.ACL_EXPIRED, "Access Control Expired"), _obj7);
export var HISTORY_ACTION_TYPE = (_defineProperty(_obj8 = {}, HistoryActionType.CONNECT, "Connect"), _defineProperty(_obj8, HistoryActionType.DISCONNECT, "Disconnect"), _defineProperty(_obj8, HistoryActionType.LOGIN, "User Login"), _defineProperty(_obj8, HistoryActionType.LOGOUT, "User Logout"), _defineProperty(_obj8, HistoryActionType.LOCKED, "Account Locked"), _defineProperty(_obj8, HistoryActionType.EXPIRED, "Account Expired"), _defineProperty(_obj8, HistoryActionType.LOCKED_MANUALLY, "Account Locked Manually"), _defineProperty(_obj8, HistoryActionType.UNLOCK, "Account Unlocked"), _obj8);
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_minifier/tests/fixture/issues/firebase-core/1/input.js | JavaScript | (self["webpackChunk_N_E"] = self["webpackChunk_N_E"] || []).push([
[819],
{
/***/ 4444: /***/ function (
__unused_webpack_module,
__webpack_exports__,
__webpack_require__
) {
"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ LL: function () {
return /* binding */ ErrorFactory;
},
/* harmony export */ m9: function () {
return /* binding */ getModularInstance;
},
/* harmony export */ ru: function () {
return /* binding */ isBrowserExtension;
},
/* harmony export */ d: function () {
return /* binding */ isElectron;
},
/* harmony export */ w1: function () {
return /* binding */ isIE;
},
/* harmony export */ uI: function () {
return /* binding */ isMobileCordova;
},
/* harmony export */ b$: function () {
return /* binding */ isReactNative;
},
/* harmony export */ Mn: function () {
return /* binding */ isUWP;
},
/* harmony export */
});
/* unused harmony exports CONSTANTS, Deferred, FirebaseError, MAX_VALUE_MILLIS, RANDOM_FACTOR, Sha1, areCookiesEnabled, assert, assertionError, async, base64, base64Decode, base64Encode, base64urlEncodeWithoutPadding, calculateBackoffMillis, contains, createMockUserToken, createSubscribe, decode, deepCopy, deepEqual, deepExtend, errorPrefix, extractQuerystring, getGlobal, getUA, isAdmin, isBrowser, isEmpty, isIndexedDBAvailable, isNode, isNodeSdk, isSafari, isValidFormat, isValidTimestamp, issuedAtTime, jsonEval, map, ordinal, querystring, querystringDecode, safeGet, stringLength, stringToByteArray, stringify, validateArgCount, validateCallback, validateContextObject, validateIndexedDBOpenable, validateNamespace */
/**
* @license
* Copyright 2017 Google 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.
*/
/**
* @fileoverview Firebase constants. Some of these (@defines) can be overridden at compile-time.
*/
const CONSTANTS = {
/**
* @define {boolean} Whether this is the client Node.js SDK.
*/
NODE_CLIENT: false,
/**
* @define {boolean} Whether this is the Admin Node.js SDK.
*/
NODE_ADMIN: false,
/**
* Firebase SDK Version
*/
SDK_VERSION: "${JSCORE_VERSION}",
};
/**
* @license
* Copyright 2017 Google 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.
*/
/**
* Throws an error if the provided assertion is falsy
*/
const assert = function (assertion, message) {
if (!assertion) {
throw assertionError(message);
}
};
/**
* Returns an Error object suitable for throwing.
*/
const assertionError = function (message) {
return new Error(
"Firebase Database (" +
CONSTANTS.SDK_VERSION +
") INTERNAL ASSERT FAILED: " +
message
);
};
/**
* @license
* Copyright 2017 Google 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.
*/
const stringToByteArray$1 = function (str) {
// TODO(user): Use native implementations if/when available
const out = [];
let p = 0;
for (let i = 0; i < str.length; i++) {
let c = str.charCodeAt(i);
if (c < 128) {
out[p++] = c;
} else if (c < 2048) {
out[p++] = (c >> 6) | 192;
out[p++] = (c & 63) | 128;
} else if (
(c & 0xfc00) === 0xd800 &&
i + 1 < str.length &&
(str.charCodeAt(i + 1) & 0xfc00) === 0xdc00
) {
// Surrogate Pair
c =
0x10000 +
((c & 0x03ff) << 10) +
(str.charCodeAt(++i) & 0x03ff);
out[p++] = (c >> 18) | 240;
out[p++] = ((c >> 12) & 63) | 128;
out[p++] = ((c >> 6) & 63) | 128;
out[p++] = (c & 63) | 128;
} else {
out[p++] = (c >> 12) | 224;
out[p++] = ((c >> 6) & 63) | 128;
out[p++] = (c & 63) | 128;
}
}
return out;
};
/**
* Turns an array of numbers into the string given by the concatenation of the
* characters to which the numbers correspond.
* @param bytes Array of numbers representing characters.
* @return Stringification of the array.
*/
const byteArrayToString = function (bytes) {
// TODO(user): Use native implementations if/when available
const out = [];
let pos = 0,
c = 0;
while (pos < bytes.length) {
const c1 = bytes[pos++];
if (c1 < 128) {
out[c++] = String.fromCharCode(c1);
} else if (c1 > 191 && c1 < 224) {
const c2 = bytes[pos++];
out[c++] = String.fromCharCode(
((c1 & 31) << 6) | (c2 & 63)
);
} else if (c1 > 239 && c1 < 365) {
// Surrogate Pair
const c2 = bytes[pos++];
const c3 = bytes[pos++];
const c4 = bytes[pos++];
const u =
(((c1 & 7) << 18) |
((c2 & 63) << 12) |
((c3 & 63) << 6) |
(c4 & 63)) -
0x10000;
out[c++] = String.fromCharCode(0xd800 + (u >> 10));
out[c++] = String.fromCharCode(0xdc00 + (u & 1023));
} else {
const c2 = bytes[pos++];
const c3 = bytes[pos++];
out[c++] = String.fromCharCode(
((c1 & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63)
);
}
}
return out.join("");
};
// We define it as an object literal instead of a class because a class compiled down to es5 can't
// be treeshaked. https://github.com/rollup/rollup/issues/1691
// Static lookup maps, lazily populated by init_()
const base64 = {
/**
* Maps bytes to characters.
*/
byteToCharMap_: null,
/**
* Maps characters to bytes.
*/
charToByteMap_: null,
/**
* Maps bytes to websafe characters.
* @private
*/
byteToCharMapWebSafe_: null,
/**
* Maps websafe characters to bytes.
* @private
*/
charToByteMapWebSafe_: null,
/**
* Our default alphabet, shared between
* ENCODED_VALS and ENCODED_VALS_WEBSAFE
*/
ENCODED_VALS_BASE:
"ABCDEFGHIJKLMNOPQRSTUVWXYZ" +
"abcdefghijklmnopqrstuvwxyz" +
"0123456789",
/**
* Our default alphabet. Value 64 (=) is special; it means "nothing."
*/
get ENCODED_VALS() {
return this.ENCODED_VALS_BASE + "+/=";
},
/**
* Our websafe alphabet.
*/
get ENCODED_VALS_WEBSAFE() {
return this.ENCODED_VALS_BASE + "-_.";
},
/**
* Whether this browser supports the atob and btoa functions. This extension
* started at Mozilla but is now implemented by many browsers. We use the
* ASSUME_* variables to avoid pulling in the full useragent detection library
* but still allowing the standard per-browser compilations.
*
*/
HAS_NATIVE_SUPPORT: typeof atob === "function",
/**
* Base64-encode an array of bytes.
*
* @param input An array of bytes (numbers with
* value in [0, 255]) to encode.
* @param webSafe Boolean indicating we should use the
* alternative alphabet.
* @return The base64 encoded string.
*/
encodeByteArray(input, webSafe) {
if (!Array.isArray(input)) {
throw Error(
"encodeByteArray takes an array as a parameter"
);
}
this.init_();
const byteToCharMap = webSafe
? this.byteToCharMapWebSafe_
: this.byteToCharMap_;
const output = [];
for (let i = 0; i < input.length; i += 3) {
const byte1 = input[i];
const haveByte2 = i + 1 < input.length;
const byte2 = haveByte2 ? input[i + 1] : 0;
const haveByte3 = i + 2 < input.length;
const byte3 = haveByte3 ? input[i + 2] : 0;
const outByte1 = byte1 >> 2;
const outByte2 = ((byte1 & 0x03) << 4) | (byte2 >> 4);
let outByte3 = ((byte2 & 0x0f) << 2) | (byte3 >> 6);
let outByte4 = byte3 & 0x3f;
if (!haveByte3) {
outByte4 = 64;
if (!haveByte2) {
outByte3 = 64;
}
}
output.push(
byteToCharMap[outByte1],
byteToCharMap[outByte2],
byteToCharMap[outByte3],
byteToCharMap[outByte4]
);
}
return output.join("");
},
/**
* Base64-encode a string.
*
* @param input A string to encode.
* @param webSafe If true, we should use the
* alternative alphabet.
* @return The base64 encoded string.
*/
encodeString(input, webSafe) {
// Shortcut for Mozilla browsers that implement
// a native base64 encoder in the form of "btoa/atob"
if (this.HAS_NATIVE_SUPPORT && !webSafe) {
return btoa(input);
}
return this.encodeByteArray(
stringToByteArray$1(input),
webSafe
);
},
/**
* Base64-decode a string.
*
* @param input to decode.
* @param webSafe True if we should use the
* alternative alphabet.
* @return string representing the decoded value.
*/
decodeString(input, webSafe) {
// Shortcut for Mozilla browsers that implement
// a native base64 encoder in the form of "btoa/atob"
if (this.HAS_NATIVE_SUPPORT && !webSafe) {
return atob(input);
}
return byteArrayToString(
this.decodeStringToByteArray(input, webSafe)
);
},
/**
* Base64-decode a string.
*
* In base-64 decoding, groups of four characters are converted into three
* bytes. If the encoder did not apply padding, the input length may not
* be a multiple of 4.
*
* In this case, the last group will have fewer than 4 characters, and
* padding will be inferred. If the group has one or two characters, it decodes
* to one byte. If the group has three characters, it decodes to two bytes.
*
* @param input Input to decode.
* @param webSafe True if we should use the web-safe alphabet.
* @return bytes representing the decoded value.
*/
decodeStringToByteArray(input, webSafe) {
this.init_();
const charToByteMap = webSafe
? this.charToByteMapWebSafe_
: this.charToByteMap_;
const output = [];
for (let i = 0; i < input.length; ) {
const byte1 = charToByteMap[input.charAt(i++)];
const haveByte2 = i < input.length;
const byte2 = haveByte2
? charToByteMap[input.charAt(i)]
: 0;
++i;
const haveByte3 = i < input.length;
const byte3 = haveByte3
? charToByteMap[input.charAt(i)]
: 64;
++i;
const haveByte4 = i < input.length;
const byte4 = haveByte4
? charToByteMap[input.charAt(i)]
: 64;
++i;
if (
byte1 == null ||
byte2 == null ||
byte3 == null ||
byte4 == null
) {
throw Error();
}
const outByte1 = (byte1 << 2) | (byte2 >> 4);
output.push(outByte1);
if (byte3 !== 64) {
const outByte2 =
((byte2 << 4) & 0xf0) | (byte3 >> 2);
output.push(outByte2);
if (byte4 !== 64) {
const outByte3 = ((byte3 << 6) & 0xc0) | byte4;
output.push(outByte3);
}
}
}
return output;
},
/**
* Lazy static initialization function. Called before
* accessing any of the static map variables.
* @private
*/
init_() {
if (!this.byteToCharMap_) {
this.byteToCharMap_ = {};
this.charToByteMap_ = {};
this.byteToCharMapWebSafe_ = {};
this.charToByteMapWebSafe_ = {};
// We want quick mappings back and forth, so we precompute two maps.
for (let i = 0; i < this.ENCODED_VALS.length; i++) {
this.byteToCharMap_[i] =
this.ENCODED_VALS.charAt(i);
this.charToByteMap_[this.byteToCharMap_[i]] = i;
this.byteToCharMapWebSafe_[i] =
this.ENCODED_VALS_WEBSAFE.charAt(i);
this.charToByteMapWebSafe_[
this.byteToCharMapWebSafe_[i]
] = i;
// Be forgiving when decoding and correctly decode both encodings.
if (i >= this.ENCODED_VALS_BASE.length) {
this.charToByteMap_[
this.ENCODED_VALS_WEBSAFE.charAt(i)
] = i;
this.charToByteMapWebSafe_[
this.ENCODED_VALS.charAt(i)
] = i;
}
}
}
},
};
/**
* URL-safe base64 encoding
*/
const base64Encode = function (str) {
const utf8Bytes = stringToByteArray$1(str);
return base64.encodeByteArray(utf8Bytes, true);
};
/**
* URL-safe base64 encoding (without "." padding in the end).
* e.g. Used in JSON Web Token (JWT) parts.
*/
const base64urlEncodeWithoutPadding = function (str) {
// Use base64url encoding and remove padding in the end (dot characters).
return base64Encode(str).replace(/\./g, "");
};
/**
* URL-safe base64 decoding
*
* NOTE: DO NOT use the global atob() function - it does NOT support the
* base64Url variant encoding.
*
* @param str To be decoded
* @return Decoded result, if possible
*/
const base64Decode = function (str) {
try {
return base64.decodeString(str, true);
} catch (e) {
console.error("base64Decode failed: ", e);
}
return null;
};
/**
* @license
* Copyright 2017 Google 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.
*/
/**
* Do a deep-copy of basic JavaScript Objects or Arrays.
*/
function deepCopy(value) {
return deepExtend(undefined, value);
}
/**
* Copy properties from source to target (recursively allows extension
* of Objects and Arrays). Scalar values in the target are over-written.
* If target is undefined, an object of the appropriate type will be created
* (and returned).
*
* We recursively copy all child properties of plain Objects in the source- so
* that namespace- like dictionaries are merged.
*
* Note that the target can be a function, in which case the properties in
* the source Object are copied onto it as static properties of the Function.
*
* Note: we don't merge __proto__ to prevent prototype pollution
*/
function deepExtend(target, source) {
if (!(source instanceof Object)) {
return source;
}
switch (source.constructor) {
case Date:
// Treat Dates like scalars; if the target date object had any child
// properties - they will be lost!
const dateValue = source;
return new Date(dateValue.getTime());
case Object:
if (target === undefined) {
target = {};
}
break;
case Array:
// Always copy the array source and overwrite the target.
target = [];
break;
default:
// Not a plain Object - treat it as a scalar.
return source;
}
for (const prop in source) {
// use isValidKey to guard against prototype pollution. See https://snyk.io/vuln/SNYK-JS-LODASH-450202
if (!source.hasOwnProperty(prop) || !isValidKey(prop)) {
continue;
}
target[prop] = deepExtend(target[prop], source[prop]);
}
return target;
}
function isValidKey(key) {
return key !== "__proto__";
}
/**
* @license
* Copyright 2017 Google 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.
*/
class Deferred {
constructor() {
this.reject = () => {};
this.resolve = () => {};
this.promise = new Promise((resolve, reject) => {
this.resolve = resolve;
this.reject = reject;
});
}
/**
* Our API internals are not promiseified and cannot because our callback APIs have subtle expectations around
* invoking promises inline, which Promises are forbidden to do. This method accepts an optional node-style callback
* and returns a node-style callback which will resolve or reject the Deferred's promise.
*/
wrapCallback(callback) {
return (error, value) => {
if (error) {
this.reject(error);
} else {
this.resolve(value);
}
if (typeof callback === "function") {
// Attaching noop handler just in case developer wasn't expecting
// promises
this.promise.catch(() => {});
// Some of our callbacks don't expect a value and our own tests
// assert that the parameter length is 1
if (callback.length === 1) {
callback(error);
} else {
callback(error, value);
}
}
};
}
}
/**
* @license
* Copyright 2021 Google 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.
*/
function createMockUserToken(token, projectId) {
if (token.uid) {
throw new Error(
'The "uid" field is no longer supported by mockUserToken. Please use "sub" instead for Firebase Auth User ID.'
);
}
// Unsecured JWTs use "none" as the algorithm.
const header = {
alg: "none",
type: "JWT",
};
const project = projectId || "demo-project";
const iat = token.iat || 0;
const sub = token.sub || token.user_id;
if (!sub) {
throw new Error(
"mockUserToken must contain 'sub' or 'user_id' field!"
);
}
const payload = Object.assign(
{
// Set all required fields to decent defaults
iss: `https://securetoken.google.com/${project}`,
aud: project,
iat,
exp: iat + 3600,
auth_time: iat,
sub,
user_id: sub,
firebase: {
sign_in_provider: "custom",
identities: {},
},
},
token
);
// Unsecured JWTs use the empty string as a signature.
const signature = "";
return [
base64urlEncodeWithoutPadding(JSON.stringify(header)),
base64urlEncodeWithoutPadding(JSON.stringify(payload)),
signature,
].join(".");
}
/**
* @license
* Copyright 2017 Google 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.
*/
/**
* Returns navigator.userAgent string or '' if it's not defined.
* @return user agent string
*/
function getUA() {
if (
typeof navigator !== "undefined" &&
typeof navigator["userAgent"] === "string"
) {
return navigator["userAgent"];
} else {
return "";
}
}
/**
* Detect Cordova / PhoneGap / Ionic frameworks on a mobile device.
*
* Deliberately does not rely on checking `file://` URLs (as this fails PhoneGap
* in the Ripple emulator) nor Cordova `onDeviceReady`, which would normally
* wait for a callback.
*/
function isMobileCordova() {
return (
typeof window !== "undefined" &&
// @ts-ignore Setting up an broadly applicable index signature for Window
// just to deal with this case would probably be a bad idea.
!!(
window["cordova"] ||
window["phonegap"] ||
window["PhoneGap"]
) &&
/ios|iphone|ipod|ipad|android|blackberry|iemobile/i.test(
getUA()
)
);
}
/**
* Detect Node.js.
*
* @return true if Node.js environment is detected.
*/
// Node detection logic from: https://github.com/iliakan/detect-node/
function isNode() {
try {
return (
Object.prototype.toString.call(
__webpack_require__.g.process
) === "[object process]"
);
} catch (e) {
return false;
}
}
/**
* Detect Browser Environment
*/
function isBrowser() {
return typeof self === "object" && self.self === self;
}
function isBrowserExtension() {
const runtime =
typeof chrome === "object"
? chrome.runtime
: typeof browser === "object"
? browser.runtime
: undefined;
return typeof runtime === "object" && runtime.id !== undefined;
}
/**
* Detect React Native.
*
* @return true if ReactNative environment is detected.
*/
function isReactNative() {
return (
typeof navigator === "object" &&
navigator["product"] === "ReactNative"
);
}
/** Detects Electron apps. */
function isElectron() {
return getUA().indexOf("Electron/") >= 0;
}
/** Detects Internet Explorer. */
function isIE() {
const ua = getUA();
return ua.indexOf("MSIE ") >= 0 || ua.indexOf("Trident/") >= 0;
}
/** Detects Universal Windows Platform apps. */
function isUWP() {
return getUA().indexOf("MSAppHost/") >= 0;
}
/**
* Detect whether the current SDK build is the Node version.
*
* @return true if it's the Node SDK build.
*/
function isNodeSdk() {
return (
CONSTANTS.NODE_CLIENT === true ||
CONSTANTS.NODE_ADMIN === true
);
}
/** Returns true if we are running in Safari. */
function isSafari() {
return (
!isNode() &&
navigator.userAgent.includes("Safari") &&
!navigator.userAgent.includes("Chrome")
);
}
/**
* This method checks if indexedDB is supported by current browser/service worker context
* @return true if indexedDB is supported by current browser/service worker context
*/
function isIndexedDBAvailable() {
return typeof indexedDB === "object";
}
/**
* This method validates browser/sw context for indexedDB by opening a dummy indexedDB database and reject
* if errors occur during the database open operation.
*
* @throws exception if current browser/sw context can't run idb.open (ex: Safari iframe, Firefox
* private browsing)
*/
function validateIndexedDBOpenable() {
return new Promise((resolve, reject) => {
try {
let preExist = true;
const DB_CHECK_NAME =
"validate-browser-context-for-indexeddb-analytics-module";
const request = self.indexedDB.open(DB_CHECK_NAME);
request.onsuccess = () => {
request.result.close();
// delete database only when it doesn't pre-exist
if (!preExist) {
self.indexedDB.deleteDatabase(DB_CHECK_NAME);
}
resolve(true);
};
request.onupgradeneeded = () => {
preExist = false;
};
request.onerror = () => {
var _a;
reject(
((_a = request.error) === null || _a === void 0
? void 0
: _a.message) || ""
);
};
} catch (error) {
reject(error);
}
});
}
/**
*
* This method checks whether cookie is enabled within current browser
* @return true if cookie is enabled within current browser
*/
function areCookiesEnabled() {
if (
typeof navigator === "undefined" ||
!navigator.cookieEnabled
) {
return false;
}
return true;
}
/**
* Polyfill for `globalThis` object.
* @returns the `globalThis` object for the given environment.
*/
function getGlobal() {
if (typeof self !== "undefined") {
return self;
}
if (typeof window !== "undefined") {
return window;
}
if (typeof __webpack_require__.g !== "undefined") {
return __webpack_require__.g;
}
throw new Error("Unable to locate global object.");
}
/**
* @license
* Copyright 2017 Google 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.
*/
/**
* @fileoverview Standardized Firebase Error.
*
* Usage:
*
* // Typescript string literals for type-safe codes
* type Err =
* 'unknown' |
* 'object-not-found'
* ;
*
* // Closure enum for type-safe error codes
* // at-enum {string}
* var Err = {
* UNKNOWN: 'unknown',
* OBJECT_NOT_FOUND: 'object-not-found',
* }
*
* let errors: Map<Err, string> = {
* 'generic-error': "Unknown error",
* 'file-not-found': "Could not find file: {$file}",
* };
*
* // Type-safe function - must pass a valid error code as param.
* let error = new ErrorFactory<Err>('service', 'Service', errors);
*
* ...
* throw error.create(Err.GENERIC);
* ...
* throw error.create(Err.FILE_NOT_FOUND, {'file': fileName});
* ...
* // Service: Could not file file: foo.txt (service/file-not-found).
*
* catch (e) {
* assert(e.message === "Could not find file: foo.txt.");
* if (e.code === 'service/file-not-found') {
* console.log("Could not read file: " + e['file']);
* }
* }
*/
const ERROR_NAME = "FirebaseError";
// Based on code from:
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error#Custom_Error_Types
class FirebaseError extends Error {
constructor(code, message, customData) {
super(message);
this.code = code;
this.customData = customData;
this.name = ERROR_NAME;
// Fix For ES5
// https://github.com/Microsoft/TypeScript-wiki/blob/master/Breaking-Changes.md#extending-built-ins-like-error-array-and-map-may-no-longer-work
Object.setPrototypeOf(this, FirebaseError.prototype);
// Maintains proper stack trace for where our error was thrown.
// Only available on V8.
if (Error.captureStackTrace) {
Error.captureStackTrace(
this,
ErrorFactory.prototype.create
);
}
}
}
class ErrorFactory {
constructor(service, serviceName, errors) {
this.service = service;
this.serviceName = serviceName;
this.errors = errors;
}
create(code, ...data) {
const customData = data[0] || {};
const fullCode = `${this.service}/${code}`;
const template = this.errors[code];
const message = template
? replaceTemplate(template, customData)
: "Error";
// Service Name: Error message (service/code).
const fullMessage = `${this.serviceName}: ${message} (${fullCode}).`;
const error = new FirebaseError(
fullCode,
fullMessage,
customData
);
return error;
}
}
function replaceTemplate(template, data) {
return template.replace(PATTERN, (_, key) => {
const value = data[key];
return value != null ? String(value) : `<${key}?>`;
});
}
const PATTERN = /\{\$([^}]+)}/g;
/**
* @license
* Copyright 2017 Google 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.
*/
/**
* Evaluates a JSON string into a javascript object.
*
* @param {string} str A string containing JSON.
* @return {*} The javascript object representing the specified JSON.
*/
function jsonEval(str) {
return JSON.parse(str);
}
/**
* Returns JSON representing a javascript object.
* @param {*} data Javascript object to be stringified.
* @return {string} The JSON contents of the object.
*/
function stringify(data) {
return JSON.stringify(data);
}
/**
* @license
* Copyright 2017 Google 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.
*/
/**
* Decodes a Firebase auth. token into constituent parts.
*
* Notes:
* - May return with invalid / incomplete claims if there's no native base64 decoding support.
* - Doesn't check if the token is actually valid.
*/
const decode = function (token) {
let header = {},
claims = {},
data = {},
signature = "";
try {
const parts = token.split(".");
header = jsonEval(base64Decode(parts[0]) || "");
claims = jsonEval(base64Decode(parts[1]) || "");
signature = parts[2];
data = claims["d"] || {};
delete claims["d"];
} catch (e) {}
return {
header,
claims,
data,
signature,
};
};
/**
* Decodes a Firebase auth. token and checks the validity of its time-based claims. Will return true if the
* token is within the time window authorized by the 'nbf' (not-before) and 'iat' (issued-at) claims.
*
* Notes:
* - May return a false negative if there's no native base64 decoding support.
* - Doesn't check if the token is actually valid.
*/
const isValidTimestamp = function (token) {
const claims = decode(token).claims;
const now = Math.floor(new Date().getTime() / 1000);
let validSince = 0,
validUntil = 0;
if (typeof claims === "object") {
if (claims.hasOwnProperty("nbf")) {
validSince = claims["nbf"];
} else if (claims.hasOwnProperty("iat")) {
validSince = claims["iat"];
}
if (claims.hasOwnProperty("exp")) {
validUntil = claims["exp"];
} else {
// token will expire after 24h by default
validUntil = validSince + 86400;
}
}
return (
!!now &&
!!validSince &&
!!validUntil &&
now >= validSince &&
now <= validUntil
);
};
/**
* Decodes a Firebase auth. token and returns its issued at time if valid, null otherwise.
*
* Notes:
* - May return null if there's no native base64 decoding support.
* - Doesn't check if the token is actually valid.
*/
const issuedAtTime = function (token) {
const claims = decode(token).claims;
if (
typeof claims === "object" &&
claims.hasOwnProperty("iat")
) {
return claims["iat"];
}
return null;
};
/**
* Decodes a Firebase auth. token and checks the validity of its format. Expects a valid issued-at time.
*
* Notes:
* - May return a false negative if there's no native base64 decoding support.
* - Doesn't check if the token is actually valid.
*/
const isValidFormat = function (token) {
const decoded = decode(token),
claims = decoded.claims;
return (
!!claims &&
typeof claims === "object" &&
claims.hasOwnProperty("iat")
);
};
/**
* Attempts to peer into an auth token and determine if it's an admin auth token by looking at the claims portion.
*
* Notes:
* - May return a false negative if there's no native base64 decoding support.
* - Doesn't check if the token is actually valid.
*/
const isAdmin = function (token) {
const claims = decode(token).claims;
return typeof claims === "object" && claims["admin"] === true;
};
/**
* @license
* Copyright 2017 Google 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.
*/
function contains(obj, key) {
return Object.prototype.hasOwnProperty.call(obj, key);
}
function safeGet(obj, key) {
if (Object.prototype.hasOwnProperty.call(obj, key)) {
return obj[key];
} else {
return undefined;
}
}
function isEmpty(obj) {
for (const key in obj) {
if (Object.prototype.hasOwnProperty.call(obj, key)) {
return false;
}
}
return true;
}
function map(obj, fn, contextObj) {
const res = {};
for (const key in obj) {
if (Object.prototype.hasOwnProperty.call(obj, key)) {
res[key] = fn.call(contextObj, obj[key], key, obj);
}
}
return res;
}
/**
* Deep equal two objects. Support Arrays and Objects.
*/
function deepEqual(a, b) {
if (a === b) {
return true;
}
const aKeys = Object.keys(a);
const bKeys = Object.keys(b);
for (const k of aKeys) {
if (!bKeys.includes(k)) {
return false;
}
const aProp = a[k];
const bProp = b[k];
if (isObject(aProp) && isObject(bProp)) {
if (!deepEqual(aProp, bProp)) {
return false;
}
} else if (aProp !== bProp) {
return false;
}
}
for (const k of bKeys) {
if (!aKeys.includes(k)) {
return false;
}
}
return true;
}
function isObject(thing) {
return thing !== null && typeof thing === "object";
}
/**
* @license
* Copyright 2017 Google 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.
*/
/**
* Returns a querystring-formatted string (e.g. &arg=val&arg2=val2) from a
* params object (e.g. {arg: 'val', arg2: 'val2'})
* Note: You must prepend it with ? when adding it to a URL.
*/
function querystring(querystringParams) {
const params = [];
for (const [key, value] of Object.entries(querystringParams)) {
if (Array.isArray(value)) {
value.forEach((arrayVal) => {
params.push(
encodeURIComponent(key) +
"=" +
encodeURIComponent(arrayVal)
);
});
} else {
params.push(
encodeURIComponent(key) +
"=" +
encodeURIComponent(value)
);
}
}
return params.length ? "&" + params.join("&") : "";
}
/**
* Decodes a querystring (e.g. ?arg=val&arg2=val2) into a params object
* (e.g. {arg: 'val', arg2: 'val2'})
*/
function querystringDecode(querystring) {
const obj = {};
const tokens = querystring.replace(/^\?/, "").split("&");
tokens.forEach((token) => {
if (token) {
const [key, value] = token.split("=");
obj[decodeURIComponent(key)] =
decodeURIComponent(value);
}
});
return obj;
}
/**
* Extract the query string part of a URL, including the leading question mark (if present).
*/
function extractQuerystring(url) {
const queryStart = url.indexOf("?");
if (!queryStart) {
return "";
}
const fragmentStart = url.indexOf("#", queryStart);
return url.substring(
queryStart,
fragmentStart > 0 ? fragmentStart : undefined
);
}
/**
* @license
* Copyright 2017 Google 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.
*/
/**
* @fileoverview SHA-1 cryptographic hash.
* Variable names follow the notation in FIPS PUB 180-3:
* http://csrc.nist.gov/publications/fips/fips180-3/fips180-3_final.pdf.
*
* Usage:
* var sha1 = new sha1();
* sha1.update(bytes);
* var hash = sha1.digest();
*
* Performance:
* Chrome 23: ~400 Mbit/s
* Firefox 16: ~250 Mbit/s
*
*/
/**
* SHA-1 cryptographic hash constructor.
*
* The properties declared here are discussed in the above algorithm document.
* @constructor
* @final
* @struct
*/
class Sha1 {
constructor() {
/**
* Holds the previous values of accumulated variables a-e in the compress_
* function.
* @private
*/
this.chain_ = [];
/**
* A buffer holding the partially computed hash result.
* @private
*/
this.buf_ = [];
/**
* An array of 80 bytes, each a part of the message to be hashed. Referred to
* as the message schedule in the docs.
* @private
*/
this.W_ = [];
/**
* Contains data needed to pad messages less than 64 bytes.
* @private
*/
this.pad_ = [];
/**
* @private {number}
*/
this.inbuf_ = 0;
/**
* @private {number}
*/
this.total_ = 0;
this.blockSize = 512 / 8;
this.pad_[0] = 128;
for (let i = 1; i < this.blockSize; ++i) {
this.pad_[i] = 0;
}
this.reset();
}
reset() {
this.chain_[0] = 0x67452301;
this.chain_[1] = 0xefcdab89;
this.chain_[2] = 0x98badcfe;
this.chain_[3] = 0x10325476;
this.chain_[4] = 0xc3d2e1f0;
this.inbuf_ = 0;
this.total_ = 0;
}
/**
* Internal compress helper function.
* @param buf Block to compress.
* @param offset Offset of the block in the buffer.
* @private
*/
compress_(buf, offset) {
if (!offset) {
offset = 0;
}
const W = this.W_;
// get 16 big endian words
if (typeof buf === "string") {
for (let i = 0; i < 16; i++) {
// TODO(user): [bug 8140122] Recent versions of Safari for Mac OS and iOS
// have a bug that turns the post-increment ++ operator into pre-increment
// during JIT compilation. We have code that depends heavily on SHA-1 for
// correctness and which is affected by this bug, so I've removed all uses
// of post-increment ++ in which the result value is used. We can revert
// this change once the Safari bug
// (https://bugs.webkit.org/show_bug.cgi?id=109036) has been fixed and
// most clients have been updated.
W[i] =
(buf.charCodeAt(offset) << 24) |
(buf.charCodeAt(offset + 1) << 16) |
(buf.charCodeAt(offset + 2) << 8) |
buf.charCodeAt(offset + 3);
offset += 4;
}
} else {
for (let i = 0; i < 16; i++) {
W[i] =
(buf[offset] << 24) |
(buf[offset + 1] << 16) |
(buf[offset + 2] << 8) |
buf[offset + 3];
offset += 4;
}
}
// expand to 80 words
for (let i = 16; i < 80; i++) {
const t = W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16];
W[i] = ((t << 1) | (t >>> 31)) & 0xffffffff;
}
let a = this.chain_[0];
let b = this.chain_[1];
let c = this.chain_[2];
let d = this.chain_[3];
let e = this.chain_[4];
let f, k;
// TODO(user): Try to unroll this loop to speed up the computation.
for (let i = 0; i < 80; i++) {
if (i < 40) {
if (i < 20) {
f = d ^ (b & (c ^ d));
k = 0x5a827999;
} else {
f = b ^ c ^ d;
k = 0x6ed9eba1;
}
} else {
if (i < 60) {
f = (b & c) | (d & (b | c));
k = 0x8f1bbcdc;
} else {
f = b ^ c ^ d;
k = 0xca62c1d6;
}
}
const t =
(((a << 5) | (a >>> 27)) + f + e + k + W[i]) &
0xffffffff;
e = d;
d = c;
c = ((b << 30) | (b >>> 2)) & 0xffffffff;
b = a;
a = t;
}
this.chain_[0] = (this.chain_[0] + a) & 0xffffffff;
this.chain_[1] = (this.chain_[1] + b) & 0xffffffff;
this.chain_[2] = (this.chain_[2] + c) & 0xffffffff;
this.chain_[3] = (this.chain_[3] + d) & 0xffffffff;
this.chain_[4] = (this.chain_[4] + e) & 0xffffffff;
}
update(bytes, length) {
// TODO(johnlenz): tighten the function signature and remove this check
if (bytes == null) {
return;
}
if (length === undefined) {
length = bytes.length;
}
const lengthMinusBlock = length - this.blockSize;
let n = 0;
// Using local instead of member variables gives ~5% speedup on Firefox 16.
const buf = this.buf_;
let inbuf = this.inbuf_;
// The outer while loop should execute at most twice.
while (n < length) {
// When we have no data in the block to top up, we can directly process the
// input buffer (assuming it contains sufficient data). This gives ~25%
// speedup on Chrome 23 and ~15% speedup on Firefox 16, but requires that
// the data is provided in large chunks (or in multiples of 64 bytes).
if (inbuf === 0) {
while (n <= lengthMinusBlock) {
this.compress_(bytes, n);
n += this.blockSize;
}
}
if (typeof bytes === "string") {
while (n < length) {
buf[inbuf] = bytes.charCodeAt(n);
++inbuf;
++n;
if (inbuf === this.blockSize) {
this.compress_(buf);
inbuf = 0;
// Jump to the outer loop so we use the full-block optimization.
break;
}
}
} else {
while (n < length) {
buf[inbuf] = bytes[n];
++inbuf;
++n;
if (inbuf === this.blockSize) {
this.compress_(buf);
inbuf = 0;
// Jump to the outer loop so we use the full-block optimization.
break;
}
}
}
}
this.inbuf_ = inbuf;
this.total_ += length;
}
/** @override */
digest() {
const digest = [];
let totalBits = this.total_ * 8;
// Add pad 0x80 0x00*.
if (this.inbuf_ < 56) {
this.update(this.pad_, 56 - this.inbuf_);
} else {
this.update(
this.pad_,
this.blockSize - (this.inbuf_ - 56)
);
}
// Add # bits.
for (let i = this.blockSize - 1; i >= 56; i--) {
this.buf_[i] = totalBits & 255;
totalBits /= 256; // Don't use bit-shifting here!
}
this.compress_(this.buf_);
let n = 0;
for (let i = 0; i < 5; i++) {
for (let j = 24; j >= 0; j -= 8) {
digest[n] = (this.chain_[i] >> j) & 255;
++n;
}
}
return digest;
}
}
/**
* Helper to make a Subscribe function (just like Promise helps make a
* Thenable).
*
* @param executor Function which can make calls to a single Observer
* as a proxy.
* @param onNoObservers Callback when count of Observers goes to zero.
*/
function createSubscribe(executor, onNoObservers) {
const proxy = new ObserverProxy(executor, onNoObservers);
return proxy.subscribe.bind(proxy);
}
/**
* Implement fan-out for any number of Observers attached via a subscribe
* function.
*/
class ObserverProxy {
/**
* @param executor Function which can make calls to a single Observer
* as a proxy.
* @param onNoObservers Callback when count of Observers goes to zero.
*/
constructor(executor, onNoObservers) {
this.observers = [];
this.unsubscribes = [];
this.observerCount = 0;
// Micro-task scheduling by calling task.then().
this.task = Promise.resolve();
this.finalized = false;
this.onNoObservers = onNoObservers;
// Call the executor asynchronously so subscribers that are called
// synchronously after the creation of the subscribe function
// can still receive the very first value generated in the executor.
this.task
.then(() => {
executor(this);
})
.catch((e) => {
this.error(e);
});
}
next(value) {
this.forEachObserver((observer) => {
observer.next(value);
});
}
error(error) {
this.forEachObserver((observer) => {
observer.error(error);
});
this.close(error);
}
complete() {
this.forEachObserver((observer) => {
observer.complete();
});
this.close();
}
/**
* Subscribe function that can be used to add an Observer to the fan-out list.
*
* - We require that no event is sent to a subscriber sychronously to their
* call to subscribe().
*/
subscribe(nextOrObserver, error, complete) {
let observer;
if (
nextOrObserver === undefined &&
error === undefined &&
complete === undefined
) {
throw new Error("Missing Observer.");
}
// Assemble an Observer object when passed as callback functions.
if (
implementsAnyMethods(nextOrObserver, [
"next",
"error",
"complete",
])
) {
observer = nextOrObserver;
} else {
observer = {
next: nextOrObserver,
error,
complete,
};
}
if (observer.next === undefined) {
observer.next = noop;
}
if (observer.error === undefined) {
observer.error = noop;
}
if (observer.complete === undefined) {
observer.complete = noop;
}
const unsub = this.unsubscribeOne.bind(
this,
this.observers.length
);
// Attempt to subscribe to a terminated Observable - we
// just respond to the Observer with the final error or complete
// event.
if (this.finalized) {
// eslint-disable-next-line @typescript-eslint/no-floating-promises
this.task.then(() => {
try {
if (this.finalError) {
observer.error(this.finalError);
} else {
observer.complete();
}
} catch (e) {
// nothing
}
return;
});
}
this.observers.push(observer);
return unsub;
}
// Unsubscribe is synchronous - we guarantee that no events are sent to
// any unsubscribed Observer.
unsubscribeOne(i) {
if (
this.observers === undefined ||
this.observers[i] === undefined
) {
return;
}
delete this.observers[i];
this.observerCount -= 1;
if (
this.observerCount === 0 &&
this.onNoObservers !== undefined
) {
this.onNoObservers(this);
}
}
forEachObserver(fn) {
if (this.finalized) {
// Already closed by previous event....just eat the additional values.
return;
}
// Since sendOne calls asynchronously - there is no chance that
// this.observers will become undefined.
for (let i = 0; i < this.observers.length; i++) {
this.sendOne(i, fn);
}
}
// Call the Observer via one of it's callback function. We are careful to
// confirm that the observe has not been unsubscribed since this asynchronous
// function had been queued.
sendOne(i, fn) {
// Execute the callback asynchronously
// eslint-disable-next-line @typescript-eslint/no-floating-promises
this.task.then(() => {
if (
this.observers !== undefined &&
this.observers[i] !== undefined
) {
try {
fn(this.observers[i]);
} catch (e) {
// Ignore exceptions raised in Observers or missing methods of an
// Observer.
// Log error to console. b/31404806
if (
typeof console !== "undefined" &&
console.error
) {
console.error(e);
}
}
}
});
}
close(err) {
if (this.finalized) {
return;
}
this.finalized = true;
if (err !== undefined) {
this.finalError = err;
}
// Proxy is no longer needed - garbage collect references
// eslint-disable-next-line @typescript-eslint/no-floating-promises
this.task.then(() => {
this.observers = undefined;
this.onNoObservers = undefined;
});
}
}
/** Turn synchronous function into one called asynchronously. */
// eslint-disable-next-line @typescript-eslint/ban-types
function async(fn, onError) {
return (...args) => {
Promise.resolve(true)
.then(() => {
fn(...args);
})
.catch((error) => {
if (onError) {
onError(error);
}
});
};
}
/**
* Return true if the object passed in implements any of the named methods.
*/
function implementsAnyMethods(obj, methods) {
if (typeof obj !== "object" || obj === null) {
return false;
}
for (const method of methods) {
if (method in obj && typeof obj[method] === "function") {
return true;
}
}
return false;
}
function noop() {
// do nothing
}
/**
* @license
* Copyright 2017 Google 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.
*/
/**
* Check to make sure the appropriate number of arguments are provided for a public function.
* Throws an error if it fails.
*
* @param fnName The function name
* @param minCount The minimum number of arguments to allow for the function call
* @param maxCount The maximum number of argument to allow for the function call
* @param argCount The actual number of arguments provided.
*/
const validateArgCount = function (
fnName,
minCount,
maxCount,
argCount
) {
let argError;
if (argCount < minCount) {
argError = "at least " + minCount;
} else if (argCount > maxCount) {
argError =
maxCount === 0 ? "none" : "no more than " + maxCount;
}
if (argError) {
const error =
fnName +
" failed: Was called with " +
argCount +
(argCount === 1 ? " argument." : " arguments.") +
" Expects " +
argError +
".";
throw new Error(error);
}
};
/**
* Generates a string to prefix an error message about failed argument validation
*
* @param fnName The function name
* @param argName The name of the argument
* @return The prefix to add to the error thrown for validation.
*/
function errorPrefix(fnName, argName) {
return `${fnName} failed: ${argName} argument `;
}
/**
* @param fnName
* @param argumentNumber
* @param namespace
* @param optional
*/
function validateNamespace(fnName, namespace, optional) {
if (optional && !namespace) {
return;
}
if (typeof namespace !== "string") {
//TODO: I should do more validation here. We only allow certain chars in namespaces.
throw new Error(
errorPrefix(fnName, "namespace") +
"must be a valid firebase namespace."
);
}
}
function validateCallback(
fnName,
argumentName,
// eslint-disable-next-line @typescript-eslint/ban-types
callback,
optional
) {
if (optional && !callback) {
return;
}
if (typeof callback !== "function") {
throw new Error(
errorPrefix(fnName, argumentName) +
"must be a valid function."
);
}
}
function validateContextObject(
fnName,
argumentName,
context,
optional
) {
if (optional && !context) {
return;
}
if (typeof context !== "object" || context === null) {
throw new Error(
errorPrefix(fnName, argumentName) +
"must be a valid context object."
);
}
}
/**
* @license
* Copyright 2017 Google 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.
*/
// Code originally came from goog.crypt.stringToUtf8ByteArray, but for some reason they
// automatically replaced '\r\n' with '\n', and they didn't handle surrogate pairs,
// so it's been modified.
// Note that not all Unicode characters appear as single characters in JavaScript strings.
// fromCharCode returns the UTF-16 encoding of a character - so some Unicode characters
// use 2 characters in Javascript. All 4-byte UTF-8 characters begin with a first
// character in the range 0xD800 - 0xDBFF (the first character of a so-called surrogate
// pair).
// See http://www.ecma-international.org/ecma-262/5.1/#sec-15.1.3
/**
* @param {string} str
* @return {Array}
*/
const stringToByteArray = function (str) {
const out = [];
let p = 0;
for (let i = 0; i < str.length; i++) {
let c = str.charCodeAt(i);
// Is this the lead surrogate in a surrogate pair?
if (c >= 0xd800 && c <= 0xdbff) {
const high = c - 0xd800; // the high 10 bits.
i++;
assert(
i < str.length,
"Surrogate pair missing trail surrogate."
);
const low = str.charCodeAt(i) - 0xdc00; // the low 10 bits.
c = 0x10000 + (high << 10) + low;
}
if (c < 128) {
out[p++] = c;
} else if (c < 2048) {
out[p++] = (c >> 6) | 192;
out[p++] = (c & 63) | 128;
} else if (c < 65536) {
out[p++] = (c >> 12) | 224;
out[p++] = ((c >> 6) & 63) | 128;
out[p++] = (c & 63) | 128;
} else {
out[p++] = (c >> 18) | 240;
out[p++] = ((c >> 12) & 63) | 128;
out[p++] = ((c >> 6) & 63) | 128;
out[p++] = (c & 63) | 128;
}
}
return out;
};
/**
* Calculate length without actually converting; useful for doing cheaper validation.
* @param {string} str
* @return {number}
*/
const stringLength = function (str) {
let p = 0;
for (let i = 0; i < str.length; i++) {
const c = str.charCodeAt(i);
if (c < 128) {
p++;
} else if (c < 2048) {
p += 2;
} else if (c >= 0xd800 && c <= 0xdbff) {
// Lead surrogate of a surrogate pair. The pair together will take 4 bytes to represent.
p += 4;
i++; // skip trail surrogate.
} else {
p += 3;
}
}
return p;
};
/**
* @license
* Copyright 2019 Google 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.
*/
/**
* The amount of milliseconds to exponentially increase.
*/
const DEFAULT_INTERVAL_MILLIS = 1000;
/**
* The factor to backoff by.
* Should be a number greater than 1.
*/
const DEFAULT_BACKOFF_FACTOR = 2;
/**
* The maximum milliseconds to increase to.
*
* <p>Visible for testing
*/
const MAX_VALUE_MILLIS =
/* unused pure expression or super */ null &&
4 * 60 * 60 * 1000; // Four hours, like iOS and Android.
/**
* The percentage of backoff time to randomize by.
* See
* http://go/safe-client-behavior#step-1-determine-the-appropriate-retry-interval-to-handle-spike-traffic
* for context.
*
* <p>Visible for testing
*/
const RANDOM_FACTOR = 0.5;
/**
* Based on the backoff method from
* https://github.com/google/closure-library/blob/master/closure/goog/math/exponentialbackoff.js.
* Extracted here so we don't need to pass metadata and a stateful ExponentialBackoff object around.
*/
function calculateBackoffMillis(
backoffCount,
intervalMillis = DEFAULT_INTERVAL_MILLIS,
backoffFactor = DEFAULT_BACKOFF_FACTOR
) {
// Calculates an exponentially increasing value.
// Deviation: calculates value from count and a constant interval, so we only need to save value
// and count to restore state.
const currBaseValue =
intervalMillis * Math.pow(backoffFactor, backoffCount);
// A random "fuzz" to avoid waves of retries.
// Deviation: randomFactor is required.
const randomWait = Math.round(
// A fraction of the backoff value to add/subtract.
// Deviation: changes multiplication order to improve readability.
RANDOM_FACTOR *
currBaseValue *
// A random float (rounded to int by Math.round above) in the range [-1, 1]. Determines
// if we add or subtract.
(Math.random() - 0.5) *
2
);
// Limits backoff to max to avoid effectively permanent backoff.
return Math.min(MAX_VALUE_MILLIS, currBaseValue + randomWait);
}
/**
* @license
* Copyright 2020 Google 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.
*/
/**
* Provide English ordinal letters after a number
*/
function ordinal(i) {
if (!Number.isFinite(i)) {
return `${i}`;
}
return i + indicator(i);
}
function indicator(i) {
i = Math.abs(i);
const cent = i % 100;
if (cent >= 10 && cent <= 20) {
return "th";
}
const dec = i % 10;
if (dec === 1) {
return "st";
}
if (dec === 2) {
return "nd";
}
if (dec === 3) {
return "rd";
}
return "th";
}
/**
* @license
* Copyright 2021 Google 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.
*/
function getModularInstance(service) {
if (service && service._delegate) {
return service._delegate;
} else {
return service;
}
}
//# sourceMappingURL=index.esm2017.js.map
/***/
},
/***/ 3510: /***/ function (
__unused_webpack_module,
__webpack_exports__,
__webpack_require__
) {
"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ jK: function () {
return /* binding */ ErrorCode;
},
/* harmony export */ ju: function () {
return /* binding */ Event;
},
/* harmony export */ tw: function () {
return /* binding */ EventType;
},
/* harmony export */ zI: function () {
return /* binding */ FetchXmlHttpFactory;
},
/* harmony export */ kN: function () {
return /* binding */ Stat;
},
/* harmony export */ ii: function () {
return /* binding */ WebChannel;
},
/* harmony export */ JJ: function () {
return /* binding */ XhrIo;
},
/* harmony export */ UE: function () {
return /* binding */ createWebChannelTransport;
},
/* harmony export */ FJ: function () {
return /* binding */ getStatEventTarget;
},
/* harmony export */
});
/* unused harmony export default */
var commonjsGlobal =
typeof globalThis !== "undefined"
? globalThis
: typeof window !== "undefined"
? window
: typeof __webpack_require__.g !== "undefined"
? __webpack_require__.g
: typeof self !== "undefined"
? self
: {};
var esm = {};
/*
Copyright The Closure Library Authors.
SPDX-License-Identifier: Apache-2.0
*/
var k,
goog = goog || {},
l = commonjsGlobal || self;
function aa() {}
function ba(a) {
var b = typeof a;
b =
"object" != b
? b
: a
? Array.isArray(a)
? "array"
: b
: "null";
return (
"array" == b ||
("object" == b && "number" == typeof a.length)
);
}
function p(a) {
var b = typeof a;
return ("object" == b && null != a) || "function" == b;
}
function da(a) {
return (
(Object.prototype.hasOwnProperty.call(a, ea) && a[ea]) ||
(a[ea] = ++fa)
);
}
var ea = "closure_uid_" + ((1e9 * Math.random()) >>> 0),
fa = 0;
function ha(a, b, c) {
return a.call.apply(a.bind, arguments);
}
function ia(a, b, c) {
if (!a) throw Error();
if (2 < arguments.length) {
var d = Array.prototype.slice.call(arguments, 2);
return function () {
var e = Array.prototype.slice.call(arguments);
Array.prototype.unshift.apply(e, d);
return a.apply(b, e);
};
}
return function () {
return a.apply(b, arguments);
};
}
function q(a, b, c) {
Function.prototype.bind &&
-1 != Function.prototype.bind.toString().indexOf("native code")
? (q = ha)
: (q = ia);
return q.apply(null, arguments);
}
function ja(a, b) {
var c = Array.prototype.slice.call(arguments, 1);
return function () {
var d = c.slice();
d.push.apply(d, arguments);
return a.apply(this, d);
};
}
function t(a, b) {
function c() {}
c.prototype = b.prototype;
a.Z = b.prototype;
a.prototype = new c();
a.prototype.constructor = a;
a.Vb = function (d, e, f) {
for (
var h = Array(arguments.length - 2), n = 2;
n < arguments.length;
n++
)
h[n - 2] = arguments[n];
return b.prototype[e].apply(d, h);
};
}
function v() {
this.s = this.s;
this.o = this.o;
}
var ka = 0,
la = {};
v.prototype.s = !1;
v.prototype.na = function () {
if (!this.s && ((this.s = !0), this.M(), 0 != ka)) {
var a = da(this);
delete la[a];
}
};
v.prototype.M = function () {
if (this.o) for (; this.o.length; ) this.o.shift()();
};
const ma = Array.prototype.indexOf
? function (a, b) {
return Array.prototype.indexOf.call(a, b, void 0);
}
: function (a, b) {
if ("string" === typeof a)
return "string" !== typeof b || 1 != b.length
? -1
: a.indexOf(b, 0);
for (let c = 0; c < a.length; c++)
if (c in a && a[c] === b) return c;
return -1;
},
na = Array.prototype.forEach
? function (a, b, c) {
Array.prototype.forEach.call(a, b, c);
}
: function (a, b, c) {
const d = a.length,
e = "string" === typeof a ? a.split("") : a;
for (let f = 0; f < d; f++)
f in e && b.call(c, e[f], f, a);
};
function oa(a) {
a: {
var b = pa;
const c = a.length,
d = "string" === typeof a ? a.split("") : a;
for (let e = 0; e < c; e++)
if (e in d && b.call(void 0, d[e], e, a)) {
b = e;
break a;
}
b = -1;
}
return 0 > b
? null
: "string" === typeof a
? a.charAt(b)
: a[b];
}
function qa(a) {
return Array.prototype.concat.apply([], arguments);
}
function ra(a) {
const b = a.length;
if (0 < b) {
const c = Array(b);
for (let d = 0; d < b; d++) c[d] = a[d];
return c;
}
return [];
}
function sa(a) {
return /^[\s\xa0]*$/.test(a);
}
var ta = String.prototype.trim
? function (a) {
return a.trim();
}
: function (a) {
return /^[\s\xa0]*([\s\S]*?)[\s\xa0]*$/.exec(a)[1];
};
function w(a, b) {
return -1 != a.indexOf(b);
}
function ua(a, b) {
return a < b ? -1 : a > b ? 1 : 0;
}
var x;
a: {
var va = l.navigator;
if (va) {
var wa = va.userAgent;
if (wa) {
x = wa;
break a;
}
}
x = "";
}
function xa(a, b, c) {
for (const d in a) b.call(c, a[d], d, a);
}
function ya(a) {
const b = {};
for (const c in a) b[c] = a[c];
return b;
}
var za =
"constructor hasOwnProperty isPrototypeOf propertyIsEnumerable toLocaleString toString valueOf".split(
" "
);
function Aa(a, b) {
let c, d;
for (let e = 1; e < arguments.length; e++) {
d = arguments[e];
for (c in d) a[c] = d[c];
for (let f = 0; f < za.length; f++)
(c = za[f]),
Object.prototype.hasOwnProperty.call(d, c) &&
(a[c] = d[c]);
}
}
function Ca(a) {
Ca[" "](a);
return a;
}
Ca[" "] = aa;
function Fa(a) {
var b = Ga;
return Object.prototype.hasOwnProperty.call(b, 9)
? b[9]
: (b[9] = a(9));
}
var Ha = w(x, "Opera"),
y = w(x, "Trident") || w(x, "MSIE"),
Ia = w(x, "Edge"),
Ja = Ia || y,
Ka =
w(x, "Gecko") &&
!(w(x.toLowerCase(), "webkit") && !w(x, "Edge")) &&
!(w(x, "Trident") || w(x, "MSIE")) &&
!w(x, "Edge"),
La = w(x.toLowerCase(), "webkit") && !w(x, "Edge");
function Ma() {
var a = l.document;
return a ? a.documentMode : void 0;
}
var Na;
a: {
var Oa = "",
Pa = (function () {
var a = x;
if (Ka) return /rv:([^\);]+)(\)|;)/.exec(a);
if (Ia) return /Edge\/([\d\.]+)/.exec(a);
if (y)
return /\b(?:MSIE|rv)[: ]([^\);]+)(\)|;)/.exec(a);
if (La) return /WebKit\/(\S+)/.exec(a);
if (Ha) return /(?:Version)[ \/]?(\S+)/.exec(a);
})();
Pa && (Oa = Pa ? Pa[1] : "");
if (y) {
var Qa = Ma();
if (null != Qa && Qa > parseFloat(Oa)) {
Na = String(Qa);
break a;
}
}
Na = Oa;
}
var Ga = {};
function Ra() {
return Fa(function () {
let a = 0;
const b = ta(String(Na)).split("."),
c = ta("9").split("."),
d = Math.max(b.length, c.length);
for (let h = 0; 0 == a && h < d; h++) {
var e = b[h] || "",
f = c[h] || "";
do {
e = /(\d*)(\D*)(.*)/.exec(e) || ["", "", "", ""];
f = /(\d*)(\D*)(.*)/.exec(f) || ["", "", "", ""];
if (0 == e[0].length && 0 == f[0].length) break;
a =
ua(
0 == e[1].length ? 0 : parseInt(e[1], 10),
0 == f[1].length ? 0 : parseInt(f[1], 10)
) ||
ua(0 == e[2].length, 0 == f[2].length) ||
ua(e[2], f[2]);
e = e[3];
f = f[3];
} while (0 == a);
}
return 0 <= a;
});
}
var Sa;
if (l.document && y) {
var Ta = Ma();
Sa = Ta ? Ta : parseInt(Na, 10) || void 0;
} else Sa = void 0;
var Ua = Sa;
var Va = (function () {
if (!l.addEventListener || !Object.defineProperty) return !1;
var a = !1,
b = Object.defineProperty({}, "passive", {
get: function () {
a = !0;
},
});
try {
l.addEventListener("test", aa, b),
l.removeEventListener("test", aa, b);
} catch (c) {}
return a;
})();
function z(a, b) {
this.type = a;
this.g = this.target = b;
this.defaultPrevented = !1;
}
z.prototype.h = function () {
this.defaultPrevented = !0;
};
function A(a, b) {
z.call(this, a ? a.type : "");
this.relatedTarget = this.g = this.target = null;
this.button =
this.screenY =
this.screenX =
this.clientY =
this.clientX =
0;
this.key = "";
this.metaKey = this.shiftKey = this.altKey = this.ctrlKey = !1;
this.state = null;
this.pointerId = 0;
this.pointerType = "";
this.i = null;
if (a) {
var c = (this.type = a.type),
d =
a.changedTouches && a.changedTouches.length
? a.changedTouches[0]
: null;
this.target = a.target || a.srcElement;
this.g = b;
if ((b = a.relatedTarget)) {
if (Ka) {
a: {
try {
Ca(b.nodeName);
var e = !0;
break a;
} catch (f) {}
e = !1;
}
e || (b = null);
}
} else
"mouseover" == c
? (b = a.fromElement)
: "mouseout" == c && (b = a.toElement);
this.relatedTarget = b;
d
? ((this.clientX =
void 0 !== d.clientX ? d.clientX : d.pageX),
(this.clientY =
void 0 !== d.clientY ? d.clientY : d.pageY),
(this.screenX = d.screenX || 0),
(this.screenY = d.screenY || 0))
: ((this.clientX =
void 0 !== a.clientX ? a.clientX : a.pageX),
(this.clientY =
void 0 !== a.clientY ? a.clientY : a.pageY),
(this.screenX = a.screenX || 0),
(this.screenY = a.screenY || 0));
this.button = a.button;
this.key = a.key || "";
this.ctrlKey = a.ctrlKey;
this.altKey = a.altKey;
this.shiftKey = a.shiftKey;
this.metaKey = a.metaKey;
this.pointerId = a.pointerId || 0;
this.pointerType =
"string" === typeof a.pointerType
? a.pointerType
: Wa[a.pointerType] || "";
this.state = a.state;
this.i = a;
a.defaultPrevented && A.Z.h.call(this);
}
}
t(A, z);
var Wa = { 2: "touch", 3: "pen", 4: "mouse" };
A.prototype.h = function () {
A.Z.h.call(this);
var a = this.i;
a.preventDefault ? a.preventDefault() : (a.returnValue = !1);
};
var B = "closure_listenable_" + ((1e6 * Math.random()) | 0);
var Xa = 0;
function Ya(a, b, c, d, e) {
this.listener = a;
this.proxy = null;
this.src = b;
this.type = c;
this.capture = !!d;
this.ia = e;
this.key = ++Xa;
this.ca = this.fa = !1;
}
function Za(a) {
a.ca = !0;
a.listener = null;
a.proxy = null;
a.src = null;
a.ia = null;
}
function $a(a) {
this.src = a;
this.g = {};
this.h = 0;
}
$a.prototype.add = function (a, b, c, d, e) {
var f = a.toString();
a = this.g[f];
a || ((a = this.g[f] = []), this.h++);
var h = ab(a, b, d, e);
-1 < h
? ((b = a[h]), c || (b.fa = !1))
: ((b = new Ya(b, this.src, f, !!d, e)),
(b.fa = c),
a.push(b));
return b;
};
function bb(a, b) {
var c = b.type;
if (c in a.g) {
var d = a.g[c],
e = ma(d, b),
f;
(f = 0 <= e) && Array.prototype.splice.call(d, e, 1);
f && (Za(b), 0 == a.g[c].length && (delete a.g[c], a.h--));
}
}
function ab(a, b, c, d) {
for (var e = 0; e < a.length; ++e) {
var f = a[e];
if (
!f.ca &&
f.listener == b &&
f.capture == !!c &&
f.ia == d
)
return e;
}
return -1;
}
var cb = "closure_lm_" + ((1e6 * Math.random()) | 0),
db = {};
function fb(a, b, c, d, e) {
if (d && d.once) return gb(a, b, c, d, e);
if (Array.isArray(b)) {
for (var f = 0; f < b.length; f++) fb(a, b[f], c, d, e);
return null;
}
c = hb(c);
return a && a[B]
? a.N(b, c, p(d) ? !!d.capture : !!d, e)
: ib(a, b, c, !1, d, e);
}
function ib(a, b, c, d, e, f) {
if (!b) throw Error("Invalid event type");
var h = p(e) ? !!e.capture : !!e,
n = jb(a);
n || (a[cb] = n = new $a(a));
c = n.add(b, c, d, h, f);
if (c.proxy) return c;
d = kb();
c.proxy = d;
d.src = a;
d.listener = c;
if (a.addEventListener)
Va || (e = h),
void 0 === e && (e = !1),
a.addEventListener(b.toString(), d, e);
else if (a.attachEvent) a.attachEvent(lb(b.toString()), d);
else if (a.addListener && a.removeListener) a.addListener(d);
else
throw Error(
"addEventListener and attachEvent are unavailable."
);
return c;
}
function kb() {
function a(c) {
return b.call(a.src, a.listener, c);
}
var b = mb;
return a;
}
function gb(a, b, c, d, e) {
if (Array.isArray(b)) {
for (var f = 0; f < b.length; f++) gb(a, b[f], c, d, e);
return null;
}
c = hb(c);
return a && a[B]
? a.O(b, c, p(d) ? !!d.capture : !!d, e)
: ib(a, b, c, !0, d, e);
}
function nb(a, b, c, d, e) {
if (Array.isArray(b))
for (var f = 0; f < b.length; f++) nb(a, b[f], c, d, e);
else
((d = p(d) ? !!d.capture : !!d), (c = hb(c)), a && a[B])
? ((a = a.i),
(b = String(b).toString()),
b in a.g &&
((f = a.g[b]),
(c = ab(f, c, d, e)),
-1 < c &&
(Za(f[c]),
Array.prototype.splice.call(f, c, 1),
0 == f.length && (delete a.g[b], a.h--))))
: a &&
(a = jb(a)) &&
((b = a.g[b.toString()]),
(a = -1),
b && (a = ab(b, c, d, e)),
(c = -1 < a ? b[a] : null) && ob(c));
}
function ob(a) {
if ("number" !== typeof a && a && !a.ca) {
var b = a.src;
if (b && b[B]) bb(b.i, a);
else {
var c = a.type,
d = a.proxy;
b.removeEventListener
? b.removeEventListener(c, d, a.capture)
: b.detachEvent
? b.detachEvent(lb(c), d)
: b.addListener &&
b.removeListener &&
b.removeListener(d);
(c = jb(b))
? (bb(c, a),
0 == c.h && ((c.src = null), (b[cb] = null)))
: Za(a);
}
}
}
function lb(a) {
return a in db ? db[a] : (db[a] = "on" + a);
}
function mb(a, b) {
if (a.ca) a = !0;
else {
b = new A(b, this);
var c = a.listener,
d = a.ia || a.src;
a.fa && ob(a);
a = c.call(d, b);
}
return a;
}
function jb(a) {
a = a[cb];
return a instanceof $a ? a : null;
}
var pb = "__closure_events_fn_" + ((1e9 * Math.random()) >>> 0);
function hb(a) {
if ("function" === typeof a) return a;
a[pb] ||
(a[pb] = function (b) {
return a.handleEvent(b);
});
return a[pb];
}
function C() {
v.call(this);
this.i = new $a(this);
this.P = this;
this.I = null;
}
t(C, v);
C.prototype[B] = !0;
C.prototype.removeEventListener = function (a, b, c, d) {
nb(this, a, b, c, d);
};
function D(a, b) {
var c,
d = a.I;
if (d) for (c = []; d; d = d.I) c.push(d);
a = a.P;
d = b.type || b;
if ("string" === typeof b) b = new z(b, a);
else if (b instanceof z) b.target = b.target || a;
else {
var e = b;
b = new z(d, a);
Aa(b, e);
}
e = !0;
if (c)
for (var f = c.length - 1; 0 <= f; f--) {
var h = (b.g = c[f]);
e = qb(h, d, !0, b) && e;
}
h = b.g = a;
e = qb(h, d, !0, b) && e;
e = qb(h, d, !1, b) && e;
if (c)
for (f = 0; f < c.length; f++)
(h = b.g = c[f]), (e = qb(h, d, !1, b) && e);
}
C.prototype.M = function () {
C.Z.M.call(this);
if (this.i) {
var a = this.i,
c;
for (c in a.g) {
for (var d = a.g[c], e = 0; e < d.length; e++) Za(d[e]);
delete a.g[c];
a.h--;
}
}
this.I = null;
};
C.prototype.N = function (a, b, c, d) {
return this.i.add(String(a), b, !1, c, d);
};
C.prototype.O = function (a, b, c, d) {
return this.i.add(String(a), b, !0, c, d);
};
function qb(a, b, c, d) {
b = a.i.g[String(b)];
if (!b) return !0;
b = b.concat();
for (var e = !0, f = 0; f < b.length; ++f) {
var h = b[f];
if (h && !h.ca && h.capture == c) {
var n = h.listener,
u = h.ia || h.src;
h.fa && bb(a.i, h);
e = !1 !== n.call(u, d) && e;
}
}
return e && !d.defaultPrevented;
}
var rb = l.JSON.stringify;
function sb() {
var a = tb;
let b = null;
a.g &&
((b = a.g),
(a.g = a.g.next),
a.g || (a.h = null),
(b.next = null));
return b;
}
class ub {
constructor() {
this.h = this.g = null;
}
add(a, b) {
const c = vb.get();
c.set(a, b);
this.h ? (this.h.next = c) : (this.g = c);
this.h = c;
}
}
var vb = new (class {
constructor(a, b) {
this.i = a;
this.j = b;
this.h = 0;
this.g = null;
}
get() {
let a;
0 < this.h
? (this.h--,
(a = this.g),
(this.g = a.next),
(a.next = null))
: (a = this.i());
return a;
}
})(
() => new wb(),
(a) => a.reset()
);
class wb {
constructor() {
this.next = this.g = this.h = null;
}
set(a, b) {
this.h = a;
this.g = b;
this.next = null;
}
reset() {
this.next = this.g = this.h = null;
}
}
function yb(a) {
l.setTimeout(() => {
throw a;
}, 0);
}
function zb(a, b) {
Ab || Bb();
Cb || (Ab(), (Cb = !0));
tb.add(a, b);
}
var Ab;
function Bb() {
var a = l.Promise.resolve(void 0);
Ab = function () {
a.then(Db);
};
}
var Cb = !1,
tb = new ub();
function Db() {
for (var a; (a = sb()); ) {
try {
a.h.call(a.g);
} catch (c) {
yb(c);
}
var b = vb;
b.j(a);
100 > b.h && (b.h++, (a.next = b.g), (b.g = a));
}
Cb = !1;
}
function Eb(a, b) {
C.call(this);
this.h = a || 1;
this.g = b || l;
this.j = q(this.kb, this);
this.l = Date.now();
}
t(Eb, C);
k = Eb.prototype;
k.da = !1;
k.S = null;
k.kb = function () {
if (this.da) {
var a = Date.now() - this.l;
0 < a && a < 0.8 * this.h
? (this.S = this.g.setTimeout(this.j, this.h - a))
: (this.S &&
(this.g.clearTimeout(this.S), (this.S = null)),
D(this, "tick"),
this.da && (Fb(this), this.start()));
}
};
k.start = function () {
this.da = !0;
this.S ||
((this.S = this.g.setTimeout(this.j, this.h)),
(this.l = Date.now()));
};
function Fb(a) {
a.da = !1;
a.S && (a.g.clearTimeout(a.S), (a.S = null));
}
k.M = function () {
Eb.Z.M.call(this);
Fb(this);
delete this.g;
};
function Gb(a, b, c) {
if ("function" === typeof a) c && (a = q(a, c));
else if (a && "function" == typeof a.handleEvent)
a = q(a.handleEvent, a);
else throw Error("Invalid listener argument");
return 2147483647 < Number(b) ? -1 : l.setTimeout(a, b || 0);
}
function Hb(a) {
a.g = Gb(() => {
a.g = null;
a.i && ((a.i = !1), Hb(a));
}, a.j);
const b = a.h;
a.h = null;
a.m.apply(null, b);
}
class Ib extends v {
constructor(a, b) {
super();
this.m = a;
this.j = b;
this.h = null;
this.i = !1;
this.g = null;
}
l(a) {
this.h = arguments;
this.g ? (this.i = !0) : Hb(this);
}
M() {
super.M();
this.g &&
(l.clearTimeout(this.g),
(this.g = null),
(this.i = !1),
(this.h = null));
}
}
function E(a) {
v.call(this);
this.h = a;
this.g = {};
}
t(E, v);
var Jb = [];
function Kb(a, b, c, d) {
Array.isArray(c) || (c && (Jb[0] = c.toString()), (c = Jb));
for (var e = 0; e < c.length; e++) {
var f = fb(b, c[e], d || a.handleEvent, !1, a.h || a);
if (!f) break;
a.g[f.key] = f;
}
}
function Lb(a) {
xa(
a.g,
function (b, c) {
this.g.hasOwnProperty(c) && ob(b);
},
a
);
a.g = {};
}
E.prototype.M = function () {
E.Z.M.call(this);
Lb(this);
};
E.prototype.handleEvent = function () {
throw Error("EventHandler.handleEvent not implemented");
};
function Mb() {
this.g = !0;
}
Mb.prototype.Aa = function () {
this.g = !1;
};
function Nb(a, b, c, d, e, f) {
a.info(function () {
if (a.g)
if (f) {
var h = "";
for (
var n = f.split("&"), u = 0;
u < n.length;
u++
) {
var m = n[u].split("=");
if (1 < m.length) {
var r = m[0];
m = m[1];
var G = r.split("_");
h =
2 <= G.length && "type" == G[1]
? h + (r + "=" + m + "&")
: h + (r + "=redacted&");
}
}
} else h = null;
else h = f;
return (
"XMLHTTP REQ (" +
d +
") [attempt " +
e +
"]: " +
b +
"\n" +
c +
"\n" +
h
);
});
}
function Ob(a, b, c, d, e, f, h) {
a.info(function () {
return (
"XMLHTTP RESP (" +
d +
") [ attempt " +
e +
"]: " +
b +
"\n" +
c +
"\n" +
f +
" " +
h
);
});
}
function F(a, b, c, d) {
a.info(function () {
return (
"XMLHTTP TEXT (" +
b +
"): " +
Pb(a, c) +
(d ? " " + d : "")
);
});
}
function Qb(a, b) {
a.info(function () {
return "TIMEOUT: " + b;
});
}
Mb.prototype.info = function () {};
function Pb(a, b) {
if (!a.g) return b;
if (!b) return null;
try {
var c = JSON.parse(b);
if (c)
for (a = 0; a < c.length; a++)
if (Array.isArray(c[a])) {
var d = c[a];
if (!(2 > d.length)) {
var e = d[1];
if (Array.isArray(e) && !(1 > e.length)) {
var f = e[0];
if (
"noop" != f &&
"stop" != f &&
"close" != f
)
for (var h = 1; h < e.length; h++)
e[h] = "";
}
}
}
return rb(c);
} catch (n) {
return b;
}
}
var H = {},
Rb = null;
function Sb() {
return (Rb = Rb || new C());
}
H.Ma = "serverreachability";
function Tb(a) {
z.call(this, H.Ma, a);
}
t(Tb, z);
function I(a) {
const b = Sb();
D(b, new Tb(b, a));
}
H.STAT_EVENT = "statevent";
function Ub(a, b) {
z.call(this, H.STAT_EVENT, a);
this.stat = b;
}
t(Ub, z);
function J(a) {
const b = Sb();
D(b, new Ub(b, a));
}
H.Na = "timingevent";
function Vb(a, b) {
z.call(this, H.Na, a);
this.size = b;
}
t(Vb, z);
function K(a, b) {
if ("function" !== typeof a)
throw Error("Fn must not be null and must be a function");
return l.setTimeout(function () {
a();
}, b);
}
var Wb = {
NO_ERROR: 0,
lb: 1,
yb: 2,
xb: 3,
sb: 4,
wb: 5,
zb: 6,
Ja: 7,
TIMEOUT: 8,
Cb: 9,
};
var Xb = {
qb: "complete",
Mb: "success",
Ka: "error",
Ja: "abort",
Eb: "ready",
Fb: "readystatechange",
TIMEOUT: "timeout",
Ab: "incrementaldata",
Db: "progress",
tb: "downloadprogress",
Ub: "uploadprogress",
};
function Yb() {}
Yb.prototype.h = null;
function Zb(a) {
return a.h || (a.h = a.i());
}
function $b() {}
var L = { OPEN: "a", pb: "b", Ka: "c", Bb: "d" };
function ac() {
z.call(this, "d");
}
t(ac, z);
function bc() {
z.call(this, "c");
}
t(bc, z);
var cc;
function dc() {}
t(dc, Yb);
dc.prototype.g = function () {
return new XMLHttpRequest();
};
dc.prototype.i = function () {
return {};
};
cc = new dc();
function M(a, b, c, d) {
this.l = a;
this.j = b;
this.m = c;
this.X = d || 1;
this.V = new E(this);
this.P = ec;
a = Ja ? 125 : void 0;
this.W = new Eb(a);
this.H = null;
this.i = !1;
this.s =
this.A =
this.v =
this.K =
this.F =
this.Y =
this.B =
null;
this.D = [];
this.g = null;
this.C = 0;
this.o = this.u = null;
this.N = -1;
this.I = !1;
this.O = 0;
this.L = null;
this.aa = this.J = this.$ = this.U = !1;
this.h = new fc();
}
function fc() {
this.i = null;
this.g = "";
this.h = !1;
}
var ec = 45e3,
gc = {},
hc = {};
k = M.prototype;
k.setTimeout = function (a) {
this.P = a;
};
function ic(a, b, c) {
a.K = 1;
a.v = jc(N(b));
a.s = c;
a.U = !0;
kc(a, null);
}
function kc(a, b) {
a.F = Date.now();
lc(a);
a.A = N(a.v);
var c = a.A,
d = a.X;
Array.isArray(d) || (d = [String(d)]);
mc(c.h, "t", d);
a.C = 0;
c = a.l.H;
a.h = new fc();
a.g = nc(a.l, c ? b : null, !a.s);
0 < a.O && (a.L = new Ib(q(a.Ia, a, a.g), a.O));
Kb(a.V, a.g, "readystatechange", a.gb);
b = a.H ? ya(a.H) : {};
a.s
? (a.u || (a.u = "POST"),
(b["Content-Type"] = "application/x-www-form-urlencoded"),
a.g.ea(a.A, a.u, a.s, b))
: ((a.u = "GET"), a.g.ea(a.A, a.u, null, b));
I(1);
Nb(a.j, a.u, a.A, a.m, a.X, a.s);
}
k.gb = function (a) {
a = a.target;
const b = this.L;
b && 3 == O(a) ? b.l() : this.Ia(a);
};
k.Ia = function (a) {
try {
if (a == this.g)
a: {
const r = O(this.g);
var b = this.g.Da();
const G = this.g.ba();
if (
!(3 > r) &&
(3 != r ||
Ja ||
(this.g &&
(this.h.h ||
this.g.ga() ||
oc(this.g))))
) {
this.I ||
4 != r ||
7 == b ||
(8 == b || 0 >= G ? I(3) : I(2));
pc(this);
var c = this.g.ba();
this.N = c;
b: if (qc(this)) {
var d = oc(this.g);
a = "";
var e = d.length,
f = 4 == O(this.g);
if (!this.h.i) {
if (
"undefined" === typeof TextDecoder
) {
P(this);
rc(this);
var h = "";
break b;
}
this.h.i = new l.TextDecoder();
}
for (b = 0; b < e; b++)
(this.h.h = !0),
(a += this.h.i.decode(d[b], {
stream: f && b == e - 1,
}));
d.splice(0, e);
this.h.g += a;
this.C = 0;
h = this.h.g;
} else h = this.g.ga();
this.i = 200 == c;
Ob(
this.j,
this.u,
this.A,
this.m,
this.X,
r,
c
);
if (this.i) {
if (this.$ && !this.J) {
b: {
if (this.g) {
var n,
u = this.g;
if (
(n = u.g
? u.g.getResponseHeader(
"X-HTTP-Initial-Response"
)
: null) &&
!sa(n)
) {
var m = n;
break b;
}
}
m = null;
}
if ((c = m))
F(
this.j,
this.m,
c,
"Initial handshake response via X-HTTP-Initial-Response"
),
(this.J = !0),
sc(this, c);
else {
this.i = !1;
this.o = 3;
J(12);
P(this);
rc(this);
break a;
}
}
this.U
? (tc(this, r, h),
Ja &&
this.i &&
3 == r &&
(Kb(
this.V,
this.W,
"tick",
this.fb
),
this.W.start()))
: (F(this.j, this.m, h, null),
sc(this, h));
4 == r && P(this);
this.i &&
!this.I &&
(4 == r
? uc(this.l, this)
: ((this.i = !1), lc(this)));
} else
400 == c && 0 < h.indexOf("Unknown SID")
? ((this.o = 3), J(12))
: ((this.o = 0), J(13)),
P(this),
rc(this);
}
}
} catch (r) {
} finally {
}
};
function qc(a) {
return a.g ? "GET" == a.u && 2 != a.K && a.l.Ba : !1;
}
function tc(a, b, c) {
let d = !0,
e;
for (; !a.I && a.C < c.length; )
if (((e = vc(a, c)), e == hc)) {
4 == b && ((a.o = 4), J(14), (d = !1));
F(a.j, a.m, null, "[Incomplete Response]");
break;
} else if (e == gc) {
a.o = 4;
J(15);
F(a.j, a.m, c, "[Invalid Chunk]");
d = !1;
break;
} else F(a.j, a.m, e, null), sc(a, e);
qc(a) && e != hc && e != gc && ((a.h.g = ""), (a.C = 0));
4 != b ||
0 != c.length ||
a.h.h ||
((a.o = 1), J(16), (d = !1));
a.i = a.i && d;
d
? 0 < c.length &&
!a.aa &&
((a.aa = !0),
(b = a.l),
b.g == a &&
b.$ &&
!b.L &&
(b.h.info(
"Great, no buffering proxy detected. Bytes received: " +
c.length
),
wc(b),
(b.L = !0),
J(11)))
: (F(a.j, a.m, c, "[Invalid Chunked Response]"),
P(a),
rc(a));
}
k.fb = function () {
if (this.g) {
var a = O(this.g),
b = this.g.ga();
this.C < b.length &&
(pc(this),
tc(this, a, b),
this.i && 4 != a && lc(this));
}
};
function vc(a, b) {
var c = a.C,
d = b.indexOf("\n", c);
if (-1 == d) return hc;
c = Number(b.substring(c, d));
if (isNaN(c)) return gc;
d += 1;
if (d + c > b.length) return hc;
b = b.substr(d, c);
a.C = d + c;
return b;
}
k.cancel = function () {
this.I = !0;
P(this);
};
function lc(a) {
a.Y = Date.now() + a.P;
xc(a, a.P);
}
function xc(a, b) {
if (null != a.B) throw Error("WatchDog timer not null");
a.B = K(q(a.eb, a), b);
}
function pc(a) {
a.B && (l.clearTimeout(a.B), (a.B = null));
}
k.eb = function () {
this.B = null;
const a = Date.now();
0 <= a - this.Y
? (Qb(this.j, this.A),
2 != this.K && (I(3), J(17)),
P(this),
(this.o = 2),
rc(this))
: xc(this, this.Y - a);
};
function rc(a) {
0 == a.l.G || a.I || uc(a.l, a);
}
function P(a) {
pc(a);
var b = a.L;
b && "function" == typeof b.na && b.na();
a.L = null;
Fb(a.W);
Lb(a.V);
a.g && ((b = a.g), (a.g = null), b.abort(), b.na());
}
function sc(a, b) {
try {
var c = a.l;
if (0 != c.G && (c.g == a || yc(c.i, a)))
if (((c.I = a.N), !a.J && yc(c.i, a) && 3 == c.G)) {
try {
var d = c.Ca.g.parse(b);
} catch (m) {
d = null;
}
if (Array.isArray(d) && 3 == d.length) {
var e = d;
if (0 == e[0])
a: {
if (!c.u) {
if (c.g)
if (c.g.F + 3e3 < a.F)
zc(c), Ac(c);
else break a;
Bc(c);
J(18);
}
}
else
(c.ta = e[1]),
0 < c.ta - c.U &&
37500 > e[2] &&
c.N &&
0 == c.A &&
!c.v &&
(c.v = K(q(c.ab, c), 6e3));
if (1 >= Cc(c.i) && c.ka) {
try {
c.ka();
} catch (m) {}
c.ka = void 0;
}
} else Q(c, 11);
} else if (((a.J || c.g == a) && zc(c), !sa(b)))
for (
e = c.Ca.g.parse(b), b = 0;
b < e.length;
b++
) {
let m = e[b];
c.U = m[0];
m = m[1];
if (2 == c.G)
if ("c" == m[0]) {
c.J = m[1];
c.la = m[2];
const r = m[3];
null != r &&
((c.ma = r),
c.h.info("VER=" + c.ma));
const G = m[4];
null != G &&
((c.za = G),
c.h.info("SVER=" + c.za));
const Da = m[5];
null != Da &&
"number" === typeof Da &&
0 < Da &&
((d = 1.5 * Da),
(c.K = d),
c.h.info(
"backChannelRequestTimeoutMs_=" +
d
));
d = c;
const ca = a.g;
if (ca) {
const Ea = ca.g
? ca.g.getResponseHeader(
"X-Client-Wire-Protocol"
)
: null;
if (Ea) {
var f = d.i;
!f.g &&
(w(Ea, "spdy") ||
w(Ea, "quic") ||
w(Ea, "h2")) &&
((f.j = f.l),
(f.g = new Set()),
f.h &&
(Dc(f, f.h),
(f.h = null)));
}
if (d.D) {
const xb = ca.g
? ca.g.getResponseHeader(
"X-HTTP-Session-Id"
)
: null;
xb &&
((d.sa = xb),
R(d.F, d.D, xb));
}
}
c.G = 3;
c.j && c.j.xa();
c.$ &&
((c.O = Date.now() - a.F),
c.h.info(
"Handshake RTT: " + c.O + "ms"
));
d = c;
var h = a;
d.oa = Ec(d, d.H ? d.la : null, d.W);
if (h.J) {
Fc(d.i, h);
var n = h,
u = d.K;
u && n.setTimeout(u);
n.B && (pc(n), lc(n));
d.g = h;
} else Gc(d);
0 < c.l.length && Hc(c);
} else
("stop" != m[0] && "close" != m[0]) ||
Q(c, 7);
else
3 == c.G &&
("stop" == m[0] || "close" == m[0]
? "stop" == m[0]
? Q(c, 7)
: Ic(c)
: "noop" != m[0] &&
c.j &&
c.j.wa(m),
(c.A = 0));
}
I(4);
} catch (m) {}
}
function Jc(a) {
if (a.R && "function" == typeof a.R) return a.R();
if ("string" === typeof a) return a.split("");
if (ba(a)) {
for (var b = [], c = a.length, d = 0; d < c; d++)
b.push(a[d]);
return b;
}
b = [];
c = 0;
for (d in a) b[c++] = a[d];
return b;
}
function Kc(a, b) {
if (a.forEach && "function" == typeof a.forEach)
a.forEach(b, void 0);
else if (ba(a) || "string" === typeof a) na(a, b, void 0);
else {
if (a.T && "function" == typeof a.T) var c = a.T();
else if (a.R && "function" == typeof a.R) c = void 0;
else if (ba(a) || "string" === typeof a) {
c = [];
for (var d = a.length, e = 0; e < d; e++) c.push(e);
} else for (e in ((c = []), (d = 0), a)) c[d++] = e;
d = Jc(a);
e = d.length;
for (var f = 0; f < e; f++)
b.call(void 0, d[f], c && c[f], a);
}
}
function S(a, b) {
this.h = {};
this.g = [];
this.i = 0;
var c = arguments.length;
if (1 < c) {
if (c % 2) throw Error("Uneven number of arguments");
for (var d = 0; d < c; d += 2)
this.set(arguments[d], arguments[d + 1]);
} else if (a)
if (a instanceof S)
for (c = a.T(), d = 0; d < c.length; d++)
this.set(c[d], a.get(c[d]));
else for (d in a) this.set(d, a[d]);
}
k = S.prototype;
k.R = function () {
Lc(this);
for (var a = [], b = 0; b < this.g.length; b++)
a.push(this.h[this.g[b]]);
return a;
};
k.T = function () {
Lc(this);
return this.g.concat();
};
function Lc(a) {
if (a.i != a.g.length) {
for (var b = 0, c = 0; b < a.g.length; ) {
var d = a.g[b];
T(a.h, d) && (a.g[c++] = d);
b++;
}
a.g.length = c;
}
if (a.i != a.g.length) {
var e = {};
for (c = b = 0; b < a.g.length; )
(d = a.g[b]),
T(e, d) || ((a.g[c++] = d), (e[d] = 1)),
b++;
a.g.length = c;
}
}
k.get = function (a, b) {
return T(this.h, a) ? this.h[a] : b;
};
k.set = function (a, b) {
T(this.h, a) || (this.i++, this.g.push(a));
this.h[a] = b;
};
k.forEach = function (a, b) {
for (var c = this.T(), d = 0; d < c.length; d++) {
var e = c[d],
f = this.get(e);
a.call(b, f, e, this);
}
};
function T(a, b) {
return Object.prototype.hasOwnProperty.call(a, b);
}
var Mc =
/^(?:([^:/?#.]+):)?(?:\/\/(?:([^\\/?#]*)@)?([^\\/?#]*?)(?::([0-9]+))?(?=[\\/?#]|$))?([^?#]+)?(?:\?([^#]*))?(?:#([\s\S]*))?$/;
function Nc(a, b) {
if (a) {
a = a.split("&");
for (var c = 0; c < a.length; c++) {
var d = a[c].indexOf("="),
e = null;
if (0 <= d) {
var f = a[c].substring(0, d);
e = a[c].substring(d + 1);
} else f = a[c];
b(
f,
e ? decodeURIComponent(e.replace(/\+/g, " ")) : ""
);
}
}
}
function U(a, b) {
this.i = this.s = this.j = "";
this.m = null;
this.o = this.l = "";
this.g = !1;
if (a instanceof U) {
this.g = void 0 !== b ? b : a.g;
Oc(this, a.j);
this.s = a.s;
Pc(this, a.i);
Qc(this, a.m);
this.l = a.l;
b = a.h;
var c = new Rc();
c.i = b.i;
b.g && ((c.g = new S(b.g)), (c.h = b.h));
Sc(this, c);
this.o = a.o;
} else
a && (c = String(a).match(Mc))
? ((this.g = !!b),
Oc(this, c[1] || "", !0),
(this.s = Tc(c[2] || "")),
Pc(this, c[3] || "", !0),
Qc(this, c[4]),
(this.l = Tc(c[5] || "", !0)),
Sc(this, c[6] || "", !0),
(this.o = Tc(c[7] || "")))
: ((this.g = !!b), (this.h = new Rc(null, this.g)));
}
U.prototype.toString = function () {
var a = [],
b = this.j;
b && a.push(Uc(b, Vc, !0), ":");
var c = this.i;
if (c || "file" == b)
a.push("//"),
(b = this.s) && a.push(Uc(b, Vc, !0), "@"),
a.push(
encodeURIComponent(String(c)).replace(
/%25([0-9a-fA-F]{2})/g,
"%$1"
)
),
(c = this.m),
null != c && a.push(":", String(c));
if ((c = this.l))
this.i && "/" != c.charAt(0) && a.push("/"),
a.push(Uc(c, "/" == c.charAt(0) ? Wc : Xc, !0));
(c = this.h.toString()) && a.push("?", c);
(c = this.o) && a.push("#", Uc(c, Yc));
return a.join("");
};
function N(a) {
return new U(a);
}
function Oc(a, b, c) {
a.j = c ? Tc(b, !0) : b;
a.j && (a.j = a.j.replace(/:$/, ""));
}
function Pc(a, b, c) {
a.i = c ? Tc(b, !0) : b;
}
function Qc(a, b) {
if (b) {
b = Number(b);
if (isNaN(b) || 0 > b) throw Error("Bad port number " + b);
a.m = b;
} else a.m = null;
}
function Sc(a, b, c) {
b instanceof Rc
? ((a.h = b), Zc(a.h, a.g))
: (c || (b = Uc(b, $c)), (a.h = new Rc(b, a.g)));
}
function R(a, b, c) {
a.h.set(b, c);
}
function jc(a) {
R(
a,
"zx",
Math.floor(2147483648 * Math.random()).toString(36) +
Math.abs(
Math.floor(2147483648 * Math.random()) ^ Date.now()
).toString(36)
);
return a;
}
function ad(a) {
return a instanceof U ? N(a) : new U(a, void 0);
}
function bd(a, b, c, d) {
var e = new U(null, void 0);
a && Oc(e, a);
b && Pc(e, b);
c && Qc(e, c);
d && (e.l = d);
return e;
}
function Tc(a, b) {
return a
? b
? decodeURI(a.replace(/%25/g, "%2525"))
: decodeURIComponent(a)
: "";
}
function Uc(a, b, c) {
return "string" === typeof a
? ((a = encodeURI(a).replace(b, cd)),
c && (a = a.replace(/%25([0-9a-fA-F]{2})/g, "%$1")),
a)
: null;
}
function cd(a) {
a = a.charCodeAt(0);
return (
"%" + ((a >> 4) & 15).toString(16) + (a & 15).toString(16)
);
}
var Vc = /[#\/\?@]/g,
Xc = /[#\?:]/g,
Wc = /[#\?]/g,
$c = /[#\?@]/g,
Yc = /#/g;
function Rc(a, b) {
this.h = this.g = null;
this.i = a || null;
this.j = !!b;
}
function V(a) {
a.g ||
((a.g = new S()),
(a.h = 0),
a.i &&
Nc(a.i, function (b, c) {
a.add(decodeURIComponent(b.replace(/\+/g, " ")), c);
}));
}
k = Rc.prototype;
k.add = function (a, b) {
V(this);
this.i = null;
a = W(this, a);
var c = this.g.get(a);
c || this.g.set(a, (c = []));
c.push(b);
this.h += 1;
return this;
};
function dd(a, b) {
V(a);
b = W(a, b);
T(a.g.h, b) &&
((a.i = null),
(a.h -= a.g.get(b).length),
(a = a.g),
T(a.h, b) &&
(delete a.h[b], a.i--, a.g.length > 2 * a.i && Lc(a)));
}
function ed(a, b) {
V(a);
b = W(a, b);
return T(a.g.h, b);
}
k.forEach = function (a, b) {
V(this);
this.g.forEach(function (c, d) {
na(
c,
function (e) {
a.call(b, e, d, this);
},
this
);
}, this);
};
k.T = function () {
V(this);
for (
var a = this.g.R(), b = this.g.T(), c = [], d = 0;
d < b.length;
d++
)
for (var e = a[d], f = 0; f < e.length; f++) c.push(b[d]);
return c;
};
k.R = function (a) {
V(this);
var b = [];
if ("string" === typeof a)
ed(this, a) && (b = qa(b, this.g.get(W(this, a))));
else {
a = this.g.R();
for (var c = 0; c < a.length; c++) b = qa(b, a[c]);
}
return b;
};
k.set = function (a, b) {
V(this);
this.i = null;
a = W(this, a);
ed(this, a) && (this.h -= this.g.get(a).length);
this.g.set(a, [b]);
this.h += 1;
return this;
};
k.get = function (a, b) {
if (!a) return b;
a = this.R(a);
return 0 < a.length ? String(a[0]) : b;
};
function mc(a, b, c) {
dd(a, b);
0 < c.length &&
((a.i = null), a.g.set(W(a, b), ra(c)), (a.h += c.length));
}
k.toString = function () {
if (this.i) return this.i;
if (!this.g) return "";
for (var a = [], b = this.g.T(), c = 0; c < b.length; c++) {
var d = b[c],
e = encodeURIComponent(String(d));
d = this.R(d);
for (var f = 0; f < d.length; f++) {
var h = e;
"" !== d[f] &&
(h += "=" + encodeURIComponent(String(d[f])));
a.push(h);
}
}
return (this.i = a.join("&"));
};
function W(a, b) {
b = String(b);
a.j && (b = b.toLowerCase());
return b;
}
function Zc(a, b) {
b &&
!a.j &&
(V(a),
(a.i = null),
a.g.forEach(function (c, d) {
var e = d.toLowerCase();
d != e && (dd(this, d), mc(this, e, c));
}, a));
a.j = b;
}
var fd = class {
constructor(a, b) {
this.h = a;
this.g = b;
}
};
function gd(a) {
this.l = a || hd;
l.PerformanceNavigationTiming
? ((a = l.performance.getEntriesByType("navigation")),
(a =
0 < a.length &&
("hq" == a[0].nextHopProtocol ||
"h2" == a[0].nextHopProtocol)))
: (a = !!(l.g && l.g.Ea && l.g.Ea() && l.g.Ea().Zb));
this.j = a ? this.l : 1;
this.g = null;
1 < this.j && (this.g = new Set());
this.h = null;
this.i = [];
}
var hd = 10;
function id(a) {
return a.h ? !0 : a.g ? a.g.size >= a.j : !1;
}
function Cc(a) {
return a.h ? 1 : a.g ? a.g.size : 0;
}
function yc(a, b) {
return a.h ? a.h == b : a.g ? a.g.has(b) : !1;
}
function Dc(a, b) {
a.g ? a.g.add(b) : (a.h = b);
}
function Fc(a, b) {
a.h && a.h == b
? (a.h = null)
: a.g && a.g.has(b) && a.g.delete(b);
}
gd.prototype.cancel = function () {
this.i = jd(this);
if (this.h) this.h.cancel(), (this.h = null);
else if (this.g && 0 !== this.g.size) {
for (const a of this.g.values()) a.cancel();
this.g.clear();
}
};
function jd(a) {
if (null != a.h) return a.i.concat(a.h.D);
if (null != a.g && 0 !== a.g.size) {
let b = a.i;
for (const c of a.g.values()) b = b.concat(c.D);
return b;
}
return ra(a.i);
}
function kd() {}
kd.prototype.stringify = function (a) {
return l.JSON.stringify(a, void 0);
};
kd.prototype.parse = function (a) {
return l.JSON.parse(a, void 0);
};
function ld() {
this.g = new kd();
}
function md(a, b, c) {
const d = c || "";
try {
Kc(a, function (e, f) {
let h = e;
p(e) && (h = rb(e));
b.push(d + f + "=" + encodeURIComponent(h));
});
} catch (e) {
throw (
(b.push(d + "type=" + encodeURIComponent("_badmap")), e)
);
}
}
function nd(a, b) {
const c = new Mb();
if (l.Image) {
const d = new Image();
d.onload = ja(od, c, d, "TestLoadImage: loaded", !0, b);
d.onerror = ja(od, c, d, "TestLoadImage: error", !1, b);
d.onabort = ja(od, c, d, "TestLoadImage: abort", !1, b);
d.ontimeout = ja(od, c, d, "TestLoadImage: timeout", !1, b);
l.setTimeout(function () {
if (d.ontimeout) d.ontimeout();
}, 1e4);
d.src = a;
} else b(!1);
}
function od(a, b, c, d, e) {
try {
(b.onload = null),
(b.onerror = null),
(b.onabort = null),
(b.ontimeout = null),
e(d);
} catch (f) {}
}
function pd(a) {
this.l = a.$b || null;
this.j = a.ib || !1;
}
t(pd, Yb);
pd.prototype.g = function () {
return new qd(this.l, this.j);
};
pd.prototype.i = (function (a) {
return function () {
return a;
};
})({});
function qd(a, b) {
C.call(this);
this.D = a;
this.u = b;
this.m = void 0;
this.readyState = rd;
this.status = 0;
this.responseType =
this.responseText =
this.response =
this.statusText =
"";
this.onreadystatechange = null;
this.v = new Headers();
this.h = null;
this.C = "GET";
this.B = "";
this.g = !1;
this.A = this.j = this.l = null;
}
t(qd, C);
var rd = 0;
k = qd.prototype;
k.open = function (a, b) {
if (this.readyState != rd)
throw (this.abort(), Error("Error reopening a connection"));
this.C = a;
this.B = b;
this.readyState = 1;
sd(this);
};
k.send = function (a) {
if (1 != this.readyState)
throw (this.abort(), Error("need to call open() first. "));
this.g = !0;
const b = {
headers: this.v,
method: this.C,
credentials: this.m,
cache: void 0,
};
a && (b.body = a);
(this.D || l)
.fetch(new Request(this.B, b))
.then(this.Va.bind(this), this.ha.bind(this));
};
k.abort = function () {
this.response = this.responseText = "";
this.v = new Headers();
this.status = 0;
this.j && this.j.cancel("Request was aborted.");
1 <= this.readyState &&
this.g &&
4 != this.readyState &&
((this.g = !1), td(this));
this.readyState = rd;
};
k.Va = function (a) {
if (
this.g &&
((this.l = a),
this.h ||
((this.status = this.l.status),
(this.statusText = this.l.statusText),
(this.h = a.headers),
(this.readyState = 2),
sd(this)),
this.g && ((this.readyState = 3), sd(this), this.g))
)
if ("arraybuffer" === this.responseType)
a.arrayBuffer().then(
this.Ta.bind(this),
this.ha.bind(this)
);
else if (
"undefined" !== typeof l.ReadableStream &&
"body" in a
) {
this.j = a.body.getReader();
if (this.u) {
if (this.responseType)
throw Error(
'responseType must be empty for "streamBinaryChunks" mode responses.'
);
this.response = [];
} else
(this.response = this.responseText = ""),
(this.A = new TextDecoder());
ud(this);
} else
a.text().then(this.Ua.bind(this), this.ha.bind(this));
};
function ud(a) {
a.j.read().then(a.Sa.bind(a)).catch(a.ha.bind(a));
}
k.Sa = function (a) {
if (this.g) {
if (this.u && a.value) this.response.push(a.value);
else if (!this.u) {
var b = a.value ? a.value : new Uint8Array(0);
if ((b = this.A.decode(b, { stream: !a.done })))
this.response = this.responseText += b;
}
a.done ? td(this) : sd(this);
3 == this.readyState && ud(this);
}
};
k.Ua = function (a) {
this.g && ((this.response = this.responseText = a), td(this));
};
k.Ta = function (a) {
this.g && ((this.response = a), td(this));
};
k.ha = function () {
this.g && td(this);
};
function td(a) {
a.readyState = 4;
a.l = null;
a.j = null;
a.A = null;
sd(a);
}
k.setRequestHeader = function (a, b) {
this.v.append(a, b);
};
k.getResponseHeader = function (a) {
return this.h ? this.h.get(a.toLowerCase()) || "" : "";
};
k.getAllResponseHeaders = function () {
if (!this.h) return "";
const a = [],
b = this.h.entries();
for (var c = b.next(); !c.done; )
(c = c.value), a.push(c[0] + ": " + c[1]), (c = b.next());
return a.join("\r\n");
};
function sd(a) {
a.onreadystatechange && a.onreadystatechange.call(a);
}
Object.defineProperty(qd.prototype, "withCredentials", {
get: function () {
return "include" === this.m;
},
set: function (a) {
this.m = a ? "include" : "same-origin";
},
});
var vd = l.JSON.parse;
function X(a) {
C.call(this);
this.headers = new S();
this.u = a || null;
this.h = !1;
this.C = this.g = null;
this.H = "";
this.m = 0;
this.j = "";
this.l = this.F = this.v = this.D = !1;
this.B = 0;
this.A = null;
this.J = wd;
this.K = this.L = !1;
}
t(X, C);
var wd = "",
xd = /^https?$/i,
yd = ["POST", "PUT"];
k = X.prototype;
k.ea = function (a, b, c, d) {
if (this.g)
throw Error(
"[goog.net.XhrIo] Object is active with another request=" +
this.H +
"; newUri=" +
a
);
b = b ? b.toUpperCase() : "GET";
this.H = a;
this.j = "";
this.m = 0;
this.D = !1;
this.h = !0;
this.g = this.u ? this.u.g() : cc.g();
this.C = this.u ? Zb(this.u) : Zb(cc);
this.g.onreadystatechange = q(this.Fa, this);
try {
(this.F = !0), this.g.open(b, String(a), !0), (this.F = !1);
} catch (f) {
zd(this, f);
return;
}
a = c || "";
const e = new S(this.headers);
d &&
Kc(d, function (f, h) {
e.set(h, f);
});
d = oa(e.T());
c = l.FormData && a instanceof l.FormData;
!(0 <= ma(yd, b)) ||
d ||
c ||
e.set(
"Content-Type",
"application/x-www-form-urlencoded;charset=utf-8"
);
e.forEach(function (f, h) {
this.g.setRequestHeader(h, f);
}, this);
this.J && (this.g.responseType = this.J);
"withCredentials" in this.g &&
this.g.withCredentials !== this.L &&
(this.g.withCredentials = this.L);
try {
Ad(this),
0 < this.B &&
((this.K = Bd(this.g))
? ((this.g.timeout = this.B),
(this.g.ontimeout = q(this.pa, this)))
: (this.A = Gb(this.pa, this.B, this))),
(this.v = !0),
this.g.send(a),
(this.v = !1);
} catch (f) {
zd(this, f);
}
};
function Bd(a) {
return (
y &&
Ra() &&
"number" === typeof a.timeout &&
void 0 !== a.ontimeout
);
}
function pa(a) {
return "content-type" == a.toLowerCase();
}
k.pa = function () {
"undefined" != typeof goog &&
this.g &&
((this.j = "Timed out after " + this.B + "ms, aborting"),
(this.m = 8),
D(this, "timeout"),
this.abort(8));
};
function zd(a, b) {
a.h = !1;
a.g && ((a.l = !0), a.g.abort(), (a.l = !1));
a.j = b;
a.m = 5;
Cd(a);
Dd(a);
}
function Cd(a) {
a.D || ((a.D = !0), D(a, "complete"), D(a, "error"));
}
k.abort = function (a) {
this.g &&
this.h &&
((this.h = !1),
(this.l = !0),
this.g.abort(),
(this.l = !1),
(this.m = a || 7),
D(this, "complete"),
D(this, "abort"),
Dd(this));
};
k.M = function () {
this.g &&
(this.h &&
((this.h = !1),
(this.l = !0),
this.g.abort(),
(this.l = !1)),
Dd(this, !0));
X.Z.M.call(this);
};
k.Fa = function () {
this.s || (this.F || this.v || this.l ? Ed(this) : this.cb());
};
k.cb = function () {
Ed(this);
};
function Ed(a) {
if (
a.h &&
"undefined" != typeof goog &&
(!a.C[1] || 4 != O(a) || 2 != a.ba())
)
if (a.v && 4 == O(a)) Gb(a.Fa, 0, a);
else if ((D(a, "readystatechange"), 4 == O(a))) {
a.h = !1;
try {
const n = a.ba();
a: switch (n) {
case 200:
case 201:
case 202:
case 204:
case 206:
case 304:
case 1223:
var b = !0;
break a;
default:
b = !1;
}
var c;
if (!(c = b)) {
var d;
if ((d = 0 === n)) {
var e = String(a.H).match(Mc)[1] || null;
if (!e && l.self && l.self.location) {
var f = l.self.location.protocol;
e = f.substr(0, f.length - 1);
}
d = !xd.test(e ? e.toLowerCase() : "");
}
c = d;
}
if (c) D(a, "complete"), D(a, "success");
else {
a.m = 6;
try {
var h = 2 < O(a) ? a.g.statusText : "";
} catch (u) {
h = "";
}
a.j = h + " [" + a.ba() + "]";
Cd(a);
}
} finally {
Dd(a);
}
}
}
function Dd(a, b) {
if (a.g) {
Ad(a);
const c = a.g,
d = a.C[0] ? aa : null;
a.g = null;
a.C = null;
b || D(a, "ready");
try {
c.onreadystatechange = d;
} catch (e) {}
}
}
function Ad(a) {
a.g && a.K && (a.g.ontimeout = null);
a.A && (l.clearTimeout(a.A), (a.A = null));
}
function O(a) {
return a.g ? a.g.readyState : 0;
}
k.ba = function () {
try {
return 2 < O(this) ? this.g.status : -1;
} catch (a) {
return -1;
}
};
k.ga = function () {
try {
return this.g ? this.g.responseText : "";
} catch (a) {
return "";
}
};
k.Qa = function (a) {
if (this.g) {
var b = this.g.responseText;
a && 0 == b.indexOf(a) && (b = b.substring(a.length));
return vd(b);
}
};
function oc(a) {
try {
if (!a.g) return null;
if ("response" in a.g) return a.g.response;
switch (a.J) {
case wd:
case "text":
return a.g.responseText;
case "arraybuffer":
if ("mozResponseArrayBuffer" in a.g)
return a.g.mozResponseArrayBuffer;
}
return null;
} catch (b) {
return null;
}
}
k.Da = function () {
return this.m;
};
k.La = function () {
return "string" === typeof this.j ? this.j : String(this.j);
};
function Fd(a) {
let b = "";
xa(a, function (c, d) {
b += d;
b += ":";
b += c;
b += "\r\n";
});
return b;
}
function Gd(a, b, c) {
a: {
for (d in c) {
var d = !1;
break a;
}
d = !0;
}
d ||
((c = Fd(c)),
"string" === typeof a
? null != c && encodeURIComponent(String(c))
: R(a, b, c));
}
function Hd(a, b, c) {
return c && c.internalChannelParams
? c.internalChannelParams[a] || b
: b;
}
function Id(a) {
this.za = 0;
this.l = [];
this.h = new Mb();
this.la =
this.oa =
this.F =
this.W =
this.g =
this.sa =
this.D =
this.aa =
this.o =
this.P =
this.s =
null;
this.Za = this.V = 0;
this.Xa = Hd("failFast", !1, a);
this.N = this.v = this.u = this.m = this.j = null;
this.X = !0;
this.I = this.ta = this.U = -1;
this.Y = this.A = this.C = 0;
this.Pa = Hd("baseRetryDelayMs", 5e3, a);
this.$a = Hd("retryDelaySeedMs", 1e4, a);
this.Ya = Hd("forwardChannelMaxRetries", 2, a);
this.ra = Hd("forwardChannelRequestTimeoutMs", 2e4, a);
this.qa = (a && a.xmlHttpFactory) || void 0;
this.Ba = (a && a.Yb) || !1;
this.K = void 0;
this.H = (a && a.supportsCrossDomainXhr) || !1;
this.J = "";
this.i = new gd(a && a.concurrentRequestLimit);
this.Ca = new ld();
this.ja = (a && a.fastHandshake) || !1;
this.Ra = (a && a.Wb) || !1;
a && a.Aa && this.h.Aa();
a && a.forceLongPolling && (this.X = !1);
this.$ =
(!this.ja && this.X && a && a.detectBufferingProxy) || !1;
this.ka = void 0;
this.O = 0;
this.L = !1;
this.B = null;
this.Wa = !a || !1 !== a.Xb;
}
k = Id.prototype;
k.ma = 8;
k.G = 1;
function Ic(a) {
Jd(a);
if (3 == a.G) {
var b = a.V++,
c = N(a.F);
R(c, "SID", a.J);
R(c, "RID", b);
R(c, "TYPE", "terminate");
Kd(a, c);
b = new M(a, a.h, b, void 0);
b.K = 2;
b.v = jc(N(c));
c = !1;
l.navigator &&
l.navigator.sendBeacon &&
(c = l.navigator.sendBeacon(b.v.toString(), ""));
!c && l.Image && ((new Image().src = b.v), (c = !0));
c || ((b.g = nc(b.l, null)), b.g.ea(b.v));
b.F = Date.now();
lc(b);
}
Ld(a);
}
k.hb = function (a) {
try {
this.h.info("Origin Trials invoked: " + a);
} catch (b) {}
};
function Ac(a) {
a.g && (wc(a), a.g.cancel(), (a.g = null));
}
function Jd(a) {
Ac(a);
a.u && (l.clearTimeout(a.u), (a.u = null));
zc(a);
a.i.cancel();
a.m &&
("number" === typeof a.m && l.clearTimeout(a.m),
(a.m = null));
}
function Md(a, b) {
a.l.push(new fd(a.Za++, b));
3 == a.G && Hc(a);
}
function Hc(a) {
id(a.i) || a.m || ((a.m = !0), zb(a.Ha, a), (a.C = 0));
}
function Nd(a, b) {
if (Cc(a.i) >= a.i.j - (a.m ? 1 : 0)) return !1;
if (a.m) return (a.l = b.D.concat(a.l)), !0;
if (1 == a.G || 2 == a.G || a.C >= (a.Xa ? 0 : a.Ya)) return !1;
a.m = K(q(a.Ha, a, b), Od(a, a.C));
a.C++;
return !0;
}
k.Ha = function (a) {
if (this.m)
if (((this.m = null), 1 == this.G)) {
if (!a) {
this.V = Math.floor(1e5 * Math.random());
a = this.V++;
const e = new M(this, this.h, a, void 0);
let f = this.s;
this.P &&
(f
? ((f = ya(f)), Aa(f, this.P))
: (f = this.P));
null === this.o && (e.H = f);
if (this.ja)
a: {
var b = 0;
for (var c = 0; c < this.l.length; c++) {
b: {
var d = this.l[c];
if (
"__data__" in d.g &&
((d = d.g.__data__),
"string" === typeof d)
) {
d = d.length;
break b;
}
d = void 0;
}
if (void 0 === d) break;
b += d;
if (4096 < b) {
b = c;
break a;
}
if (
4096 === b ||
c === this.l.length - 1
) {
b = c + 1;
break a;
}
}
b = 1e3;
}
else b = 1e3;
b = Pd(this, e, b);
c = N(this.F);
R(c, "RID", a);
R(c, "CVER", 22);
this.D && R(c, "X-HTTP-Session-Id", this.D);
Kd(this, c);
this.o && f && Gd(c, this.o, f);
Dc(this.i, e);
this.Ra && R(c, "TYPE", "init");
this.ja
? (R(c, "$req", b),
R(c, "SID", "null"),
(e.$ = !0),
ic(e, c, null))
: ic(e, c, b);
this.G = 2;
}
} else
3 == this.G &&
(a
? Qd(this, a)
: 0 == this.l.length || id(this.i) || Qd(this));
};
function Qd(a, b) {
var c;
b ? (c = b.m) : (c = a.V++);
const d = N(a.F);
R(d, "SID", a.J);
R(d, "RID", c);
R(d, "AID", a.U);
Kd(a, d);
a.o && a.s && Gd(d, a.o, a.s);
c = new M(a, a.h, c, a.C + 1);
null === a.o && (c.H = a.s);
b && (a.l = b.D.concat(a.l));
b = Pd(a, c, 1e3);
c.setTimeout(
Math.round(0.5 * a.ra) +
Math.round(0.5 * a.ra * Math.random())
);
Dc(a.i, c);
ic(c, d, b);
}
function Kd(a, b) {
a.j &&
Kc({}, function (c, d) {
R(b, d, c);
});
}
function Pd(a, b, c) {
c = Math.min(a.l.length, c);
var d = a.j ? q(a.j.Oa, a.j, a) : null;
a: {
var e = a.l;
let f = -1;
for (;;) {
const h = ["count=" + c];
-1 == f
? 0 < c
? ((f = e[0].h), h.push("ofs=" + f))
: (f = 0)
: h.push("ofs=" + f);
let n = !0;
for (let u = 0; u < c; u++) {
let m = e[u].h;
const r = e[u].g;
m -= f;
if (0 > m)
(f = Math.max(0, e[u].h - 100)), (n = !1);
else
try {
md(r, h, "req" + m + "_");
} catch (G) {
d && d(r);
}
}
if (n) {
d = h.join("&");
break a;
}
}
}
a = a.l.splice(0, c);
b.D = a;
return d;
}
function Gc(a) {
a.g || a.u || ((a.Y = 1), zb(a.Ga, a), (a.A = 0));
}
function Bc(a) {
if (a.g || a.u || 3 <= a.A) return !1;
a.Y++;
a.u = K(q(a.Ga, a), Od(a, a.A));
a.A++;
return !0;
}
k.Ga = function () {
this.u = null;
Rd(this);
if (this.$ && !(this.L || null == this.g || 0 >= this.O)) {
var a = 2 * this.O;
this.h.info("BP detection timer enabled: " + a);
this.B = K(q(this.bb, this), a);
}
};
k.bb = function () {
this.B &&
((this.B = null),
this.h.info("BP detection timeout reached."),
this.h.info(
"Buffering proxy detected and switch to long-polling!"
),
(this.N = !1),
(this.L = !0),
J(10),
Ac(this),
Rd(this));
};
function wc(a) {
null != a.B && (l.clearTimeout(a.B), (a.B = null));
}
function Rd(a) {
a.g = new M(a, a.h, "rpc", a.Y);
null === a.o && (a.g.H = a.s);
a.g.O = 0;
var b = N(a.oa);
R(b, "RID", "rpc");
R(b, "SID", a.J);
R(b, "CI", a.N ? "0" : "1");
R(b, "AID", a.U);
Kd(a, b);
R(b, "TYPE", "xmlhttp");
a.o && a.s && Gd(b, a.o, a.s);
a.K && a.g.setTimeout(a.K);
var c = a.g;
a = a.la;
c.K = 1;
c.v = jc(N(b));
c.s = null;
c.U = !0;
kc(c, a);
}
k.ab = function () {
null != this.v && ((this.v = null), Ac(this), Bc(this), J(19));
};
function zc(a) {
null != a.v && (l.clearTimeout(a.v), (a.v = null));
}
function uc(a, b) {
var c = null;
if (a.g == b) {
zc(a);
wc(a);
a.g = null;
var d = 2;
} else if (yc(a.i, b)) (c = b.D), Fc(a.i, b), (d = 1);
else return;
a.I = b.N;
if (0 != a.G)
if (b.i)
if (1 == d) {
c = b.s ? b.s.length : 0;
b = Date.now() - b.F;
var e = a.C;
d = Sb();
D(d, new Vb(d, c, b, e));
Hc(a);
} else Gc(a);
else if (
((e = b.o),
3 == e ||
(0 == e && 0 < a.I) ||
!((1 == d && Nd(a, b)) || (2 == d && Bc(a))))
)
switch (
(c &&
0 < c.length &&
((b = a.i), (b.i = b.i.concat(c))),
e)
) {
case 1:
Q(a, 5);
break;
case 4:
Q(a, 10);
break;
case 3:
Q(a, 6);
break;
default:
Q(a, 2);
}
}
function Od(a, b) {
let c = a.Pa + Math.floor(Math.random() * a.$a);
a.j || (c *= 2);
return c * b;
}
function Q(a, b) {
a.h.info("Error code " + b);
if (2 == b) {
var c = null;
a.j && (c = null);
var d = q(a.jb, a);
c ||
((c = new U("//www.google.com/images/cleardot.gif")),
(l.location && "http" == l.location.protocol) ||
Oc(c, "https"),
jc(c));
nd(c.toString(), d);
} else J(2);
a.G = 0;
a.j && a.j.va(b);
Ld(a);
Jd(a);
}
k.jb = function (a) {
a
? (this.h.info("Successfully pinged google.com"), J(2))
: (this.h.info("Failed to ping google.com"), J(1));
};
function Ld(a) {
a.G = 0;
a.I = -1;
if (a.j) {
if (0 != jd(a.i).length || 0 != a.l.length)
(a.i.i.length = 0), ra(a.l), (a.l.length = 0);
a.j.ua();
}
}
function Ec(a, b, c) {
let d = ad(c);
if ("" != d.i) b && Pc(d, b + "." + d.i), Qc(d, d.m);
else {
const e = l.location;
d = bd(
e.protocol,
b ? b + "." + e.hostname : e.hostname,
+e.port,
c
);
}
a.aa &&
xa(a.aa, function (e, f) {
R(d, f, e);
});
b = a.D;
c = a.sa;
b && c && R(d, b, c);
R(d, "VER", a.ma);
Kd(a, d);
return d;
}
function nc(a, b, c) {
if (b && !a.H)
throw Error(
"Can't create secondary domain capable XhrIo object."
);
b =
c && a.Ba && !a.qa
? new X(new pd({ ib: !0 }))
: new X(a.qa);
b.L = a.H;
return b;
}
function Sd() {}
k = Sd.prototype;
k.xa = function () {};
k.wa = function () {};
k.va = function () {};
k.ua = function () {};
k.Oa = function () {};
function Td() {
if (y && !(10 <= Number(Ua)))
throw Error("Environmental error: no available transport.");
}
Td.prototype.g = function (a, b) {
return new Y(a, b);
};
function Y(a, b) {
C.call(this);
this.g = new Id(b);
this.l = a;
this.h = (b && b.messageUrlParams) || null;
a = (b && b.messageHeaders) || null;
b &&
b.clientProtocolHeaderRequired &&
(a
? (a["X-Client-Protocol"] = "webchannel")
: (a = { "X-Client-Protocol": "webchannel" }));
this.g.s = a;
a = (b && b.initMessageHeaders) || null;
b &&
b.messageContentType &&
(a
? (a["X-WebChannel-Content-Type"] =
b.messageContentType)
: (a = {
"X-WebChannel-Content-Type": b.messageContentType,
}));
b &&
b.ya &&
(a
? (a["X-WebChannel-Client-Profile"] = b.ya)
: (a = { "X-WebChannel-Client-Profile": b.ya }));
this.g.P = a;
(a = b && b.httpHeadersOverwriteParam) &&
!sa(a) &&
(this.g.o = a);
this.A = (b && b.supportsCrossDomainXhr) || !1;
this.v = (b && b.sendRawJson) || !1;
(b = b && b.httpSessionIdParam) &&
!sa(b) &&
((this.g.D = b),
(a = this.h),
null !== a &&
b in a &&
((a = this.h), b in a && delete a[b]));
this.j = new Z(this);
}
t(Y, C);
Y.prototype.m = function () {
this.g.j = this.j;
this.A && (this.g.H = !0);
var a = this.g,
b = this.l,
c = this.h || void 0;
a.Wa && (a.h.info("Origin Trials enabled."), zb(q(a.hb, a, b)));
J(0);
a.W = b;
a.aa = c || {};
a.N = a.X;
a.F = Ec(a, null, a.W);
Hc(a);
};
Y.prototype.close = function () {
Ic(this.g);
};
Y.prototype.u = function (a) {
if ("string" === typeof a) {
var b = {};
b.__data__ = a;
Md(this.g, b);
} else
this.v
? ((b = {}), (b.__data__ = rb(a)), Md(this.g, b))
: Md(this.g, a);
};
Y.prototype.M = function () {
this.g.j = null;
delete this.j;
Ic(this.g);
delete this.g;
Y.Z.M.call(this);
};
function Ud(a) {
ac.call(this);
var b = a.__sm__;
if (b) {
a: {
for (const c in b) {
a = c;
break a;
}
a = void 0;
}
if ((this.i = a))
(a = this.i),
(b = null !== b && a in b ? b[a] : void 0);
this.data = b;
} else this.data = a;
}
t(Ud, ac);
function Vd() {
bc.call(this);
this.status = 1;
}
t(Vd, bc);
function Z(a) {
this.g = a;
}
t(Z, Sd);
Z.prototype.xa = function () {
D(this.g, "a");
};
Z.prototype.wa = function (a) {
D(this.g, new Ud(a));
};
Z.prototype.va = function (a) {
D(this.g, new Vd(a));
};
Z.prototype.ua = function () {
D(this.g, "b");
}; /*
Copyright 2017 Google 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.
*/
Td.prototype.createWebChannel = Td.prototype.g;
Y.prototype.send = Y.prototype.u;
Y.prototype.open = Y.prototype.m;
Y.prototype.close = Y.prototype.close;
Wb.NO_ERROR = 0;
Wb.TIMEOUT = 8;
Wb.HTTP_ERROR = 6;
Xb.COMPLETE = "complete";
$b.EventType = L;
L.OPEN = "a";
L.CLOSE = "b";
L.ERROR = "c";
L.MESSAGE = "d";
C.prototype.listen = C.prototype.N;
X.prototype.listenOnce = X.prototype.O;
X.prototype.getLastError = X.prototype.La;
X.prototype.getLastErrorCode = X.prototype.Da;
X.prototype.getStatus = X.prototype.ba;
X.prototype.getResponseJson = X.prototype.Qa;
X.prototype.getResponseText = X.prototype.ga;
X.prototype.send = X.prototype.ea;
var createWebChannelTransport = (esm.createWebChannelTransport =
function () {
return new Td();
});
var getStatEventTarget = (esm.getStatEventTarget = function () {
return Sb();
});
var ErrorCode = (esm.ErrorCode = Wb);
var EventType = (esm.EventType = Xb);
var Event = (esm.Event = H);
var Stat = (esm.Stat = {
rb: 0,
ub: 1,
vb: 2,
Ob: 3,
Tb: 4,
Qb: 5,
Rb: 6,
Pb: 7,
Nb: 8,
Sb: 9,
PROXY: 10,
NOPROXY: 11,
Lb: 12,
Hb: 13,
Ib: 14,
Gb: 15,
Jb: 16,
Kb: 17,
nb: 18,
mb: 19,
ob: 20,
});
var FetchXmlHttpFactory = (esm.FetchXmlHttpFactory = pd);
var WebChannel = (esm.WebChannel = $b);
var XhrIo = (esm.XhrIo = X);
//# sourceMappingURL=index.esm2017.js.map
/***/
},
/***/ 6257: /***/ function (
__unused_webpack_module,
__webpack_exports__,
__webpack_require__
) {
"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ hJ: function () {
return /* reexport safe */ _firebase_firestore__WEBPACK_IMPORTED_MODULE_0__.hJ;
},
/* harmony export */ PL: function () {
return /* reexport safe */ _firebase_firestore__WEBPACK_IMPORTED_MODULE_0__.PL;
},
/* harmony export */
});
/* harmony import */ var _firebase_firestore__WEBPACK_IMPORTED_MODULE_0__ =
__webpack_require__(19);
//# sourceMappingURL=index.esm.js.map
/***/
},
/***/ 8045: /***/ function (
__unused_webpack_module,
exports,
__webpack_require__
) {
"use strict";
var __webpack_unused_export__;
function _arrayWithHoles(arr) {
if (Array.isArray(arr)) return arr;
}
function _arrayWithoutHoles(arr) {
if (Array.isArray(arr)) {
for (
var i = 0, arr2 = new Array(arr.length);
i < arr.length;
i++
) {
arr2[i] = arr[i];
}
return arr2;
}
}
function _iterableToArray(iter) {
if (
Symbol.iterator in Object(iter) ||
Object.prototype.toString.call(iter) ===
"[object Arguments]"
)
return Array.from(iter);
}
function _iterableToArrayLimit(arr, i) {
var _arr = [];
var _n = true;
var _d = false;
var _e = undefined;
try {
for (
var _i = arr[Symbol.iterator](), _s;
!(_n = (_s = _i.next()).done);
_n = true
) {
_arr.push(_s.value);
if (i && _arr.length === i) break;
}
} catch (err) {
_d = true;
_e = err;
} finally {
try {
if (!_n && _i["return"] != null) _i["return"]();
} finally {
if (_d) throw _e;
}
}
return _arr;
}
function _nonIterableRest() {
throw new TypeError(
"Invalid attempt to destructure non-iterable instance"
);
}
function _nonIterableSpread() {
throw new TypeError(
"Invalid attempt to spread non-iterable instance"
);
}
function _slicedToArray(arr, i) {
return (
_arrayWithHoles(arr) ||
_iterableToArrayLimit(arr, i) ||
_nonIterableRest()
);
}
function _toConsumableArray(arr) {
return (
_arrayWithoutHoles(arr) ||
_iterableToArray(arr) ||
_nonIterableSpread()
);
}
__webpack_unused_export__ = {
value: true,
};
exports["default"] = Image;
var _react = _interopRequireDefault(__webpack_require__(7294));
var _head = _interopRequireDefault(__webpack_require__(5443));
var _toBase64 = __webpack_require__(6978);
var _imageConfig = __webpack_require__(5809);
var _useIntersection = __webpack_require__(7190);
function _defineProperty(obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true,
});
} else {
obj[key] = value;
}
return obj;
}
function _interopRequireDefault(obj) {
return obj && obj.__esModule
? obj
: {
default: obj,
};
}
function _objectSpread(target) {
var _arguments = arguments,
_loop = function (i) {
var source = _arguments[i] != null ? _arguments[i] : {};
var ownKeys = Object.keys(source);
if (
typeof Object.getOwnPropertySymbols === "function"
) {
ownKeys = ownKeys.concat(
Object.getOwnPropertySymbols(source).filter(
function (sym) {
return Object.getOwnPropertyDescriptor(
source,
sym
).enumerable;
}
)
);
}
ownKeys.forEach(function (key) {
_defineProperty(target, key, source[key]);
});
};
for (var i = 1; i < arguments.length; i++) _loop(i);
return target;
}
function _objectWithoutProperties(source, excluded) {
if (source == null) return {};
var target = _objectWithoutPropertiesLoose(source, excluded);
var key, i;
if (Object.getOwnPropertySymbols) {
var sourceSymbolKeys = Object.getOwnPropertySymbols(source);
for (i = 0; i < sourceSymbolKeys.length; i++) {
key = sourceSymbolKeys[i];
if (excluded.indexOf(key) >= 0) continue;
if (
!Object.prototype.propertyIsEnumerable.call(
source,
key
)
)
continue;
target[key] = source[key];
}
}
return target;
}
function _objectWithoutPropertiesLoose(source, excluded) {
if (source == null) return {};
var target = {};
var sourceKeys = Object.keys(source);
var key, i;
for (i = 0; i < sourceKeys.length; i++) {
key = sourceKeys[i];
if (excluded.indexOf(key) >= 0) continue;
target[key] = source[key];
}
return target;
}
var loadedImageURLs = new Set();
var allImgs = new Map();
var perfObserver;
var emptyDataURL =
"data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7";
if (false) {
}
var VALID_LOADING_VALUES = ["lazy", "eager", undefined];
var loaders = new Map([
["default", defaultLoader],
["imgix", imgixLoader],
["cloudinary", cloudinaryLoader],
["akamai", akamaiLoader],
["custom", customLoader],
]);
var VALID_LAYOUT_VALUES = [
"fill",
"fixed",
"intrinsic",
"responsive",
undefined,
];
function isStaticRequire(src) {
return src.default !== undefined;
}
function isStaticImageData(src) {
return src.src !== undefined;
}
function isStaticImport(src) {
return (
typeof src === "object" &&
(isStaticRequire(src) || isStaticImageData(src))
);
}
var ref1 =
{
deviceSizes: [
640, 750, 828, 1080, 1200, 1920, 2048, 3840,
],
imageSizes: [16, 32, 48, 64, 96, 128, 256, 384],
path: "/_next/image",
loader: "default",
} || _imageConfig.imageConfigDefault,
configDeviceSizes = ref1.deviceSizes,
configImageSizes = ref1.imageSizes,
configLoader = ref1.loader,
configPath = ref1.path,
configDomains = ref1.domains;
// sort smallest to largest
var allSizes = _toConsumableArray(configDeviceSizes).concat(
_toConsumableArray(configImageSizes)
);
configDeviceSizes.sort(function (a, b) {
return a - b;
});
allSizes.sort(function (a, b) {
return a - b;
});
function getWidths(width, layout, sizes) {
if (sizes && (layout === "fill" || layout === "responsive")) {
// Find all the "vw" percent sizes used in the sizes prop
var viewportWidthRe = /(^|\s)(1?\d?\d)vw/g;
var percentSizes = [];
for (
var match;
(match = viewportWidthRe.exec(sizes));
match
) {
percentSizes.push(parseInt(match[2]));
}
if (percentSizes.length) {
var _Math;
var smallestRatio =
(_Math = Math).min.apply(
_Math,
_toConsumableArray(percentSizes)
) * 0.01;
return {
widths: allSizes.filter(function (s) {
return (
s >= configDeviceSizes[0] * smallestRatio
);
}),
kind: "w",
};
}
return {
widths: allSizes,
kind: "w",
};
}
if (
typeof width !== "number" ||
layout === "fill" ||
layout === "responsive"
) {
return {
widths: configDeviceSizes,
kind: "w",
};
}
var widths = _toConsumableArray(
new Set( // > are actually 3x in the green color, but only 1.5x in the red and
// > blue colors. Showing a 3x resolution image in the app vs a 2x
// > resolution image will be visually the same, though the 3x image
// > takes significantly more data. Even true 3x resolution screens are
// > wasteful as the human eye cannot see that level of detail without
// > something like a magnifying glass.
// https://blog.twitter.com/engineering/en_us/topics/infrastructure/2019/capping-image-fidelity-on-ultra-high-resolution-devices.html
[width, width * 2 /*, width * 3*/].map(function (w) {
return (
allSizes.find(function (p) {
return p >= w;
}) || allSizes[allSizes.length - 1]
);
})
)
);
return {
widths: widths,
kind: "x",
};
}
function generateImgAttrs(param) {
var src = param.src,
unoptimized = param.unoptimized,
layout = param.layout,
width = param.width,
quality = param.quality,
sizes = param.sizes,
loader = param.loader;
if (unoptimized) {
return {
src: src,
srcSet: undefined,
sizes: undefined,
};
}
var ref = getWidths(width, layout, sizes),
widths = ref.widths,
kind = ref.kind;
var last = widths.length - 1;
return {
sizes: !sizes && kind === "w" ? "100vw" : sizes,
srcSet: widths
.map(function (w, i) {
return ""
.concat(
loader({
src: src,
quality: quality,
width: w,
}),
" "
)
.concat(kind === "w" ? w : i + 1)
.concat(kind);
})
.join(", "),
// It's intended to keep `src` the last attribute because React updates
// attributes in order. If we keep `src` the first one, Safari will
// immediately start to fetch `src`, before `sizes` and `srcSet` are even
// updated by React. That causes multiple unnecessary requests if `srcSet`
// and `sizes` are defined.
// This bug cannot be reproduced in Chrome or Firefox.
src: loader({
src: src,
quality: quality,
width: widths[last],
}),
};
}
function getInt(x) {
if (typeof x === "number") {
return x;
}
if (typeof x === "string") {
return parseInt(x, 10);
}
return undefined;
}
function defaultImageLoader(loaderProps) {
var load = loaders.get(configLoader);
if (load) {
return load(
_objectSpread(
{
root: configPath,
},
loaderProps
)
);
}
throw new Error(
'Unknown "loader" found in "next.config.js". Expected: '
.concat(
_imageConfig.VALID_LOADERS.join(", "),
". Received: "
)
.concat(configLoader)
);
}
// See https://stackoverflow.com/q/39777833/266535 for why we use this ref
// handler instead of the img's onLoad attribute.
function handleLoading(
img,
src,
layout,
placeholder,
onLoadingComplete
) {
if (!img) {
return;
}
var handleLoad = function () {
if (img.src !== emptyDataURL) {
var p =
"decode" in img ? img.decode() : Promise.resolve();
p.catch(function () {}).then(function () {
if (placeholder === "blur") {
img.style.filter = "none";
img.style.backgroundSize = "none";
img.style.backgroundImage = "none";
}
loadedImageURLs.add(src);
if (onLoadingComplete) {
var naturalWidth = img.naturalWidth,
naturalHeight = img.naturalHeight;
// Pass back read-only primitive values but not the
// underlying DOM element because it could be misused.
onLoadingComplete({
naturalWidth: naturalWidth,
naturalHeight: naturalHeight,
});
}
if (false) {
var parent, ref;
}
});
}
};
if (img.complete) {
// If the real image fails to load, this will still remove the placeholder.
// This is the desired behavior for now, and will be revisited when error
// handling is worked on for the image component itself.
handleLoad();
} else {
img.onload = handleLoad;
}
}
function Image(_param) {
var src = _param.src,
sizes = _param.sizes,
_unoptimized = _param.unoptimized,
unoptimized =
_unoptimized === void 0 ? false : _unoptimized,
_priority = _param.priority,
priority = _priority === void 0 ? false : _priority,
loading = _param.loading,
_lazyBoundary = _param.lazyBoundary,
lazyBoundary =
_lazyBoundary === void 0 ? "200px" : _lazyBoundary,
className = _param.className,
quality = _param.quality,
width = _param.width,
height = _param.height,
objectFit = _param.objectFit,
objectPosition = _param.objectPosition,
onLoadingComplete = _param.onLoadingComplete,
_loader = _param.loader,
loader = _loader === void 0 ? defaultImageLoader : _loader,
_placeholder = _param.placeholder,
placeholder =
_placeholder === void 0 ? "empty" : _placeholder,
blurDataURL = _param.blurDataURL,
all = _objectWithoutProperties(_param, [
"src",
"sizes",
"unoptimized",
"priority",
"loading",
"lazyBoundary",
"className",
"quality",
"width",
"height",
"objectFit",
"objectPosition",
"onLoadingComplete",
"loader",
"placeholder",
"blurDataURL",
]);
var rest = all;
var layout = sizes ? "responsive" : "intrinsic";
if ("layout" in rest) {
// Override default layout if the user specified one:
if (rest.layout) layout = rest.layout;
// Remove property so it's not spread into image:
delete rest["layout"];
}
var staticSrc = "";
if (isStaticImport(src)) {
var staticImageData = isStaticRequire(src)
? src.default
: src;
if (!staticImageData.src) {
throw new Error(
"An object should only be passed to the image component src parameter if it comes from a static image import. It must include src. Received ".concat(
JSON.stringify(staticImageData)
)
);
}
blurDataURL = blurDataURL || staticImageData.blurDataURL;
staticSrc = staticImageData.src;
if (!layout || layout !== "fill") {
height = height || staticImageData.height;
width = width || staticImageData.width;
if (!staticImageData.height || !staticImageData.width) {
throw new Error(
"An object should only be passed to the image component src parameter if it comes from a static image import. It must include height and width. Received ".concat(
JSON.stringify(staticImageData)
)
);
}
}
}
src = typeof src === "string" ? src : staticSrc;
var widthInt = getInt(width);
var heightInt = getInt(height);
var qualityInt = getInt(quality);
var isLazy =
!priority &&
(loading === "lazy" || typeof loading === "undefined");
if (src.startsWith("data:") || src.startsWith("blob:")) {
// https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URIs
unoptimized = true;
isLazy = false;
}
if (true && loadedImageURLs.has(src)) {
isLazy = false;
}
if (false) {
var url, urlStr, VALID_BLUR_EXT;
}
var ref2 = _slicedToArray(
(0, _useIntersection).useIntersection({
rootMargin: lazyBoundary,
disabled: !isLazy,
}),
2
),
setRef = ref2[0],
isIntersected = ref2[1];
var isVisible = !isLazy || isIntersected;
var wrapperStyle = {
boxSizing: "border-box",
display: "block",
overflow: "hidden",
width: "initial",
height: "initial",
background: "none",
opacity: 1,
border: 0,
margin: 0,
padding: 0,
};
var sizerStyle = {
boxSizing: "border-box",
display: "block",
width: "initial",
height: "initial",
background: "none",
opacity: 1,
border: 0,
margin: 0,
padding: 0,
};
var hasSizer = false;
var sizerSvg;
var imgStyle = {
position: "absolute",
top: 0,
left: 0,
bottom: 0,
right: 0,
boxSizing: "border-box",
padding: 0,
border: "none",
margin: "auto",
display: "block",
width: 0,
height: 0,
minWidth: "100%",
maxWidth: "100%",
minHeight: "100%",
maxHeight: "100%",
objectFit: objectFit,
objectPosition: objectPosition,
};
var blurStyle =
placeholder === "blur"
? {
filter: "blur(20px)",
backgroundSize: objectFit || "cover",
backgroundImage: 'url("'.concat(
blurDataURL,
'")'
),
backgroundPosition: objectPosition || "0% 0%",
}
: {};
if (layout === "fill") {
// <Image src="i.png" layout="fill" />
wrapperStyle.display = "block";
wrapperStyle.position = "absolute";
wrapperStyle.top = 0;
wrapperStyle.left = 0;
wrapperStyle.bottom = 0;
wrapperStyle.right = 0;
} else if (
typeof widthInt !== "undefined" &&
typeof heightInt !== "undefined"
) {
// <Image src="i.png" width="100" height="100" />
var quotient = heightInt / widthInt;
var paddingTop = isNaN(quotient)
? "100%"
: "".concat(quotient * 100, "%");
if (layout === "responsive") {
// <Image src="i.png" width="100" height="100" layout="responsive" />
wrapperStyle.display = "block";
wrapperStyle.position = "relative";
hasSizer = true;
sizerStyle.paddingTop = paddingTop;
} else if (layout === "intrinsic") {
// <Image src="i.png" width="100" height="100" layout="intrinsic" />
wrapperStyle.display = "inline-block";
wrapperStyle.position = "relative";
wrapperStyle.maxWidth = "100%";
hasSizer = true;
sizerStyle.maxWidth = "100%";
sizerSvg = '<svg width="'
.concat(widthInt, '" height="')
.concat(
heightInt,
'" xmlns="http://www.w3.org/2000/svg" version="1.1"/>'
);
} else if (layout === "fixed") {
// <Image src="i.png" width="100" height="100" layout="fixed" />
wrapperStyle.display = "inline-block";
wrapperStyle.position = "relative";
wrapperStyle.width = widthInt;
wrapperStyle.height = heightInt;
}
} else {
// <Image src="i.png" />
if (false) {
}
}
var imgAttributes = {
src: emptyDataURL,
srcSet: undefined,
sizes: undefined,
};
if (isVisible) {
imgAttributes = generateImgAttrs({
src: src,
unoptimized: unoptimized,
layout: layout,
width: widthInt,
quality: qualityInt,
sizes: sizes,
loader: loader,
});
}
var srcString = src;
if (false) {
var fullUrl;
}
return /*#__PURE__*/ _react.default.createElement(
"span",
{
style: wrapperStyle,
},
hasSizer
? /*#__PURE__*/ _react.default.createElement(
"span",
{
style: sizerStyle,
},
sizerSvg
? /*#__PURE__*/ _react.default.createElement(
"img",
{
style: {
display: "block",
maxWidth: "100%",
width: "initial",
height: "initial",
background: "none",
opacity: 1,
border: 0,
margin: 0,
padding: 0,
},
alt: "",
"aria-hidden": true,
src: "data:image/svg+xml;base64,".concat(
(0, _toBase64).toBase64(
sizerSvg
)
),
}
)
: null
)
: null,
/*#__PURE__*/ _react.default.createElement(
"img",
Object.assign({}, rest, imgAttributes, {
decoding: "async",
"data-nimg": layout,
className: className,
ref: function (img) {
setRef(img);
handleLoading(
img,
srcString,
layout,
placeholder,
onLoadingComplete
);
},
style: _objectSpread({}, imgStyle, blurStyle),
})
),
/*#__PURE__*/ _react.default.createElement(
"noscript",
null,
/*#__PURE__*/ _react.default.createElement(
"img",
Object.assign(
{},
rest,
generateImgAttrs({
src: src,
unoptimized: unoptimized,
layout: layout,
width: widthInt,
quality: qualityInt,
sizes: sizes,
loader: loader,
}),
{
decoding: "async",
"data-nimg": layout,
style: imgStyle,
className: className,
// @ts-ignore - TODO: upgrade to `@types/react@17`
loading: loading || "lazy",
}
)
)
),
priority // for browsers that do not support `imagesrcset`, and in those cases
? // it would likely cause the incorrect image to be preloaded.
//
// https://html.spec.whatwg.org/multipage/semantics.html#attr-link-imagesrcset
/*#__PURE__*/ _react.default.createElement(
_head.default,
null,
/*#__PURE__*/ _react.default.createElement(
"link",
{
key:
"__nimg-" +
imgAttributes.src +
imgAttributes.srcSet +
imgAttributes.sizes,
rel: "preload",
as: "image",
href: imgAttributes.srcSet
? undefined
: imgAttributes.src,
// @ts-ignore: imagesrcset is not yet in the link element type.
imagesrcset: imgAttributes.srcSet,
// @ts-ignore: imagesizes is not yet in the link element type.
imagesizes: imgAttributes.sizes,
}
)
)
: null
);
}
function normalizeSrc(src) {
return src[0] === "/" ? src.slice(1) : src;
}
function imgixLoader(param) {
var root = param.root,
src = param.src,
width = param.width,
quality = param.quality;
// Demo: https://static.imgix.net/daisy.png?auto=format&fit=max&w=300
var url = new URL("".concat(root).concat(normalizeSrc(src)));
var params = url.searchParams;
params.set("auto", params.get("auto") || "format");
params.set("fit", params.get("fit") || "max");
params.set("w", params.get("w") || width.toString());
if (quality) {
params.set("q", quality.toString());
}
return url.href;
}
function akamaiLoader(param) {
var root = param.root,
src = param.src,
width = param.width;
return ""
.concat(root)
.concat(normalizeSrc(src), "?imwidth=")
.concat(width);
}
function cloudinaryLoader(param) {
var root = param.root,
src = param.src,
width = param.width,
quality = param.quality;
// Demo: https://res.cloudinary.com/demo/image/upload/w_300,c_limit,q_auto/turtles.jpg
var params = [
"f_auto",
"c_limit",
"w_" + width,
"q_" + (quality || "auto"),
];
var paramsString = params.join(",") + "/";
return ""
.concat(root)
.concat(paramsString)
.concat(normalizeSrc(src));
}
function customLoader(param) {
var src = param.src;
throw new Error(
'Image with src "'.concat(
src,
'" is missing "loader" prop.'
) +
"\nRead more: https://nextjs.org/docs/messages/next-image-missing-loader"
);
}
function defaultLoader(param) {
var root = param.root,
src = param.src,
width = param.width,
quality = param.quality;
if (false) {
var parsedSrc, missingValues;
}
return ""
.concat(root, "?url=")
.concat(encodeURIComponent(src), "&w=")
.concat(width, "&q=")
.concat(quality || 75);
} //# sourceMappingURL=image.js.map
/***/
},
/***/ 7190: /***/ function (
__unused_webpack_module,
exports,
__webpack_require__
) {
"use strict";
function _arrayWithHoles(arr) {
if (Array.isArray(arr)) return arr;
}
function _iterableToArrayLimit(arr, i) {
var _arr = [];
var _n = true;
var _d = false;
var _e = undefined;
try {
for (
var _i = arr[Symbol.iterator](), _s;
!(_n = (_s = _i.next()).done);
_n = true
) {
_arr.push(_s.value);
if (i && _arr.length === i) break;
}
} catch (err) {
_d = true;
_e = err;
} finally {
try {
if (!_n && _i["return"] != null) _i["return"]();
} finally {
if (_d) throw _e;
}
}
return _arr;
}
function _nonIterableRest() {
throw new TypeError(
"Invalid attempt to destructure non-iterable instance"
);
}
function _slicedToArray(arr, i) {
return (
_arrayWithHoles(arr) ||
_iterableToArrayLimit(arr, i) ||
_nonIterableRest()
);
}
Object.defineProperty(exports, "__esModule", {
value: true,
});
exports.useIntersection = useIntersection;
var _react = __webpack_require__(7294);
var _requestIdleCallback = __webpack_require__(9311);
var hasIntersectionObserver =
typeof IntersectionObserver !== "undefined";
function useIntersection(param) {
var rootMargin = param.rootMargin,
disabled = param.disabled;
var isDisabled = disabled || !hasIntersectionObserver;
var unobserve = (0, _react).useRef();
var ref = _slicedToArray((0, _react).useState(false), 2),
visible = ref[0],
setVisible = ref[1];
var setRef = (0, _react).useCallback(
function (el) {
if (unobserve.current) {
unobserve.current();
unobserve.current = undefined;
}
if (isDisabled || visible) return;
if (el && el.tagName) {
unobserve.current = observe(
el,
function (isVisible) {
return isVisible && setVisible(isVisible);
},
{
rootMargin: rootMargin,
}
);
}
},
[isDisabled, rootMargin, visible]
);
(0, _react).useEffect(
function () {
if (!hasIntersectionObserver) {
if (!visible) {
var idleCallback = (0,
_requestIdleCallback).requestIdleCallback(
function () {
return setVisible(true);
}
);
return function () {
return (0,
_requestIdleCallback).cancelIdleCallback(
idleCallback
);
};
}
}
},
[visible]
);
return [setRef, visible];
}
function observe(element, callback, options) {
var ref = createObserver(options),
id = ref.id,
observer = ref.observer,
elements = ref.elements;
elements.set(element, callback);
observer.observe(element);
return function unobserve() {
elements.delete(element);
observer.unobserve(element);
// Destroy observer when there's nothing left to watch:
if (elements.size === 0) {
observer.disconnect();
observers.delete(id);
}
};
}
var observers = new Map();
function createObserver(options) {
var id = options.rootMargin || "";
var instance = observers.get(id);
if (instance) {
return instance;
}
var elements = new Map();
var observer = new IntersectionObserver(function (entries) {
entries.forEach(function (entry) {
var callback = elements.get(entry.target);
var isVisible =
entry.isIntersecting || entry.intersectionRatio > 0;
if (callback && isVisible) {
callback(isVisible);
}
});
}, options);
observers.set(
id,
(instance = {
id: id,
observer: observer,
elements: elements,
})
);
return instance;
} //# sourceMappingURL=use-intersection.js.map
/***/
},
/***/ 6978: /***/ function (__unused_webpack_module, exports) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true,
});
exports.toBase64 = toBase64;
function toBase64(str) {
if (false) {
} else {
return window.btoa(str);
}
} //# sourceMappingURL=to-base-64.js.map
/***/
},
/***/ 5809: /***/ function (__unused_webpack_module, exports) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true,
});
exports.imageConfigDefault = exports.VALID_LOADERS = void 0;
const VALID_LOADERS = [
"default",
"imgix",
"cloudinary",
"akamai",
"custom",
];
exports.VALID_LOADERS = VALID_LOADERS;
const imageConfigDefault = {
deviceSizes: [640, 750, 828, 1080, 1200, 1920, 2048, 3840],
imageSizes: [16, 32, 48, 64, 96, 128, 256, 384],
path: "/_next/image",
loader: "default",
domains: [],
disableStaticImages: false,
minimumCacheTTL: 60,
formats: ["image/webp"],
};
exports.imageConfigDefault = imageConfigDefault;
//# sourceMappingURL=image-config.js.map
/***/
},
/***/ 9008: /***/ function (
module,
__unused_webpack_exports,
__webpack_require__
) {
module.exports = __webpack_require__(5443);
/***/
},
/***/ 5675: /***/ function (
module,
__unused_webpack_exports,
__webpack_require__
) {
module.exports = __webpack_require__(8045);
/***/
},
/***/ 2238: /***/ function (
__unused_webpack___webpack_module__,
__webpack_exports__,
__webpack_require__
) {
"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ Jn: function () {
return /* binding */ SDK_VERSION;
},
/* harmony export */ Xd: function () {
return /* binding */ _registerComponent;
},
/* harmony export */ KN: function () {
return /* binding */ registerVersion;
},
/* harmony export */
});
/* unused harmony exports _DEFAULT_ENTRY_NAME, _addComponent, _addOrOverwriteComponent, _apps, _clearComponents, _components, _getProvider, _removeServiceInstance, deleteApp, getApp, getApps, initializeApp, onLog, setLogLevel */
/* harmony import */ var _firebase_component__WEBPACK_IMPORTED_MODULE_0__ =
__webpack_require__(8463);
/* harmony import */ var _firebase_logger__WEBPACK_IMPORTED_MODULE_1__ =
__webpack_require__(3333);
/* harmony import */ var _firebase_util__WEBPACK_IMPORTED_MODULE_2__ =
__webpack_require__(4444);
/**
* @license
* Copyright 2019 Google 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.
*/
class PlatformLoggerServiceImpl {
constructor(container) {
this.container = container;
}
// In initial implementation, this will be called by installations on
// auth token refresh, and installations will send this string.
getPlatformInfoString() {
const providers = this.container.getProviders();
// Loop through providers and get library/version pairs from any that are
// version components.
return providers
.map((provider) => {
if (isVersionServiceProvider(provider)) {
const service = provider.getImmediate();
return `${service.library}/${service.version}`;
} else {
return null;
}
})
.filter((logString) => logString)
.join(" ");
}
}
/**
*
* @param provider check if this provider provides a VersionService
*
* NOTE: Using Provider<'app-version'> is a hack to indicate that the provider
* provides VersionService. The provider is not necessarily a 'app-version'
* provider.
*/
function isVersionServiceProvider(provider) {
const component = provider.getComponent();
return (
(component === null || component === void 0
? void 0
: component.type) === "VERSION" /* VERSION */
);
}
const name$o = "@firebase/app";
const version$1 = "0.7.8";
/**
* @license
* Copyright 2019 Google 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.
*/
const logger =
new _firebase_logger__WEBPACK_IMPORTED_MODULE_1__ /* .Logger */.Yd(
"@firebase/app"
);
const name$n = "@firebase/app-compat";
const name$m = "@firebase/analytics-compat";
const name$l = "@firebase/analytics";
const name$k = "@firebase/app-check-compat";
const name$j = "@firebase/app-check";
const name$i = "@firebase/auth";
const name$h = "@firebase/auth-compat";
const name$g = "@firebase/database";
const name$f = "@firebase/database-compat";
const name$e = "@firebase/functions";
const name$d = "@firebase/functions-compat";
const name$c = "@firebase/installations";
const name$b = "@firebase/installations-compat";
const name$a = "@firebase/messaging";
const name$9 = "@firebase/messaging-compat";
const name$8 = "@firebase/performance";
const name$7 = "@firebase/performance-compat";
const name$6 = "@firebase/remote-config";
const name$5 = "@firebase/remote-config-compat";
const name$4 = "@firebase/storage";
const name$3 = "@firebase/storage-compat";
const name$2 = "@firebase/firestore";
const name$1 = "@firebase/firestore-compat";
const name = "firebase";
const version = "9.4.1";
/**
* @license
* Copyright 2019 Google 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.
*/
/**
* The default app name
*
* @internal
*/
const DEFAULT_ENTRY_NAME = "[DEFAULT]";
const PLATFORM_LOG_STRING = {
[name$o]: "fire-core",
[name$n]: "fire-core-compat",
[name$l]: "fire-analytics",
[name$m]: "fire-analytics-compat",
[name$j]: "fire-app-check",
[name$k]: "fire-app-check-compat",
[name$i]: "fire-auth",
[name$h]: "fire-auth-compat",
[name$g]: "fire-rtdb",
[name$f]: "fire-rtdb-compat",
[name$e]: "fire-fn",
[name$d]: "fire-fn-compat",
[name$c]: "fire-iid",
[name$b]: "fire-iid-compat",
[name$a]: "fire-fcm",
[name$9]: "fire-fcm-compat",
[name$8]: "fire-perf",
[name$7]: "fire-perf-compat",
[name$6]: "fire-rc",
[name$5]: "fire-rc-compat",
[name$4]: "fire-gcs",
[name$3]: "fire-gcs-compat",
[name$2]: "fire-fst",
[name$1]: "fire-fst-compat",
"fire-js": "fire-js",
[name]: "fire-js-all",
};
/**
* @license
* Copyright 2019 Google 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.
*/
/**
* @internal
*/
const _apps = new Map();
/**
* Registered components.
*
* @internal
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const _components = new Map();
/**
* @param component - the component being added to this app's container
*
* @internal
*/
function _addComponent(app, component) {
try {
app.container.addComponent(component);
} catch (e) {
logger.debug(
`Component ${component.name} failed to register with FirebaseApp ${app.name}`,
e
);
}
}
/**
*
* @internal
*/
function _addOrOverwriteComponent(app, component) {
app.container.addOrOverwriteComponent(component);
}
/**
*
* @param component - the component to register
* @returns whether or not the component is registered successfully
*
* @internal
*/
function _registerComponent(component) {
const componentName = component.name;
if (_components.has(componentName)) {
logger.debug(
`There were multiple attempts to register component ${componentName}.`
);
return false;
}
_components.set(componentName, component);
// add the component to existing app instances
for (const app of _apps.values()) {
_addComponent(app, component);
}
return true;
}
/**
*
* @param app - FirebaseApp instance
* @param name - service name
*
* @returns the provider for the service with the matching name
*
* @internal
*/
function _getProvider(app, name) {
return app.container.getProvider(name);
}
/**
*
* @param app - FirebaseApp instance
* @param name - service name
* @param instanceIdentifier - service instance identifier in case the service supports multiple instances
*
* @internal
*/
function _removeServiceInstance(
app,
name,
instanceIdentifier = DEFAULT_ENTRY_NAME
) {
_getProvider(app, name).clearInstance(instanceIdentifier);
}
/**
* Test only
*
* @internal
*/
function _clearComponents() {
_components.clear();
}
/**
* @license
* Copyright 2019 Google 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.
*/
const ERRORS = {
["no-app" /* NO_APP */]:
"No Firebase App '{$appName}' has been created - " +
"call Firebase App.initializeApp()",
["bad-app-name" /* BAD_APP_NAME */]:
"Illegal App name: '{$appName}",
["duplicate-app" /* DUPLICATE_APP */]:
"Firebase App named '{$appName}' already exists with different options or config",
["app-deleted" /* APP_DELETED */]:
"Firebase App named '{$appName}' already deleted",
["invalid-app-argument" /* INVALID_APP_ARGUMENT */]:
"firebase.{$appName}() takes either no argument or a " +
"Firebase App instance.",
["invalid-log-argument" /* INVALID_LOG_ARGUMENT */]:
"First argument to `onLog` must be null or a function.",
};
const ERROR_FACTORY =
new _firebase_util__WEBPACK_IMPORTED_MODULE_2__ /* .ErrorFactory */.LL(
"app",
"Firebase",
ERRORS
);
/**
* @license
* Copyright 2019 Google 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.
*/
class FirebaseAppImpl {
constructor(options, config, container) {
this._isDeleted = false;
this._options = Object.assign({}, options);
this._config = Object.assign({}, config);
this._name = config.name;
this._automaticDataCollectionEnabled =
config.automaticDataCollectionEnabled;
this._container = container;
this.container.addComponent(
new Component("app", () => this, "PUBLIC" /* PUBLIC */)
);
}
get automaticDataCollectionEnabled() {
this.checkDestroyed();
return this._automaticDataCollectionEnabled;
}
set automaticDataCollectionEnabled(val) {
this.checkDestroyed();
this._automaticDataCollectionEnabled = val;
}
get name() {
this.checkDestroyed();
return this._name;
}
get options() {
this.checkDestroyed();
return this._options;
}
get config() {
this.checkDestroyed();
return this._config;
}
get container() {
return this._container;
}
get isDeleted() {
return this._isDeleted;
}
set isDeleted(val) {
this._isDeleted = val;
}
/**
* This function will throw an Error if the App has already been deleted -
* use before performing API actions on the App.
*/
checkDestroyed() {
if (this.isDeleted) {
throw ERROR_FACTORY.create(
"app-deleted" /* APP_DELETED */,
{ appName: this._name }
);
}
}
}
/**
* @license
* Copyright 2019 Google 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.
*/
/**
* The current SDK version.
*
* @public
*/
const SDK_VERSION = version;
function initializeApp(options, rawConfig = {}) {
if (typeof rawConfig !== "object") {
const name = rawConfig;
rawConfig = { name };
}
const config = Object.assign(
{
name: DEFAULT_ENTRY_NAME,
automaticDataCollectionEnabled: false,
},
rawConfig
);
const name = config.name;
if (typeof name !== "string" || !name) {
throw ERROR_FACTORY.create(
"bad-app-name" /* BAD_APP_NAME */,
{
appName: String(name),
}
);
}
const existingApp = _apps.get(name);
if (existingApp) {
// return the existing app if options and config deep equal the ones in the existing app.
if (
deepEqual(options, existingApp.options) &&
deepEqual(config, existingApp.config)
) {
return existingApp;
} else {
throw ERROR_FACTORY.create(
"duplicate-app" /* DUPLICATE_APP */,
{ appName: name }
);
}
}
const container = new ComponentContainer(name);
for (const component of _components.values()) {
container.addComponent(component);
}
const newApp = new FirebaseAppImpl(options, config, container);
_apps.set(name, newApp);
return newApp;
}
/**
* Retrieves a {@link @firebase/app#FirebaseApp} instance.
*
* When called with no arguments, the default app is returned. When an app name
* is provided, the app corresponding to that name is returned.
*
* An exception is thrown if the app being retrieved has not yet been
* initialized.
*
* @example
* ```javascript
* // Return the default app
* const app = getApp();
* ```
*
* @example
* ```javascript
* // Return a named app
* const otherApp = getApp("otherApp");
* ```
*
* @param name - Optional name of the app to return. If no name is
* provided, the default is `"[DEFAULT]"`.
*
* @returns The app corresponding to the provided app name.
* If no app name is provided, the default app is returned.
*
* @public
*/
function getApp(name = DEFAULT_ENTRY_NAME) {
const app = _apps.get(name);
if (!app) {
throw ERROR_FACTORY.create("no-app" /* NO_APP */, {
appName: name,
});
}
return app;
}
/**
* A (read-only) array of all initialized apps.
* @public
*/
function getApps() {
return Array.from(_apps.values());
}
/**
* Renders this app unusable and frees the resources of all associated
* services.
*
* @example
* ```javascript
* deleteApp(app)
* .then(function() {
* console.log("App deleted successfully");
* })
* .catch(function(error) {
* console.log("Error deleting app:", error);
* });
* ```
*
* @public
*/
async function deleteApp(app) {
const name = app.name;
if (_apps.has(name)) {
_apps.delete(name);
await Promise.all(
app.container
.getProviders()
.map((provider) => provider.delete())
);
app.isDeleted = true;
}
}
/**
* Registers a library's name and version for platform logging purposes.
* @param library - Name of 1p or 3p library (e.g. firestore, angularfire)
* @param version - Current version of that library.
* @param variant - Bundle variant, e.g., node, rn, etc.
*
* @public
*/
function registerVersion(libraryKeyOrName, version, variant) {
var _a;
// TODO: We can use this check to whitelist strings when/if we set up
// a good whitelist system.
let library =
(_a = PLATFORM_LOG_STRING[libraryKeyOrName]) !== null &&
_a !== void 0
? _a
: libraryKeyOrName;
if (variant) {
library += `-${variant}`;
}
const libraryMismatch = library.match(/\s|\//);
const versionMismatch = version.match(/\s|\//);
if (libraryMismatch || versionMismatch) {
const warning = [
`Unable to register library "${library}" with version "${version}":`,
];
if (libraryMismatch) {
warning.push(
`library name "${library}" contains illegal characters (whitespace or "/")`
);
}
if (libraryMismatch && versionMismatch) {
warning.push("and");
}
if (versionMismatch) {
warning.push(
`version name "${version}" contains illegal characters (whitespace or "/")`
);
}
logger.warn(warning.join(" "));
return;
}
_registerComponent(
new _firebase_component__WEBPACK_IMPORTED_MODULE_0__ /* .Component */.wA(
`${library}-version`,
() => ({ library, version }),
"VERSION" /* VERSION */
)
);
}
/**
* Sets log handler for all Firebase SDKs.
* @param logCallback - An optional custom log handler that executes user code whenever
* the Firebase SDK makes a logging call.
*
* @public
*/
function onLog(logCallback, options) {
if (logCallback !== null && typeof logCallback !== "function") {
throw ERROR_FACTORY.create(
"invalid-log-argument" /* INVALID_LOG_ARGUMENT */
);
}
setUserLogHandler(logCallback, options);
}
/**
* Sets log level for all Firebase SDKs.
*
* All of the log types above the current log level are captured (i.e. if
* you set the log level to `info`, errors are logged, but `debug` and
* `verbose` logs are not).
*
* @public
*/
function setLogLevel(logLevel) {
setLogLevel$1(logLevel);
}
/**
* @license
* Copyright 2019 Google 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.
*/
function registerCoreComponents(variant) {
_registerComponent(
new _firebase_component__WEBPACK_IMPORTED_MODULE_0__ /* .Component */.wA(
"platform-logger",
(container) => new PlatformLoggerServiceImpl(container),
"PRIVATE" /* PRIVATE */
)
);
// Register `app` package.
registerVersion(name$o, version$1, variant);
// BUILD_TARGET will be replaced by values like esm5, esm2017, cjs5, etc during the compilation
registerVersion(name$o, version$1, "esm2017");
// Register platform SDK identifier (no version).
registerVersion("fire-js", "");
}
/**
* Firebase App
*
* @remarks This package coordinates the communication between the different Firebase components
* @packageDocumentation
*/
registerCoreComponents("");
//# sourceMappingURL=index.esm2017.js.map
/***/
},
/***/ 8463: /***/ function (
__unused_webpack___webpack_module__,
__webpack_exports__,
__webpack_require__
) {
"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ wA: function () {
return /* binding */ Component;
},
/* harmony export */
});
/* unused harmony exports ComponentContainer, Provider */
/* harmony import */ var _firebase_util__WEBPACK_IMPORTED_MODULE_0__ =
__webpack_require__(4444);
/**
* Component for service name T, e.g. `auth`, `auth-internal`
*/
class Component {
/**
*
* @param name The public service name, e.g. app, auth, firestore, database
* @param instanceFactory Service factory responsible for creating the public interface
* @param type whether the service provided by the component is public or private
*/
constructor(name, instanceFactory, type) {
this.name = name;
this.instanceFactory = instanceFactory;
this.type = type;
this.multipleInstances = false;
/**
* Properties to be added to the service namespace
*/
this.serviceProps = {};
this.instantiationMode = "LAZY" /* LAZY */;
this.onInstanceCreated = null;
}
setInstantiationMode(mode) {
this.instantiationMode = mode;
return this;
}
setMultipleInstances(multipleInstances) {
this.multipleInstances = multipleInstances;
return this;
}
setServiceProps(props) {
this.serviceProps = props;
return this;
}
setInstanceCreatedCallback(callback) {
this.onInstanceCreated = callback;
return this;
}
}
/**
* @license
* Copyright 2019 Google 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.
*/
const DEFAULT_ENTRY_NAME = "[DEFAULT]";
/**
* @license
* Copyright 2019 Google 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.
*/
/**
* Provider for instance for service name T, e.g. 'auth', 'auth-internal'
* NameServiceMapping[T] is an alias for the type of the instance
*/
class Provider {
constructor(name, container) {
this.name = name;
this.container = container;
this.component = null;
this.instances = new Map();
this.instancesDeferred = new Map();
this.instancesOptions = new Map();
this.onInitCallbacks = new Map();
}
/**
* @param identifier A provider can provide mulitple instances of a service
* if this.component.multipleInstances is true.
*/
get(identifier) {
// if multipleInstances is not supported, use the default name
const normalizedIdentifier =
this.normalizeInstanceIdentifier(identifier);
if (!this.instancesDeferred.has(normalizedIdentifier)) {
const deferred = new Deferred();
this.instancesDeferred.set(
normalizedIdentifier,
deferred
);
if (
this.isInitialized(normalizedIdentifier) ||
this.shouldAutoInitialize()
) {
// initialize the service if it can be auto-initialized
try {
const instance = this.getOrInitializeService({
instanceIdentifier: normalizedIdentifier,
});
if (instance) {
deferred.resolve(instance);
}
} catch (e) {
// when the instance factory throws an exception during get(), it should not cause
// a fatal error. We just return the unresolved promise in this case.
}
}
}
return this.instancesDeferred.get(normalizedIdentifier)
.promise;
}
getImmediate(options) {
var _a;
// if multipleInstances is not supported, use the default name
const normalizedIdentifier =
this.normalizeInstanceIdentifier(
options === null || options === void 0
? void 0
: options.identifier
);
const optional =
(_a =
options === null || options === void 0
? void 0
: options.optional) !== null && _a !== void 0
? _a
: false;
if (
this.isInitialized(normalizedIdentifier) ||
this.shouldAutoInitialize()
) {
try {
return this.getOrInitializeService({
instanceIdentifier: normalizedIdentifier,
});
} catch (e) {
if (optional) {
return null;
} else {
throw e;
}
}
} else {
// In case a component is not initialized and should/can not be auto-initialized at the moment, return null if the optional flag is set, or throw
if (optional) {
return null;
} else {
throw Error(
`Service ${this.name} is not available`
);
}
}
}
getComponent() {
return this.component;
}
setComponent(component) {
if (component.name !== this.name) {
throw Error(
`Mismatching Component ${component.name} for Provider ${this.name}.`
);
}
if (this.component) {
throw Error(
`Component for ${this.name} has already been provided`
);
}
this.component = component;
// return early without attempting to initialize the component if the component requires explicit initialization (calling `Provider.initialize()`)
if (!this.shouldAutoInitialize()) {
return;
}
// if the service is eager, initialize the default instance
if (isComponentEager(component)) {
try {
this.getOrInitializeService({
instanceIdentifier: DEFAULT_ENTRY_NAME,
});
} catch (e) {
// when the instance factory for an eager Component throws an exception during the eager
// initialization, it should not cause a fatal error.
// TODO: Investigate if we need to make it configurable, because some component may want to cause
// a fatal error in this case?
}
}
// Create service instances for the pending promises and resolve them
// NOTE: if this.multipleInstances is false, only the default instance will be created
// and all promises with resolve with it regardless of the identifier.
for (const [
instanceIdentifier,
instanceDeferred,
] of this.instancesDeferred.entries()) {
const normalizedIdentifier =
this.normalizeInstanceIdentifier(
instanceIdentifier
);
try {
// `getOrInitializeService()` should always return a valid instance since a component is guaranteed. use ! to make typescript happy.
const instance = this.getOrInitializeService({
instanceIdentifier: normalizedIdentifier,
});
instanceDeferred.resolve(instance);
} catch (e) {
// when the instance factory throws an exception, it should not cause
// a fatal error. We just leave the promise unresolved.
}
}
}
clearInstance(identifier = DEFAULT_ENTRY_NAME) {
this.instancesDeferred.delete(identifier);
this.instancesOptions.delete(identifier);
this.instances.delete(identifier);
}
// app.delete() will call this method on every provider to delete the services
// TODO: should we mark the provider as deleted?
async delete() {
const services = Array.from(this.instances.values());
await Promise.all([
...services
.filter((service) => "INTERNAL" in service) // legacy services
// eslint-disable-next-line @typescript-eslint/no-explicit-any
.map((service) => service.INTERNAL.delete()),
...services
.filter((service) => "_delete" in service) // modularized services
// eslint-disable-next-line @typescript-eslint/no-explicit-any
.map((service) => service._delete()),
]);
}
isComponentSet() {
return this.component != null;
}
isInitialized(identifier = DEFAULT_ENTRY_NAME) {
return this.instances.has(identifier);
}
getOptions(identifier = DEFAULT_ENTRY_NAME) {
return this.instancesOptions.get(identifier) || {};
}
initialize(opts = {}) {
const { options = {} } = opts;
const normalizedIdentifier =
this.normalizeInstanceIdentifier(
opts.instanceIdentifier
);
if (this.isInitialized(normalizedIdentifier)) {
throw Error(
`${this.name}(${normalizedIdentifier}) has already been initialized`
);
}
if (!this.isComponentSet()) {
throw Error(
`Component ${this.name} has not been registered yet`
);
}
const instance = this.getOrInitializeService({
instanceIdentifier: normalizedIdentifier,
options,
});
// resolve any pending promise waiting for the service instance
for (const [
instanceIdentifier,
instanceDeferred,
] of this.instancesDeferred.entries()) {
const normalizedDeferredIdentifier =
this.normalizeInstanceIdentifier(
instanceIdentifier
);
if (
normalizedIdentifier ===
normalizedDeferredIdentifier
) {
instanceDeferred.resolve(instance);
}
}
return instance;
}
/**
*
* @param callback - a function that will be invoked after the provider has been initialized by calling provider.initialize().
* The function is invoked SYNCHRONOUSLY, so it should not execute any longrunning tasks in order to not block the program.
*
* @param identifier An optional instance identifier
* @returns a function to unregister the callback
*/
onInit(callback, identifier) {
var _a;
const normalizedIdentifier =
this.normalizeInstanceIdentifier(identifier);
const existingCallbacks =
(_a =
this.onInitCallbacks.get(normalizedIdentifier)) !==
null && _a !== void 0
? _a
: new Set();
existingCallbacks.add(callback);
this.onInitCallbacks.set(
normalizedIdentifier,
existingCallbacks
);
const existingInstance =
this.instances.get(normalizedIdentifier);
if (existingInstance) {
callback(existingInstance, normalizedIdentifier);
}
return () => {
existingCallbacks.delete(callback);
};
}
/**
* Invoke onInit callbacks synchronously
* @param instance the service instance`
*/
invokeOnInitCallbacks(instance, identifier) {
const callbacks = this.onInitCallbacks.get(identifier);
if (!callbacks) {
return;
}
for (const callback of callbacks) {
try {
callback(instance, identifier);
} catch (_a) {
// ignore errors in the onInit callback
}
}
}
getOrInitializeService({ instanceIdentifier, options = {} }) {
let instance = this.instances.get(instanceIdentifier);
if (!instance && this.component) {
instance = this.component.instanceFactory(
this.container,
{
instanceIdentifier:
normalizeIdentifierForFactory(
instanceIdentifier
),
options,
}
);
this.instances.set(instanceIdentifier, instance);
this.instancesOptions.set(instanceIdentifier, options);
/**
* Invoke onInit listeners.
* Note this.component.onInstanceCreated is different, which is used by the component creator,
* while onInit listeners are registered by consumers of the provider.
*/
this.invokeOnInitCallbacks(
instance,
instanceIdentifier
);
/**
* Order is important
* onInstanceCreated() should be called after this.instances.set(instanceIdentifier, instance); which
* makes `isInitialized()` return true.
*/
if (this.component.onInstanceCreated) {
try {
this.component.onInstanceCreated(
this.container,
instanceIdentifier,
instance
);
} catch (_a) {
// ignore errors in the onInstanceCreatedCallback
}
}
}
return instance || null;
}
normalizeInstanceIdentifier(identifier = DEFAULT_ENTRY_NAME) {
if (this.component) {
return this.component.multipleInstances
? identifier
: DEFAULT_ENTRY_NAME;
} else {
return identifier; // assume multiple instances are supported before the component is provided.
}
}
shouldAutoInitialize() {
return (
!!this.component &&
this.component.instantiationMode !==
"EXPLICIT" /* EXPLICIT */
);
}
}
// undefined should be passed to the service factory for the default instance
function normalizeIdentifierForFactory(identifier) {
return identifier === DEFAULT_ENTRY_NAME
? undefined
: identifier;
}
function isComponentEager(component) {
return component.instantiationMode === "EAGER" /* EAGER */;
}
/**
* @license
* Copyright 2019 Google 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.
*/
/**
* ComponentContainer that provides Providers for service name T, e.g. `auth`, `auth-internal`
*/
class ComponentContainer {
constructor(name) {
this.name = name;
this.providers = new Map();
}
/**
*
* @param component Component being added
* @param overwrite When a component with the same name has already been registered,
* if overwrite is true: overwrite the existing component with the new component and create a new
* provider with the new component. It can be useful in tests where you want to use different mocks
* for different tests.
* if overwrite is false: throw an exception
*/
addComponent(component) {
const provider = this.getProvider(component.name);
if (provider.isComponentSet()) {
throw new Error(
`Component ${component.name} has already been registered with ${this.name}`
);
}
provider.setComponent(component);
}
addOrOverwriteComponent(component) {
const provider = this.getProvider(component.name);
if (provider.isComponentSet()) {
// delete the existing provider from the container, so we can register the new component
this.providers.delete(component.name);
}
this.addComponent(component);
}
/**
* getProvider provides a type safe interface where it can only be called with a field name
* present in NameServiceMapping interface.
*
* Firebase SDKs providing services should extend NameServiceMapping interface to register
* themselves.
*/
getProvider(name) {
if (this.providers.has(name)) {
return this.providers.get(name);
}
// create a Provider for a service that hasn't registered with Firebase
const provider = new Provider(name, this);
this.providers.set(name, provider);
return provider;
}
getProviders() {
return Array.from(this.providers.values());
}
}
//# sourceMappingURL=index.esm2017.js.map
/***/
},
/***/ 3333: /***/ function (
__unused_webpack___webpack_module__,
__webpack_exports__,
__webpack_require__
) {
"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ in: function () {
return /* binding */ LogLevel;
},
/* harmony export */ Yd: function () {
return /* binding */ Logger;
},
/* harmony export */
});
/* unused harmony exports setLogLevel, setUserLogHandler */
/**
* @license
* Copyright 2017 Google 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.
*/
/**
* A container for all of the Logger instances
*/
const instances = [];
/**
* The JS SDK supports 5 log levels and also allows a user the ability to
* silence the logs altogether.
*
* The order is a follows:
* DEBUG < VERBOSE < INFO < WARN < ERROR
*
* All of the log types above the current log level will be captured (i.e. if
* you set the log level to `INFO`, errors will still be logged, but `DEBUG` and
* `VERBOSE` logs will not)
*/
var LogLevel;
(function (LogLevel) {
LogLevel[(LogLevel["DEBUG"] = 0)] = "DEBUG";
LogLevel[(LogLevel["VERBOSE"] = 1)] = "VERBOSE";
LogLevel[(LogLevel["INFO"] = 2)] = "INFO";
LogLevel[(LogLevel["WARN"] = 3)] = "WARN";
LogLevel[(LogLevel["ERROR"] = 4)] = "ERROR";
LogLevel[(LogLevel["SILENT"] = 5)] = "SILENT";
})(LogLevel || (LogLevel = {}));
const levelStringToEnum = {
debug: LogLevel.DEBUG,
verbose: LogLevel.VERBOSE,
info: LogLevel.INFO,
warn: LogLevel.WARN,
error: LogLevel.ERROR,
silent: LogLevel.SILENT,
};
/**
* The default log level
*/
const defaultLogLevel = LogLevel.INFO;
/**
* By default, `console.debug` is not displayed in the developer console (in
* chrome). To avoid forcing users to have to opt-in to these logs twice
* (i.e. once for firebase, and once in the console), we are sending `DEBUG`
* logs to the `console.log` function.
*/
const ConsoleMethod = {
[LogLevel.DEBUG]: "log",
[LogLevel.VERBOSE]: "log",
[LogLevel.INFO]: "info",
[LogLevel.WARN]: "warn",
[LogLevel.ERROR]: "error",
};
/**
* The default log handler will forward DEBUG, VERBOSE, INFO, WARN, and ERROR
* messages on to their corresponding console counterparts (if the log method
* is supported by the current log level)
*/
const defaultLogHandler = (instance, logType, ...args) => {
if (logType < instance.logLevel) {
return;
}
const now = new Date().toISOString();
const method = ConsoleMethod[logType];
if (method) {
console[method](`[${now}] ${instance.name}:`, ...args);
} else {
throw new Error(
`Attempted to log a message with an invalid logType (value: ${logType})`
);
}
};
class Logger {
/**
* Gives you an instance of a Logger to capture messages according to
* Firebase's logging scheme.
*
* @param name The name that the logs will be associated with
*/
constructor(name) {
this.name = name;
/**
* The log level of the given Logger instance.
*/
this._logLevel = defaultLogLevel;
/**
* The main (internal) log handler for the Logger instance.
* Can be set to a new function in internal package code but not by user.
*/
this._logHandler = defaultLogHandler;
/**
* The optional, additional, user-defined log handler for the Logger instance.
*/
this._userLogHandler = null;
/**
* Capture the current instance for later use
*/
instances.push(this);
}
get logLevel() {
return this._logLevel;
}
set logLevel(val) {
if (!(val in LogLevel)) {
throw new TypeError(
`Invalid value "${val}" assigned to \`logLevel\``
);
}
this._logLevel = val;
}
// Workaround for setter/getter having to be the same type.
setLogLevel(val) {
this._logLevel =
typeof val === "string" ? levelStringToEnum[val] : val;
}
get logHandler() {
return this._logHandler;
}
set logHandler(val) {
if (typeof val !== "function") {
throw new TypeError(
"Value assigned to `logHandler` must be a function"
);
}
this._logHandler = val;
}
get userLogHandler() {
return this._userLogHandler;
}
set userLogHandler(val) {
this._userLogHandler = val;
}
/**
* The functions below are all based on the `console` interface
*/
debug(...args) {
this._userLogHandler &&
this._userLogHandler(this, LogLevel.DEBUG, ...args);
this._logHandler(this, LogLevel.DEBUG, ...args);
}
log(...args) {
this._userLogHandler &&
this._userLogHandler(this, LogLevel.VERBOSE, ...args);
this._logHandler(this, LogLevel.VERBOSE, ...args);
}
info(...args) {
this._userLogHandler &&
this._userLogHandler(this, LogLevel.INFO, ...args);
this._logHandler(this, LogLevel.INFO, ...args);
}
warn(...args) {
this._userLogHandler &&
this._userLogHandler(this, LogLevel.WARN, ...args);
this._logHandler(this, LogLevel.WARN, ...args);
}
error(...args) {
this._userLogHandler &&
this._userLogHandler(this, LogLevel.ERROR, ...args);
this._logHandler(this, LogLevel.ERROR, ...args);
}
}
function setLogLevel(level) {
instances.forEach((inst) => {
inst.setLogLevel(level);
});
}
function setUserLogHandler(logCallback, options) {
for (const instance of instances) {
let customLogLevel = null;
if (options && options.level) {
customLogLevel = levelStringToEnum[options.level];
}
if (logCallback === null) {
instance.userLogHandler = null;
} else {
instance.userLogHandler = (
instance,
level,
...args
) => {
const message = args
.map((arg) => {
if (arg == null) {
return null;
} else if (typeof arg === "string") {
return arg;
} else if (
typeof arg === "number" ||
typeof arg === "boolean"
) {
return arg.toString();
} else if (arg instanceof Error) {
return arg.message;
} else {
try {
return JSON.stringify(arg);
} catch (ignored) {
return null;
}
}
})
.filter((arg) => arg)
.join(" ");
if (
level >=
(customLogLevel !== null &&
customLogLevel !== void 0
? customLogLevel
: instance.logLevel)
) {
logCallback({
level: LogLevel[level].toLowerCase(),
message,
args,
type: instance.name,
});
}
};
}
}
}
//# sourceMappingURL=index.esm2017.js.map
/***/
},
},
]);
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_minifier/tests/fixture/issues/firebase-core/1/output.js | JavaScript | (self.webpackChunk_N_E = self.webpackChunk_N_E || []).push([
[
819
],
{
/***/ 4444: /***/ function(__unused_webpack_module, __webpack_exports__, __webpack_require__) {
"use strict";
/**
* @license
* Copyright 2017 Google 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.
*/ /**
* Returns navigator.userAgent string or '' if it's not defined.
* @return user agent string
*/ function getUA() {
return "undefined" != typeof navigator && "string" == typeof navigator.userAgent ? navigator.userAgent : "";
}
/**
* Detect Cordova / PhoneGap / Ionic frameworks on a mobile device.
*
* Deliberately does not rely on checking `file://` URLs (as this fails PhoneGap
* in the Ripple emulator) nor Cordova `onDeviceReady`, which would normally
* wait for a callback.
*/ function isMobileCordova() {
return "undefined" != typeof window && // @ts-ignore Setting up an broadly applicable index signature for Window
// just to deal with this case would probably be a bad idea.
!!(window.cordova || window.phonegap || window.PhoneGap) && /ios|iphone|ipod|ipad|android|blackberry|iemobile/i.test(getUA());
}
function isBrowserExtension() {
const runtime = "object" == typeof chrome ? chrome.runtime : "object" == typeof browser ? browser.runtime : void 0;
return "object" == typeof runtime && void 0 !== runtime.id;
}
/**
* Detect React Native.
*
* @return true if ReactNative environment is detected.
*/ function isReactNative() {
return "object" == typeof navigator && "ReactNative" === navigator.product;
}
/** Detects Electron apps. */ function isElectron() {
return getUA().indexOf("Electron/") >= 0;
}
/** Detects Internet Explorer. */ function isIE() {
const ua = getUA();
return ua.indexOf("MSIE ") >= 0 || ua.indexOf("Trident/") >= 0;
}
/** Detects Universal Windows Platform apps. */ function isUWP() {
return getUA().indexOf("MSAppHost/") >= 0;
}
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ LL: function() {
return /* binding */ ErrorFactory;
},
/* harmony export */ m9: function() {
return /* binding */ getModularInstance;
},
/* harmony export */ ru: function() {
return /* binding */ isBrowserExtension;
},
/* harmony export */ d: function() {
return /* binding */ isElectron;
},
/* harmony export */ w1: function() {
return /* binding */ isIE;
},
/* harmony export */ uI: function() {
return /* binding */ isMobileCordova;
},
/* harmony export */ b$: function() {
return /* binding */ isReactNative;
},
/* harmony export */ Mn: function() {
return /* binding */ isUWP;
}
});
// Based on code from:
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error#Custom_Error_Types
class FirebaseError extends Error {
constructor(code, message, customData){
super(message), this.code = code, this.customData = customData, this.name = "FirebaseError", // Fix For ES5
// https://github.com/Microsoft/TypeScript-wiki/blob/master/Breaking-Changes.md#extending-built-ins-like-error-array-and-map-may-no-longer-work
Object.setPrototypeOf(this, FirebaseError.prototype), Error.captureStackTrace && Error.captureStackTrace(this, ErrorFactory.prototype.create);
}
}
class ErrorFactory {
constructor(service, serviceName, errors){
this.service = service, this.serviceName = serviceName, this.errors = errors;
}
create(code, ...data) {
const customData = data[0] || {}, fullCode = `${this.service}/${code}`, template = this.errors[code], message = template ? template.replace(PATTERN, (_, key)=>{
const value = customData[key];
return null != value ? String(value) : `<${key}?>`;
}) : "Error", fullMessage = `${this.serviceName}: ${message} (${fullCode}).`;
return new FirebaseError(fullCode, fullMessage, customData);
}
}
const PATTERN = /\{\$([^}]+)}/g;
/**
* @license
* Copyright 2021 Google 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.
*/ function getModularInstance(service) {
return service && service._delegate ? service._delegate : service;
}
//# sourceMappingURL=index.esm2017.js.map
/***/ },
/***/ 3510: /***/ function(__unused_webpack_module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ jK: function() {
return /* binding */ ErrorCode;
},
/* harmony export */ ju: function() {
return /* binding */ Event;
},
/* harmony export */ tw: function() {
return /* binding */ EventType;
},
/* harmony export */ zI: function() {
return /* binding */ FetchXmlHttpFactory;
},
/* harmony export */ kN: function() {
return /* binding */ Stat;
},
/* harmony export */ ii: function() {
return /* binding */ WebChannel;
},
/* harmony export */ JJ: function() {
return /* binding */ XhrIo;
},
/* harmony export */ UE: function() {
return /* binding */ createWebChannelTransport;
},
/* harmony export */ FJ: function() {
return /* binding */ getStatEventTarget;
}
});
/* unused harmony export default */ var a, x, Na, Ab, cc, k, commonjsGlobal = "undefined" != typeof globalThis ? globalThis : "undefined" != typeof window ? window : void 0 !== __webpack_require__.g ? __webpack_require__.g : "undefined" != typeof self ? self : {}, esm = {}, goog = goog || {}, l = commonjsGlobal || self;
function aa() {}
function ba(a) {
var b = typeof a;
return "array" == (b = "object" != b ? b : a ? Array.isArray(a) ? "array" : b : "null") || "object" == b && "number" == typeof a.length;
}
function p(a) {
var b = typeof a;
return "object" == b && null != a || "function" == b;
}
function ha(a, b, c) {
return a.call.apply(a.bind, arguments);
}
function ia(a, b, c) {
if (!a) throw Error();
if (2 < arguments.length) {
var d = Array.prototype.slice.call(arguments, 2);
return function() {
var e = Array.prototype.slice.call(arguments);
return Array.prototype.unshift.apply(e, d), a.apply(b, e);
};
}
return function() {
return a.apply(b, arguments);
};
}
function q(a, b, c) {
return (q = Function.prototype.bind && -1 != Function.prototype.bind.toString().indexOf("native code") ? ha : ia).apply(null, arguments);
}
function ja(a, b) {
var c = Array.prototype.slice.call(arguments, 1);
return function() {
var d = c.slice();
return d.push.apply(d, arguments), a.apply(this, d);
};
}
function t(a, b) {
function c() {}
c.prototype = b.prototype, a.Z = b.prototype, a.prototype = new c(), a.prototype.constructor = a, a.Vb = function(d, e, f) {
for(var h = Array(arguments.length - 2), n = 2; n < arguments.length; n++)h[n - 2] = arguments[n];
return b.prototype[e].apply(d, h);
};
}
function v() {
this.s = this.s, this.o = this.o;
}
v.prototype.s = !1, v.prototype.na = function() {
this.s || (this.s = !0, this.M());
}, v.prototype.M = function() {
if (this.o) for(; this.o.length;)this.o.shift()();
};
const ma = Array.prototype.indexOf ? function(a, b) {
return Array.prototype.indexOf.call(a, b, void 0);
} : function(a, b) {
if ("string" == typeof a) return "string" != typeof b || 1 != b.length ? -1 : a.indexOf(b, 0);
for(let c = 0; c < a.length; c++)if (c in a && a[c] === b) return c;
return -1;
}, na = Array.prototype.forEach ? function(a, b, c) {
Array.prototype.forEach.call(a, b, c);
} : function(a, b, c) {
const d = a.length, e = "string" == typeof a ? a.split("") : a;
for(let f = 0; f < d; f++)f in e && b.call(c, e[f], f, a);
};
function qa(a) {
return Array.prototype.concat.apply([], arguments);
}
function ra(a) {
const b = a.length;
if (0 < b) {
const c = Array(b);
for(let d = 0; d < b; d++)c[d] = a[d];
return c;
}
return [];
}
function sa(a) {
return /^[\s\xa0]*$/.test(a);
}
var ta = String.prototype.trim ? function(a) {
return a.trim();
} : function(a) {
return /^[\s\xa0]*([\s\S]*?)[\s\xa0]*$/.exec(a)[1];
};
function w(a, b) {
return -1 != a.indexOf(b);
}
a: {
var va = l.navigator;
if (va) {
var wa = va.userAgent;
if (wa) {
x = wa;
break a;
}
}
x = "";
}
function xa(a, b, c) {
for(const d in a)b.call(c, a[d], d, a);
}
function ya(a) {
const b = {};
for(const c in a)b[c] = a[c];
return b;
}
var za = "constructor hasOwnProperty isPrototypeOf propertyIsEnumerable toLocaleString toString valueOf".split(" ");
function Aa(a, b) {
let c, d;
for(let e = 1; e < arguments.length; e++){
for(c in d = arguments[e])a[c] = d[c];
for(let f = 0; f < za.length; f++)c = za[f], Object.prototype.hasOwnProperty.call(d, c) && (a[c] = d[c]);
}
}
function Ca(a) {
return Ca[" "](a), a;
}
Ca[" "] = aa;
var Ha = w(x, "Opera"), y = w(x, "Trident") || w(x, "MSIE"), Ia = w(x, "Edge"), Ja = Ia || y, Ka = w(x, "Gecko") && !(w(x.toLowerCase(), "webkit") && !w(x, "Edge")) && !(w(x, "Trident") || w(x, "MSIE")) && !w(x, "Edge"), La = w(x.toLowerCase(), "webkit") && !w(x, "Edge");
function Ma() {
var a = l.document;
return a ? a.documentMode : void 0;
}
a: {
var a1, Oa = "", Pa = (a1 = x, Ka ? /rv:([^\);]+)(\)|;)/.exec(a1) : Ia ? /Edge\/([\d\.]+)/.exec(a1) : y ? /\b(?:MSIE|rv)[: ]([^\);]+)(\)|;)/.exec(a1) : La ? /WebKit\/(\S+)/.exec(a1) : Ha ? /(?:Version)[ \/]?(\S+)/.exec(a1) : void 0);
if (Pa && (Oa = Pa ? Pa[1] : ""), y) {
var Qa = Ma();
if (null != Qa && Qa > parseFloat(Oa)) {
Na = String(Qa);
break a;
}
}
Na = Oa;
}
var Ga = {}, Ua = l.document && y && (Ma() || parseInt(Na, 10)) || void 0, Va = function() {
if (!l.addEventListener || !Object.defineProperty) return !1;
var a = !1, b = Object.defineProperty({}, "passive", {
get: function() {
a = !0;
}
});
try {
l.addEventListener("test", aa, b), l.removeEventListener("test", aa, b);
} catch (c) {}
return a;
}();
function z(a, b) {
this.type = a, this.g = this.target = b, this.defaultPrevented = !1;
}
function A(a, b) {
if (z.call(this, a ? a.type : ""), this.relatedTarget = this.g = this.target = null, this.button = this.screenY = this.screenX = this.clientY = this.clientX = 0, this.key = "", this.metaKey = this.shiftKey = this.altKey = this.ctrlKey = !1, this.state = null, this.pointerId = 0, this.pointerType = "", this.i = null, a) {
var c = this.type = a.type, d = a.changedTouches && a.changedTouches.length ? a.changedTouches[0] : null;
if (this.target = a.target || a.srcElement, this.g = b, b = a.relatedTarget) {
if (Ka) {
a: {
try {
Ca(b.nodeName);
var e = !0;
break a;
} catch (f) {}
e = !1;
}
e || (b = null);
}
} else "mouseover" == c ? b = a.fromElement : "mouseout" == c && (b = a.toElement);
this.relatedTarget = b, d ? (this.clientX = void 0 !== d.clientX ? d.clientX : d.pageX, this.clientY = void 0 !== d.clientY ? d.clientY : d.pageY, this.screenX = d.screenX || 0, this.screenY = d.screenY || 0) : (this.clientX = void 0 !== a.clientX ? a.clientX : a.pageX, this.clientY = void 0 !== a.clientY ? a.clientY : a.pageY, this.screenX = a.screenX || 0, this.screenY = a.screenY || 0), this.button = a.button, this.key = a.key || "", this.ctrlKey = a.ctrlKey, this.altKey = a.altKey, this.shiftKey = a.shiftKey, this.metaKey = a.metaKey, this.pointerId = a.pointerId || 0, this.pointerType = "string" == typeof a.pointerType ? a.pointerType : Wa[a.pointerType] || "", this.state = a.state, this.i = a, a.defaultPrevented && A.Z.h.call(this);
}
}
z.prototype.h = function() {
this.defaultPrevented = !0;
}, t(A, z);
var Wa = {
2: "touch",
3: "pen",
4: "mouse"
};
A.prototype.h = function() {
A.Z.h.call(this);
var a = this.i;
a.preventDefault ? a.preventDefault() : a.returnValue = !1;
};
var B = "closure_listenable_" + (1e6 * Math.random() | 0), Xa = 0;
function Ya(a, b, c, d, e) {
this.listener = a, this.proxy = null, this.src = b, this.type = c, this.capture = !!d, this.ia = e, this.key = ++Xa, this.ca = this.fa = !1;
}
function Za(a) {
a.ca = !0, a.listener = null, a.proxy = null, a.src = null, a.ia = null;
}
function $a(a) {
this.src = a, this.g = {}, this.h = 0;
}
function bb(a, b) {
var c = b.type;
if (c in a.g) {
var f, d = a.g[c], e = ma(d, b);
(f = 0 <= e) && Array.prototype.splice.call(d, e, 1), f && (Za(b), 0 == a.g[c].length && (delete a.g[c], a.h--));
}
}
function ab(a, b, c, d) {
for(var e = 0; e < a.length; ++e){
var f = a[e];
if (!f.ca && f.listener == b && !!c == f.capture && f.ia == d) return e;
}
return -1;
}
$a.prototype.add = function(a, b, c, d, e) {
var f = a.toString();
(a = this.g[f]) || (a = this.g[f] = [], this.h++);
var h = ab(a, b, d, e);
return -1 < h ? (b = a[h], c || (b.fa = !1)) : ((b = new Ya(b, this.src, f, !!d, e)).fa = c, a.push(b)), b;
};
var cb = "closure_lm_" + (1e6 * Math.random() | 0), db = {};
function ib(a, b, c, d, e, f) {
if (!b) throw Error("Invalid event type");
var h = p(e) ? !!e.capture : !!e, n = jb(a);
if (n || (a[cb] = n = new $a(a)), (c = n.add(b, c, d, h, f)).proxy) return c;
if (d = function a(c) {
return mb.call(a.src, a.listener, c);
}, c.proxy = d, d.src = a, d.listener = c, a.addEventListener) Va || (e = h), void 0 === e && (e = !1), a.addEventListener(b.toString(), d, e);
else if (a.attachEvent) a.attachEvent(lb(b.toString()), d);
else if (a.addListener && a.removeListener) a.addListener(d);
else throw Error("addEventListener and attachEvent are unavailable.");
return c;
}
function ob(a) {
if ("number" != typeof a && a && !a.ca) {
var b = a.src;
if (b && b[B]) bb(b.i, a);
else {
var c = a.type, d = a.proxy;
b.removeEventListener ? b.removeEventListener(c, d, a.capture) : b.detachEvent ? b.detachEvent(lb(c), d) : b.addListener && b.removeListener && b.removeListener(d), (c = jb(b)) ? (bb(c, a), 0 == c.h && (c.src = null, b[cb] = null)) : Za(a);
}
}
}
function lb(a) {
return a in db ? db[a] : db[a] = "on" + a;
}
function mb(a, b) {
if (a.ca) a = !0;
else {
b = new A(b, this);
var c = a.listener, d = a.ia || a.src;
a.fa && ob(a), a = c.call(d, b);
}
return a;
}
function jb(a) {
return (a = a[cb]) instanceof $a ? a : null;
}
var pb = "__closure_events_fn_" + (1e9 * Math.random() >>> 0);
function hb(a) {
return "function" == typeof a ? a : (a[pb] || (a[pb] = function(b) {
return a.handleEvent(b);
}), a[pb]);
}
function C() {
v.call(this), this.i = new $a(this), this.P = this, this.I = null;
}
function D(a, b) {
var c, d = a.I;
if (d) for(c = []; d; d = d.I)c.push(d);
if (a = a.P, d = b.type || b, "string" == typeof b) b = new z(b, a);
else if (b instanceof z) b.target = b.target || a;
else {
var e = b;
Aa(b = new z(d, a), e);
}
if (e = !0, c) for(var f = c.length - 1; 0 <= f; f--){
var h = b.g = c[f];
e = qb(h, d, !0, b) && e;
}
if (e = qb(h = b.g = a, d, !0, b) && e, e = qb(h, d, !1, b) && e, c) for(f = 0; f < c.length; f++)e = qb(h = b.g = c[f], d, !1, b) && e;
}
function qb(a, b, c, d) {
if (!(b = a.i.g[String(b)])) return !0;
b = b.concat();
for(var e = !0, f = 0; f < b.length; ++f){
var h = b[f];
if (h && !h.ca && h.capture == c) {
var n = h.listener, u = h.ia || h.src;
h.fa && bb(a.i, h), e = !1 !== n.call(u, d) && e;
}
}
return e && !d.defaultPrevented;
}
t(C, v), C.prototype[B] = !0, C.prototype.removeEventListener = function(a, b, c, d) {
!function nb(a, b, c, d, e) {
if (Array.isArray(b)) for(var f = 0; f < b.length; f++)nb(a, b[f], c, d, e);
else (d = p(d) ? !!d.capture : !!d, c = hb(c), a && a[B]) ? (a = a.i, (b = String(b).toString()) in a.g && -1 < (c = ab(f = a.g[b], c, d, e)) && (Za(f[c]), Array.prototype.splice.call(f, c, 1), 0 == f.length && (delete a.g[b], a.h--))) : a && (a = jb(a)) && (b = a.g[b.toString()], a = -1, b && (a = ab(b, c, d, e)), (c = -1 < a ? b[a] : null) && ob(c));
}(this, a, b, c, d);
}, C.prototype.M = function() {
if (C.Z.M.call(this), this.i) {
var c, a = this.i;
for(c in a.g){
for(var d = a.g[c], e = 0; e < d.length; e++)Za(d[e]);
delete a.g[c], a.h--;
}
}
this.I = null;
}, C.prototype.N = function(a, b, c, d) {
return this.i.add(String(a), b, !1, c, d);
}, C.prototype.O = function(a, b, c, d) {
return this.i.add(String(a), b, !0, c, d);
};
var rb = l.JSON.stringify, vb = new class {
constructor(a, b){
this.i = a, this.j = b, this.h = 0, this.g = null;
}
get() {
let a;
return 0 < this.h ? (this.h--, a = this.g, this.g = a.next, a.next = null) : a = this.i(), a;
}
}(()=>new wb(), (a)=>a.reset());
class wb {
constructor(){
this.next = this.g = this.h = null;
}
set(a, b) {
this.h = a, this.g = b, this.next = null;
}
reset() {
this.next = this.g = this.h = null;
}
}
function zb(a, b) {
var a1;
Ab || (a1 = l.Promise.resolve(void 0), Ab = function() {
a1.then(Db);
}), Cb || (Ab(), Cb = !0), tb.add(a, b);
}
var Cb = !1, tb = new class {
constructor(){
this.h = this.g = null;
}
add(a, b) {
const c = vb.get();
c.set(a, b), this.h ? this.h.next = c : this.g = c, this.h = c;
}
}();
function Db() {
let b;
for(var a; b = null, tb.g && (b = tb.g, tb.g = tb.g.next, tb.g || (tb.h = null), b.next = null), a = b;){
try {
a.h.call(a.g);
} catch (c) {
!function(a) {
l.setTimeout(()=>{
throw a;
}, 0);
}(c);
}
vb.j(a), 100 > vb.h && (vb.h++, a.next = vb.g, vb.g = a);
}
Cb = !1;
}
function Eb(a, b) {
C.call(this), this.h = a || 1, this.g = b || l, this.j = q(this.kb, this), this.l = Date.now();
}
function Fb(a) {
a.da = !1, a.S && (a.g.clearTimeout(a.S), a.S = null);
}
function Gb(a, b, c) {
if ("function" == typeof a) c && (a = q(a, c));
else if (a && "function" == typeof a.handleEvent) a = q(a.handleEvent, a);
else throw Error("Invalid listener argument");
return 2147483647 < Number(b) ? -1 : l.setTimeout(a, b || 0);
}
t(Eb, C), (k = Eb.prototype).da = !1, k.S = null, k.kb = function() {
if (this.da) {
var a = Date.now() - this.l;
0 < a && a < 0.8 * this.h ? this.S = this.g.setTimeout(this.j, this.h - a) : (this.S && (this.g.clearTimeout(this.S), this.S = null), D(this, "tick"), this.da && (Fb(this), this.start()));
}
}, k.start = function() {
this.da = !0, this.S || (this.S = this.g.setTimeout(this.j, this.h), this.l = Date.now());
}, k.M = function() {
Eb.Z.M.call(this), Fb(this), delete this.g;
};
class Ib extends v {
constructor(a, b){
super(), this.m = a, this.j = b, this.h = null, this.i = !1, this.g = null;
}
l(a) {
this.h = arguments, this.g ? this.i = !0 : function Hb(a) {
a.g = Gb(()=>{
a.g = null, a.i && (a.i = !1, Hb(a));
}, a.j);
const b = a.h;
a.h = null, a.m.apply(null, b);
}(this);
}
M() {
super.M(), this.g && (l.clearTimeout(this.g), this.g = null, this.i = !1, this.h = null);
}
}
function E(a) {
v.call(this), this.h = a, this.g = {};
}
t(E, v);
var Jb = [];
function Kb(a, b, c, d) {
Array.isArray(c) || (c && (Jb[0] = c.toString()), c = Jb);
for(var e = 0; e < c.length; e++){
var f = function fb(a, b, c, d, e) {
if (d && d.once) return function gb(a, b, c, d, e) {
if (Array.isArray(b)) {
for(var f = 0; f < b.length; f++)gb(a, b[f], c, d, e);
return null;
}
return c = hb(c), a && a[B] ? a.O(b, c, p(d) ? !!d.capture : !!d, e) : ib(a, b, c, !0, d, e);
}(a, b, c, d, e);
if (Array.isArray(b)) {
for(var f = 0; f < b.length; f++)fb(a, b[f], c, d, e);
return null;
}
return c = hb(c), a && a[B] ? a.N(b, c, p(d) ? !!d.capture : !!d, e) : ib(a, b, c, !1, d, e);
}(b, c[e], d || a.handleEvent, !1, a.h || a);
if (!f) break;
a.g[f.key] = f;
}
}
function Lb(a) {
xa(a.g, function(b, c) {
this.g.hasOwnProperty(c) && ob(b);
}, a), a.g = {};
}
function Mb() {
this.g = !0;
}
function F(a, b, c, d) {
a.info(function() {
return "XMLHTTP TEXT (" + b + "): " + function(a, b) {
if (!a.g) return b;
if (!b) return null;
try {
var c = JSON.parse(b);
if (c) {
for(a = 0; a < c.length; a++)if (Array.isArray(c[a])) {
var d = c[a];
if (!(2 > d.length)) {
var e = d[1];
if (Array.isArray(e) && !(1 > e.length)) {
var f = e[0];
if ("noop" != f && "stop" != f && "close" != f) for(var h = 1; h < e.length; h++)e[h] = "";
}
}
}
}
return rb(c);
} catch (n) {
return b;
}
}(a, c) + (d ? " " + d : "");
});
}
E.prototype.M = function() {
E.Z.M.call(this), Lb(this);
}, E.prototype.handleEvent = function() {
throw Error("EventHandler.handleEvent not implemented");
}, Mb.prototype.Aa = function() {
this.g = !1;
}, Mb.prototype.info = function() {};
var H = {}, Rb = null;
function Sb() {
return Rb = Rb || new C();
}
function Tb(a) {
z.call(this, H.Ma, a);
}
function I(a) {
const b = Sb();
D(b, new Tb(b, a));
}
function Ub(a, b) {
z.call(this, H.STAT_EVENT, a), this.stat = b;
}
function J(a) {
const b = Sb();
D(b, new Ub(b, a));
}
function Vb(a, b) {
z.call(this, H.Na, a), this.size = b;
}
function K(a, b) {
if ("function" != typeof a) throw Error("Fn must not be null and must be a function");
return l.setTimeout(function() {
a();
}, b);
}
H.Ma = "serverreachability", t(Tb, z), H.STAT_EVENT = "statevent", t(Ub, z), H.Na = "timingevent", t(Vb, z);
var Wb = {
NO_ERROR: 0,
lb: 1,
yb: 2,
xb: 3,
sb: 4,
wb: 5,
zb: 6,
Ja: 7,
TIMEOUT: 8,
Cb: 9
}, Xb = {
qb: "complete",
Mb: "success",
Ka: "error",
Ja: "abort",
Eb: "ready",
Fb: "readystatechange",
TIMEOUT: "timeout",
Ab: "incrementaldata",
Db: "progress",
tb: "downloadprogress",
Ub: "uploadprogress"
};
function Yb() {}
function Zb(a) {
return a.h || (a.h = a.i());
}
function $b() {}
Yb.prototype.h = null;
var L = {
OPEN: "a",
pb: "b",
Ka: "c",
Bb: "d"
};
function ac() {
z.call(this, "d");
}
function bc() {
z.call(this, "c");
}
function dc() {}
function M(a, b, c, d) {
this.l = a, this.j = b, this.m = c, this.X = d || 1, this.V = new E(this), this.P = ec, a = Ja ? 125 : void 0, this.W = new Eb(a), this.H = null, this.i = !1, this.s = this.A = this.v = this.K = this.F = this.Y = this.B = null, this.D = [], this.g = null, this.C = 0, this.o = this.u = null, this.N = -1, this.I = !1, this.O = 0, this.L = null, this.aa = this.J = this.$ = this.U = !1, this.h = new fc();
}
function fc() {
this.i = null, this.g = "", this.h = !1;
}
t(ac, z), t(bc, z), t(dc, Yb), dc.prototype.g = function() {
return new XMLHttpRequest();
}, dc.prototype.i = function() {
return {};
}, cc = new dc();
var ec = 45e3, gc = {}, hc = {};
function ic(a, b, c) {
a.K = 1, a.v = jc(N(b)), a.s = c, a.U = !0, kc(a, null);
}
function kc(a, b) {
a.F = Date.now(), lc(a), a.A = N(a.v);
var c = a.A, d = a.X;
Array.isArray(d) || (d = [
String(d)
]), mc(c.h, "t", d), a.C = 0, c = a.l.H, a.h = new fc(), a.g = nc(a.l, c ? b : null, !a.s), 0 < a.O && (a.L = new Ib(q(a.Ia, a, a.g), a.O)), Kb(a.V, a.g, "readystatechange", a.gb), b = a.H ? ya(a.H) : {}, a.s ? (a.u || (a.u = "POST"), b["Content-Type"] = "application/x-www-form-urlencoded", a.g.ea(a.A, a.u, a.s, b)) : (a.u = "GET", a.g.ea(a.A, a.u, null, b)), I(1), function(a, b, c, d, e, f) {
a.info(function() {
if (a.g) {
if (f) for(var h = "", n = f.split("&"), u = 0; u < n.length; u++){
var m = n[u].split("=");
if (1 < m.length) {
var r = m[0];
m = m[1];
var G = r.split("_");
h = 2 <= G.length && "type" == G[1] ? h + (r + "=") + m + "&" : h + (r + "=redacted&");
}
}
else h = null;
} else h = f;
return "XMLHTTP REQ (" + d + ") [attempt " + e + "]: " + b + "\n" + c + "\n" + h;
});
}(a.j, a.u, a.A, a.m, a.X, a.s);
}
function qc(a) {
return !!a.g && "GET" == a.u && 2 != a.K && a.l.Ba;
}
function tc(a, b, c) {
let d = !0, e;
for(; !a.I && a.C < c.length;)if ((e = function(a, b) {
var c = a.C, d = b.indexOf("\n", c);
return -1 == d ? hc : isNaN(c = Number(b.substring(c, d))) ? gc : (d += 1) + c > b.length ? hc : (b = b.substr(d, c), a.C = d + c, b);
}(a, c)) == hc) {
4 == b && (a.o = 4, J(14), d = !1), F(a.j, a.m, null, "[Incomplete Response]");
break;
} else if (e == gc) {
a.o = 4, J(15), F(a.j, a.m, c, "[Invalid Chunk]"), d = !1;
break;
} else F(a.j, a.m, e, null), sc(a, e);
qc(a) && e != hc && e != gc && (a.h.g = "", a.C = 0), 4 != b || 0 != c.length || a.h.h || (a.o = 1, J(16), d = !1), a.i = a.i && d, d ? 0 < c.length && !a.aa && (a.aa = !0, (b = a.l).g == a && b.$ && !b.L && (b.h.info("Great, no buffering proxy detected. Bytes received: " + c.length), wc(b), b.L = !0, J(11))) : (F(a.j, a.m, c, "[Invalid Chunked Response]"), P(a), rc(a));
}
function lc(a) {
a.Y = Date.now() + a.P, xc(a, a.P);
}
function xc(a, b) {
if (null != a.B) throw Error("WatchDog timer not null");
a.B = K(q(a.eb, a), b);
}
function pc(a) {
a.B && (l.clearTimeout(a.B), a.B = null);
}
function rc(a) {
0 == a.l.G || a.I || uc(a.l, a);
}
function P(a) {
pc(a);
var b = a.L;
b && "function" == typeof b.na && b.na(), a.L = null, Fb(a.W), Lb(a.V), a.g && (b = a.g, a.g = null, b.abort(), b.na());
}
function sc(a, b) {
try {
var c = a.l;
if (0 != c.G && (c.g == a || yc(c.i, a))) {
if (c.I = a.N, !a.J && yc(c.i, a) && 3 == c.G) {
try {
var d = c.Ca.g.parse(b);
} catch (m) {
d = null;
}
if (Array.isArray(d) && 3 == d.length) {
var e = d;
if (0 == e[0]) {
a: if (!c.u) {
if (c.g) {
if (c.g.F + 3e3 < a.F) zc(c), Ac(c);
else break a;
}
Bc(c), J(18);
}
} else c.ta = e[1], 0 < c.ta - c.U && 37500 > e[2] && c.N && 0 == c.A && !c.v && (c.v = K(q(c.ab, c), 6e3));
if (1 >= Cc(c.i) && c.ka) {
try {
c.ka();
} catch (m) {}
c.ka = void 0;
}
} else Q(c, 11);
} else if ((a.J || c.g == a) && zc(c), !sa(b)) for(e = c.Ca.g.parse(b), b = 0; b < e.length; b++){
let m = e[b];
if (c.U = m[0], m = m[1], 2 == c.G) {
if ("c" == m[0]) {
c.J = m[1], c.la = m[2];
const r = m[3];
null != r && (c.ma = r, c.h.info("VER=" + c.ma));
const G = m[4];
null != G && (c.za = G, c.h.info("SVER=" + c.za));
const Da = m[5];
null != Da && "number" == typeof Da && 0 < Da && (c.K = d = 1.5 * Da, c.h.info("backChannelRequestTimeoutMs_=" + d)), d = c;
const ca = a.g;
if (ca) {
const Ea = ca.g ? ca.g.getResponseHeader("X-Client-Wire-Protocol") : null;
if (Ea) {
var f = d.i;
!f.g && (w(Ea, "spdy") || w(Ea, "quic") || w(Ea, "h2")) && (f.j = f.l, f.g = new Set(), f.h && (Dc(f, f.h), f.h = null));
}
if (d.D) {
const xb = ca.g ? ca.g.getResponseHeader("X-HTTP-Session-Id") : null;
xb && (d.sa = xb, R(d.F, d.D, xb));
}
}
if (c.G = 3, c.j && c.j.xa(), c.$ && (c.O = Date.now() - a.F, c.h.info("Handshake RTT: " + c.O + "ms")), (d = c).oa = Ec(d, d.H ? d.la : null, d.W), a.J) {
Fc(d.i, a);
var u = d.K;
u && a.setTimeout(u), a.B && (pc(a), lc(a)), d.g = a;
} else Gc(d);
0 < c.l.length && Hc(c);
} else "stop" != m[0] && "close" != m[0] || Q(c, 7);
} else 3 == c.G && ("stop" == m[0] || "close" == m[0] ? "stop" == m[0] ? Q(c, 7) : Ic(c) : "noop" != m[0] && c.j && c.j.wa(m), c.A = 0);
}
}
I(4);
} catch (m) {}
}
function Kc(a, b) {
if (a.forEach && "function" == typeof a.forEach) a.forEach(b, void 0);
else if (ba(a) || "string" == typeof a) na(a, b, void 0);
else {
if (a.T && "function" == typeof a.T) var c = a.T();
else if (a.R && "function" == typeof a.R) c = void 0;
else if (ba(a) || "string" == typeof a) {
c = [];
for(var d = a.length, e = 0; e < d; e++)c.push(e);
} else for(e in c = [], d = 0, a)c[d++] = e;
e = (d = function(a) {
if (a.R && "function" == typeof a.R) return a.R();
if ("string" == typeof a) return a.split("");
if (ba(a)) {
for(var b = [], c = a.length, d = 0; d < c; d++)b.push(a[d]);
return b;
}
for(d in b = [], c = 0, a)b[c++] = a[d];
return b;
}(a)).length;
for(var f = 0; f < e; f++)b.call(void 0, d[f], c && c[f], a);
}
}
function S(a, b) {
this.h = {}, this.g = [], this.i = 0;
var c = arguments.length;
if (1 < c) {
if (c % 2) throw Error("Uneven number of arguments");
for(var d = 0; d < c; d += 2)this.set(arguments[d], arguments[d + 1]);
} else if (a) {
if (a instanceof S) for(c = a.T(), d = 0; d < c.length; d++)this.set(c[d], a.get(c[d]));
else for(d in a)this.set(d, a[d]);
}
}
function Lc(a) {
if (a.i != a.g.length) {
for(var b = 0, c = 0; b < a.g.length;){
var d = a.g[b];
T(a.h, d) && (a.g[c++] = d), b++;
}
a.g.length = c;
}
if (a.i != a.g.length) {
var e = {};
for(c = b = 0; b < a.g.length;)T(e, d = a.g[b]) || (a.g[c++] = d, e[d] = 1), b++;
a.g.length = c;
}
}
function T(a, b) {
return Object.prototype.hasOwnProperty.call(a, b);
}
(k = M.prototype).setTimeout = function(a) {
this.P = a;
}, k.gb = function(a) {
a = a.target;
const b = this.L;
b && 3 == O(a) ? b.l() : this.Ia(a);
}, k.Ia = function(a) {
try {
if (a == this.g) a: {
const r = O(this.g);
var b = this.g.Da();
const G = this.g.ba();
if (!(3 > r) && (3 != r || Ja || this.g && (this.h.h || this.g.ga() || oc(this.g)))) {
this.I || 4 != r || 7 == b || (8 == b || 0 >= G ? I(3) : I(2)), pc(this);
var c = this.g.ba();
this.N = c;
b: if (qc(this)) {
var d = oc(this.g);
a = "";
var e = d.length, f = 4 == O(this.g);
if (!this.h.i) {
if ("undefined" == typeof TextDecoder) {
P(this), rc(this);
var h = "";
break b;
}
this.h.i = new l.TextDecoder();
}
for(b = 0; b < e; b++)this.h.h = !0, a += this.h.i.decode(d[b], {
stream: f && b == e - 1
});
d.splice(0, e), this.h.g += a, this.C = 0, h = this.h.g;
} else h = this.g.ga();
if (this.i = 200 == c, function(a, b, c, d, e, f, h) {
a.info(function() {
return "XMLHTTP RESP (" + d + ") [ attempt " + e + "]: " + b + "\n" + c + "\n" + f + " " + h;
});
}(this.j, this.u, this.A, this.m, this.X, r, c), this.i) {
if (this.$ && !this.J) {
b: {
if (this.g) {
var n, u = this.g;
if ((n = u.g ? u.g.getResponseHeader("X-HTTP-Initial-Response") : null) && !sa(n)) {
var m = n;
break b;
}
}
m = null;
}
if (c = m) F(this.j, this.m, c, "Initial handshake response via X-HTTP-Initial-Response"), this.J = !0, sc(this, c);
else {
this.i = !1, this.o = 3, J(12), P(this), rc(this);
break a;
}
}
this.U ? (tc(this, r, h), Ja && this.i && 3 == r && (Kb(this.V, this.W, "tick", this.fb), this.W.start())) : (F(this.j, this.m, h, null), sc(this, h)), 4 == r && P(this), this.i && !this.I && (4 == r ? uc(this.l, this) : (this.i = !1, lc(this)));
} else 400 == c && 0 < h.indexOf("Unknown SID") ? (this.o = 3, J(12)) : (this.o = 0, J(13)), P(this), rc(this);
}
}
} catch (r) {} finally{}
}, k.fb = function() {
if (this.g) {
var a = O(this.g), b = this.g.ga();
this.C < b.length && (pc(this), tc(this, a, b), this.i && 4 != a && lc(this));
}
}, k.cancel = function() {
this.I = !0, P(this);
}, k.eb = function() {
this.B = null;
const a = Date.now();
0 <= a - this.Y ? (function(a, b) {
a.info(function() {
return "TIMEOUT: " + b;
});
}(this.j, this.A), 2 != this.K && (I(3), J(17)), P(this), this.o = 2, rc(this)) : xc(this, this.Y - a);
}, (k = S.prototype).R = function() {
Lc(this);
for(var a = [], b = 0; b < this.g.length; b++)a.push(this.h[this.g[b]]);
return a;
}, k.T = function() {
return Lc(this), this.g.concat();
}, k.get = function(a, b) {
return T(this.h, a) ? this.h[a] : b;
}, k.set = function(a, b) {
T(this.h, a) || (this.i++, this.g.push(a)), this.h[a] = b;
}, k.forEach = function(a, b) {
for(var c = this.T(), d = 0; d < c.length; d++){
var e = c[d], f = this.get(e);
a.call(b, f, e, this);
}
};
var Mc = /^(?:([^:/?#.]+):)?(?:\/\/(?:([^\\/?#]*)@)?([^\\/?#]*?)(?::([0-9]+))?(?=[\\/?#]|$))?([^?#]+)?(?:\?([^#]*))?(?:#([\s\S]*))?$/;
function U(a, b) {
if (this.i = this.s = this.j = "", this.m = null, this.o = this.l = "", this.g = !1, a instanceof U) {
this.g = void 0 !== b ? b : a.g, Oc(this, a.j), this.s = a.s, Pc(this, a.i), Qc(this, a.m), this.l = a.l, b = a.h;
var c = new Rc();
c.i = b.i, b.g && (c.g = new S(b.g), c.h = b.h), Sc(this, c), this.o = a.o;
} else a && (c = String(a).match(Mc)) ? (this.g = !!b, Oc(this, c[1] || "", !0), this.s = Tc(c[2] || ""), Pc(this, c[3] || "", !0), Qc(this, c[4]), this.l = Tc(c[5] || "", !0), Sc(this, c[6] || "", !0), this.o = Tc(c[7] || "")) : (this.g = !!b, this.h = new Rc(null, this.g));
}
function N(a) {
return new U(a);
}
function Oc(a, b, c) {
a.j = c ? Tc(b, !0) : b, a.j && (a.j = a.j.replace(/:$/, ""));
}
function Pc(a, b, c) {
a.i = c ? Tc(b, !0) : b;
}
function Qc(a, b) {
if (b) {
if (isNaN(b = Number(b)) || 0 > b) throw Error("Bad port number " + b);
a.m = b;
} else a.m = null;
}
function Sc(a, b, c) {
var a1, b1;
b instanceof Rc ? (a.h = b, a1 = a.h, (b1 = a.g) && !a1.j && (V(a1), a1.i = null, a1.g.forEach(function(c, d) {
var e = d.toLowerCase();
d != e && (dd(this, d), mc(this, e, c));
}, a1)), a1.j = b1) : (c || (b = Uc(b, $c)), a.h = new Rc(b, a.g));
}
function R(a, b, c) {
a.h.set(b, c);
}
function jc(a) {
return R(a, "zx", Math.floor(2147483648 * Math.random()).toString(36) + Math.abs(Math.floor(2147483648 * Math.random()) ^ Date.now()).toString(36)), a;
}
function Tc(a, b) {
return a ? b ? decodeURI(a.replace(/%25/g, "%2525")) : decodeURIComponent(a) : "";
}
function Uc(a, b, c) {
return "string" == typeof a ? (a = encodeURI(a).replace(b, cd), c && (a = a.replace(/%25([0-9a-fA-F]{2})/g, "%$1")), a) : null;
}
function cd(a) {
return "%" + ((a = a.charCodeAt(0)) >> 4 & 15).toString(16) + (15 & a).toString(16);
}
U.prototype.toString = function() {
var a = [], b = this.j;
b && a.push(Uc(b, Vc, !0), ":");
var c = this.i;
return (c || "file" == b) && (a.push("//"), (b = this.s) && a.push(Uc(b, Vc, !0), "@"), a.push(encodeURIComponent(String(c)).replace(/%25([0-9a-fA-F]{2})/g, "%$1")), null != (c = this.m) && a.push(":", String(c))), (c = this.l) && (this.i && "/" != c.charAt(0) && a.push("/"), a.push(Uc(c, "/" == c.charAt(0) ? Wc : Xc, !0))), (c = this.h.toString()) && a.push("?", c), (c = this.o) && a.push("#", Uc(c, Yc)), a.join("");
};
var Vc = /[#\/\?@]/g, Xc = /[#\?:]/g, Wc = /[#\?]/g, $c = /[#\?@]/g, Yc = /#/g;
function Rc(a, b) {
this.h = this.g = null, this.i = a || null, this.j = !!b;
}
function V(a) {
a.g || (a.g = new S(), a.h = 0, a.i && function(a, b) {
if (a) {
a = a.split("&");
for(var c = 0; c < a.length; c++){
var d = a[c].indexOf("="), e = null;
if (0 <= d) {
var f = a[c].substring(0, d);
e = a[c].substring(d + 1);
} else f = a[c];
b(f, e ? decodeURIComponent(e.replace(/\+/g, " ")) : "");
}
}
}(a.i, function(b, c) {
a.add(decodeURIComponent(b.replace(/\+/g, " ")), c);
}));
}
function dd(a, b) {
V(a), b = W(a, b), T(a.g.h, b) && (a.i = null, a.h -= a.g.get(b).length, T((a = a.g).h, b) && (delete a.h[b], a.i--, a.g.length > 2 * a.i && Lc(a)));
}
function ed(a, b) {
return V(a), b = W(a, b), T(a.g.h, b);
}
function mc(a, b, c) {
dd(a, b), 0 < c.length && (a.i = null, a.g.set(W(a, b), ra(c)), a.h += c.length);
}
function W(a, b) {
return b = String(b), a.j && (b = b.toLowerCase()), b;
}
(k = Rc.prototype).add = function(a, b) {
V(this), this.i = null, a = W(this, a);
var c = this.g.get(a);
return c || this.g.set(a, c = []), c.push(b), this.h += 1, this;
}, k.forEach = function(a, b) {
V(this), this.g.forEach(function(c, d) {
na(c, function(e) {
a.call(b, e, d, this);
}, this);
}, this);
}, k.T = function() {
V(this);
for(var a = this.g.R(), b = this.g.T(), c = [], d = 0; d < b.length; d++)for(var e = a[d], f = 0; f < e.length; f++)c.push(b[d]);
return c;
}, k.R = function(a) {
V(this);
var b = [];
if ("string" == typeof a) ed(this, a) && (b = qa(b, this.g.get(W(this, a))));
else {
a = this.g.R();
for(var c = 0; c < a.length; c++)b = qa(b, a[c]);
}
return b;
}, k.set = function(a, b) {
return V(this), this.i = null, ed(this, a = W(this, a)) && (this.h -= this.g.get(a).length), this.g.set(a, [
b
]), this.h += 1, this;
}, k.get = function(a, b) {
return a && 0 < (a = this.R(a)).length ? String(a[0]) : b;
}, k.toString = function() {
if (this.i) return this.i;
if (!this.g) return "";
for(var a = [], b = this.g.T(), c = 0; c < b.length; c++){
var d = b[c], e = encodeURIComponent(String(d));
d = this.R(d);
for(var f = 0; f < d.length; f++){
var h = e;
"" !== d[f] && (h += "=" + encodeURIComponent(String(d[f]))), a.push(h);
}
}
return this.i = a.join("&");
};
var fd = class {
constructor(a, b){
this.h = a, this.g = b;
}
};
function gd(a) {
this.l = a || hd, a = l.PerformanceNavigationTiming ? 0 < (a = l.performance.getEntriesByType("navigation")).length && ("hq" == a[0].nextHopProtocol || "h2" == a[0].nextHopProtocol) : !!(l.g && l.g.Ea && l.g.Ea() && l.g.Ea().Zb), this.j = a ? this.l : 1, this.g = null, 1 < this.j && (this.g = new Set()), this.h = null, this.i = [];
}
var hd = 10;
function id(a) {
return !!a.h || !!a.g && a.g.size >= a.j;
}
function Cc(a) {
return a.h ? 1 : a.g ? a.g.size : 0;
}
function yc(a, b) {
return a.h ? a.h == b : !!a.g && a.g.has(b);
}
function Dc(a, b) {
a.g ? a.g.add(b) : a.h = b;
}
function Fc(a, b) {
a.h && a.h == b ? a.h = null : a.g && a.g.has(b) && a.g.delete(b);
}
function jd(a) {
if (null != a.h) return a.i.concat(a.h.D);
if (null != a.g && 0 !== a.g.size) {
let b = a.i;
for (const c of a.g.values())b = b.concat(c.D);
return b;
}
return ra(a.i);
}
function kd() {}
function ld() {
this.g = new kd();
}
function od(a, b, c, d, e) {
try {
b.onload = null, b.onerror = null, b.onabort = null, b.ontimeout = null, e(d);
} catch (f) {}
}
function pd(a) {
this.l = a.$b || null, this.j = a.ib || !1;
}
function qd(a, b) {
C.call(this), this.D = a, this.u = b, this.m = void 0, this.readyState = rd, this.status = 0, this.responseType = this.responseText = this.response = this.statusText = "", this.onreadystatechange = null, this.v = new Headers(), this.h = null, this.C = "GET", this.B = "", this.g = !1, this.A = this.j = this.l = null;
}
gd.prototype.cancel = function() {
if (this.i = jd(this), this.h) this.h.cancel(), this.h = null;
else if (this.g && 0 !== this.g.size) {
for (const a of this.g.values())a.cancel();
this.g.clear();
}
}, kd.prototype.stringify = function(a) {
return l.JSON.stringify(a, void 0);
}, kd.prototype.parse = function(a) {
return l.JSON.parse(a, void 0);
}, t(pd, Yb), pd.prototype.g = function() {
return new qd(this.l, this.j);
}, pd.prototype.i = (a = {}, function() {
return a;
}), t(qd, C);
var rd = 0;
function ud(a) {
a.j.read().then(a.Sa.bind(a)).catch(a.ha.bind(a));
}
function td(a) {
a.readyState = 4, a.l = null, a.j = null, a.A = null, sd(a);
}
function sd(a) {
a.onreadystatechange && a.onreadystatechange.call(a);
}
(k = qd.prototype).open = function(a, b) {
if (this.readyState != rd) throw this.abort(), Error("Error reopening a connection");
this.C = a, this.B = b, this.readyState = 1, sd(this);
}, k.send = function(a) {
if (1 != this.readyState) throw this.abort(), Error("need to call open() first. ");
this.g = !0;
const b = {
headers: this.v,
method: this.C,
credentials: this.m,
cache: void 0
};
a && (b.body = a), (this.D || l).fetch(new Request(this.B, b)).then(this.Va.bind(this), this.ha.bind(this));
}, k.abort = function() {
this.response = this.responseText = "", this.v = new Headers(), this.status = 0, this.j && this.j.cancel("Request was aborted."), 1 <= this.readyState && this.g && 4 != this.readyState && (this.g = !1, td(this)), this.readyState = rd;
}, k.Va = function(a) {
if (this.g && (this.l = a, this.h || (this.status = this.l.status, this.statusText = this.l.statusText, this.h = a.headers, this.readyState = 2, sd(this)), this.g && (this.readyState = 3, sd(this), this.g))) {
if ("arraybuffer" === this.responseType) a.arrayBuffer().then(this.Ta.bind(this), this.ha.bind(this));
else if (void 0 !== l.ReadableStream && "body" in a) {
if (this.j = a.body.getReader(), this.u) {
if (this.responseType) throw Error('responseType must be empty for "streamBinaryChunks" mode responses.');
this.response = [];
} else this.response = this.responseText = "", this.A = new TextDecoder();
ud(this);
} else a.text().then(this.Ua.bind(this), this.ha.bind(this));
}
}, k.Sa = function(a) {
if (this.g) {
if (this.u && a.value) this.response.push(a.value);
else if (!this.u) {
var b = a.value ? a.value : new Uint8Array(0);
(b = this.A.decode(b, {
stream: !a.done
})) && (this.response = this.responseText += b);
}
a.done ? td(this) : sd(this), 3 == this.readyState && ud(this);
}
}, k.Ua = function(a) {
this.g && (this.response = this.responseText = a, td(this));
}, k.Ta = function(a) {
this.g && (this.response = a, td(this));
}, k.ha = function() {
this.g && td(this);
}, k.setRequestHeader = function(a, b) {
this.v.append(a, b);
}, k.getResponseHeader = function(a) {
return this.h && this.h.get(a.toLowerCase()) || "";
}, k.getAllResponseHeaders = function() {
if (!this.h) return "";
const a = [], b = this.h.entries();
for(var c = b.next(); !c.done;)a.push((c = c.value)[0] + ": " + c[1]), c = b.next();
return a.join("\r\n");
}, Object.defineProperty(qd.prototype, "withCredentials", {
get: function() {
return "include" === this.m;
},
set: function(a) {
this.m = a ? "include" : "same-origin";
}
});
var vd = l.JSON.parse;
function X(a) {
C.call(this), this.headers = new S(), this.u = a || null, this.h = !1, this.C = this.g = null, this.H = "", this.m = 0, this.j = "", this.l = this.F = this.v = this.D = !1, this.B = 0, this.A = null, this.J = wd, this.K = this.L = !1;
}
t(X, C);
var wd = "", xd = /^https?$/i, yd = [
"POST",
"PUT"
];
function pa(a) {
return "content-type" == a.toLowerCase();
}
function zd(a, b) {
a.h = !1, a.g && (a.l = !0, a.g.abort(), a.l = !1), a.j = b, a.m = 5, Cd(a), Dd(a);
}
function Cd(a) {
a.D || (a.D = !0, D(a, "complete"), D(a, "error"));
}
function Ed(a) {
if (a.h && void 0 !== goog && (!a.C[1] || 4 != O(a) || 2 != a.ba())) {
if (a.v && 4 == O(a)) Gb(a.Fa, 0, a);
else if (D(a, "readystatechange"), 4 == O(a)) {
a.h = !1;
try {
const n = a.ba();
switch(n){
case 200:
case 201:
case 202:
case 204:
case 206:
case 304:
case 1223:
var c, d, b = !0;
break;
default:
b = !1;
}
if (!(c = b)) {
if (d = 0 === n) {
var e = String(a.H).match(Mc)[1] || null;
if (!e && l.self && l.self.location) {
var f = l.self.location.protocol;
e = f.substr(0, f.length - 1);
}
d = !xd.test(e ? e.toLowerCase() : "");
}
c = d;
}
if (c) D(a, "complete"), D(a, "success");
else {
a.m = 6;
try {
var h = 2 < O(a) ? a.g.statusText : "";
} catch (u) {
h = "";
}
a.j = h + " [" + a.ba() + "]", Cd(a);
}
} finally{
Dd(a);
}
}
}
}
function Dd(a, b) {
if (a.g) {
Ad(a);
const c = a.g, d = a.C[0] ? aa : null;
a.g = null, a.C = null, b || D(a, "ready");
try {
c.onreadystatechange = d;
} catch (e) {}
}
}
function Ad(a) {
a.g && a.K && (a.g.ontimeout = null), a.A && (l.clearTimeout(a.A), a.A = null);
}
function O(a) {
return a.g ? a.g.readyState : 0;
}
function oc(a) {
try {
if (!a.g) return null;
if ("response" in a.g) return a.g.response;
switch(a.J){
case wd:
case "text":
return a.g.responseText;
case "arraybuffer":
if ("mozResponseArrayBuffer" in a.g) return a.g.mozResponseArrayBuffer;
}
return null;
} catch (b) {
return null;
}
}
function Gd(a, b, c) {
let b1;
a: {
for(d in c){
var d = !1;
break a;
}
d = !0;
}
d || (b1 = "", xa(c, function(c, d) {
b1 += d, b1 += ":", b1 += c, b1 += "\r\n";
}), c = b1, "string" == typeof a ? null != c && encodeURIComponent(String(c)) : R(a, b, c));
}
function Hd(a, b, c) {
return c && c.internalChannelParams && c.internalChannelParams[a] || b;
}
function Id(a) {
this.za = 0, this.l = [], this.h = new Mb(), this.la = this.oa = this.F = this.W = this.g = this.sa = this.D = this.aa = this.o = this.P = this.s = null, this.Za = this.V = 0, this.Xa = Hd("failFast", !1, a), this.N = this.v = this.u = this.m = this.j = null, this.X = !0, this.I = this.ta = this.U = -1, this.Y = this.A = this.C = 0, this.Pa = Hd("baseRetryDelayMs", 5e3, a), this.$a = Hd("retryDelaySeedMs", 1e4, a), this.Ya = Hd("forwardChannelMaxRetries", 2, a), this.ra = Hd("forwardChannelRequestTimeoutMs", 2e4, a), this.qa = a && a.xmlHttpFactory || void 0, this.Ba = a && a.Yb || !1, this.K = void 0, this.H = a && a.supportsCrossDomainXhr || !1, this.J = "", this.i = new gd(a && a.concurrentRequestLimit), this.Ca = new ld(), this.ja = a && a.fastHandshake || !1, this.Ra = a && a.Wb || !1, a && a.Aa && this.h.Aa(), a && a.forceLongPolling && (this.X = !1), this.$ = !this.ja && this.X && a && a.detectBufferingProxy || !1, this.ka = void 0, this.O = 0, this.L = !1, this.B = null, this.Wa = !a || !1 !== a.Xb;
}
function Ic(a) {
if (Jd(a), 3 == a.G) {
var b = a.V++, c = N(a.F);
R(c, "SID", a.J), R(c, "RID", b), R(c, "TYPE", "terminate"), Kd(a, c), (b = new M(a, a.h, b, void 0)).K = 2, b.v = jc(N(c)), c = !1, l.navigator && l.navigator.sendBeacon && (c = l.navigator.sendBeacon(b.v.toString(), "")), !c && l.Image && (new Image().src = b.v, c = !0), c || (b.g = nc(b.l, null), b.g.ea(b.v)), b.F = Date.now(), lc(b);
}
Ld(a);
}
function Ac(a) {
a.g && (wc(a), a.g.cancel(), a.g = null);
}
function Jd(a) {
Ac(a), a.u && (l.clearTimeout(a.u), a.u = null), zc(a), a.i.cancel(), a.m && ("number" == typeof a.m && l.clearTimeout(a.m), a.m = null);
}
function Md(a, b) {
a.l.push(new fd(a.Za++, b)), 3 == a.G && Hc(a);
}
function Hc(a) {
id(a.i) || a.m || (a.m = !0, zb(a.Ha, a), a.C = 0);
}
function Qd(a, b) {
var c;
c = b ? b.m : a.V++;
const d = N(a.F);
R(d, "SID", a.J), R(d, "RID", c), R(d, "AID", a.U), Kd(a, d), a.o && a.s && Gd(d, a.o, a.s), c = new M(a, a.h, c, a.C + 1), null === a.o && (c.H = a.s), b && (a.l = b.D.concat(a.l)), b = Pd(a, c, 1e3), c.setTimeout(Math.round(0.5 * a.ra) + Math.round(0.5 * a.ra * Math.random())), Dc(a.i, c), ic(c, d, b);
}
function Kd(a, b) {
a.j && Kc({}, function(c, d) {
R(b, d, c);
});
}
function Pd(a, b, c) {
c = Math.min(a.l.length, c);
var d = a.j ? q(a.j.Oa, a.j, a) : null;
a: {
var e = a.l;
let f = -1;
for(;;){
const h = [
"count=" + c
];
-1 == f ? 0 < c ? (f = e[0].h, h.push("ofs=" + f)) : f = 0 : h.push("ofs=" + f);
let n = !0;
for(let u = 0; u < c; u++){
let m = e[u].h;
const r = e[u].g;
if (0 > (m -= f)) f = Math.max(0, e[u].h - 100), n = !1;
else try {
!function(a, b, c) {
const d = c || "";
try {
Kc(a, function(e, f) {
let h = e;
p(e) && (h = rb(e)), b.push(d + f + "=" + encodeURIComponent(h));
});
} catch (e) {
throw b.push(d + "type=" + encodeURIComponent("_badmap")), e;
}
}(r, h, "req" + m + "_");
} catch (G) {
d && d(r);
}
}
if (n) {
d = h.join("&");
break a;
}
}
}
return b.D = a = a.l.splice(0, c), d;
}
function Gc(a) {
a.g || a.u || (a.Y = 1, zb(a.Ga, a), a.A = 0);
}
function Bc(a) {
return !a.g && !a.u && !(3 <= a.A) && (a.Y++, a.u = K(q(a.Ga, a), Od(a, a.A)), a.A++, !0);
}
function wc(a) {
null != a.B && (l.clearTimeout(a.B), a.B = null);
}
function Rd(a) {
a.g = new M(a, a.h, "rpc", a.Y), null === a.o && (a.g.H = a.s), a.g.O = 0;
var b = N(a.oa);
R(b, "RID", "rpc"), R(b, "SID", a.J), R(b, "CI", a.N ? "0" : "1"), R(b, "AID", a.U), Kd(a, b), R(b, "TYPE", "xmlhttp"), a.o && a.s && Gd(b, a.o, a.s), a.K && a.g.setTimeout(a.K);
var c = a.g;
a = a.la, c.K = 1, c.v = jc(N(b)), c.s = null, c.U = !0, kc(c, a);
}
function zc(a) {
null != a.v && (l.clearTimeout(a.v), a.v = null);
}
function uc(a, b) {
var c = null;
if (a.g == b) {
zc(a), wc(a), a.g = null;
var d = 2;
} else {
if (!yc(a.i, b)) return;
c = b.D, Fc(a.i, b), d = 1;
}
if (a.I = b.N, 0 != a.G) {
if (b.i) {
if (1 == d) {
c = b.s ? b.s.length : 0, b = Date.now() - b.F;
var b1, e = a.C;
D(d = Sb(), new Vb(d, c, b, e)), Hc(a);
} else Gc(a);
} else if (3 == (e = b.o) || 0 == e && 0 < a.I || !(1 == d && (b1 = b, !(Cc(a.i) >= a.i.j - +!!a.m) && (a.m ? (a.l = b1.D.concat(a.l), !0) : 1 != a.G && 2 != a.G && !(a.C >= (a.Xa ? 0 : a.Ya)) && (a.m = K(q(a.Ha, a, b1), Od(a, a.C)), a.C++, !0))) || 2 == d && Bc(a))) switch(c && 0 < c.length && ((b = a.i).i = b.i.concat(c)), e){
case 1:
Q(a, 5);
break;
case 4:
Q(a, 10);
break;
case 3:
Q(a, 6);
break;
default:
Q(a, 2);
}
}
}
function Od(a, b) {
let c = a.Pa + Math.floor(Math.random() * a.$a);
return a.j || (c *= 2), c * b;
}
function Q(a, b) {
if (a.h.info("Error code " + b), 2 == b) {
var c = null;
a.j && (c = null);
var d = q(a.jb, a);
c || (c = new U("//www.google.com/images/cleardot.gif"), l.location && "http" == l.location.protocol || Oc(c, "https"), jc(c)), function(a, b) {
const c = new Mb();
if (l.Image) {
const d = new Image();
d.onload = ja(od, c, d, "TestLoadImage: loaded", !0, b), d.onerror = ja(od, c, d, "TestLoadImage: error", !1, b), d.onabort = ja(od, c, d, "TestLoadImage: abort", !1, b), d.ontimeout = ja(od, c, d, "TestLoadImage: timeout", !1, b), l.setTimeout(function() {
d.ontimeout && d.ontimeout();
}, 1e4), d.src = a;
} else b(!1);
}(c.toString(), d);
} else J(2);
a.G = 0, a.j && a.j.va(b), Ld(a), Jd(a);
}
function Ld(a) {
a.G = 0, a.I = -1, a.j && ((0 != jd(a.i).length || 0 != a.l.length) && (a.i.i.length = 0, ra(a.l), a.l.length = 0), a.j.ua());
}
function Ec(a, b, c) {
var a1, a2, b1, c1, d, e;
let d1 = (a1 = c) instanceof U ? N(a1) : new U(a1, void 0);
if ("" != d1.i) b && Pc(d1, b + "." + d1.i), Qc(d1, d1.m);
else {
const e1 = l.location;
a2 = e1.protocol, b1 = b ? b + "." + e1.hostname : e1.hostname, c1 = +e1.port, d = c, e = new U(null, void 0), a2 && Oc(e, a2), b1 && Pc(e, b1), c1 && Qc(e, c1), d && (e.l = d), d1 = e;
}
return a.aa && xa(a.aa, function(e, f) {
R(d1, f, e);
}), b = a.D, c = a.sa, b && c && R(d1, b, c), R(d1, "VER", a.ma), Kd(a, d1), d1;
}
function nc(a, b, c) {
if (b && !a.H) throw Error("Can't create secondary domain capable XhrIo object.");
return (b = new X(c && a.Ba && !a.qa ? new pd({
ib: !0
}) : a.qa)).L = a.H, b;
}
function Sd() {}
function Td() {
if (y && !(10 <= Number(Ua))) throw Error("Environmental error: no available transport.");
}
function Y(a, b) {
C.call(this), this.g = new Id(b), this.l = a, this.h = b && b.messageUrlParams || null, a = b && b.messageHeaders || null, b && b.clientProtocolHeaderRequired && (a ? a["X-Client-Protocol"] = "webchannel" : a = {
"X-Client-Protocol": "webchannel"
}), this.g.s = a, a = b && b.initMessageHeaders || null, b && b.messageContentType && (a ? a["X-WebChannel-Content-Type"] = b.messageContentType : a = {
"X-WebChannel-Content-Type": b.messageContentType
}), b && b.ya && (a ? a["X-WebChannel-Client-Profile"] = b.ya : a = {
"X-WebChannel-Client-Profile": b.ya
}), this.g.P = a, (a = b && b.httpHeadersOverwriteParam) && !sa(a) && (this.g.o = a), this.A = b && b.supportsCrossDomainXhr || !1, this.v = b && b.sendRawJson || !1, (b = b && b.httpSessionIdParam) && !sa(b) && (this.g.D = b, null !== (a = this.h) && b in a && b in (a = this.h) && delete a[b]), this.j = new Z(this);
}
function Ud(a) {
ac.call(this);
var b = a.__sm__;
if (b) {
a: {
for(const c in b){
a = c;
break a;
}
a = void 0;
}
(this.i = a) && (a = this.i, b = null !== b && a in b ? b[a] : void 0), this.data = b;
} else this.data = a;
}
function Vd() {
bc.call(this), this.status = 1;
}
function Z(a) {
this.g = a;
}
(k = X.prototype).ea = function(a, b, c, d) {
if (this.g) throw Error("[goog.net.XhrIo] Object is active with another request=" + this.H + "; newUri=" + a);
b = b ? b.toUpperCase() : "GET", this.H = a, this.j = "", this.m = 0, this.D = !1, this.h = !0, this.g = this.u ? this.u.g() : cc.g(), this.C = this.u ? Zb(this.u) : Zb(cc), this.g.onreadystatechange = q(this.Fa, this);
try {
this.F = !0, this.g.open(b, String(a), !0), this.F = !1;
} catch (f) {
zd(this, f);
return;
}
a = c || "";
const e = new S(this.headers);
d && Kc(d, function(f, h) {
e.set(h, f);
}), d = function(a) {
a: {
var b = pa;
const c = a.length, d = "string" == typeof a ? a.split("") : a;
for(let e = 0; e < c; e++)if (e in d && b.call(void 0, d[e], e, a)) {
b = e;
break a;
}
b = -1;
}
return 0 > b ? null : "string" == typeof a ? a.charAt(b) : a[b];
}(e.T()), c = l.FormData && a instanceof l.FormData, !(0 <= ma(yd, b)) || d || c || e.set("Content-Type", "application/x-www-form-urlencoded;charset=utf-8"), e.forEach(function(f, h) {
this.g.setRequestHeader(h, f);
}, this), this.J && (this.g.responseType = this.J), "withCredentials" in this.g && this.g.withCredentials !== this.L && (this.g.withCredentials = this.L);
try {
var a1;
Ad(this), 0 < this.B && ((this.K = (a1 = this.g, y && (Object.prototype.hasOwnProperty.call(Ga, 9) ? Ga[9] : Ga[9] = function() {
let a = 0;
const b = ta(String(Na)).split("."), c = ta("9").split("."), d = Math.max(b.length, c.length);
for(let h = 0; 0 == a && h < d; h++){
var a1, b1, a2, b2, a3, b3, e = b[h] || "", f = c[h] || "";
do {
if (e = /(\d*)(\D*)(.*)/.exec(e) || [
"",
"",
"",
""
], f = /(\d*)(\D*)(.*)/.exec(f) || [
"",
"",
"",
""
], 0 == e[0].length && 0 == f[0].length) break;
a1 = 0 == e[1].length ? 0 : parseInt(e[1], 10), b1 = 0 == f[1].length ? 0 : parseInt(f[1], 10), a = (a1 < b1 ? -1 : +(a1 > b1)) || (a2 = 0 == e[2].length, b2 = 0 == f[2].length, a2 < b2 ? -1 : +(a2 > b2)) || (a3 = e[2], b3 = f[2], a3 < b3 ? -1 : +(a3 > b3)), e = e[3], f = f[3];
}while (0 == a)
}
return 0 <= a;
}(9)) && "number" == typeof a1.timeout && void 0 !== a1.ontimeout)) ? (this.g.timeout = this.B, this.g.ontimeout = q(this.pa, this)) : this.A = Gb(this.pa, this.B, this)), this.v = !0, this.g.send(a), this.v = !1;
} catch (f) {
zd(this, f);
}
}, k.pa = function() {
void 0 !== goog && this.g && (this.j = "Timed out after " + this.B + "ms, aborting", this.m = 8, D(this, "timeout"), this.abort(8));
}, k.abort = function(a) {
this.g && this.h && (this.h = !1, this.l = !0, this.g.abort(), this.l = !1, this.m = a || 7, D(this, "complete"), D(this, "abort"), Dd(this));
}, k.M = function() {
this.g && (this.h && (this.h = !1, this.l = !0, this.g.abort(), this.l = !1), Dd(this, !0)), X.Z.M.call(this);
}, k.Fa = function() {
this.s || (this.F || this.v || this.l ? Ed(this) : this.cb());
}, k.cb = function() {
Ed(this);
}, k.ba = function() {
try {
return 2 < O(this) ? this.g.status : -1;
} catch (a) {
return -1;
}
}, k.ga = function() {
try {
return this.g ? this.g.responseText : "";
} catch (a) {
return "";
}
}, k.Qa = function(a) {
if (this.g) {
var b = this.g.responseText;
return a && 0 == b.indexOf(a) && (b = b.substring(a.length)), vd(b);
}
}, k.Da = function() {
return this.m;
}, k.La = function() {
return "string" == typeof this.j ? this.j : String(this.j);
}, (k = Id.prototype).ma = 8, k.G = 1, k.hb = function(a) {
try {
this.h.info("Origin Trials invoked: " + a);
} catch (b) {}
}, k.Ha = function(a) {
if (this.m) {
if (this.m = null, 1 == this.G) {
if (!a) {
this.V = Math.floor(1e5 * Math.random()), a = this.V++;
const e = new M(this, this.h, a, void 0);
let f = this.s;
if (this.P && (f ? Aa(f = ya(f), this.P) : f = this.P), null === this.o && (e.H = f), this.ja) a: {
for(var b = 0, c = 0; c < this.l.length; c++){
b: {
var d = this.l[c];
if ("__data__" in d.g && "string" == typeof (d = d.g.__data__)) {
d = d.length;
break b;
}
d = void 0;
}
if (void 0 === d) break;
if (4096 < (b += d)) {
b = c;
break a;
}
if (4096 === b || c === this.l.length - 1) {
b = c + 1;
break a;
}
}
b = 1e3;
}
else b = 1e3;
b = Pd(this, e, b), R(c = N(this.F), "RID", a), R(c, "CVER", 22), this.D && R(c, "X-HTTP-Session-Id", this.D), Kd(this, c), this.o && f && Gd(c, this.o, f), Dc(this.i, e), this.Ra && R(c, "TYPE", "init"), this.ja ? (R(c, "$req", b), R(c, "SID", "null"), e.$ = !0, ic(e, c, null)) : ic(e, c, b), this.G = 2;
}
} else 3 == this.G && (a ? Qd(this, a) : 0 == this.l.length || id(this.i) || Qd(this));
}
}, k.Ga = function() {
if (this.u = null, Rd(this), this.$ && !(this.L || null == this.g || 0 >= this.O)) {
var a = 2 * this.O;
this.h.info("BP detection timer enabled: " + a), this.B = K(q(this.bb, this), a);
}
}, k.bb = function() {
this.B && (this.B = null, this.h.info("BP detection timeout reached."), this.h.info("Buffering proxy detected and switch to long-polling!"), this.N = !1, this.L = !0, J(10), Ac(this), Rd(this));
}, k.ab = function() {
null != this.v && (this.v = null, Ac(this), Bc(this), J(19));
}, k.jb = function(a) {
a ? (this.h.info("Successfully pinged google.com"), J(2)) : (this.h.info("Failed to ping google.com"), J(1));
}, (k = Sd.prototype).xa = function() {}, k.wa = function() {}, k.va = function() {}, k.ua = function() {}, k.Oa = function() {}, Td.prototype.g = function(a, b) {
return new Y(a, b);
}, t(Y, C), Y.prototype.m = function() {
this.g.j = this.j, this.A && (this.g.H = !0);
var a = this.g, b = this.l, c = this.h || void 0;
a.Wa && (a.h.info("Origin Trials enabled."), zb(q(a.hb, a, b))), J(0), a.W = b, a.aa = c || {}, a.N = a.X, a.F = Ec(a, null, a.W), Hc(a);
}, Y.prototype.close = function() {
Ic(this.g);
}, Y.prototype.u = function(a) {
if ("string" == typeof a) {
var b = {};
b.__data__ = a, Md(this.g, b);
} else this.v ? ((b = {}).__data__ = rb(a), Md(this.g, b)) : Md(this.g, a);
}, Y.prototype.M = function() {
this.g.j = null, delete this.j, Ic(this.g), delete this.g, Y.Z.M.call(this);
}, t(Ud, ac), t(Vd, bc), t(Z, Sd), Z.prototype.xa = function() {
D(this.g, "a");
}, Z.prototype.wa = function(a) {
D(this.g, new Ud(a));
}, Z.prototype.va = function(a) {
D(this.g, new Vd(a));
}, Z.prototype.ua = function() {
D(this.g, "b");
}, Td.prototype.createWebChannel = Td.prototype.g, Y.prototype.send = Y.prototype.u, Y.prototype.open = Y.prototype.m, Y.prototype.close = Y.prototype.close, Wb.NO_ERROR = 0, Wb.TIMEOUT = 8, Wb.HTTP_ERROR = 6, Xb.COMPLETE = "complete", $b.EventType = L, L.OPEN = "a", L.CLOSE = "b", L.ERROR = "c", L.MESSAGE = "d", C.prototype.listen = C.prototype.N, X.prototype.listenOnce = X.prototype.O, X.prototype.getLastError = X.prototype.La, X.prototype.getLastErrorCode = X.prototype.Da, X.prototype.getStatus = X.prototype.ba, X.prototype.getResponseJson = X.prototype.Qa, X.prototype.getResponseText = X.prototype.ga, X.prototype.send = X.prototype.ea;
var createWebChannelTransport = esm.createWebChannelTransport = function() {
return new Td();
}, getStatEventTarget = esm.getStatEventTarget = function() {
return Sb();
}, ErrorCode = esm.ErrorCode = Wb, EventType = esm.EventType = Xb, Event = esm.Event = H, Stat = esm.Stat = {
rb: 0,
ub: 1,
vb: 2,
Ob: 3,
Tb: 4,
Qb: 5,
Rb: 6,
Pb: 7,
Nb: 8,
Sb: 9,
PROXY: 10,
NOPROXY: 11,
Lb: 12,
Hb: 13,
Ib: 14,
Gb: 15,
Jb: 16,
Kb: 17,
nb: 18,
mb: 19,
ob: 20
}, FetchXmlHttpFactory = esm.FetchXmlHttpFactory = pd, WebChannel = esm.WebChannel = $b, XhrIo = esm.XhrIo = X;
//# sourceMappingURL=index.esm2017.js.map
/***/ },
/***/ 6257: /***/ function(__unused_webpack_module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ hJ: function() {
return /* reexport safe */ _firebase_firestore__WEBPACK_IMPORTED_MODULE_0__.hJ;
},
/* harmony export */ PL: function() {
return /* reexport safe */ _firebase_firestore__WEBPACK_IMPORTED_MODULE_0__.PL;
}
});
/* harmony import */ var _firebase_firestore__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(19);
//# sourceMappingURL=index.esm.js.map
/***/ },
/***/ 8045: /***/ function(__unused_webpack_module, exports, __webpack_require__) {
"use strict";
function _toConsumableArray(arr) {
return function(arr) {
if (Array.isArray(arr)) {
for(var i = 0, arr2 = Array(arr.length); i < arr.length; i++)arr2[i] = arr[i];
return arr2;
}
}(arr) || function(iter) {
if (Symbol.iterator in Object(iter) || "[object Arguments]" === Object.prototype.toString.call(iter)) return Array.from(iter);
}(arr) || function() {
throw TypeError("Invalid attempt to spread non-iterable instance");
}();
}
exports.default = function(_param) {
var src, arr, sizerSvg, src1 = _param.src, sizes = _param.sizes, _unoptimized = _param.unoptimized, unoptimized = void 0 !== _unoptimized && _unoptimized, _priority = _param.priority, priority = void 0 !== _priority && _priority, loading = _param.loading, _lazyBoundary = _param.lazyBoundary, className = _param.className, quality = _param.quality, width = _param.width, height = _param.height, objectFit = _param.objectFit, objectPosition = _param.objectPosition, onLoadingComplete = _param.onLoadingComplete, _loader = _param.loader, loader = void 0 === _loader ? defaultImageLoader : _loader, _placeholder = _param.placeholder, placeholder = void 0 === _placeholder ? "empty" : _placeholder, blurDataURL = _param.blurDataURL, all = function(source, excluded) {
if (null == source) return {};
var key, i, target = function(source, excluded) {
if (null == source) return {};
var key, i, target = {}, sourceKeys = Object.keys(source);
for(i = 0; i < sourceKeys.length; i++)key = sourceKeys[i], excluded.indexOf(key) >= 0 || (target[key] = source[key]);
return target;
}(source, excluded);
if (Object.getOwnPropertySymbols) {
var sourceSymbolKeys = Object.getOwnPropertySymbols(source);
for(i = 0; i < sourceSymbolKeys.length; i++)key = sourceSymbolKeys[i], !(excluded.indexOf(key) >= 0) && Object.prototype.propertyIsEnumerable.call(source, key) && (target[key] = source[key]);
}
return target;
}(_param, [
"src",
"sizes",
"unoptimized",
"priority",
"loading",
"lazyBoundary",
"className",
"quality",
"width",
"height",
"objectFit",
"objectPosition",
"onLoadingComplete",
"loader",
"placeholder",
"blurDataURL"
]), layout = sizes ? "responsive" : "intrinsic";
"layout" in all && (all.layout && (layout = all.layout), // Remove property so it's not spread into image:
delete all.layout);
var staticSrc = "";
if ("object" == typeof (src = src1) && (isStaticRequire(src) || void 0 !== src.src)) {
var staticImageData = isStaticRequire(src1) ? src1.default : src1;
if (!staticImageData.src) throw Error("An object should only be passed to the image component src parameter if it comes from a static image import. It must include src. Received ".concat(JSON.stringify(staticImageData)));
if (blurDataURL = blurDataURL || staticImageData.blurDataURL, staticSrc = staticImageData.src, (!layout || "fill" !== layout) && (height = height || staticImageData.height, width = width || staticImageData.width, !staticImageData.height || !staticImageData.width)) throw Error("An object should only be passed to the image component src parameter if it comes from a static image import. It must include height and width. Received ".concat(JSON.stringify(staticImageData)));
}
src1 = "string" == typeof src1 ? src1 : staticSrc;
var widthInt = getInt(width), heightInt = getInt(height), qualityInt = getInt(quality), isLazy = !priority && ("lazy" === loading || void 0 === loading);
(src1.startsWith("data:") || src1.startsWith("blob:")) && (// https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URIs
unoptimized = !0, isLazy = !1), loadedImageURLs.has(src1) && (isLazy = !1);
var ref2 = function(arr) {
if (Array.isArray(arr)) return arr;
}(arr = _useIntersection.useIntersection({
rootMargin: void 0 === _lazyBoundary ? "200px" : _lazyBoundary,
disabled: !isLazy
})) || function(arr, i) {
var _arr = [], _n = !0, _d = !1, _e = void 0;
try {
for(var _s, _i = arr[Symbol.iterator](); !(_n = (_s = _i.next()).done) && (_arr.push(_s.value), 2 !== _arr.length); _n = !0);
} catch (err) {
_d = !0, _e = err;
} finally{
try {
_n || null == _i.return || _i.return();
} finally{
if (_d) throw _e;
}
}
return _arr;
}(arr, 0) || function() {
throw TypeError("Invalid attempt to destructure non-iterable instance");
}(), setRef = ref2[0], isIntersected = ref2[1], isVisible = !isLazy || isIntersected, wrapperStyle = {
boxSizing: "border-box",
display: "block",
overflow: "hidden",
width: "initial",
height: "initial",
background: "none",
opacity: 1,
border: 0,
margin: 0,
padding: 0
}, sizerStyle = {
boxSizing: "border-box",
display: "block",
width: "initial",
height: "initial",
background: "none",
opacity: 1,
border: 0,
margin: 0,
padding: 0
}, hasSizer = !1, imgStyle = {
position: "absolute",
top: 0,
left: 0,
bottom: 0,
right: 0,
boxSizing: "border-box",
padding: 0,
border: "none",
margin: "auto",
display: "block",
width: 0,
height: 0,
minWidth: "100%",
maxWidth: "100%",
minHeight: "100%",
maxHeight: "100%",
objectFit: objectFit,
objectPosition: objectPosition
}, blurStyle = "blur" === placeholder ? {
filter: "blur(20px)",
backgroundSize: objectFit || "cover",
backgroundImage: 'url("'.concat(blurDataURL, '")'),
backgroundPosition: objectPosition || "0% 0%"
} : {};
if ("fill" === layout) // <Image src="i.png" layout="fill" />
wrapperStyle.display = "block", wrapperStyle.position = "absolute", wrapperStyle.top = 0, wrapperStyle.left = 0, wrapperStyle.bottom = 0, wrapperStyle.right = 0;
else if (void 0 !== widthInt && void 0 !== heightInt) {
// <Image src="i.png" width="100" height="100" />
var quotient = heightInt / widthInt, paddingTop = isNaN(quotient) ? "100%" : "".concat(100 * quotient, "%");
"responsive" === layout ? (// <Image src="i.png" width="100" height="100" layout="responsive" />
wrapperStyle.display = "block", wrapperStyle.position = "relative", hasSizer = !0, sizerStyle.paddingTop = paddingTop) : "intrinsic" === layout ? (// <Image src="i.png" width="100" height="100" layout="intrinsic" />
wrapperStyle.display = "inline-block", wrapperStyle.position = "relative", wrapperStyle.maxWidth = "100%", hasSizer = !0, sizerStyle.maxWidth = "100%", sizerSvg = '<svg width="'.concat(widthInt, '" height="').concat(heightInt, '" xmlns="http://www.w3.org/2000/svg" version="1.1"/>')) : "fixed" === layout && (// <Image src="i.png" width="100" height="100" layout="fixed" />
wrapperStyle.display = "inline-block", wrapperStyle.position = "relative", wrapperStyle.width = widthInt, wrapperStyle.height = heightInt);
}
var imgAttributes = {
src: emptyDataURL,
srcSet: void 0,
sizes: void 0
};
isVisible && (imgAttributes = generateImgAttrs({
src: src1,
unoptimized: unoptimized,
layout: layout,
width: widthInt,
quality: qualityInt,
sizes: sizes,
loader: loader
}));
var srcString = src1;
return /*#__PURE__*/ _react.default.createElement("span", {
style: wrapperStyle
}, hasSizer ? /*#__PURE__*/ _react.default.createElement("span", {
style: sizerStyle
}, sizerSvg ? /*#__PURE__*/ _react.default.createElement("img", {
style: {
display: "block",
maxWidth: "100%",
width: "initial",
height: "initial",
background: "none",
opacity: 1,
border: 0,
margin: 0,
padding: 0
},
alt: "",
"aria-hidden": !0,
src: "data:image/svg+xml;base64,".concat(_toBase64.toBase64(sizerSvg))
}) : null) : null, /*#__PURE__*/ _react.default.createElement("img", Object.assign({}, all, imgAttributes, {
decoding: "async",
"data-nimg": layout,
className: className,
ref: function(img) {
setRef(img), // See https://stackoverflow.com/q/39777833/266535 for why we use this ref
// handler instead of the img's onLoad attribute.
function(img, src, layout, placeholder, onLoadingComplete) {
if (img) {
var handleLoad = function() {
img.src !== emptyDataURL && ("decode" in img ? img.decode() : Promise.resolve()).catch(function() {}).then(function() {
"blur" === placeholder && (img.style.filter = "none", img.style.backgroundSize = "none", img.style.backgroundImage = "none"), loadedImageURLs.add(src), onLoadingComplete && // Pass back read-only primitive values but not the
// underlying DOM element because it could be misused.
onLoadingComplete({
naturalWidth: img.naturalWidth,
naturalHeight: img.naturalHeight
});
});
};
img.complete ? // If the real image fails to load, this will still remove the placeholder.
// This is the desired behavior for now, and will be revisited when error
// handling is worked on for the image component itself.
handleLoad() : img.onload = handleLoad;
}
}(img, srcString, 0, placeholder, onLoadingComplete);
},
style: _objectSpread({}, imgStyle, blurStyle)
})), /*#__PURE__*/ _react.default.createElement("noscript", null, /*#__PURE__*/ _react.default.createElement("img", Object.assign({}, all, generateImgAttrs({
src: src1,
unoptimized: unoptimized,
layout: layout,
width: widthInt,
quality: qualityInt,
sizes: sizes,
loader: loader
}), {
decoding: "async",
"data-nimg": layout,
style: imgStyle,
className: className,
// @ts-ignore - TODO: upgrade to `@types/react@17`
loading: loading || "lazy"
}))), priority // for browsers that do not support `imagesrcset`, and in those cases
? //
// https://html.spec.whatwg.org/multipage/semantics.html#attr-link-imagesrcset
/*#__PURE__*/ _react.default.createElement(_head.default, null, /*#__PURE__*/ _react.default.createElement("link", {
key: "__nimg-" + imgAttributes.src + imgAttributes.srcSet + imgAttributes.sizes,
rel: "preload",
as: "image",
href: imgAttributes.srcSet ? void 0 : imgAttributes.src,
// @ts-ignore: imagesrcset is not yet in the link element type.
imagesrcset: imgAttributes.srcSet,
// @ts-ignore: imagesizes is not yet in the link element type.
imagesizes: imgAttributes.sizes
})) : null);
};
var _react = _interopRequireDefault(__webpack_require__(7294)), _head = _interopRequireDefault(__webpack_require__(5443)), _toBase64 = __webpack_require__(6978), _imageConfig = __webpack_require__(5809), _useIntersection = __webpack_require__(7190);
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
function _objectSpread(target) {
for(var _arguments = arguments, i = 1; i < arguments.length; i++)!function(i) {
var source = null != _arguments[i] ? _arguments[i] : {}, ownKeys = Object.keys(source);
"function" == typeof Object.getOwnPropertySymbols && (ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function(sym) {
return Object.getOwnPropertyDescriptor(source, sym).enumerable;
}))), ownKeys.forEach(function(key) {
var value;
value = source[key], key in target ? Object.defineProperty(target, key, {
value: value,
enumerable: !0,
configurable: !0,
writable: !0
}) : target[key] = value;
});
}(i);
return target;
}
var loadedImageURLs = new Set(), emptyDataURL = "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7", loaders = new Map([
[
"default",
function(param) {
var root = param.root, src = param.src, width = param.width, quality = param.quality;
return "".concat(root, "?url=").concat(encodeURIComponent(src), "&w=").concat(width, "&q=").concat(quality || 75);
} //# sourceMappingURL=image.js.map
],
[
"imgix",
function(param) {
var root = param.root, src = param.src, width = param.width, quality = param.quality, url = new URL("".concat(root).concat(normalizeSrc(src))), params = url.searchParams;
return params.set("auto", params.get("auto") || "format"), params.set("fit", params.get("fit") || "max"), params.set("w", params.get("w") || width.toString()), quality && params.set("q", quality.toString()), url.href;
}
],
[
"cloudinary",
function(param) {
var root = param.root, src = param.src, paramsString = [
"f_auto",
"c_limit",
"w_" + param.width,
"q_" + (param.quality || "auto")
].join(",") + "/";
return "".concat(root).concat(paramsString).concat(normalizeSrc(src));
}
],
[
"akamai",
function(param) {
var root = param.root, src = param.src, width = param.width;
return "".concat(root).concat(normalizeSrc(src), "?imwidth=").concat(width);
}
],
[
"custom",
function(param) {
var src = param.src;
throw Error('Image with src "'.concat(src, '" is missing "loader" prop.') + "\nRead more: https://nextjs.org/docs/messages/next-image-missing-loader");
}
]
]);
function isStaticRequire(src) {
return void 0 !== src.default;
}
var ref1 = {
deviceSizes: [
640,
750,
828,
1080,
1200,
1920,
2048,
3840
],
imageSizes: [
16,
32,
48,
64,
96,
128,
256,
384
],
path: "/_next/image",
loader: "default"
}, configDeviceSizes = ref1.deviceSizes, configImageSizes = ref1.imageSizes, configLoader = ref1.loader, configPath = ref1.path;
ref1.domains;
// sort smallest to largest
var allSizes = _toConsumableArray(configDeviceSizes).concat(_toConsumableArray(configImageSizes));
function generateImgAttrs(param) {
var src = param.src, unoptimized = param.unoptimized, layout = param.layout, width = param.width, quality = param.quality, sizes = param.sizes, loader = param.loader;
if (unoptimized) return {
src: src,
srcSet: void 0,
sizes: void 0
};
var ref = function(width, layout, sizes) {
if (sizes && ("fill" === layout || "responsive" === layout)) {
for(// Find all the "vw" percent sizes used in the sizes prop
var viewportWidthRe = /(^|\s)(1?\d?\d)vw/g, percentSizes = []; match = viewportWidthRe.exec(sizes); match)percentSizes.push(parseInt(match[2]));
if (percentSizes.length) {
var match, _Math, smallestRatio = 0.01 * (_Math = Math).min.apply(_Math, _toConsumableArray(percentSizes));
return {
widths: allSizes.filter(function(s) {
return s >= configDeviceSizes[0] * smallestRatio;
}),
kind: "w"
};
}
return {
widths: allSizes,
kind: "w"
};
}
return "number" != typeof width || "fill" === layout || "responsive" === layout ? {
widths: configDeviceSizes,
kind: "w"
} : {
widths: _toConsumableArray(new Set(// > blue colors. Showing a 3x resolution image in the app vs a 2x
// > resolution image will be visually the same, though the 3x image
// > takes significantly more data. Even true 3x resolution screens are
// > wasteful as the human eye cannot see that level of detail without
// > something like a magnifying glass.
// https://blog.twitter.com/engineering/en_us/topics/infrastructure/2019/capping-image-fidelity-on-ultra-high-resolution-devices.html
[
width,
2 /*, width * 3*/ * width
].map(function(w) {
return allSizes.find(function(p) {
return p >= w;
}) || allSizes[allSizes.length - 1];
}))),
kind: "x"
};
}(width, layout, sizes), widths = ref.widths, kind = ref.kind, last = widths.length - 1;
return {
sizes: sizes || "w" !== kind ? sizes : "100vw",
srcSet: widths.map(function(w, i) {
return "".concat(loader({
src: src,
quality: quality,
width: w
}), " ").concat("w" === kind ? w : i + 1).concat(kind);
}).join(", "),
// It's intended to keep `src` the last attribute because React updates
// attributes in order. If we keep `src` the first one, Safari will
// immediately start to fetch `src`, before `sizes` and `srcSet` are even
// updated by React. That causes multiple unnecessary requests if `srcSet`
// and `sizes` are defined.
// This bug cannot be reproduced in Chrome or Firefox.
src: loader({
src: src,
quality: quality,
width: widths[last]
})
};
}
function getInt(x) {
return "number" == typeof x ? x : "string" == typeof x ? parseInt(x, 10) : void 0;
}
function defaultImageLoader(loaderProps) {
var load = loaders.get(configLoader);
if (load) return load(_objectSpread({
root: configPath
}, loaderProps));
throw Error('Unknown "loader" found in "next.config.js". Expected: '.concat(_imageConfig.VALID_LOADERS.join(", "), ". Received: ").concat(configLoader));
}
function normalizeSrc(src) {
return "/" === src[0] ? src.slice(1) : src;
}
configDeviceSizes.sort(function(a, b) {
return a - b;
}), allSizes.sort(function(a, b) {
return a - b;
});
/***/ },
/***/ 7190: /***/ function(__unused_webpack_module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: !0
}), exports.useIntersection = function(param) {
var arr, rootMargin = param.rootMargin, isDisabled = param.disabled || !hasIntersectionObserver, unobserve = _react.useRef(), ref = function(arr) {
if (Array.isArray(arr)) return arr;
}(arr = _react.useState(!1)) || function(arr, i) {
var _arr = [], _n = !0, _d = !1, _e = void 0;
try {
for(var _s, _i = arr[Symbol.iterator](); !(_n = (_s = _i.next()).done) && (_arr.push(_s.value), 2 !== _arr.length); _n = !0);
} catch (err) {
_d = !0, _e = err;
} finally{
try {
_n || null == _i.return || _i.return();
} finally{
if (_d) throw _e;
}
}
return _arr;
}(arr, 0) || function() {
throw TypeError("Invalid attempt to destructure non-iterable instance");
}(), visible = ref[0], setVisible = ref[1], setRef = _react.useCallback(function(el) {
var ref, id, observer, elements;
unobserve.current && (unobserve.current(), unobserve.current = void 0), !isDisabled && !visible && el && el.tagName && (id = (ref = function(options) {
var id = options.rootMargin || "", instance = observers.get(id);
if (instance) return instance;
var elements = new Map(), observer = new IntersectionObserver(function(entries) {
entries.forEach(function(entry) {
var callback = elements.get(entry.target), isVisible = entry.isIntersecting || entry.intersectionRatio > 0;
callback && isVisible && callback(isVisible);
});
}, options);
return observers.set(id, instance = {
id: id,
observer: observer,
elements: elements
}), instance;
} //# sourceMappingURL=use-intersection.js.map
({
rootMargin: rootMargin
})).id, observer = ref.observer, (elements = ref.elements).set(el, function(isVisible) {
return isVisible && setVisible(isVisible);
}), observer.observe(el), unobserve.current = function() {
elements.delete(el), observer.unobserve(el), 0 === elements.size && (observer.disconnect(), observers.delete(id));
});
}, [
isDisabled,
rootMargin,
visible
]);
return _react.useEffect(function() {
if (!hasIntersectionObserver && !visible) {
var idleCallback = _requestIdleCallback.requestIdleCallback(function() {
return setVisible(!0);
});
return function() {
return _requestIdleCallback.cancelIdleCallback(idleCallback);
};
}
}, [
visible
]), [
setRef,
visible
];
};
var _react = __webpack_require__(7294), _requestIdleCallback = __webpack_require__(9311), hasIntersectionObserver = "undefined" != typeof IntersectionObserver, observers = new Map();
/***/ },
/***/ 6978: /***/ function(__unused_webpack_module, exports) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: !0
}), exports.toBase64 = function(str) {
return window.btoa(str);
} //# sourceMappingURL=to-base-64.js.map
;
/***/ },
/***/ 5809: /***/ function(__unused_webpack_module, exports) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: !0
}), exports.imageConfigDefault = exports.VALID_LOADERS = void 0, exports.VALID_LOADERS = [
"default",
"imgix",
"cloudinary",
"akamai",
"custom"
], exports.imageConfigDefault = {
deviceSizes: [
640,
750,
828,
1080,
1200,
1920,
2048,
3840
],
imageSizes: [
16,
32,
48,
64,
96,
128,
256,
384
],
path: "/_next/image",
loader: "default",
domains: [],
disableStaticImages: !1,
minimumCacheTTL: 60,
formats: [
"image/webp"
]
};
//# sourceMappingURL=image-config.js.map
/***/ },
/***/ 9008: /***/ function(module, __unused_webpack_exports, __webpack_require__) {
module.exports = __webpack_require__(5443);
/***/ },
/***/ 5675: /***/ function(module, __unused_webpack_exports, __webpack_require__) {
module.exports = __webpack_require__(8045);
/***/ },
/***/ 2238: /***/ function(__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ Jn: function() {
return /* binding */ SDK_VERSION;
},
/* harmony export */ Xd: function() {
return /* binding */ _registerComponent;
},
/* harmony export */ KN: function() {
return /* binding */ registerVersion;
}
});
/* unused harmony exports _DEFAULT_ENTRY_NAME, _addComponent, _addOrOverwriteComponent, _apps, _clearComponents, _components, _getProvider, _removeServiceInstance, deleteApp, getApp, getApps, initializeApp, onLog, setLogLevel */ /* harmony import */ var _firebase_component__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(8463), _firebase_logger__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(3333), _firebase_util__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(4444);
/**
* @license
* Copyright 2019 Google 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.
*/ class PlatformLoggerServiceImpl {
constructor(container){
this.container = container;
}
// In initial implementation, this will be called by installations on
// auth token refresh, and installations will send this string.
getPlatformInfoString() {
// Loop through providers and get library/version pairs from any that are
// version components.
return this.container.getProviders().map((provider)=>{
if (!/**
*
* @param provider check if this provider provides a VersionService
*
* NOTE: Using Provider<'app-version'> is a hack to indicate that the provider
* provides VersionService. The provider is not necessarily a 'app-version'
* provider.
*/ function(provider) {
const component = provider.getComponent();
return (null == component ? void 0 : component.type) === "VERSION" /* VERSION */ ;
}(provider)) return null;
{
const service = provider.getImmediate();
return `${service.library}/${service.version}`;
}
}).filter((logString)=>logString).join(" ");
}
}
const name$o = "@firebase/app", version$1 = "0.7.8", logger = new _firebase_logger__WEBPACK_IMPORTED_MODULE_1__ /* .Logger */ .Yd("@firebase/app"), PLATFORM_LOG_STRING = {
[name$o]: "fire-core",
"@firebase/app-compat": "fire-core-compat",
"@firebase/analytics": "fire-analytics",
"@firebase/analytics-compat": "fire-analytics-compat",
"@firebase/app-check": "fire-app-check",
"@firebase/app-check-compat": "fire-app-check-compat",
"@firebase/auth": "fire-auth",
"@firebase/auth-compat": "fire-auth-compat",
"@firebase/database": "fire-rtdb",
"@firebase/database-compat": "fire-rtdb-compat",
"@firebase/functions": "fire-fn",
"@firebase/functions-compat": "fire-fn-compat",
"@firebase/installations": "fire-iid",
"@firebase/installations-compat": "fire-iid-compat",
"@firebase/messaging": "fire-fcm",
"@firebase/messaging-compat": "fire-fcm-compat",
"@firebase/performance": "fire-perf",
"@firebase/performance-compat": "fire-perf-compat",
"@firebase/remote-config": "fire-rc",
"@firebase/remote-config-compat": "fire-rc-compat",
"@firebase/storage": "fire-gcs",
"@firebase/storage-compat": "fire-gcs-compat",
"@firebase/firestore": "fire-fst",
"@firebase/firestore-compat": "fire-fst-compat",
"fire-js": "fire-js",
firebase: "fire-js-all"
}, _apps = new Map(), _components = new Map();
/**
*
* @param component - the component to register
* @returns whether or not the component is registered successfully
*
* @internal
*/ function _registerComponent(component) {
const componentName = component.name;
if (_components.has(componentName)) return logger.debug(`There were multiple attempts to register component ${componentName}.`), !1;
// add the component to existing app instances
for (const app of (_components.set(componentName, component), _apps.values()))!/**
* @param component - the component being added to this app's container
*
* @internal
*/ function(app, component) {
try {
app.container.addComponent(component);
} catch (e) {
logger.debug(`Component ${component.name} failed to register with FirebaseApp ${app.name}`, e);
}
}(app, component);
return !0;
}
new _firebase_util__WEBPACK_IMPORTED_MODULE_2__ /* .ErrorFactory */ .LL("app", "Firebase", {
"no-app": "No Firebase App '{$appName}' has been created - call Firebase App.initializeApp()",
"bad-app-name": "Illegal App name: '{$appName}",
"duplicate-app": "Firebase App named '{$appName}' already exists with different options or config",
"app-deleted": "Firebase App named '{$appName}' already deleted",
"invalid-app-argument": "firebase.{$appName}() takes either no argument or a Firebase App instance.",
"invalid-log-argument": "First argument to `onLog` must be null or a function."
});
/**
* @license
* Copyright 2019 Google 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.
*/ /**
* The current SDK version.
*
* @public
*/ const SDK_VERSION = "9.4.1";
/**
* Registers a library's name and version for platform logging purposes.
* @param library - Name of 1p or 3p library (e.g. firestore, angularfire)
* @param version - Current version of that library.
* @param variant - Bundle variant, e.g., node, rn, etc.
*
* @public
*/ function registerVersion(libraryKeyOrName, version, variant) {
var _a;
// TODO: We can use this check to whitelist strings when/if we set up
// a good whitelist system.
let library = null !== (_a = PLATFORM_LOG_STRING[libraryKeyOrName]) && void 0 !== _a ? _a : libraryKeyOrName;
variant && (library += `-${variant}`);
const libraryMismatch = library.match(/\s|\//), versionMismatch = version.match(/\s|\//);
if (libraryMismatch || versionMismatch) {
const warning = [
`Unable to register library "${library}" with version "${version}":`
];
libraryMismatch && warning.push(`library name "${library}" contains illegal characters (whitespace or "/")`), libraryMismatch && versionMismatch && warning.push("and"), versionMismatch && warning.push(`version name "${version}" contains illegal characters (whitespace or "/")`), logger.warn(warning.join(" "));
return;
}
_registerComponent(new _firebase_component__WEBPACK_IMPORTED_MODULE_0__ /* .Component */ .wA(`${library}-version`, ()=>({
library,
version
}), "VERSION" /* VERSION */ ));
}
/**
* Firebase App
*
* @remarks This package coordinates the communication between the different Firebase components
* @packageDocumentation
*/ _registerComponent(new _firebase_component__WEBPACK_IMPORTED_MODULE_0__ /* .Component */ .wA("platform-logger", (container)=>new PlatformLoggerServiceImpl(container), "PRIVATE" /* PRIVATE */ )), // Register `app` package.
registerVersion(name$o, version$1, ""), // BUILD_TARGET will be replaced by values like esm5, esm2017, cjs5, etc during the compilation
registerVersion(name$o, version$1, "esm2017"), // Register platform SDK identifier (no version).
registerVersion("fire-js", "");
//# sourceMappingURL=index.esm2017.js.map
/***/ },
/***/ 8463: /***/ function(__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ wA: function() {
return /* binding */ Component;
}
}), __webpack_require__(4444);
/**
* Component for service name T, e.g. `auth`, `auth-internal`
*/ class Component {
/**
*
* @param name The public service name, e.g. app, auth, firestore, database
* @param instanceFactory Service factory responsible for creating the public interface
* @param type whether the service provided by the component is public or private
*/ constructor(name, instanceFactory, type){
this.name = name, this.instanceFactory = instanceFactory, this.type = type, this.multipleInstances = !1, /**
* Properties to be added to the service namespace
*/ this.serviceProps = {}, this.instantiationMode = "LAZY" /* LAZY */ , this.onInstanceCreated = null;
}
setInstantiationMode(mode) {
return this.instantiationMode = mode, this;
}
setMultipleInstances(multipleInstances) {
return this.multipleInstances = multipleInstances, this;
}
setServiceProps(props) {
return this.serviceProps = props, this;
}
setInstanceCreatedCallback(callback) {
return this.onInstanceCreated = callback, this;
}
}
//# sourceMappingURL=index.esm2017.js.map
/***/ },
/***/ 3333: /***/ function(__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) {
"use strict";
var LogLevel, LogLevel1;
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ in: function() {
return /* binding */ LogLevel;
},
/* harmony export */ Yd: function() {
return /* binding */ Logger;
}
});
/* unused harmony exports setLogLevel, setUserLogHandler */ /**
* @license
* Copyright 2017 Google 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.
*/ /**
* A container for all of the Logger instances
*/ const instances = [];
(LogLevel1 = LogLevel || (LogLevel = {}))[LogLevel1.DEBUG = 0] = "DEBUG", LogLevel1[LogLevel1.VERBOSE = 1] = "VERBOSE", LogLevel1[LogLevel1.INFO = 2] = "INFO", LogLevel1[LogLevel1.WARN = 3] = "WARN", LogLevel1[LogLevel1.ERROR = 4] = "ERROR", LogLevel1[LogLevel1.SILENT = 5] = "SILENT";
const levelStringToEnum = {
debug: LogLevel.DEBUG,
verbose: LogLevel.VERBOSE,
info: LogLevel.INFO,
warn: LogLevel.WARN,
error: LogLevel.ERROR,
silent: LogLevel.SILENT
}, defaultLogLevel = LogLevel.INFO, ConsoleMethod = {
[LogLevel.DEBUG]: "log",
[LogLevel.VERBOSE]: "log",
[LogLevel.INFO]: "info",
[LogLevel.WARN]: "warn",
[LogLevel.ERROR]: "error"
}, defaultLogHandler = (instance, logType, ...args)=>{
if (logType < instance.logLevel) return;
const now = new Date().toISOString(), method = ConsoleMethod[logType];
if (method) console[method](`[${now}] ${instance.name}:`, ...args);
else throw Error(`Attempted to log a message with an invalid logType (value: ${logType})`);
};
class Logger {
/**
* Gives you an instance of a Logger to capture messages according to
* Firebase's logging scheme.
*
* @param name The name that the logs will be associated with
*/ constructor(name){
this.name = name, /**
* The log level of the given Logger instance.
*/ this._logLevel = defaultLogLevel, /**
* The main (internal) log handler for the Logger instance.
* Can be set to a new function in internal package code but not by user.
*/ this._logHandler = defaultLogHandler, /**
* The optional, additional, user-defined log handler for the Logger instance.
*/ this._userLogHandler = null, /**
* Capture the current instance for later use
*/ instances.push(this);
}
get logLevel() {
return this._logLevel;
}
set logLevel(val) {
if (!(val in LogLevel)) throw TypeError(`Invalid value "${val}" assigned to \`logLevel\``);
this._logLevel = val;
}
// Workaround for setter/getter having to be the same type.
setLogLevel(val) {
this._logLevel = "string" == typeof val ? levelStringToEnum[val] : val;
}
get logHandler() {
return this._logHandler;
}
set logHandler(val) {
if ("function" != typeof val) throw TypeError("Value assigned to `logHandler` must be a function");
this._logHandler = val;
}
get userLogHandler() {
return this._userLogHandler;
}
set userLogHandler(val) {
this._userLogHandler = val;
}
/**
* The functions below are all based on the `console` interface
*/ debug(...args) {
this._userLogHandler && this._userLogHandler(this, LogLevel.DEBUG, ...args), this._logHandler(this, LogLevel.DEBUG, ...args);
}
log(...args) {
this._userLogHandler && this._userLogHandler(this, LogLevel.VERBOSE, ...args), this._logHandler(this, LogLevel.VERBOSE, ...args);
}
info(...args) {
this._userLogHandler && this._userLogHandler(this, LogLevel.INFO, ...args), this._logHandler(this, LogLevel.INFO, ...args);
}
warn(...args) {
this._userLogHandler && this._userLogHandler(this, LogLevel.WARN, ...args), this._logHandler(this, LogLevel.WARN, ...args);
}
error(...args) {
this._userLogHandler && this._userLogHandler(this, LogLevel.ERROR, ...args), this._logHandler(this, LogLevel.ERROR, ...args);
}
}
//# sourceMappingURL=index.esm2017.js.map
/***/ }
}
]);
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_minifier/tests/fixture/issues/firebase-firestore/1/output.js | JavaScript | "use strict";
(self.webpackChunk_N_E = self.webpackChunk_N_E || []).push([
[
16
],
{
/***/ 19: /***/ function(__unused_webpack_module, __webpack_exports__, __webpack_require__) {
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ hJ: function() {
return /* binding */ ba;
},
/* harmony export */ PL: function() {
return /* binding */ lh;
}
});
/* unused harmony exports AbstractUserDataWriter, Bytes, CACHE_SIZE_UNLIMITED, CollectionReference, DocumentReference, DocumentSnapshot, FieldPath, FieldValue, Firestore, FirestoreError, GeoPoint, LoadBundleTask, Query, QueryConstraint, QueryDocumentSnapshot, QuerySnapshot, SnapshotMetadata, Timestamp, Transaction, WriteBatch, _DatabaseId, _DocumentKey, _EmptyCredentialsProvider, _FieldPath, _cast, _debugAssert, _isBase64Available, _logWarn, _validateIsNotUsedTogether, addDoc, arrayRemove, arrayUnion, clearIndexedDbPersistence, collectionGroup, connectFirestoreEmulator, deleteDoc, deleteField, disableNetwork, doc, documentId, enableIndexedDbPersistence, enableMultiTabIndexedDbPersistence, enableNetwork, endAt, endBefore, ensureFirestoreConfigured, executeWrite, getDoc, getDocFromCache, getDocFromServer, getDocsFromCache, getDocsFromServer, getFirestore, increment, initializeFirestore, limit, limitToLast, loadBundle, namedQuery, onSnapshot, onSnapshotsInSync, orderBy, query, queryEqual, refEqual, runTransaction, serverTimestamp, setDoc, setLogLevel, snapshotEqual, startAfter, startAt, terminate, updateDoc, waitForPendingWrites, where, writeBatch */ /* harmony import */ var hn, ln, _firebase_app__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(2238), _firebase_component__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(8463), _firebase_logger__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(3333), _firebase_util__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(4444), _firebase_webchannel_wrapper__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(3510);
__webpack_require__(4155);
const S = "@firebase/firestore";
/**
* @license
* Copyright 2017 Google 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.
*/ /**
* Simple wrapper around a nullable UID. Mostly exists to make code more
* readable.
*/ class D {
constructor(t){
this.uid = t;
}
isAuthenticated() {
return null != this.uid;
}
/**
* Returns a key representing this user, suitable for inclusion in a
* dictionary.
*/ toKey() {
return this.isAuthenticated() ? "uid:" + this.uid : "anonymous-user";
}
isEqual(t) {
return t.uid === this.uid;
}
}
/** A user with a null UID. */ D.UNAUTHENTICATED = new D(null), // TODO(mikelehen): Look into getting a proper uid-equivalent for
// non-FirebaseAuth providers.
D.GOOGLE_CREDENTIALS = new D("google-credentials-uid"), D.FIRST_PARTY = new D("first-party-uid"), D.MOCK_USER = new D("mock-user");
/**
* @license
* Copyright 2017 Google 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.
*/ let C = "9.4.0";
/**
* @license
* Copyright 2017 Google 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.
*/ const N = new _firebase_logger__WEBPACK_IMPORTED_MODULE_2__ /* .Logger */ .Yd("@firebase/firestore");
// Helper methods are needed because variables can't be exported as read/write
function x() {
return N.logLevel;
}
function $(t, ...e) {
if (N.logLevel <= _firebase_logger__WEBPACK_IMPORTED_MODULE_2__ /* .LogLevel.DEBUG */ .in.DEBUG) {
const n = e.map(M);
N.debug(`Firestore (${C}): ${t}`, ...n);
}
}
function O(t, ...e) {
if (N.logLevel <= _firebase_logger__WEBPACK_IMPORTED_MODULE_2__ /* .LogLevel.ERROR */ .in.ERROR) {
const n = e.map(M);
N.error(`Firestore (${C}): ${t}`, ...n);
}
}
/**
* @internal
*/ function F(t, ...e) {
if (N.logLevel <= _firebase_logger__WEBPACK_IMPORTED_MODULE_2__ /* .LogLevel.WARN */ .in.WARN) {
const n = e.map(M);
N.warn(`Firestore (${C}): ${t}`, ...n);
}
}
/**
* Converts an additional log parameter to a string representation.
*/ function M(t) {
if ("string" == typeof t) return t;
try {
return JSON.stringify(t);
} catch (e) {
// Converting to JSON failed, just log the object directly
return t;
}
}
/**
* @license
* Copyright 2017 Google 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.
*/ /**
* Unconditionally fails, throwing an Error with the given message.
* Messages are stripped in production builds.
*
* Returns `never` and can be used in expressions:
* @example
* let futureVar = fail('not implemented yet');
*/ function L(t = "Unexpected state") {
// Log the failure in addition to throw an exception, just in case the
// exception is swallowed.
const e = `FIRESTORE (${C}) INTERNAL ASSERTION FAILED: ` + t;
// NOTE: We don't use FirestoreError here because these are internal failures
// that cannot be handled by the user. (Also it would create a circular
// dependency between the error and assert modules which doesn't work.)
throw O(e), Error(e);
}
/**
* @license
* Copyright 2017 Google 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.
*/ const K = {
// Causes are copied from:
// https://github.com/grpc/grpc/blob/bceec94ea4fc5f0085d81235d8e1c06798dc341a/include/grpc%2B%2B/impl/codegen/status_code_enum.h
/** Not an error; returned on success. */ OK: "ok",
/** The operation was cancelled (typically by the caller). */ CANCELLED: "cancelled",
/** Unknown error or an error from a different error domain. */ UNKNOWN: "unknown",
/**
* Client specified an invalid argument. Note that this differs from
* FAILED_PRECONDITION. INVALID_ARGUMENT indicates arguments that are
* problematic regardless of the state of the system (e.g., a malformed file
* name).
*/ INVALID_ARGUMENT: "invalid-argument",
/**
* Deadline expired before operation could complete. For operations that
* change the state of the system, this error may be returned even if the
* operation has completed successfully. For example, a successful response
* from a server could have been delayed long enough for the deadline to
* expire.
*/ DEADLINE_EXCEEDED: "deadline-exceeded",
/** Some requested entity (e.g., file or directory) was not found. */ NOT_FOUND: "not-found",
/**
* Some entity that we attempted to create (e.g., file or directory) already
* exists.
*/ ALREADY_EXISTS: "already-exists",
/**
* The caller does not have permission to execute the specified operation.
* PERMISSION_DENIED must not be used for rejections caused by exhausting
* some resource (use RESOURCE_EXHAUSTED instead for those errors).
* PERMISSION_DENIED must not be used if the caller can not be identified
* (use UNAUTHENTICATED instead for those errors).
*/ PERMISSION_DENIED: "permission-denied",
/**
* The request does not have valid authentication credentials for the
* operation.
*/ UNAUTHENTICATED: "unauthenticated",
/**
* Some resource has been exhausted, perhaps a per-user quota, or perhaps the
* entire file system is out of space.
*/ RESOURCE_EXHAUSTED: "resource-exhausted",
/**
* Operation was rejected because the system is not in a state required for
* the operation's execution. For example, directory to be deleted may be
* non-empty, an rmdir operation is applied to a non-directory, etc.
*
* A litmus test that may help a service implementor in deciding
* between FAILED_PRECONDITION, ABORTED, and UNAVAILABLE:
* (a) Use UNAVAILABLE if the client can retry just the failing call.
* (b) Use ABORTED if the client should retry at a higher-level
* (e.g., restarting a read-modify-write sequence).
* (c) Use FAILED_PRECONDITION if the client should not retry until
* the system state has been explicitly fixed. E.g., if an "rmdir"
* fails because the directory is non-empty, FAILED_PRECONDITION
* should be returned since the client should not retry unless
* they have first fixed up the directory by deleting files from it.
* (d) Use FAILED_PRECONDITION if the client performs conditional
* REST Get/Update/Delete on a resource and the resource on the
* server does not match the condition. E.g., conflicting
* read-modify-write on the same resource.
*/ FAILED_PRECONDITION: "failed-precondition",
/**
* The operation was aborted, typically due to a concurrency issue like
* sequencer check failures, transaction aborts, etc.
*
* See litmus test above for deciding between FAILED_PRECONDITION, ABORTED,
* and UNAVAILABLE.
*/ ABORTED: "aborted",
/**
* Operation was attempted past the valid range. E.g., seeking or reading
* past end of file.
*
* Unlike INVALID_ARGUMENT, this error indicates a problem that may be fixed
* if the system state changes. For example, a 32-bit file system will
* generate INVALID_ARGUMENT if asked to read at an offset that is not in the
* range [0,2^32-1], but it will generate OUT_OF_RANGE if asked to read from
* an offset past the current file size.
*
* There is a fair bit of overlap between FAILED_PRECONDITION and
* OUT_OF_RANGE. We recommend using OUT_OF_RANGE (the more specific error)
* when it applies so that callers who are iterating through a space can
* easily look for an OUT_OF_RANGE error to detect when they are done.
*/ OUT_OF_RANGE: "out-of-range",
/** Operation is not implemented or not supported/enabled in this service. */ UNIMPLEMENTED: "unimplemented",
/**
* Internal errors. Means some invariants expected by underlying System has
* been broken. If you see one of these errors, Something is very broken.
*/ INTERNAL: "internal",
/**
* The service is currently unavailable. This is a most likely a transient
* condition and may be corrected by retrying with a backoff.
*
* See litmus test above for deciding between FAILED_PRECONDITION, ABORTED,
* and UNAVAILABLE.
*/ UNAVAILABLE: "unavailable",
/** Unrecoverable data loss or corruption. */ DATA_LOSS: "data-loss"
};
/** An error returned by a Firestore operation. */ class j extends Error {
/** @hideconstructor */ constructor(/**
* The backend error code associated with this error.
*/ t, /**
* A custom error description.
*/ e){
super(e), this.code = t, this.message = e, /** The custom name for all FirestoreErrors. */ this.name = "FirebaseError", // HACK: We write a toString property directly because Error is not a real
// class and so inheritance does not work correctly. We could alternatively
// do the same "back-door inheritance" trick that FirebaseError does.
this.toString = ()=>`${this.name}: [code=${this.code}]: ${this.message}`;
}
}
/**
* @license
* Copyright 2017 Google 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.
*/ class Q {
constructor(){
this.promise = new Promise((t, e)=>{
this.resolve = t, this.reject = e;
});
}
}
/**
* @license
* Copyright 2017 Google 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.
*/ class W {
constructor(t, e){
this.user = e, this.type = "OAuth", this.authHeaders = {}, // Set the headers using Object Literal notation to avoid minification
this.authHeaders.Authorization = `Bearer ${t}`;
}
}
/**
* A CredentialsProvider that always yields an empty token.
* @internal
*/ class G {
getToken() {
return Promise.resolve(null);
}
invalidateToken() {}
start(t, e) {
// Fire with initial user.
t.enqueueRetryable(()=>e(D.UNAUTHENTICATED));
}
shutdown() {}
}
class H {
constructor(t){
this.t = t, /** Tracks the current User. */ this.currentUser = D.UNAUTHENTICATED, /**
* Counter used to detect if the token changed while a getToken request was
* outstanding.
*/ this.i = 0, this.forceRefresh = !1, this.auth = null;
}
start(t, e) {
let n = this.i;
// A change listener that prevents double-firing for the same token change.
const s = (t)=>this.i !== n ? (n = this.i, e(t)) : Promise.resolve();
// A promise that can be waited on to block on the next token change.
// This promise is re-created after each change.
let i = new Q();
this.o = ()=>{
this.i++, this.currentUser = this.u(), i.resolve(), i = new Q(), t.enqueueRetryable(()=>s(this.currentUser));
};
const r = ()=>{
const e = i;
t.enqueueRetryable(async ()=>{
await e.promise, await s(this.currentUser);
});
}, o = (t)=>{
$("FirebaseCredentialsProvider", "Auth detected"), this.auth = t, this.auth.addAuthTokenListener(this.o), r();
};
this.t.onInit((t)=>o(t)), // Our users can initialize Auth right after Firestore, so we give it
// a chance to register itself with the component framework before we
// determine whether to start up in unauthenticated mode.
setTimeout(()=>{
if (!this.auth) {
const t = this.t.getImmediate({
optional: !0
});
t ? o(t) : ($("FirebaseCredentialsProvider", "Auth not yet detected"), i.resolve(), i = new Q());
}
}, 0), r();
}
getToken() {
// Take note of the current value of the tokenCounter so that this method
// can fail (with an ABORTED error) if there is a token change while the
// request is outstanding.
const t = this.i, e = this.forceRefresh;
return this.forceRefresh = !1, this.auth ? this.auth.getToken(e).then((e)=>// Cancel the request since the token changed while the request was
// outstanding so the response is potentially for a previous user (which
// user, we can't be sure).
this.i !== t ? ($("FirebaseCredentialsProvider", "getToken aborted due to token change."), this.getToken()) : e ? ("string" == typeof e.accessToken || L(), new W(e.accessToken, this.currentUser)) : null) : Promise.resolve(null);
}
invalidateToken() {
this.forceRefresh = !0;
}
shutdown() {
this.auth && this.auth.removeAuthTokenListener(this.o);
}
// Auth.getUid() can return null even with a user logged in. It is because
// getUid() is synchronous, but the auth code populating Uid is asynchronous.
// This method should only be called in the AuthTokenListener callback
// to guarantee to get the actual user.
u() {
const t = this.auth && this.auth.getUid();
return null === t || "string" == typeof t || L(), new D(t);
}
}
/*
* FirstPartyToken provides a fresh token each time its value
* is requested, because if the token is too old, requests will be rejected.
* Technically this may no longer be necessary since the SDK should gracefully
* recover from unauthenticated errors (see b/33147818 for context), but it's
* safer to keep the implementation as-is.
*/ class J {
constructor(t, e, n){
this.h = t, this.l = e, this.m = n, this.type = "FirstParty", this.user = D.FIRST_PARTY;
}
get authHeaders() {
const t = {
"X-Goog-AuthUser": this.l
}, e = this.h.auth.getAuthHeaderValueForFirstParty([]);
// Use array notation to prevent minification
return e && (t.Authorization = e), this.m && (t["X-Goog-Iam-Authorization-Token"] = this.m), t;
}
}
/*
* Provides user credentials required for the Firestore JavaScript SDK
* to authenticate the user, using technique that is only available
* to applications hosted by Google.
*/ class Y {
constructor(t, e, n){
this.h = t, this.l = e, this.m = n;
}
getToken() {
return Promise.resolve(new J(this.h, this.l, this.m));
}
start(t, e) {
// Fire with initial uid.
t.enqueueRetryable(()=>e(D.FIRST_PARTY));
}
shutdown() {}
invalidateToken() {}
}
/**
* Builds a CredentialsProvider depending on the type of
* the credentials passed in.
*/ /**
* @license
* Copyright 2018 Google 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.
*/ /**
* `ListenSequence` is a monotonic sequence. It is initialized with a minimum value to
* exceed. All subsequent calls to next will return increasing values. If provided with a
* `SequenceNumberSyncer`, it will additionally bump its next value when told of a new value, as
* well as write out sequence numbers that it produces via `next()`.
*/ class X {
constructor(t, e){
this.previousValue = t, e && (e.sequenceNumberHandler = (t)=>this.g(t), this.p = (t)=>e.writeSequenceNumber(t));
}
g(t) {
return this.previousValue = Math.max(t, this.previousValue), this.previousValue;
}
next() {
const t = ++this.previousValue;
return this.p && this.p(t), t;
}
}
/**
* @license
* Copyright 2017 Google 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.
*/ X.T = -1;
class tt {
static I() {
// Alphanumeric characters
const t = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789", e = Math.floor(256 / t.length) * t.length;
// The largest byte value that is a multiple of `char.length`.
let n = "";
for(; n.length < 20;){
const s = /**
* @license
* Copyright 2020 Google 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.
*/ /**
* Generates `nBytes` of random bytes.
*
* If `nBytes < 0` , an error will be thrown.
*/ function(t) {
// Polyfills for IE and WebWorker by using `self` and `msCrypto` when `crypto` is not available.
const e = // eslint-disable-next-line @typescript-eslint/no-explicit-any
"undefined" != typeof self && (self.crypto || self.msCrypto), n = new Uint8Array(40);
if (e && "function" == typeof e.getRandomValues) e.getRandomValues(n);
else for(let e = 0; e < 40; e++)n[e] = Math.floor(256 * Math.random());
return n;
}(0);
for(let i = 0; i < s.length; ++i)// Only accept values that are [0, maxMultiple), this ensures they can
// be evenly mapped to indices of `chars` via a modulo operation.
n.length < 20 && s[i] < e && (n += t.charAt(s[i] % t.length));
}
return n;
}
}
function et(t, e) {
return t < e ? -1 : +(t > e);
}
/** Helper to compare arrays using isEqual(). */ function nt(t, e, n) {
return t.length === e.length && t.every((t, s)=>n(t, e[s]));
}
/**
* @license
* Copyright 2017 Google 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.
*/ // The earliest date supported by Firestore timestamps (0001-01-01T00:00:00Z).
/**
* A `Timestamp` represents a point in time independent of any time zone or
* calendar, represented as seconds and fractions of seconds at nanosecond
* resolution in UTC Epoch time.
*
* It is encoded using the Proleptic Gregorian Calendar which extends the
* Gregorian calendar backwards to year one. It is encoded assuming all minutes
* are 60 seconds long, i.e. leap seconds are "smeared" so that no leap second
* table is needed for interpretation. Range is from 0001-01-01T00:00:00Z to
* 9999-12-31T23:59:59.999999999Z.
*
* For examples and further specifications, refer to the
* {@link https://github.com/google/protobuf/blob/master/src/google/protobuf/timestamp.proto | Timestamp definition}.
*/ class it {
/**
* Creates a new timestamp.
*
* @param seconds - The number of seconds of UTC time since Unix epoch
* 1970-01-01T00:00:00Z. Must be from 0001-01-01T00:00:00Z to
* 9999-12-31T23:59:59Z inclusive.
* @param nanoseconds - The non-negative fractions of a second at nanosecond
* resolution. Negative second values with fractions must still have
* non-negative nanoseconds values that count forward in time. Must be
* from 0 to 999,999,999 inclusive.
*/ constructor(/**
* The number of seconds of UTC time since Unix epoch 1970-01-01T00:00:00Z.
*/ t, /**
* The fractions of a second at nanosecond resolution.*
*/ e){
if (this.seconds = t, this.nanoseconds = e, e < 0 || e >= 1e9) throw new j(K.INVALID_ARGUMENT, "Timestamp nanoseconds out of range: " + e);
if (t < -62135596800 || t >= 253402300800) throw new j(K.INVALID_ARGUMENT, "Timestamp seconds out of range: " + t);
}
/**
* Creates a new timestamp with the current date, with millisecond precision.
*
* @returns a new timestamp representing the current date.
*/ static now() {
return it.fromMillis(Date.now());
}
/**
* Creates a new timestamp from the given date.
*
* @param date - The date to initialize the `Timestamp` from.
* @returns A new `Timestamp` representing the same point in time as the given
* date.
*/ static fromDate(t) {
return it.fromMillis(t.getTime());
}
/**
* Creates a new timestamp from the given number of milliseconds.
*
* @param milliseconds - Number of milliseconds since Unix epoch
* 1970-01-01T00:00:00Z.
* @returns A new `Timestamp` representing the same point in time as the given
* number of milliseconds.
*/ static fromMillis(t) {
const e = Math.floor(t / 1e3), n = Math.floor(1e6 * (t - 1e3 * e));
return new it(e, n);
}
/**
* Converts a `Timestamp` to a JavaScript `Date` object. This conversion
* causes a loss of precision since `Date` objects only support millisecond
* precision.
*
* @returns JavaScript `Date` object representing the same point in time as
* this `Timestamp`, with millisecond precision.
*/ toDate() {
return new Date(this.toMillis());
}
/**
* Converts a `Timestamp` to a numeric timestamp (in milliseconds since
* epoch). This operation causes a loss of precision.
*
* @returns The point in time corresponding to this timestamp, represented as
* the number of milliseconds since Unix epoch 1970-01-01T00:00:00Z.
*/ toMillis() {
return 1e3 * this.seconds + this.nanoseconds / 1e6;
}
_compareTo(t) {
return this.seconds === t.seconds ? et(this.nanoseconds, t.nanoseconds) : et(this.seconds, t.seconds);
}
/**
* Returns true if this `Timestamp` is equal to the provided one.
*
* @param other - The `Timestamp` to compare against.
* @returns true if this `Timestamp` is equal to the provided one.
*/ isEqual(t) {
return t.seconds === this.seconds && t.nanoseconds === this.nanoseconds;
}
/** Returns a textual representation of this `Timestamp`. */ toString() {
return "Timestamp(seconds=" + this.seconds + ", nanoseconds=" + this.nanoseconds + ")";
}
/** Returns a JSON-serializable representation of this `Timestamp`. */ toJSON() {
return {
seconds: this.seconds,
nanoseconds: this.nanoseconds
};
}
/**
* Converts this object to a primitive string, which allows `Timestamp` objects
* to be compared using the `>`, `<=`, `>=` and `>` operators.
*/ valueOf() {
// Note: Up to 12 decimal digits are required to represent all valid
// 'seconds' values.
return String(this.seconds - -62135596800).padStart(12, "0") + "." + String(this.nanoseconds).padStart(9, "0");
}
}
/**
* @license
* Copyright 2017 Google 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.
*/ /**
* A version of a document in Firestore. This corresponds to the version
* timestamp, such as update_time or read_time.
*/ class rt {
constructor(t){
this.timestamp = t;
}
static fromTimestamp(t) {
return new rt(t);
}
static min() {
return new rt(new it(0, 0));
}
compareTo(t) {
return this.timestamp._compareTo(t.timestamp);
}
isEqual(t) {
return this.timestamp.isEqual(t.timestamp);
}
/** Returns a number representation of the version for use in spec tests. */ toMicroseconds() {
// Convert to microseconds.
return 1e6 * this.timestamp.seconds + this.timestamp.nanoseconds / 1e3;
}
toString() {
return "SnapshotVersion(" + this.timestamp.toString() + ")";
}
toTimestamp() {
return this.timestamp;
}
}
/**
* @license
* Copyright 2017 Google 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.
*/ function ot(t) {
let e = 0;
for(const n in t)Object.prototype.hasOwnProperty.call(t, n) && e++;
return e;
}
function ct(t, e) {
for(const n in t)Object.prototype.hasOwnProperty.call(t, n) && e(n, t[n]);
}
/**
* @license
* Copyright 2017 Google 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.
*/ /**
* Path represents an ordered sequence of string segments.
*/ class ut {
constructor(t, e, n){
void 0 === e ? e = 0 : e > t.length && L(), void 0 === n ? n = t.length - e : n > t.length - e && L(), this.segments = t, this.offset = e, this.len = n;
}
get length() {
return this.len;
}
isEqual(t) {
return 0 === ut.comparator(this, t);
}
child(t) {
const e = this.segments.slice(this.offset, this.limit());
return t instanceof ut ? t.forEach((t)=>{
e.push(t);
}) : e.push(t), this.construct(e);
}
/** The index of one past the last segment of the path. */ limit() {
return this.offset + this.length;
}
popFirst(t) {
return t = void 0 === t ? 1 : t, this.construct(this.segments, this.offset + t, this.length - t);
}
popLast() {
return this.construct(this.segments, this.offset, this.length - 1);
}
firstSegment() {
return this.segments[this.offset];
}
lastSegment() {
return this.get(this.length - 1);
}
get(t) {
return this.segments[this.offset + t];
}
isEmpty() {
return 0 === this.length;
}
isPrefixOf(t) {
if (t.length < this.length) return !1;
for(let e = 0; e < this.length; e++)if (this.get(e) !== t.get(e)) return !1;
return !0;
}
isImmediateParentOf(t) {
if (this.length + 1 !== t.length) return !1;
for(let e = 0; e < this.length; e++)if (this.get(e) !== t.get(e)) return !1;
return !0;
}
forEach(t) {
for(let e = this.offset, n = this.limit(); e < n; e++)t(this.segments[e]);
}
toArray() {
return this.segments.slice(this.offset, this.limit());
}
static comparator(t, e) {
const n = Math.min(t.length, e.length);
for(let s = 0; s < n; s++){
const n = t.get(s), i = e.get(s);
if (n < i) return -1;
if (n > i) return 1;
}
return t.length < e.length ? -1 : +(t.length > e.length);
}
}
/**
* A slash-separated path for navigating resources (documents and collections)
* within Firestore.
*
* @internal
*/ class ht extends ut {
construct(t, e, n) {
return new ht(t, e, n);
}
canonicalString() {
// NOTE: The client is ignorant of any path segments containing escape
// sequences (e.g. __id123__) and just passes them through raw (they exist
// for legacy reasons and should not be used frequently).
return this.toArray().join("/");
}
toString() {
return this.canonicalString();
}
/**
* Creates a resource path from the given slash-delimited string. If multiple
* arguments are provided, all components are combined. Leading and trailing
* slashes from all components are ignored.
*/ static fromString(...t) {
// NOTE: The client is ignorant of any path segments containing escape
// sequences (e.g. __id123__) and just passes them through raw (they exist
// for legacy reasons and should not be used frequently).
const e = [];
for (const n of t){
if (n.indexOf("//") >= 0) throw new j(K.INVALID_ARGUMENT, `Invalid segment (${n}). Paths must not contain // in them.`);
// Strip leading and traling slashed.
e.push(...n.split("/").filter((t)=>t.length > 0));
}
return new ht(e);
}
static emptyPath() {
return new ht([]);
}
}
const lt = /^[_a-zA-Z][_a-zA-Z0-9]*$/;
/**
* A dot-separated path for navigating sub-objects within a document.
* @internal
*/ class ft extends ut {
construct(t, e, n) {
return new ft(t, e, n);
}
/**
* Returns true if the string could be used as a segment in a field path
* without escaping.
*/ static isValidIdentifier(t) {
return lt.test(t);
}
canonicalString() {
return this.toArray().map((t)=>(t = t.replace(/\\/g, "\\\\").replace(/`/g, "\\`"), ft.isValidIdentifier(t) || (t = "`" + t + "`"), t)).join(".");
}
toString() {
return this.canonicalString();
}
/**
* Returns true if this field references the key of a document.
*/ isKeyField() {
return 1 === this.length && "__name__" === this.get(0);
}
/**
* The field designating the key of a document.
*/ static keyField() {
return new ft([
"__name__"
]);
}
/**
* Parses a field string from the given server-formatted string.
*
* - Splitting the empty string is not allowed (for now at least).
* - Empty segments within the string (e.g. if there are two consecutive
* separators) are not allowed.
*
* TODO(b/37244157): we should make this more strict. Right now, it allows
* non-identifier path components, even if they aren't escaped.
*/ static fromServerFormat(t) {
const e = [];
let n = "", s = 0;
const i = ()=>{
if (0 === n.length) throw new j(K.INVALID_ARGUMENT, `Invalid field path (${t}). Paths must not be empty, begin with '.', end with '.', or contain '..'`);
e.push(n), n = "";
};
let r = !1;
for(; s < t.length;){
const e = t[s];
if ("\\" === e) {
if (s + 1 === t.length) throw new j(K.INVALID_ARGUMENT, "Path has trailing escape character: " + t);
const e = t[s + 1];
if ("\\" !== e && "." !== e && "`" !== e) throw new j(K.INVALID_ARGUMENT, "Path has invalid escape sequence: " + t);
n += e, s += 2;
} else "`" === e ? r = !r : "." !== e || r ? n += e : i(), s++;
}
if (i(), r) throw new j(K.INVALID_ARGUMENT, "Unterminated ` in path: " + t);
return new ft(e);
}
static emptyPath() {
return new ft([]);
}
}
/**
* @license
* Copyright 2020 Google 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.
*/ /**
* Immutable class that represents a "proto" byte string.
*
* Proto byte strings can either be Base64-encoded strings or Uint8Arrays when
* sent on the wire. This class abstracts away this differentiation by holding
* the proto byte string in a common class that must be converted into a string
* before being sent as a proto.
* @internal
*/ class _t {
constructor(t){
this.binaryString = t;
}
static fromBase64String(t) {
return new _t(atob(t));
}
static fromUint8Array(t) {
return new _t(/**
* Helper function to convert an Uint8array to a binary string.
*/ function(t) {
let e = "";
for(let n = 0; n < t.length; ++n)e += String.fromCharCode(t[n]);
return e;
}(/**
* Helper function to convert a binary string to an Uint8Array.
*/ t));
}
toBase64() {
return btoa(this.binaryString);
}
toUint8Array() {
return function(t) {
const e = new Uint8Array(t.length);
for(let n = 0; n < t.length; n++)e[n] = t.charCodeAt(n);
return e;
}(/**
* @license
* Copyright 2020 Google 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.
*/ // A RegExp matching ISO 8601 UTC timestamps with optional fraction.
this.binaryString);
}
approximateByteSize() {
return 2 * this.binaryString.length;
}
compareTo(t) {
return et(this.binaryString, t.binaryString);
}
isEqual(t) {
return this.binaryString === t.binaryString;
}
}
_t.EMPTY_BYTE_STRING = new _t("");
const mt = new RegExp(/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.(\d+))?Z$/);
/**
* Converts the possible Proto values for a timestamp value into a "seconds and
* nanos" representation.
*/ function gt(t) {
// The json interface (for the browser) will return an iso timestamp string,
// while the proto js library (for node) will return a
// google.protobuf.Timestamp instance.
if (t || L(), "string" == typeof t) {
// The date string can have higher precision (nanos) than the Date class
// (millis), so we do some custom parsing here.
// Parse the nanos right out of the string.
let e = 0;
const n = mt.exec(t);
if (n || L(), n[1]) {
// Pad the fraction out to 9 digits (nanos).
let t = n[1];
e = Number(t = (t + "000000000").substr(0, 9));
}
return {
seconds: Math.floor(new Date(t).getTime() / 1e3),
nanos: e
};
}
return {
seconds: yt(t.seconds),
nanos: yt(t.nanos)
};
}
/**
* Converts the possible Proto types for numbers into a JavaScript number.
* Returns 0 if the value is not numeric.
*/ function yt(t) {
// TODO(bjornick): Handle int64 greater than 53 bits.
return "number" == typeof t ? t : "string" == typeof t ? Number(t) : 0;
}
/** Converts the possible Proto types for Blobs into a ByteString. */ function pt(t) {
return "string" == typeof t ? _t.fromBase64String(t) : _t.fromUint8Array(t);
}
/**
* @license
* Copyright 2020 Google 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.
*/ /**
* Represents a locally-applied ServerTimestamp.
*
* Server Timestamps are backed by MapValues that contain an internal field
* `__type__` with a value of `server_timestamp`. The previous value and local
* write time are stored in its `__previous_value__` and `__local_write_time__`
* fields respectively.
*
* Notes:
* - ServerTimestampValue instances are created as the result of applying a
* transform. They can only exist in the local view of a document. Therefore
* they do not need to be parsed or serialized.
* - When evaluated locally (e.g. for snapshot.data()), they by default
* evaluate to `null`. This behavior can be configured by passing custom
* FieldValueOptions to value().
* - With respect to other ServerTimestampValues, they sort by their
* localWriteTime.
*/ function Tt(t) {
var e, n;
return "server_timestamp" === (null === (n = ((null === (e = null == t ? void 0 : t.mapValue) || void 0 === e ? void 0 : e.fields) || {}).__type__) || void 0 === n ? void 0 : n.stringValue);
}
/**
* Returns the local time at which this timestamp was first set.
*/ function It(t) {
const e = gt(t.mapValue.fields.__local_write_time__.timestampValue);
return new it(e.seconds, e.nanos);
}
/**
* @license
* Copyright 2017 Google 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.
*/ /** Sentinel value that sorts before any Mutation Batch ID. */ /**
* Returns whether a variable is either undefined or null.
*/ function At(t) {
return null == t;
}
/** Returns whether the value represents -0. */ function Rt(t) {
// Detect if the value is -0.0. Based on polyfill from
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is
return 0 === t && 1 / t == -1 / 0;
}
/**
* @license
* Copyright 2017 Google 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.
*/ /**
* @internal
*/ class Pt {
constructor(t){
this.path = t;
}
static fromPath(t) {
return new Pt(ht.fromString(t));
}
static fromName(t) {
return new Pt(ht.fromString(t).popFirst(5));
}
/** Returns true if the document is in the specified collectionId. */ hasCollectionId(t) {
return this.path.length >= 2 && this.path.get(this.path.length - 2) === t;
}
isEqual(t) {
return null !== t && 0 === ht.comparator(this.path, t.path);
}
toString() {
return this.path.toString();
}
static comparator(t, e) {
return ht.comparator(t.path, e.path);
}
static isDocumentKey(t) {
return t.length % 2 == 0;
}
/**
* Creates and returns a new document key with the given segments.
*
* @param segments - The segments of the path to the document
* @returns A new instance of DocumentKey
*/ static fromSegments(t) {
return new Pt(new ht(t.slice()));
}
}
/**
* @license
* Copyright 2020 Google 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.
*/ /** Extracts the backend's type order for the provided value. */ function vt(t) {
return "nullValue" in t ? 0 /* NullValue */ : "booleanValue" in t ? 1 /* BooleanValue */ : "integerValue" in t || "doubleValue" in t ? 2 /* NumberValue */ : "timestampValue" in t ? 3 /* TimestampValue */ : "stringValue" in t ? 5 /* StringValue */ : "bytesValue" in t ? 6 /* BlobValue */ : "referenceValue" in t ? 7 /* RefValue */ : "geoPointValue" in t ? 8 /* GeoPointValue */ : "arrayValue" in t ? 9 /* ArrayValue */ : "mapValue" in t ? Tt(t) ? 4 /* ServerTimestampValue */ : 10 /* ObjectValue */ : L();
}
/** Tests `left` and `right` for equality based on the backend semantics. */ function Vt(t, e) {
const n = vt(t);
if (n !== vt(e)) return !1;
switch(n){
case 0 /* NullValue */ :
return !0;
case 1 /* BooleanValue */ :
return t.booleanValue === e.booleanValue;
case 4 /* ServerTimestampValue */ :
return It(t).isEqual(It(e));
case 3 /* TimestampValue */ :
return function(t, e) {
if ("string" == typeof t.timestampValue && "string" == typeof e.timestampValue && t.timestampValue.length === e.timestampValue.length) // Use string equality for ISO 8601 timestamps
return t.timestampValue === e.timestampValue;
const n = gt(t.timestampValue), s = gt(e.timestampValue);
return n.seconds === s.seconds && n.nanos === s.nanos;
}(t, e);
case 5 /* StringValue */ :
return t.stringValue === e.stringValue;
case 6 /* BlobValue */ :
return pt(t.bytesValue).isEqual(pt(e.bytesValue));
case 7 /* RefValue */ :
return t.referenceValue === e.referenceValue;
case 8 /* GeoPointValue */ :
return yt(t.geoPointValue.latitude) === yt(e.geoPointValue.latitude) && yt(t.geoPointValue.longitude) === yt(e.geoPointValue.longitude);
case 2 /* NumberValue */ :
return function(t, e) {
if ("integerValue" in t && "integerValue" in e) return yt(t.integerValue) === yt(e.integerValue);
if ("doubleValue" in t && "doubleValue" in e) {
const n = yt(t.doubleValue), s = yt(e.doubleValue);
return n === s ? Rt(n) === Rt(s) : isNaN(n) && isNaN(s);
}
return !1;
}(t, e);
case 9 /* ArrayValue */ :
return nt(t.arrayValue.values || [], e.arrayValue.values || [], Vt);
case 10 /* ObjectValue */ :
return function(t, e) {
const n = t.mapValue.fields || {}, s = e.mapValue.fields || {};
if (ot(n) !== ot(s)) return !1;
for(const t in n)if (n.hasOwnProperty(t) && (void 0 === s[t] || !Vt(n[t], s[t]))) return !1;
return !0;
}(/** Returns true if the ArrayValue contains the specified element. */ t, e);
default:
return L();
}
}
function St(t, e) {
return void 0 !== (t.values || []).find((t)=>Vt(t, e));
}
function Dt(t, e) {
const n = vt(t), s = vt(e);
if (n !== s) return et(n, s);
switch(n){
case 0 /* NullValue */ :
return 0;
case 1 /* BooleanValue */ :
return et(t.booleanValue, e.booleanValue);
case 2 /* NumberValue */ :
return function(t, e) {
const n = yt(t.integerValue || t.doubleValue), s = yt(e.integerValue || e.doubleValue);
return n < s ? -1 : n > s ? 1 : n === s ? 0 : isNaN(n) ? isNaN(s) ? 0 : -1 : 1;
}(t, e);
case 3 /* TimestampValue */ :
return Ct(t.timestampValue, e.timestampValue);
case 4 /* ServerTimestampValue */ :
return Ct(It(t), It(e));
case 5 /* StringValue */ :
return et(t.stringValue, e.stringValue);
case 6 /* BlobValue */ :
return function(t, e) {
const n = pt(t), s = pt(e);
return n.compareTo(s);
}(t.bytesValue, e.bytesValue);
case 7 /* RefValue */ :
return function(t, e) {
const n = t.split("/"), s = e.split("/");
for(let t = 0; t < n.length && t < s.length; t++){
const e = et(n[t], s[t]);
if (0 !== e) return e;
}
return et(n.length, s.length);
}(t.referenceValue, e.referenceValue);
case 8 /* GeoPointValue */ :
return function(t, e) {
const n = et(yt(t.latitude), yt(e.latitude));
return 0 !== n ? n : et(yt(t.longitude), yt(e.longitude));
}(t.geoPointValue, e.geoPointValue);
case 9 /* ArrayValue */ :
return function(t, e) {
const n = t.values || [], s = e.values || [];
for(let t = 0; t < n.length && t < s.length; ++t){
const e = Dt(n[t], s[t]);
if (e) return e;
}
return et(n.length, s.length);
}(t.arrayValue, e.arrayValue);
case 10 /* ObjectValue */ :
return function(t, e) {
const n = t.fields || {}, s = Object.keys(n), i = e.fields || {}, r = Object.keys(i);
// Even though MapValues are likely sorted correctly based on their insertion
// order (e.g. when received from the backend), local modifications can bring
// elements out of order. We need to re-sort the elements to ensure that
// canonical IDs are independent of insertion order.
s.sort(), r.sort();
for(let t = 0; t < s.length && t < r.length; ++t){
const e = et(s[t], r[t]);
if (0 !== e) return e;
const o = Dt(n[s[t]], i[r[t]]);
if (0 !== o) return o;
}
return et(s.length, r.length);
}(/**
* Generates the canonical ID for the provided field value (as used in Target
* serialization).
*/ t.mapValue, e.mapValue);
default:
throw L();
}
}
function Ct(t, e) {
if ("string" == typeof t && "string" == typeof e && t.length === e.length) return et(t, e);
const n = gt(t), s = gt(e), i = et(n.seconds, s.seconds);
return 0 !== i ? i : et(n.nanos, s.nanos);
}
function xt(t) {
var e, n;
return "nullValue" in t ? "null" : "booleanValue" in t ? "" + t.booleanValue : "integerValue" in t ? "" + t.integerValue : "doubleValue" in t ? "" + t.doubleValue : "timestampValue" in t ? function(t) {
const e = gt(t);
return `time(${e.seconds},${e.nanos})`;
}(t.timestampValue) : "stringValue" in t ? t.stringValue : "bytesValue" in t ? pt(t.bytesValue).toBase64() : "referenceValue" in t ? (n = t.referenceValue, Pt.fromName(n).toString()) : "geoPointValue" in t ? `geo(${(e = t.geoPointValue).latitude},${e.longitude})` : "arrayValue" in t ? function(t) {
let e = "[", n = !0;
for (const s of t.values || [])n ? n = !1 : e += ",", e += xt(s);
return e + "]";
}(/** Returns a reference value for the provided database and key. */ t.arrayValue) : "mapValue" in t ? function(t) {
// Iteration order in JavaScript is not guaranteed. To ensure that we generate
// matching canonical IDs for identical maps, we need to sort the keys.
const e = Object.keys(t.fields || {}).sort();
let n = "{", s = !0;
for (const i of e)s ? s = !1 : n += ",", n += `${i}:${xt(t.fields[i])}`;
return n + "}";
}(t.mapValue) : L();
}
/** Returns true if `value` is an IntegerValue . */ function $t(t) {
return !!t && "integerValue" in t;
}
/** Returns true if `value` is a DoubleValue. */ /** Returns true if `value` is an ArrayValue. */ function Ot(t) {
return !!t && "arrayValue" in t;
}
/** Returns true if `value` is a NullValue. */ function Ft(t) {
return !!t && "nullValue" in t;
}
/** Returns true if `value` is NaN. */ function Mt(t) {
return !!t && "doubleValue" in t && isNaN(Number(t.doubleValue));
}
/** Returns true if `value` is a MapValue. */ function Lt(t) {
return !!t && "mapValue" in t;
}
/** Creates a deep copy of `source`. */ function Bt(t) {
if (t.geoPointValue) return {
geoPointValue: Object.assign({}, t.geoPointValue)
};
if (t.timestampValue && "object" == typeof t.timestampValue) return {
timestampValue: Object.assign({}, t.timestampValue)
};
if (t.mapValue) {
const e = {
mapValue: {
fields: {}
}
};
return ct(t.mapValue.fields, (t, n)=>e.mapValue.fields[t] = Bt(n)), e;
}
if (t.arrayValue) {
const e = {
arrayValue: {
values: []
}
};
for(let n = 0; n < (t.arrayValue.values || []).length; ++n)e.arrayValue.values[n] = Bt(t.arrayValue.values[n]);
return e;
}
return Object.assign({}, t);
}
/**
* @license
* Copyright 2017 Google 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.
*/ /**
* An ObjectValue represents a MapValue in the Firestore Proto and offers the
* ability to add and remove fields (via the ObjectValueBuilder).
*/ class Ut {
constructor(t){
this.value = t;
}
static empty() {
return new Ut({
mapValue: {}
});
}
/**
* Returns the value at the given path or null.
*
* @param path - the path to search
* @returns The value at the path or null if the path is not set.
*/ field(t) {
if (t.isEmpty()) return this.value;
{
let e = this.value;
for(let n = 0; n < t.length - 1; ++n)if (!Lt(e = (e.mapValue.fields || {})[t.get(n)])) return null;
return (e = (e.mapValue.fields || {})[t.lastSegment()]) || null;
}
}
/**
* Sets the field to the provided value.
*
* @param path - The field path to set.
* @param value - The value to set.
*/ set(t, e) {
this.getFieldsMap(t.popLast())[t.lastSegment()] = Bt(e);
}
/**
* Sets the provided fields to the provided values.
*
* @param data - A map of fields to values (or null for deletes).
*/ setAll(t) {
let e = ft.emptyPath(), n = {}, s = [];
t.forEach((t, i)=>{
if (!e.isImmediateParentOf(i)) {
// Insert the accumulated changes at this parent location
const t = this.getFieldsMap(e);
this.applyChanges(t, n, s), n = {}, s = [], e = i.popLast();
}
t ? n[i.lastSegment()] = Bt(t) : s.push(i.lastSegment());
});
const i = this.getFieldsMap(e);
this.applyChanges(i, n, s);
}
/**
* Removes the field at the specified path. If there is no field at the
* specified path, nothing is changed.
*
* @param path - The field path to remove.
*/ delete(t) {
const e = this.field(t.popLast());
Lt(e) && e.mapValue.fields && delete e.mapValue.fields[t.lastSegment()];
}
isEqual(t) {
return Vt(this.value, t.value);
}
/**
* Returns the map that contains the leaf element of `path`. If the parent
* entry does not yet exist, or if it is not a map, a new map will be created.
*/ getFieldsMap(t) {
let e = this.value;
e.mapValue.fields || (e.mapValue = {
fields: {}
});
for(let n = 0; n < t.length; ++n){
let s = e.mapValue.fields[t.get(n)];
Lt(s) && s.mapValue.fields || (s = {
mapValue: {
fields: {}
}
}, e.mapValue.fields[t.get(n)] = s), e = s;
}
return e.mapValue.fields;
}
/**
* Modifies `fieldsMap` by adding, replacing or deleting the specified
* entries.
*/ applyChanges(t, e, n) {
for (const e1 of (ct(e, (e, n)=>t[e] = n), n))delete t[e1];
}
clone() {
return new Ut(Bt(this.value));
}
}
/**
* @license
* Copyright 2017 Google 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.
*/ /**
* Represents a document in Firestore with a key, version, data and whether it
* has local mutations applied to it.
*
* Documents can transition between states via `convertToFoundDocument()`,
* `convertToNoDocument()` and `convertToUnknownDocument()`. If a document does
* not transition to one of these states even after all mutations have been
* applied, `isValidDocument()` returns false and the document should be removed
* from all views.
*/ class Kt {
constructor(t, e, n, s, i){
this.key = t, this.documentType = e, this.version = n, this.data = s, this.documentState = i;
}
/**
* Creates a document with no known version or data, but which can serve as
* base document for mutations.
*/ static newInvalidDocument(t) {
return new Kt(t, 0 /* INVALID */ , rt.min(), Ut.empty(), 0 /* SYNCED */ );
}
/**
* Creates a new document that is known to exist with the given data at the
* given version.
*/ static newFoundDocument(t, e, n) {
return new Kt(t, 1 /* FOUND_DOCUMENT */ , e, n, 0 /* SYNCED */ );
}
/** Creates a new document that is known to not exist at the given version. */ static newNoDocument(t, e) {
return new Kt(t, 2 /* NO_DOCUMENT */ , e, Ut.empty(), 0 /* SYNCED */ );
}
/**
* Creates a new document that is known to exist at the given version but
* whose data is not known (e.g. a document that was updated without a known
* base document).
*/ static newUnknownDocument(t, e) {
return new Kt(t, 3 /* UNKNOWN_DOCUMENT */ , e, Ut.empty(), 2 /* HAS_COMMITTED_MUTATIONS */ );
}
/**
* Changes the document type to indicate that it exists and that its version
* and data are known.
*/ convertToFoundDocument(t, e) {
return this.version = t, this.documentType = 1, this.data = e, this.documentState = 0, this;
}
/**
* Changes the document type to indicate that it doesn't exist at the given
* version.
*/ convertToNoDocument(t) {
return this.version = t, this.documentType = 2, this.data = Ut.empty(), this.documentState = 0, this;
}
/**
* Changes the document type to indicate that it exists at a given version but
* that its data is not known (e.g. a document that was updated without a known
* base document).
*/ convertToUnknownDocument(t) {
return this.version = t, this.documentType = 3, this.data = Ut.empty(), this.documentState = 2, this;
}
setHasCommittedMutations() {
return this.documentState = 2, this;
}
setHasLocalMutations() {
return this.documentState = 1, this;
}
get hasLocalMutations() {
return 1 /* HAS_LOCAL_MUTATIONS */ === this.documentState;
}
get hasCommittedMutations() {
return 2 /* HAS_COMMITTED_MUTATIONS */ === this.documentState;
}
get hasPendingWrites() {
return this.hasLocalMutations || this.hasCommittedMutations;
}
isValidDocument() {
return 0 /* INVALID */ !== this.documentType;
}
isFoundDocument() {
return 1 /* FOUND_DOCUMENT */ === this.documentType;
}
isNoDocument() {
return 2 /* NO_DOCUMENT */ === this.documentType;
}
isUnknownDocument() {
return 3 /* UNKNOWN_DOCUMENT */ === this.documentType;
}
isEqual(t) {
return t instanceof Kt && this.key.isEqual(t.key) && this.version.isEqual(t.version) && this.documentType === t.documentType && this.documentState === t.documentState && this.data.isEqual(t.data);
}
clone() {
return new Kt(this.key, this.documentType, this.version, this.data.clone(), this.documentState);
}
toString() {
return `Document(${this.key}, ${this.version}, ${JSON.stringify(this.data.value)}, {documentType: ${this.documentType}}), {documentState: ${this.documentState}})`;
}
}
/**
* Compares the value for field `field` in the provided documents. Throws if
* the field does not exist in both documents.
*/ /**
* @license
* Copyright 2019 Google 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.
*/ // Visible for testing
class jt {
constructor(t, e = null, n = [], s = [], i = null, r = null, o = null){
this.path = t, this.collectionGroup = e, this.orderBy = n, this.filters = s, this.limit = i, this.startAt = r, this.endAt = o, this.A = null;
}
}
/**
* Initializes a Target with a path and optional additional query constraints.
* Path must currently be empty if this is a collection group query.
*
* NOTE: you should always construct `Target` from `Query.toTarget` instead of
* using this factory method, because `Query` provides an implicit `orderBy`
* property.
*/ function Qt(t, e = null, n = [], s = [], i = null, r = null, o = null) {
return new jt(t, e, n, s, i, r, o);
}
function Wt(t) {
if (null === t.A) {
let t1 = t.path.canonicalString();
null !== t.collectionGroup && (t1 += "|cg:" + t.collectionGroup), t1 += "|f:", t1 += t.filters.map((t)=>t.field.canonicalString() + t.op.toString() + xt(t.value)).join(","), t1 += "|ob:", t1 += t.orderBy.map((t)=>t.field.canonicalString() + t.dir).join(","), At(t.limit) || (t1 += "|l:", t1 += t.limit), t.startAt && (t1 += "|lb:", t1 += ce(t.startAt)), t.endAt && (t1 += "|ub:", t1 += ce(t.endAt)), t.A = t1;
}
return t.A;
}
function zt(t, e) {
var n, s, t1, e1;
if (t.limit !== e.limit || t.orderBy.length !== e.orderBy.length) return !1;
for(let n = 0; n < t.orderBy.length; n++)if (t1 = t.orderBy[n], e1 = e.orderBy[n], !(t1.dir === e1.dir && t1.field.isEqual(e1.field))) return !1;
if (t.filters.length !== e.filters.length) return !1;
for(let i = 0; i < t.filters.length; i++)if (n = t.filters[i], s = e.filters[i], n.op !== s.op || !n.field.isEqual(s.field) || !Vt(n.value, s.value)) return !1;
return t.collectionGroup === e.collectionGroup && !!t.path.isEqual(e.path) && !!le(t.startAt, e.startAt) && le(t.endAt, e.endAt);
}
function Ht(t) {
return Pt.isDocumentKey(t.path) && null === t.collectionGroup && 0 === t.filters.length;
}
class Jt extends class {
} {
constructor(t, e, n){
super(), this.field = t, this.op = e, this.value = n;
}
/**
* Creates a filter based on the provided arguments.
*/ static create(t, e, n) {
return t.isKeyField() ? "in" /* IN */ === e || "not-in" /* NOT_IN */ === e ? this.R(t, e, n) : new Xt(t, e, n) : "array-contains" /* ARRAY_CONTAINS */ === e ? new ne(t, n) : "in" /* IN */ === e ? new se(t, n) : "not-in" /* NOT_IN */ === e ? new ie(t, n) : "array-contains-any" /* ARRAY_CONTAINS_ANY */ === e ? new re(t, n) : new Jt(t, e, n);
}
static R(t, e, n) {
return "in" /* IN */ === e ? new Zt(t, n) : new te(t, n);
}
matches(t) {
const e = t.data.field(this.field);
// Types do not have to match in NOT_EQUAL filters.
return "!=" /* NOT_EQUAL */ === this.op ? null !== e && this.P(Dt(e, this.value)) : null !== e && vt(this.value) === vt(e) && this.P(Dt(e, this.value));
// Only compare types with matching backend order (such as double and int).
}
P(t) {
switch(this.op){
case "<" /* LESS_THAN */ :
return t < 0;
case "<=" /* LESS_THAN_OR_EQUAL */ :
return t <= 0;
case "==" /* EQUAL */ :
return 0 === t;
case "!=" /* NOT_EQUAL */ :
return 0 !== t;
case ">" /* GREATER_THAN */ :
return t > 0;
case ">=" /* GREATER_THAN_OR_EQUAL */ :
return t >= 0;
default:
return L();
}
}
v() {
return [
"<" /* LESS_THAN */ ,
"<=" /* LESS_THAN_OR_EQUAL */ ,
">" /* GREATER_THAN */ ,
">=" /* GREATER_THAN_OR_EQUAL */ ,
"!=" /* NOT_EQUAL */ ,
"not-in" /* NOT_IN */
].indexOf(this.op) >= 0;
}
}
class Xt extends Jt {
constructor(t, e, n){
super(t, e, n), this.key = Pt.fromName(n.referenceValue);
}
matches(t) {
const e = Pt.comparator(t.key, this.key);
return this.P(e);
}
}
/** Filter that matches on key fields within an array. */ class Zt extends Jt {
constructor(t, e){
super(t, "in" /* IN */ , e), this.keys = ee("in" /* IN */ , e);
}
matches(t) {
return this.keys.some((e)=>e.isEqual(t.key));
}
}
/** Filter that matches on key fields not present within an array. */ class te extends Jt {
constructor(t, e){
super(t, "not-in" /* NOT_IN */ , e), this.keys = ee("not-in" /* NOT_IN */ , e);
}
matches(t) {
return !this.keys.some((e)=>e.isEqual(t.key));
}
}
function ee(t, e) {
var n;
return ((null === (n = e.arrayValue) || void 0 === n ? void 0 : n.values) || []).map((t)=>Pt.fromName(t.referenceValue));
}
/** A Filter that implements the array-contains operator. */ class ne extends Jt {
constructor(t, e){
super(t, "array-contains" /* ARRAY_CONTAINS */ , e);
}
matches(t) {
const e = t.data.field(this.field);
return Ot(e) && St(e.arrayValue, this.value);
}
}
/** A Filter that implements the IN operator. */ class se extends Jt {
constructor(t, e){
super(t, "in" /* IN */ , e);
}
matches(t) {
const e = t.data.field(this.field);
return null !== e && St(this.value.arrayValue, e);
}
}
/** A Filter that implements the not-in operator. */ class ie extends Jt {
constructor(t, e){
super(t, "not-in" /* NOT_IN */ , e);
}
matches(t) {
if (St(this.value.arrayValue, {
nullValue: "NULL_VALUE"
})) return !1;
const e = t.data.field(this.field);
return null !== e && !St(this.value.arrayValue, e);
}
}
/** A Filter that implements the array-contains-any operator. */ class re extends Jt {
constructor(t, e){
super(t, "array-contains-any" /* ARRAY_CONTAINS_ANY */ , e);
}
matches(t) {
const e = t.data.field(this.field);
return !(!Ot(e) || !e.arrayValue.values) && e.arrayValue.values.some((t)=>St(this.value.arrayValue, t));
}
}
/**
* Represents a bound of a query.
*
* The bound is specified with the given components representing a position and
* whether it's just before or just after the position (relative to whatever the
* query order is).
*
* The position represents a logical index position for a query. It's a prefix
* of values for the (potentially implicit) order by clauses of a query.
*
* Bound provides a function to determine whether a document comes before or
* after a bound. This is influenced by whether the position is just before or
* just after the provided values.
*/ class oe {
constructor(t, e){
this.position = t, this.before = e;
}
}
function ce(t) {
// TODO(b/29183165): Make this collision robust.
return `${t.before ? "b" : "a"}:${t.position.map((t)=>xt(t)).join(",")}`;
}
/**
* An ordering on a field, in some Direction. Direction defaults to ASCENDING.
*/ class ae {
constructor(t, e = "asc" /* ASCENDING */ ){
this.field = t, this.dir = e;
}
}
/**
* Returns true if a document sorts before a bound using the provided sort
* order.
*/ function he(t, e, n) {
let s = 0;
for(let i = 0; i < t.position.length; i++){
const r = e[i], o = t.position[i];
if (s = r.field.isKeyField() ? Pt.comparator(Pt.fromName(o.referenceValue), n.key) : Dt(o, n.data.field(r.field)), "desc" /* DESCENDING */ === r.dir && (s *= -1), 0 !== s) break;
}
return t.before ? s <= 0 : s < 0;
}
function le(t, e) {
if (null === t) return null === e;
if (null === e || t.before !== e.before || t.position.length !== e.position.length) return !1;
for(let n = 0; n < t.position.length; n++)if (!Vt(t.position[n], e.position[n])) return !1;
return !0;
}
/**
* @license
* Copyright 2017 Google 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.
*/ /**
* Query encapsulates all the query attributes we support in the SDK. It can
* be run against the LocalStore, as well as be converted to a `Target` to
* query the RemoteStore results.
*
* Visible for testing.
*/ class fe {
/**
* Initializes a Query with a path and optional additional query constraints.
* Path must currently be empty if this is a collection group query.
*/ constructor(t, e = null, n = [], s = [], i = null, r = "F" /* First */ , o = null, c = null){
this.path = t, this.collectionGroup = e, this.explicitOrderBy = n, this.filters = s, this.limit = i, this.limitType = r, this.startAt = o, this.endAt = c, this.V = null, // The corresponding `Target` of this `Query` instance.
this.S = null, this.startAt, this.endAt;
}
}
/**
* Helper to convert a collection group query into a collection query at a
* specific path. This is used when executing collection group queries, since
* we have to split the query into a set of collection queries at multiple
* paths.
*/ function _e(t) {
return !At(t.limit) && "F" /* First */ === t.limitType;
}
function me(t) {
return !At(t.limit) && "L" /* Last */ === t.limitType;
}
/**
* Returns the implicit order by constraint that is used to execute the Query,
* which can be different from the order by constraints the user provided (e.g.
* the SDK and backend always orders by `__name__`).
*/ function Te(t) {
if (null === t.V) {
t.V = [];
const t1 = function(t) {
for (const e of t.filters)if (e.v()) return e.field;
return null;
}(t), n = t.explicitOrderBy.length > 0 ? t.explicitOrderBy[0].field : null;
if (null !== t1 && null === n) // In order to implicitly add key ordering, we must also add the
// inequality filter field for it to be a valid query.
// Note that the default inequality field and key ordering is ascending.
t1.isKeyField() || t.V.push(new ae(t1)), t.V.push(new ae(ft.keyField(), "asc" /* ASCENDING */ ));
else {
let t1 = !1;
for (const n of t.explicitOrderBy)t.V.push(n), n.field.isKeyField() && (t1 = !0);
if (!t1) {
// The order of the implicit key ordering always matches the last
// explicit order by
const t1 = t.explicitOrderBy.length > 0 ? t.explicitOrderBy[t.explicitOrderBy.length - 1].dir : "asc"; /* ASCENDING */
t.V.push(new ae(ft.keyField(), t1));
}
}
}
return t.V;
}
/**
* Converts this `Query` instance to it's corresponding `Target` representation.
*/ function Ee(t) {
if (!t.S) {
if ("F" /* First */ === t.limitType) t.S = Qt(t.path, t.collectionGroup, Te(t), t.filters, t.limit, t.startAt, t.endAt);
else {
// Flip the orderBy directions since we want the last results
const t1 = [];
for (const n of Te(t)){
const e = "desc" /* DESCENDING */ === n.dir ? "asc" /* ASCENDING */ : "desc"; /* DESCENDING */
t1.push(new ae(n.field, e));
}
// We need to swap the cursors to match the now-flipped query ordering.
const n = t.endAt ? new oe(t.endAt.position, !t.endAt.before) : null, s = t.startAt ? new oe(t.startAt.position, !t.startAt.before) : null;
// Now return as a LimitType.First query.
t.S = Qt(t.path, t.collectionGroup, t1, t.filters, t.limit, n, s);
}
}
return t.S;
}
function Ae(t, e) {
return zt(Ee(t), Ee(e)) && t.limitType === e.limitType;
}
// TODO(b/29183165): This is used to get a unique string from a query to, for
// example, use as a dictionary key, but the implementation is subject to
// collisions. Make it collision-free.
function Re(t) {
return `${Wt(Ee(t))}|lt:${t.limitType}`;
}
function be(t) {
var t1;
let e;
return `Query(target=${e = (t1 = Ee(t)).path.canonicalString(), null !== t1.collectionGroup && (e += " collectionGroup=" + t1.collectionGroup), t1.filters.length > 0 && (e += `, filters: [${t1.filters.map((t)=>`${t.field.canonicalString()} ${t.op} ${xt(t.value)}`).join(", ")}]`), At(t1.limit) || (e += ", limit: " + t1.limit), t1.orderBy.length > 0 && (e += `, orderBy: [${t1.orderBy.map((t)=>`${t.field.canonicalString()} (${t.dir})`).join(", ")}]`), t1.startAt && (e += ", startAt: " + ce(t1.startAt)), t1.endAt && (e += ", endAt: " + ce(t1.endAt)), `Target(${e})`}; limitType=${t.limitType})`;
}
/** Returns whether `doc` matches the constraints of `query`. */ function Pe(t, e) {
return e.isFoundDocument() && function(t, e) {
const n = e.key.path;
return null !== t.collectionGroup ? e.key.hasCollectionId(t.collectionGroup) && t.path.isPrefixOf(n) : Pt.isDocumentKey(t.path) ? t.path.isEqual(n) : t.path.isImmediateParentOf(n);
}(/**
* A document must have a value for every ordering clause in order to show up
* in the results.
*/ t, e) && function(t, e) {
// order by key always matches
for (const n of t.explicitOrderBy)if (!n.field.isKeyField() && null === e.data.field(n.field)) return !1;
return !0;
}(t, e) && function(t, e) {
for (const n of t.filters)if (!n.matches(e)) return !1;
return !0;
}(/** Makes sure a document is within the bounds, if provided. */ t, e) && !(/**
* Returns a new comparator function that can be used to compare two documents
* based on the Query's ordering constraint.
*/ t.startAt && !he(t.startAt, Te(t), e) || t.endAt && he(t.endAt, Te(t), e));
}
function ve(t) {
return (e, n)=>{
let s = !1;
for (const i of Te(t)){
const t = function(t, e, n) {
const s = t.field.isKeyField() ? Pt.comparator(e.key, n.key) : function(t, e, n) {
const s = e.data.field(t), i = n.data.field(t);
return null !== s && null !== i ? Dt(s, i) : L();
}(t.field, e, n);
switch(t.dir){
case "asc" /* ASCENDING */ :
return s;
case "desc" /* DESCENDING */ :
return -1 * s;
default:
return L();
}
}(i, e, n);
if (0 !== t) return t;
s = s || i.field.isKeyField();
}
return 0;
};
}
/**
* @license
* Copyright 2018 Google 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.
*/ /** Used to represent a field transform on a mutation. */ class Ne {
constructor(){
// Make sure that the structural type of `TransformOperation` is unique.
// See https://github.com/microsoft/TypeScript/issues/5451
this._ = void 0;
}
}
/** Transforms a value into a server-generated timestamp. */ class Oe extends Ne {
}
/** Transforms an array value via a union operation. */ class Fe extends Ne {
constructor(t){
super(), this.elements = t;
}
}
function Me(t, e) {
const n = Ke(e);
for (const e of t.elements)n.some((t)=>Vt(t, e)) || n.push(e);
return {
arrayValue: {
values: n
}
};
}
/** Transforms an array value via a remove operation. */ class Le extends Ne {
constructor(t){
super(), this.elements = t;
}
}
function Be(t, e) {
let n = Ke(e);
for (const e of t.elements)n = n.filter((t)=>!Vt(t, e));
return {
arrayValue: {
values: n
}
};
}
/**
* Implements the backend semantics for locally computed NUMERIC_ADD (increment)
* transforms. Converts all field values to integers or doubles, but unlike the
* backend does not cap integer values at 2^63. Instead, JavaScript number
* arithmetic is used and precision loss can occur for values greater than 2^53.
*/ class Ue extends Ne {
constructor(t, e){
super(), this.N = t, this.C = e;
}
}
function qe(t) {
return yt(t.integerValue || t.doubleValue);
}
function Ke(t) {
return Ot(t) && t.arrayValue.values ? t.arrayValue.values.slice() : [];
}
/** Returns true if the preconditions is valid for the given document. */ function ze(t, e) {
return void 0 !== t.updateTime ? e.isFoundDocument() && e.version.isEqual(t.updateTime) : void 0 === t.exists || t.exists === e.isFoundDocument();
}
/**
* A mutation describes a self-contained change to a document. Mutations can
* create, replace, delete, and update subsets of documents.
*
* Mutations not only act on the value of the document but also its version.
*
* For local mutations (mutations that haven't been committed yet), we preserve
* the existing version for Set and Patch mutations. For Delete mutations, we
* reset the version to 0.
*
* Here's the expected transition table.
*
* MUTATION APPLIED TO RESULTS IN
*
* SetMutation Document(v3) Document(v3)
* SetMutation NoDocument(v3) Document(v0)
* SetMutation InvalidDocument(v0) Document(v0)
* PatchMutation Document(v3) Document(v3)
* PatchMutation NoDocument(v3) NoDocument(v3)
* PatchMutation InvalidDocument(v0) UnknownDocument(v3)
* DeleteMutation Document(v3) NoDocument(v0)
* DeleteMutation NoDocument(v3) NoDocument(v0)
* DeleteMutation InvalidDocument(v0) NoDocument(v0)
*
* For acknowledged mutations, we use the updateTime of the WriteResponse as
* the resulting version for Set and Patch mutations. As deletes have no
* explicit update time, we use the commitTime of the WriteResponse for
* Delete mutations.
*
* If a mutation is acknowledged by the backend but fails the precondition check
* locally, we transition to an `UnknownDocument` and rely on Watch to send us
* the updated version.
*
* Field transforms are used only with Patch and Set Mutations. We use the
* `updateTransforms` message to store transforms, rather than the `transforms`s
* messages.
*
* ## Subclassing Notes
*
* Every type of mutation needs to implement its own applyToRemoteDocument() and
* applyToLocalView() to implement the actual behavior of applying the mutation
* to some source document (see `setMutationApplyToRemoteDocument()` for an
* example).
*/ class He {
}
/**
* Applies this mutation to the given document for the purposes of computing
* the new local view of a document. If the input document doesn't match the
* expected state, the document is not modified.
*
* @param mutation - The mutation to apply.
* @param document - The document to mutate. The input document can be an
* invalid document if the client has no knowledge of the pre-mutation state
* of the document.
* @param localWriteTime - A timestamp indicating the local write time of the
* batch this mutation is a part of.
*/ function Ye(t, e, n) {
t instanceof en ? function(t, e, n) {
if (!ze(t.precondition, e)) // The mutation failed to apply (e.g. a document ID created with add()
// caused a name collision).
return;
const s = t.value.clone(), i = on(t.fieldTransforms, n, e);
s.setAll(i), e.convertToFoundDocument(tn(e), s).setHasLocalMutations();
}(/**
* A mutation that modifies fields of the document at the given key with the
* given values. The values are applied through a field mask:
*
* * When a field is in both the mask and the values, the corresponding field
* is updated.
* * When a field is in neither the mask nor the values, the corresponding
* field is unmodified.
* * When a field is in the mask but not in the values, the corresponding field
* is deleted.
* * When a field is not in the mask but is in the values, the values map is
* ignored.
*/ t, e, n) : t instanceof nn ? function(t, e, n) {
if (!ze(t.precondition, e)) return;
const s = on(t.fieldTransforms, n, e), i = e.data;
i.setAll(sn(t)), i.setAll(s), e.convertToFoundDocument(tn(e), i).setHasLocalMutations();
}(/**
* Returns a FieldPath/Value map with the content of the PatchMutation.
*/ t, e, n) : ze(/**
* A mutation that verifies the existence of the document at the given key with
* the provided precondition.
*
* The `verify` operation is only used in Transactions, and this class serves
* primarily to facilitate serialization into protos.
*/ t.precondition, e) && // We don't call `setHasLocalMutations()` since we want to be backwards
// compatible with the existing SDK behavior.
e.convertToNoDocument(rt.min());
}
function Ze(t, e) {
var t1, e1;
return t.type === e.type && !!t.key.isEqual(e.key) && !!t.precondition.isEqual(e.precondition) && (t1 = t.fieldTransforms, e1 = e.fieldTransforms, !!(void 0 === t1 && void 0 === e1 || !(!t1 || !e1) && nt(t1, e1, (t, e)=>{
var t1, e1;
return t.field.isEqual(e.field) && (t1 = t.transform, e1 = e.transform, t1 instanceof Fe && e1 instanceof Fe || t1 instanceof Le && e1 instanceof Le ? nt(t1.elements, e1.elements, Vt) : t1 instanceof Ue && e1 instanceof Ue ? Vt(t1.C, e1.C) : t1 instanceof Oe && e1 instanceof Oe);
}))) && (0 /* Set */ === t.type ? t.value.isEqual(e.value) : 1 /* Patch */ !== t.type || t.data.isEqual(e.data) && t.fieldMask.isEqual(e.fieldMask));
}
/**
* Returns the version from the given document for use as the result of a
* mutation. Mutations are defined to return the version of the base document
* only if it is an existing document. Deleted and unknown documents have a
* post-mutation version of SnapshotVersion.min().
*/ function tn(t) {
return t.isFoundDocument() ? t.version : rt.min();
}
/**
* A mutation that creates or replaces the document at the given key with the
* object value contents.
*/ class en extends He {
constructor(t, e, n, s = []){
super(), this.key = t, this.value = e, this.precondition = n, this.fieldTransforms = s, this.type = 0 /* Set */ ;
}
}
class nn extends He {
constructor(t, e, n, s, i = []){
super(), this.key = t, this.data = e, this.fieldMask = n, this.precondition = s, this.fieldTransforms = i, this.type = 1 /* Patch */ ;
}
}
function sn(t) {
const e = new Map();
return t.fieldMask.fields.forEach((n)=>{
if (!n.isEmpty()) {
const s = t.data.field(n);
e.set(n, s);
}
}), e;
}
/**
* Creates a list of "transform results" (a transform result is a field value
* representing the result of applying a transform) for use after a mutation
* containing transforms has been acknowledged by the server.
*
* @param fieldTransforms - The field transforms to apply the result to.
* @param mutableDocument - The current state of the document after applying all
* previous mutations.
* @param serverTransformResults - The transform results received by the server.
* @returns The transform results list.
*/ function rn(t, e, n) {
var n1;
const s = new Map();
t.length === n.length || L();
for(let i = 0; i < n.length; i++){
const r = t[i], o = r.transform, c = e.data.field(r.field);
s.set(r.field, (n1 = n[i], o instanceof Fe ? Me(o, c) : o instanceof Le ? Be(o, c) : n1));
}
return s;
}
/**
* Creates a list of "transform results" (a transform result is a field value
* representing the result of applying a transform) for use when applying a
* transform locally.
*
* @param fieldTransforms - The field transforms to apply the result to.
* @param localWriteTime - The local time of the mutation (used to
* generate ServerTimestampValues).
* @param mutableDocument - The current state of the document after applying all
* previous mutations.
* @returns The transform results list.
*/ function on(t, e, n) {
const s = new Map();
for (const i of t){
const t = i.transform, r = n.data.field(i.field);
s.set(i.field, t instanceof Oe ? function(t, e) {
const n = {
fields: {
__type__: {
stringValue: "server_timestamp"
},
__local_write_time__: {
timestampValue: {
seconds: t.seconds,
nanos: t.nanoseconds
}
}
}
};
return e && (n.fields.__previous_value__ = e), {
mapValue: n
};
}(e, r) : t instanceof Fe ? Me(t, r) : t instanceof Le ? Be(t, r) : function(t, e) {
// PORTING NOTE: Since JavaScript's integer arithmetic is limited to 53 bit
// precision and resolves overflows by reducing precision, we do not
// manually cap overflows at 2^63.
const n = t instanceof Ue ? $t(e) || e && "doubleValue" in e ? e : {
integerValue: 0
} : null, s = qe(n) + qe(t.C);
return $t(n) && $t(t.C) ? {
integerValue: "" + s
} : /**
* @license
* Copyright 2020 Google 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.
*/ /**
* Returns an DoubleValue for `value` that is encoded based the serializer's
* `useProto3Json` setting.
*/ function(t, e) {
if (t.D) {
if (isNaN(e)) return {
doubleValue: "NaN"
};
if (e === 1 / 0) return {
doubleValue: "Infinity"
};
if (e === -1 / 0) return {
doubleValue: "-Infinity"
};
}
return {
doubleValue: Rt(e) ? "-0" : e
};
}(t.N, s);
}(t, r));
}
return s;
}
/**
* @license
* Copyright 2017 Google 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.
*/ class un {
// TODO(b/33078163): just use simplest form of existence filter for now
constructor(t){
this.count = t;
}
}
/**
* Determines whether an error code represents a permanent error when received
* in response to a write operation.
*
* Write operations must be handled specially because as of b/119437764, ABORTED
* errors on the write stream should be retried too (even though ABORTED errors
* are not generally retryable).
*
* Note that during the initial handshake on the write stream an ABORTED error
* signals that we should discard our stream token (i.e. it is permanent). This
* means a handshake error should be classified with isPermanentError, above.
*/ /**
* Maps an error Code from GRPC status code number, like 0, 1, or 14. These
* are not the same as HTTP status codes.
*
* @returns The Code equivalent to the given GRPC status code. Fails if there
* is no match.
*/ function dn(t) {
if (void 0 === t) // This shouldn't normally happen, but in certain error cases (like trying
// to send invalid proto messages) we may get an error with no GRPC code.
return O("GRPC error has no .code"), K.UNKNOWN;
switch(t){
case hn.OK:
return K.OK;
case hn.CANCELLED:
return K.CANCELLED;
case hn.UNKNOWN:
return K.UNKNOWN;
case hn.DEADLINE_EXCEEDED:
return K.DEADLINE_EXCEEDED;
case hn.RESOURCE_EXHAUSTED:
return K.RESOURCE_EXHAUSTED;
case hn.INTERNAL:
return K.INTERNAL;
case hn.UNAVAILABLE:
return K.UNAVAILABLE;
case hn.UNAUTHENTICATED:
return K.UNAUTHENTICATED;
case hn.INVALID_ARGUMENT:
return K.INVALID_ARGUMENT;
case hn.NOT_FOUND:
return K.NOT_FOUND;
case hn.ALREADY_EXISTS:
return K.ALREADY_EXISTS;
case hn.PERMISSION_DENIED:
return K.PERMISSION_DENIED;
case hn.FAILED_PRECONDITION:
return K.FAILED_PRECONDITION;
case hn.ABORTED:
return K.ABORTED;
case hn.OUT_OF_RANGE:
return K.OUT_OF_RANGE;
case hn.UNIMPLEMENTED:
return K.UNIMPLEMENTED;
case hn.DATA_LOSS:
return K.DATA_LOSS;
default:
return L();
}
}
/**
* Converts an HTTP response's error status to the equivalent error code.
*
* @param status - An HTTP error response status ("FAILED_PRECONDITION",
* "UNKNOWN", etc.)
* @returns The equivalent Code. Non-matching responses are mapped to
* Code.UNKNOWN.
*/ (ln = hn || (hn = {}))[ln.OK = 0] = "OK", ln[ln.CANCELLED = 1] = "CANCELLED", ln[ln.UNKNOWN = 2] = "UNKNOWN", ln[ln.INVALID_ARGUMENT = 3] = "INVALID_ARGUMENT", ln[ln.DEADLINE_EXCEEDED = 4] = "DEADLINE_EXCEEDED", ln[ln.NOT_FOUND = 5] = "NOT_FOUND", ln[ln.ALREADY_EXISTS = 6] = "ALREADY_EXISTS", ln[ln.PERMISSION_DENIED = 7] = "PERMISSION_DENIED", ln[ln.UNAUTHENTICATED = 16] = "UNAUTHENTICATED", ln[ln.RESOURCE_EXHAUSTED = 8] = "RESOURCE_EXHAUSTED", ln[ln.FAILED_PRECONDITION = 9] = "FAILED_PRECONDITION", ln[ln.ABORTED = 10] = "ABORTED", ln[ln.OUT_OF_RANGE = 11] = "OUT_OF_RANGE", ln[ln.UNIMPLEMENTED = 12] = "UNIMPLEMENTED", ln[ln.INTERNAL = 13] = "INTERNAL", ln[ln.UNAVAILABLE = 14] = "UNAVAILABLE", ln[ln.DATA_LOSS = 15] = "DATA_LOSS";
/**
* @license
* Copyright 2017 Google 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.
*/ // An immutable sorted map implementation, based on a Left-leaning Red-Black
// tree.
class wn {
constructor(t, e){
this.comparator = t, this.root = e || mn.EMPTY;
}
// Returns a copy of the map, with the specified key/value added or replaced.
insert(t, e) {
return new wn(this.comparator, this.root.insert(t, e, this.comparator).copy(null, null, mn.BLACK, null, null));
}
// Returns a copy of the map, with the specified key removed.
remove(t) {
return new wn(this.comparator, this.root.remove(t, this.comparator).copy(null, null, mn.BLACK, null, null));
}
// Returns the value of the node with the given key, or null.
get(t) {
let e = this.root;
for(; !e.isEmpty();){
const n = this.comparator(t, e.key);
if (0 === n) return e.value;
n < 0 ? e = e.left : n > 0 && (e = e.right);
}
return null;
}
// Returns the index of the element in this sorted map, or -1 if it doesn't
// exist.
indexOf(t) {
// Number of nodes that were pruned when descending right
let e = 0, n = this.root;
for(; !n.isEmpty();){
const s = this.comparator(t, n.key);
if (0 === s) return e + n.left.size;
s < 0 ? n = n.left : (e += n.left.size + 1, n = n.right);
}
// Node not found
return -1;
}
isEmpty() {
return this.root.isEmpty();
}
// Returns the total number of nodes in the map.
get size() {
return this.root.size;
}
// Returns the minimum key in the map.
minKey() {
return this.root.minKey();
}
// Returns the maximum key in the map.
maxKey() {
return this.root.maxKey();
}
// Traverses the map in key order and calls the specified action function
// for each key/value pair. If action returns true, traversal is aborted.
// Returns the first truthy value returned by action, or the last falsey
// value returned by action.
inorderTraversal(t) {
return this.root.inorderTraversal(t);
}
forEach(t) {
this.inorderTraversal((e, n)=>(t(e, n), !1));
}
toString() {
const t = [];
return this.inorderTraversal((e, n)=>(t.push(`${e}:${n}`), !1)), `{${t.join(", ")}}`;
}
// Traverses the map in reverse key order and calls the specified action
// function for each key/value pair. If action returns true, traversal is
// aborted.
// Returns the first truthy value returned by action, or the last falsey
// value returned by action.
reverseTraversal(t) {
return this.root.reverseTraversal(t);
}
// Returns an iterator over the SortedMap.
getIterator() {
return new _n(this.root, null, this.comparator, !1);
}
getIteratorFrom(t) {
return new _n(this.root, t, this.comparator, !1);
}
getReverseIterator() {
return new _n(this.root, null, this.comparator, !0);
}
getReverseIteratorFrom(t) {
return new _n(this.root, t, this.comparator, !0);
}
}
// end SortedMap
// An iterator over an LLRBNode.
class _n {
constructor(t, e, n, s){
this.isReverse = s, this.nodeStack = [];
let i = 1;
for(; !t.isEmpty();)if (i = e ? n(t.key, e) : 1, // flip the comparison if we're going in reverse
s && (i *= -1), i < 0) // This node is less than our start key. ignore it
t = this.isReverse ? t.left : t.right;
else {
if (0 === i) {
// This node is exactly equal to our start key. Push it on the stack,
// but stop iterating;
this.nodeStack.push(t);
break;
}
// This node is greater than our start key, add it to the stack and move
// to the next one
this.nodeStack.push(t), t = this.isReverse ? t.right : t.left;
}
}
getNext() {
let t = this.nodeStack.pop();
const e = {
key: t.key,
value: t.value
};
if (this.isReverse) for(t = t.left; !t.isEmpty();)this.nodeStack.push(t), t = t.right;
else for(t = t.right; !t.isEmpty();)this.nodeStack.push(t), t = t.left;
return e;
}
hasNext() {
return this.nodeStack.length > 0;
}
peek() {
if (0 === this.nodeStack.length) return null;
const t = this.nodeStack[this.nodeStack.length - 1];
return {
key: t.key,
value: t.value
};
}
}
// end SortedMapIterator
// Represents a node in a Left-leaning Red-Black tree.
class mn {
constructor(t, e, n, s, i){
this.key = t, this.value = e, this.color = null != n ? n : mn.RED, this.left = null != s ? s : mn.EMPTY, this.right = null != i ? i : mn.EMPTY, this.size = this.left.size + 1 + this.right.size;
}
// Returns a copy of the current node, optionally replacing pieces of it.
copy(t, e, n, s, i) {
return new mn(null != t ? t : this.key, null != e ? e : this.value, null != n ? n : this.color, null != s ? s : this.left, null != i ? i : this.right);
}
isEmpty() {
return !1;
}
// Traverses the tree in key order and calls the specified action function
// for each node. If action returns true, traversal is aborted.
// Returns the first truthy value returned by action, or the last falsey
// value returned by action.
inorderTraversal(t) {
return this.left.inorderTraversal(t) || t(this.key, this.value) || this.right.inorderTraversal(t);
}
// Traverses the tree in reverse key order and calls the specified action
// function for each node. If action returns true, traversal is aborted.
// Returns the first truthy value returned by action, or the last falsey
// value returned by action.
reverseTraversal(t) {
return this.right.reverseTraversal(t) || t(this.key, this.value) || this.left.reverseTraversal(t);
}
// Returns the minimum node in the tree.
min() {
return this.left.isEmpty() ? this : this.left.min();
}
// Returns the maximum key in the tree.
minKey() {
return this.min().key;
}
// Returns the maximum key in the tree.
maxKey() {
return this.right.isEmpty() ? this.key : this.right.maxKey();
}
// Returns new tree, with the key/value added.
insert(t, e, n) {
let s = this;
const i = n(t, s.key);
return (s = i < 0 ? s.copy(null, null, null, s.left.insert(t, e, n), null) : 0 === i ? s.copy(null, e, null, null, null) : s.copy(null, null, null, null, s.right.insert(t, e, n))).fixUp();
}
removeMin() {
if (this.left.isEmpty()) return mn.EMPTY;
let t = this;
return t.left.isRed() || t.left.left.isRed() || (t = t.moveRedLeft()), (t = t.copy(null, null, null, t.left.removeMin(), null)).fixUp();
}
// Returns new tree, with the specified item removed.
remove(t, e) {
let n, s = this;
if (0 > e(t, s.key)) s.left.isEmpty() || s.left.isRed() || s.left.left.isRed() || (s = s.moveRedLeft()), s = s.copy(null, null, null, s.left.remove(t, e), null);
else {
if (s.left.isRed() && (s = s.rotateRight()), s.right.isEmpty() || s.right.isRed() || s.right.left.isRed() || (s = s.moveRedRight()), 0 === e(t, s.key)) {
if (s.right.isEmpty()) return mn.EMPTY;
n = s.right.min(), s = s.copy(n.key, n.value, null, null, s.right.removeMin());
}
s = s.copy(null, null, null, null, s.right.remove(t, e));
}
return s.fixUp();
}
isRed() {
return this.color;
}
// Returns new tree after performing any needed rotations.
fixUp() {
let t = this;
return t.right.isRed() && !t.left.isRed() && (t = t.rotateLeft()), t.left.isRed() && t.left.left.isRed() && (t = t.rotateRight()), t.left.isRed() && t.right.isRed() && (t = t.colorFlip()), t;
}
moveRedLeft() {
let t = this.colorFlip();
return t.right.left.isRed() && (t = (t = (t = t.copy(null, null, null, null, t.right.rotateRight())).rotateLeft()).colorFlip()), t;
}
moveRedRight() {
let t = this.colorFlip();
return t.left.left.isRed() && (t = (t = t.rotateRight()).colorFlip()), t;
}
rotateLeft() {
const t = this.copy(null, null, mn.RED, null, this.right.left);
return this.right.copy(null, null, this.color, t, null);
}
rotateRight() {
const t = this.copy(null, null, mn.RED, this.left.right, null);
return this.left.copy(null, null, this.color, null, t);
}
colorFlip() {
const t = this.left.copy(null, null, !this.left.color, null, null), e = this.right.copy(null, null, !this.right.color, null, null);
return this.copy(null, null, !this.color, t, e);
}
// For testing.
checkMaxDepth() {
return Math.pow(2, this.check()) <= this.size + 1;
}
// In a balanced RB tree, the black-depth (number of black nodes) from root to
// leaves is equal on both sides. This function verifies that or asserts.
check() {
if (this.isRed() && this.left.isRed() || this.right.isRed()) throw L();
const t = this.left.check();
if (t !== this.right.check()) throw L();
return t + +!this.isRed();
}
}
// end LLRBNode
// Empty node is shared between all LLRB trees.
// eslint-disable-next-line @typescript-eslint/no-explicit-any
mn.EMPTY = null, mn.RED = !0, mn.BLACK = !1, // end LLRBEmptyNode
mn.EMPTY = new class {
constructor(){
this.size = 0;
}
get key() {
throw L();
}
get value() {
throw L();
}
get color() {
throw L();
}
get left() {
throw L();
}
get right() {
throw L();
}
// Returns a copy of the current node.
copy(t, e, n, s, i) {
return this;
}
// Returns a copy of the tree, with the specified key/value added.
insert(t, e, n) {
return new mn(t, e);
}
// Returns a copy of the tree, with the specified key removed.
remove(t, e) {
return this;
}
isEmpty() {
return !0;
}
inorderTraversal(t) {
return !1;
}
reverseTraversal(t) {
return !1;
}
minKey() {
return null;
}
maxKey() {
return null;
}
isRed() {
return !1;
}
// For testing.
checkMaxDepth() {
return !0;
}
check() {
return 0;
}
}();
/**
* @license
* Copyright 2017 Google 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.
*/ /**
* SortedSet is an immutable (copy-on-write) collection that holds elements
* in order specified by the provided comparator.
*
* NOTE: if provided comparator returns 0 for two elements, we consider them to
* be equal!
*/ class gn {
constructor(t){
this.comparator = t, this.data = new wn(this.comparator);
}
has(t) {
return null !== this.data.get(t);
}
first() {
return this.data.minKey();
}
last() {
return this.data.maxKey();
}
get size() {
return this.data.size;
}
indexOf(t) {
return this.data.indexOf(t);
}
/** Iterates elements in order defined by "comparator" */ forEach(t) {
this.data.inorderTraversal((e, n)=>(t(e), !1));
}
/** Iterates over `elem`s such that: range[0] <= elem < range[1]. */ forEachInRange(t, e) {
const n = this.data.getIteratorFrom(t[0]);
for(; n.hasNext();){
const s = n.getNext();
if (this.comparator(s.key, t[1]) >= 0) return;
e(s.key);
}
}
/**
* Iterates over `elem`s such that: start <= elem until false is returned.
*/ forEachWhile(t, e) {
let n;
for(n = void 0 !== e ? this.data.getIteratorFrom(e) : this.data.getIterator(); n.hasNext();)if (!t(n.getNext().key)) return;
}
/** Finds the least element greater than or equal to `elem`. */ firstAfterOrEqual(t) {
const e = this.data.getIteratorFrom(t);
return e.hasNext() ? e.getNext().key : null;
}
getIterator() {
return new yn(this.data.getIterator());
}
getIteratorFrom(t) {
return new yn(this.data.getIteratorFrom(t));
}
/** Inserts or updates an element */ add(t) {
return this.copy(this.data.remove(t).insert(t, !0));
}
/** Deletes an element */ delete(t) {
return this.has(t) ? this.copy(this.data.remove(t)) : this;
}
isEmpty() {
return this.data.isEmpty();
}
unionWith(t) {
let e = this;
// Make sure `result` always refers to the larger one of the two sets.
return e.size < t.size && (e = t, t = this), t.forEach((t)=>{
e = e.add(t);
}), e;
}
isEqual(t) {
if (!(t instanceof gn) || this.size !== t.size) return !1;
const e = this.data.getIterator(), n = t.data.getIterator();
for(; e.hasNext();){
const t = e.getNext().key, s = n.getNext().key;
if (0 !== this.comparator(t, s)) return !1;
}
return !0;
}
toArray() {
const t = [];
return this.forEach((e)=>{
t.push(e);
}), t;
}
toString() {
const t = [];
return this.forEach((e)=>t.push(e)), "SortedSet(" + t.toString() + ")";
}
copy(t) {
const e = new gn(this.comparator);
return e.data = t, e;
}
}
class yn {
constructor(t){
this.iter = t;
}
getNext() {
return this.iter.getNext().key;
}
hasNext() {
return this.iter.hasNext();
}
}
/**
* @license
* Copyright 2017 Google 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.
*/ const pn = new wn(Pt.comparator), En = new wn(Pt.comparator);
new wn(Pt.comparator);
const bn = new gn(Pt.comparator);
function Pn(...t) {
let e = bn;
for (const n of t)e = e.add(n);
return e;
}
const vn = new gn(et);
/**
* @license
* Copyright 2017 Google 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.
*/ /**
* An event from the RemoteStore. It is split into targetChanges (changes to the
* state or the set of documents in our watched targets) and documentUpdates
* (changes to the actual documents).
*/ class Sn {
constructor(/**
* The snapshot version this event brings us up to, or MIN if not set.
*/ t, /**
* A map from target to changes to the target. See TargetChange.
*/ e, /**
* A set of targets that is known to be inconsistent. Listens for these
* targets should be re-established without resume tokens.
*/ n, /**
* A set of which documents have changed or been deleted, along with the
* doc's new values (if not deleted).
*/ s, /**
* A set of which document updates are due only to limbo resolution targets.
*/ i){
this.snapshotVersion = t, this.targetChanges = e, this.targetMismatches = n, this.documentUpdates = s, this.resolvedLimboDocuments = i;
}
/**
* HACK: Views require RemoteEvents in order to determine whether the view is
* CURRENT, but secondary tabs don't receive remote events. So this method is
* used to create a synthesized RemoteEvent that can be used to apply a
* CURRENT status change to a View, for queries executed in a different tab.
*/ // PORTING NOTE: Multi-tab only
static createSynthesizedRemoteEventForCurrentChange(t, e) {
const n = new Map();
return n.set(t, Dn.createSynthesizedTargetChangeForCurrentChange(t, e)), new Sn(rt.min(), n, vn, pn, Pn());
}
}
/**
* A TargetChange specifies the set of changes for a specific target as part of
* a RemoteEvent. These changes track which documents are added, modified or
* removed, as well as the target's resume token and whether the target is
* marked CURRENT.
* The actual changes *to* documents are not part of the TargetChange since
* documents may be part of multiple targets.
*/ class Dn {
constructor(/**
* An opaque, server-assigned token that allows watching a query to be resumed
* after disconnecting without retransmitting all the data that matches the
* query. The resume token essentially identifies a point in time from which
* the server should resume sending results.
*/ t, /**
* The "current" (synced) status of this target. Note that "current"
* has special meaning in the RPC protocol that implies that a target is
* both up-to-date and consistent with the rest of the watch stream.
*/ e, /**
* The set of documents that were newly assigned to this target as part of
* this remote event.
*/ n, /**
* The set of documents that were already assigned to this target but received
* an update during this remote event.
*/ s, /**
* The set of documents that were removed from this target as part of this
* remote event.
*/ i){
this.resumeToken = t, this.current = e, this.addedDocuments = n, this.modifiedDocuments = s, this.removedDocuments = i;
}
/**
* This method is used to create a synthesized TargetChanges that can be used to
* apply a CURRENT status change to a View (for queries executed in a different
* tab) or for new queries (to raise snapshots with correct CURRENT status).
*/ static createSynthesizedTargetChangeForCurrentChange(t, e) {
return new Dn(_t.EMPTY_BYTE_STRING, e, Pn(), Pn(), Pn());
}
}
/**
* @license
* Copyright 2017 Google 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.
*/ /**
* Represents a changed document and a list of target ids to which this change
* applies.
*
* If document has been deleted NoDocument will be provided.
*/ class Cn {
constructor(/** The new document applies to all of these targets. */ t, /** The new document is removed from all of these targets. */ e, /** The key of the document for this change. */ n, /**
* The new document or NoDocument if it was deleted. Is null if the
* document went out of view without the server sending a new document.
*/ s){
this.k = t, this.removedTargetIds = e, this.key = n, this.$ = s;
}
}
class Nn {
constructor(t, e){
this.targetId = t, this.O = e;
}
}
class xn {
constructor(/** What kind of change occurred to the watch target. */ t, /** The target IDs that were added/removed/set. */ e, /**
* An opaque, server-assigned token that allows watching a target to be
* resumed after disconnecting without retransmitting all the data that
* matches the target. The resume token essentially identifies a point in
* time from which the server should resume sending results.
*/ n = _t.EMPTY_BYTE_STRING, /** An RPC error indicating why the watch failed. */ s = null){
this.state = t, this.targetIds = e, this.resumeToken = n, this.cause = s;
}
}
/** Tracks the internal state of a Watch target. */ class kn {
constructor(){
/**
* The number of pending responses (adds or removes) that we are waiting on.
* We only consider targets active that have no pending responses.
*/ this.F = 0, /**
* Keeps track of the document changes since the last raised snapshot.
*
* These changes are continuously updated as we receive document updates and
* always reflect the current set of changes against the last issued snapshot.
*/ this.M = Fn(), /** See public getters for explanations of these fields. */ this.L = _t.EMPTY_BYTE_STRING, this.B = !1, /**
* Whether this target state should be included in the next snapshot. We
* initialize to true so that newly-added targets are included in the next
* RemoteEvent.
*/ this.U = !0;
}
/**
* Whether this target has been marked 'current'.
*
* 'Current' has special meaning in the RPC protocol: It implies that the
* Watch backend has sent us all changes up to the point at which the target
* was added and that the target is consistent with the rest of the watch
* stream.
*/ get current() {
return this.B;
}
/** The last resume token sent to us for this target. */ get resumeToken() {
return this.L;
}
/** Whether this target has pending target adds or target removes. */ get q() {
return 0 !== this.F;
}
/** Whether we have modified any state that should trigger a snapshot. */ get K() {
return this.U;
}
/**
* Applies the resume token to the TargetChange, but only when it has a new
* value. Empty resumeTokens are discarded.
*/ j(t) {
t.approximateByteSize() > 0 && (this.U = !0, this.L = t);
}
/**
* Creates a target change from the current set of changes.
*
* To reset the document changes after raising this snapshot, call
* `clearPendingChanges()`.
*/ W() {
let t = Pn(), e = Pn(), n = Pn();
return this.M.forEach((s, i)=>{
switch(i){
case 0 /* Added */ :
t = t.add(s);
break;
case 2 /* Modified */ :
e = e.add(s);
break;
case 1 /* Removed */ :
n = n.add(s);
break;
default:
L();
}
}), new Dn(this.L, this.B, t, e, n);
}
/**
* Resets the document changes and sets `hasPendingChanges` to false.
*/ G() {
this.U = !1, this.M = Fn();
}
H(t, e) {
this.U = !0, this.M = this.M.insert(t, e);
}
J(t) {
this.U = !0, this.M = this.M.remove(t);
}
Y() {
this.F += 1;
}
X() {
this.F -= 1;
}
Z() {
this.U = !0, this.B = !0;
}
}
/**
* A helper class to accumulate watch changes into a RemoteEvent.
*/ class $n {
constructor(t){
this.tt = t, /** The internal state of all tracked targets. */ this.et = new Map(), /** Keeps track of the documents to update since the last raised snapshot. */ this.nt = pn, /** A mapping of document keys to their set of target IDs. */ this.st = On(), /**
* A list of targets with existence filter mismatches. These targets are
* known to be inconsistent and their listens needs to be re-established by
* RemoteStore.
*/ this.it = new gn(et);
}
/**
* Processes and adds the DocumentWatchChange to the current set of changes.
*/ rt(t) {
for (const e of t.k)t.$ && t.$.isFoundDocument() ? this.ot(e, t.$) : this.ct(e, t.key, t.$);
for (const e of t.removedTargetIds)this.ct(e, t.key, t.$);
}
/** Processes and adds the WatchTargetChange to the current set of changes. */ at(t) {
this.forEachTarget(t, (e)=>{
const n = this.ut(e);
switch(t.state){
case 0 /* NoChange */ :
this.ht(e) && n.j(t.resumeToken);
break;
case 1 /* Added */ :
// We need to decrement the number of pending acks needed from watch
// for this targetId.
n.X(), n.q || // We have a freshly added target, so we need to reset any state
// that we had previously. This can happen e.g. when remove and add
// back a target for existence filter mismatches.
n.G(), n.j(t.resumeToken);
break;
case 2 /* Removed */ :
// We need to keep track of removed targets to we can post-filter and
// remove any target changes.
// We need to decrement the number of pending acks needed from watch
// for this targetId.
n.X(), n.q || this.removeTarget(e);
break;
case 3 /* Current */ :
this.ht(e) && (n.Z(), n.j(t.resumeToken));
break;
case 4 /* Reset */ :
this.ht(e) && // Reset the target and synthesizes removes for all existing
// documents. The backend will re-add any documents that still
// match the target before it sends the next global snapshot.
(this.lt(e), n.j(t.resumeToken));
break;
default:
L();
}
});
}
/**
* Iterates over all targetIds that the watch change applies to: either the
* targetIds explicitly listed in the change or the targetIds of all currently
* active targets.
*/ forEachTarget(t, e) {
t.targetIds.length > 0 ? t.targetIds.forEach(e) : this.et.forEach((t, n)=>{
this.ht(n) && e(n);
});
}
/**
* Handles existence filters and synthesizes deletes for filter mismatches.
* Targets that are invalidated by filter mismatches are added to
* `pendingTargetResets`.
*/ ft(t) {
const e = t.targetId, n = t.O.count, s = this.dt(e);
if (s) {
const t = s.target;
if (Ht(t)) {
if (0 === n) {
// The existence filter told us the document does not exist. We deduce
// that this document does not exist and apply a deleted document to
// our updates. Without applying this deleted document there might be
// another query that will raise this document as part of a snapshot
// until it is resolved, essentially exposing inconsistency between
// queries.
const n = new Pt(t.path);
this.ct(e, n, Kt.newNoDocument(n, rt.min()));
} else 1 === n || L();
} else this.wt(e) !== n && // Existence filter mismatch: We reset the mapping and raise a new
// snapshot with `isFromCache:true`.
(this.lt(e), this.it = this.it.add(e));
}
}
/**
* Converts the currently accumulated state into a remote event at the
* provided snapshot version. Resets the accumulated changes before returning.
*/ _t(t) {
const e = new Map();
this.et.forEach((n, s)=>{
const i = this.dt(s);
if (i) {
if (n.current && Ht(i.target)) {
// Document queries for document that don't exist can produce an empty
// result set. To update our local cache, we synthesize a document
// delete if we have not previously received the document. This
// resolves the limbo state of the document, removing it from
// limboDocumentRefs.
// TODO(dimond): Ideally we would have an explicit lookup target
// instead resulting in an explicit delete message and we could
// remove this special logic.
const e = new Pt(i.target.path);
null !== this.nt.get(e) || this.gt(s, e) || this.ct(s, e, Kt.newNoDocument(e, t));
}
n.K && (e.set(s, n.W()), n.G());
}
});
let n = Pn();
// We extract the set of limbo-only document updates as the GC logic
// special-cases documents that do not appear in the target cache.
// TODO(gsoltis): Expand on this comment once GC is available in the JS
// client.
this.st.forEach((t, e)=>{
let s = !0;
e.forEachWhile((t)=>{
const e = this.dt(t);
return !e || 2 /* LimboResolution */ === e.purpose || (s = !1, !1);
}), s && (n = n.add(t));
});
const s = new Sn(t, e, this.it, this.nt, n);
return this.nt = pn, this.st = On(), this.it = new gn(et), s;
}
/**
* Adds the provided document to the internal list of document updates and
* its document key to the given target's mapping.
*/ // Visible for testing.
ot(t, e) {
if (!this.ht(t)) return;
const n = 2 /* Modified */ * !!this.gt(t, e.key); /* Added */
this.ut(t).H(e.key, n), this.nt = this.nt.insert(e.key, e), this.st = this.st.insert(e.key, this.yt(e.key).add(t));
}
/**
* Removes the provided document from the target mapping. If the
* document no longer matches the target, but the document's state is still
* known (e.g. we know that the document was deleted or we received the change
* that caused the filter mismatch), the new document can be provided
* to update the remote document cache.
*/ // Visible for testing.
ct(t, e, n) {
if (!this.ht(t)) return;
const s = this.ut(t);
this.gt(t, e) ? s.H(e, 1 /* Removed */ ) : // snapshot, so we can just ignore the change.
s.J(e), this.st = this.st.insert(e, this.yt(e).delete(t)), n && (this.nt = this.nt.insert(e, n));
}
removeTarget(t) {
this.et.delete(t);
}
/**
* Returns the current count of documents in the target. This includes both
* the number of documents that the LocalStore considers to be part of the
* target as well as any accumulated changes.
*/ wt(t) {
const e = this.ut(t).W();
return this.tt.getRemoteKeysForTarget(t).size + e.addedDocuments.size - e.removedDocuments.size;
}
/**
* Increment the number of acks needed from watch before we can consider the
* server to be 'in-sync' with the client's active targets.
*/ Y(t) {
this.ut(t).Y();
}
ut(t) {
let e = this.et.get(t);
return e || (e = new kn(), this.et.set(t, e)), e;
}
yt(t) {
let e = this.st.get(t);
return e || (e = new gn(et), this.st = this.st.insert(t, e)), e;
}
/**
* Verifies that the user is still interested in this target (by calling
* `getTargetDataForTarget()`) and that we are not waiting for pending ADDs
* from watch.
*/ ht(t) {
const e = null !== this.dt(t);
return e || $("WatchChangeAggregator", "Detected inactive target", t), e;
}
/**
* Returns the TargetData for an active target (i.e. a target that the user
* is still interested in that has no outstanding target change requests).
*/ dt(t) {
const e = this.et.get(t);
return e && e.q ? null : this.tt.Tt(t);
}
/**
* Resets the state of a Watch target to its initial state (e.g. sets
* 'current' to false, clears the resume token and removes its target mapping
* from all documents).
*/ lt(t) {
this.et.set(t, new kn()), this.tt.getRemoteKeysForTarget(t).forEach((e)=>{
this.ct(t, e, /*updatedDocument=*/ null);
});
}
/**
* Returns whether the LocalStore considers the document to be part of the
* specified target.
*/ gt(t, e) {
return this.tt.getRemoteKeysForTarget(t).has(e);
}
}
function On() {
return new wn(Pt.comparator);
}
function Fn() {
return new wn(Pt.comparator);
}
/**
* @license
* Copyright 2017 Google 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.
*/ const Mn = {
asc: "ASCENDING",
desc: "DESCENDING"
}, Ln = {
"<": "LESS_THAN",
"<=": "LESS_THAN_OR_EQUAL",
">": "GREATER_THAN",
">=": "GREATER_THAN_OR_EQUAL",
"==": "EQUAL",
"!=": "NOT_EQUAL",
"array-contains": "ARRAY_CONTAINS",
in: "IN",
"not-in": "NOT_IN",
"array-contains-any": "ARRAY_CONTAINS_ANY"
};
/**
* This class generates JsonObject values for the Datastore API suitable for
* sending to either GRPC stub methods or via the JSON/HTTP REST API.
*
* The serializer supports both Protobuf.js and Proto3 JSON formats. By
* setting `useProto3Json` to true, the serializer will use the Proto3 JSON
* format.
*
* For a description of the Proto3 JSON format check
* https://developers.google.com/protocol-buffers/docs/proto3#json
*
* TODO(klimt): We can remove the databaseId argument if we keep the full
* resource name in documents.
*/ class Bn {
constructor(t, e){
this.databaseId = t, this.D = e;
}
}
function jn(t) {
return t || L(), rt.fromTimestamp(function(t) {
const e = gt(t);
return new it(e.seconds, e.nanos);
}(t));
}
function Wn(t) {
const e = ht.fromString(t);
return Ts(e) || L(), e;
}
function zn(t, e) {
const n = Wn(e);
if (n.get(1) !== t.databaseId.projectId) throw new j(K.INVALID_ARGUMENT, "Tried to deserialize key from different project: " + n.get(1) + " vs " + t.databaseId.projectId);
if (n.get(3) !== t.databaseId.database) throw new j(K.INVALID_ARGUMENT, "Tried to deserialize key from different database: " + n.get(3) + " vs " + t.databaseId.database);
return new Pt(Xn(n));
}
function Hn(t, e) {
var t1;
return new ht([
"projects",
(t1 = t.databaseId).projectId,
"databases",
t1.database
]).child("documents").child(e).canonicalString();
}
function Yn(t) {
return new ht([
"projects",
t.databaseId.projectId,
"databases",
t.databaseId.database
]).canonicalString();
}
function Xn(t) {
return t.length > 4 && "documents" === t.get(4) || L(), t.popFirst(5);
}
function ls(t) {
return {
before: t.before,
values: t.position
};
}
function fs(t) {
const e = !!t.before;
return new oe(t.values || [], e);
}
function _s(t) {
return {
fieldPath: t.canonicalString()
};
}
function ms(t) {
return ft.fromServerFormat(t.fieldPath);
}
function Ts(t) {
// Resource names have at least 4 components (project ID, database ID)
return t.length >= 4 && "projects" === t.get(0) && "databases" === t.get(2);
}
/**
* @license
* Copyright 2017 Google 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.
*/ /**
* Encodes a resource path into a IndexedDb-compatible string form.
*/ function Es(t) {
let e = "";
for(let n = 0; n < t.length; n++)e.length > 0 && (e += ""), e = /** Encodes a single segment of a resource path into the given result */ function(t, e) {
let n = e;
const s = t.length;
for(let e = 0; e < s; e++){
const s = t.charAt(e);
switch(s){
case "\0":
n += "";
break;
case "":
n += "";
break;
default:
n += s;
}
}
return n;
}(t.get(n), e);
return e + "";
}
/**
* A singleton object to be stored in the 'owner' store in IndexedDb.
*
* A given database can have a single primary tab assigned at a given time. That
* tab must validate that it is still holding the primary lease before every
* operation that requires locked access. The primary tab should regularly
* write an updated timestamp to this lease to prevent other tabs from
* "stealing" the primary lease
*/ class Ps {
constructor(t, /** Whether to allow shared access from multiple tabs. */ e, n){
this.ownerId = t, this.allowTabSynchronization = e, this.leaseTimestampMs = n;
}
}
/**
* Name of the IndexedDb object store.
*
* Note that the name 'owner' is chosen to ensure backwards compatibility with
* older clients that only supported single locked access to the persistence
* layer.
*/ Ps.store = "owner", /**
* The key string used for the single object that exists in the
* DbPrimaryClient store.
*/ Ps.key = "owner";
/**
* An object to be stored in the 'mutationQueues' store in IndexedDb.
*
* Each user gets a single queue of MutationBatches to apply to the server.
* DbMutationQueue tracks the metadata about the queue.
*/ class vs {
constructor(/**
* The normalized user ID to which this queue belongs.
*/ t, /**
* An identifier for the highest numbered batch that has been acknowledged
* by the server. All MutationBatches in this queue with batchIds less
* than or equal to this value are considered to have been acknowledged by
* the server.
*
* NOTE: this is deprecated and no longer used by the code.
*/ e, /**
* A stream token that was previously sent by the server.
*
* See StreamingWriteRequest in datastore.proto for more details about
* usage.
*
* After sending this token, earlier tokens may not be used anymore so
* only a single stream token is retained.
*
* NOTE: this is deprecated and no longer used by the code.
*/ n){
this.userId = t, this.lastAcknowledgedBatchId = e, this.lastStreamToken = n;
}
}
/** Name of the IndexedDb object store. */ vs.store = "mutationQueues", /** Keys are automatically assigned via the userId property. */ vs.keyPath = "userId";
/**
* An object to be stored in the 'mutations' store in IndexedDb.
*
* Represents a batch of user-level mutations intended to be sent to the server
* in a single write. Each user-level batch gets a separate DbMutationBatch
* with a new batchId.
*/ class Vs {
constructor(/**
* The normalized user ID to which this batch belongs.
*/ t, /**
* An identifier for this batch, allocated using an auto-generated key.
*/ e, /**
* The local write time of the batch, stored as milliseconds since the
* epoch.
*/ n, /**
* A list of "mutations" that represent a partial base state from when this
* write batch was initially created. During local application of the write
* batch, these baseMutations are applied prior to the real writes in order
* to override certain document fields from the remote document cache. This
* is necessary in the case of non-idempotent writes (e.g. `increment()`
* transforms) to make sure that the local view of the modified documents
* doesn't flicker if the remote document cache receives the result of the
* non-idempotent write before the write is removed from the queue.
*
* These mutations are never sent to the backend.
*/ s, /**
* A list of mutations to apply. All mutations will be applied atomically.
*
* Mutations are serialized via toMutation().
*/ i){
this.userId = t, this.batchId = e, this.localWriteTimeMs = n, this.baseMutations = s, this.mutations = i;
}
}
/** Name of the IndexedDb object store. */ Vs.store = "mutations", /** Keys are automatically assigned via the userId, batchId properties. */ Vs.keyPath = "batchId", /** The index name for lookup of mutations by user. */ Vs.userMutationsIndex = "userMutationsIndex", /** The user mutations index is keyed by [userId, batchId] pairs. */ Vs.userMutationsKeyPath = [
"userId",
"batchId"
];
/**
* An object to be stored in the 'documentMutations' store in IndexedDb.
*
* A manually maintained index of all the mutation batches that affect a given
* document key. The rows in this table are references based on the contents of
* DbMutationBatch.mutations.
*/ class Ss {
constructor(){}
/**
* Creates a [userId] key for use in the DbDocumentMutations index to iterate
* over all of a user's document mutations.
*/ static prefixForUser(t) {
return [
t
];
}
/**
* Creates a [userId, encodedPath] key for use in the DbDocumentMutations
* index to iterate over all at document mutations for a given path or lower.
*/ static prefixForPath(t, e) {
return [
t,
Es(e)
];
}
/**
* Creates a full index key of [userId, encodedPath, batchId] for inserting
* and deleting into the DbDocumentMutations index.
*/ static key(t, e, n) {
return [
t,
Es(e),
n
];
}
}
Ss.store = "documentMutations", /**
* Because we store all the useful information for this store in the key,
* there is no useful information to store as the value. The raw (unencoded)
* path cannot be stored because IndexedDb doesn't store prototype
* information.
*/ Ss.PLACEHOLDER = new Ss();
/**
* An object to be stored in the 'remoteDocuments' store in IndexedDb.
* It represents either:
*
* - A complete document.
* - A "no document" representing a document that is known not to exist (at
* some version).
* - An "unknown document" representing a document that is known to exist (at
* some version) but whose contents are unknown.
*
* Note: This is the persisted equivalent of a MaybeDocument and could perhaps
* be made more general if necessary.
*/ class Ns {
// TODO: We are currently storing full document keys almost three times
// (once as part of the primary key, once - partly - as `parentPath` and once
// inside the encoded documents). During our next migration, we should
// rewrite the primary key as parentPath + document ID which would allow us
// to drop one value.
constructor(/**
* Set to an instance of DbUnknownDocument if the data for a document is
* not known, but it is known that a document exists at the specified
* version (e.g. it had a successful update applied to it)
*/ t, /**
* Set to an instance of a DbNoDocument if it is known that no document
* exists.
*/ e, /**
* Set to an instance of a Document if there's a cached version of the
* document.
*/ n, /**
* Documents that were written to the remote document store based on
* a write acknowledgment are marked with `hasCommittedMutations`. These
* documents are potentially inconsistent with the backend's copy and use
* the write's commit version as their document version.
*/ s, /**
* When the document was read from the backend. Undefined for data written
* prior to schema version 9.
*/ i, /**
* The path of the collection this document is part of. Undefined for data
* written prior to schema version 9.
*/ r){
this.unknownDocument = t, this.noDocument = e, this.document = n, this.hasCommittedMutations = s, this.readTime = i, this.parentPath = r;
}
}
Ns.store = "remoteDocuments", /**
* An index that provides access to all entries sorted by read time (which
* corresponds to the last modification time of each row).
*
* This index is used to provide a changelog for Multi-Tab.
*/ Ns.readTimeIndex = "readTimeIndex", Ns.readTimeIndexPath = "readTime", /**
* An index that provides access to documents in a collection sorted by read
* time.
*
* This index is used to allow the RemoteDocumentCache to fetch newly changed
* documents in a collection.
*/ Ns.collectionReadTimeIndex = "collectionReadTimeIndex", Ns.collectionReadTimeIndexPath = [
"parentPath",
"readTime"
];
/**
* Contains a single entry that has metadata about the remote document cache.
*/ class xs {
/**
* @param byteSize - Approximately the total size in bytes of all the
* documents in the document cache.
*/ constructor(t){
this.byteSize = t;
}
}
xs.store = "remoteDocumentGlobal", xs.key = "remoteDocumentGlobalKey";
/**
* An object to be stored in the 'targets' store in IndexedDb.
*
* This is based on and should be kept in sync with the proto used in the iOS
* client.
*
* Each query the client listens to against the server is tracked on disk so
* that the query can be efficiently resumed on restart.
*/ class ks {
constructor(/**
* An auto-generated sequential numeric identifier for the query.
*
* Queries are stored using their canonicalId as the key, but these
* canonicalIds can be quite long so we additionally assign a unique
* queryId which can be used by referenced data structures (e.g.
* indexes) to minimize the on-disk cost.
*/ t, /**
* The canonical string representing this query. This is not unique.
*/ e, /**
* The last readTime received from the Watch Service for this query.
*
* This is the same value as TargetChange.read_time in the protos.
*/ n, /**
* An opaque, server-assigned token that allows watching a query to be
* resumed after disconnecting without retransmitting all the data
* that matches the query. The resume token essentially identifies a
* point in time from which the server should resume sending results.
*
* This is related to the snapshotVersion in that the resumeToken
* effectively also encodes that value, but the resumeToken is opaque
* and sometimes encodes additional information.
*
* A consequence of this is that the resumeToken should be used when
* asking the server to reason about where this client is in the watch
* stream, but the client should use the snapshotVersion for its own
* purposes.
*
* This is the same value as TargetChange.resume_token in the protos.
*/ s, /**
* A sequence number representing the last time this query was
* listened to, used for garbage collection purposes.
*
* Conventionally this would be a timestamp value, but device-local
* clocks are unreliable and they must be able to create new listens
* even while disconnected. Instead this should be a monotonically
* increasing number that's incremented on each listen call.
*
* This is different from the queryId since the queryId is an
* immutable identifier assigned to the Query on first use while
* lastListenSequenceNumber is updated every time the query is
* listened to.
*/ i, /**
* Denotes the maximum snapshot version at which the associated query view
* contained no limbo documents. Undefined for data written prior to
* schema version 9.
*/ r, /**
* The query for this target.
*
* Because canonical ids are not unique we must store the actual query. We
* use the proto to have an object we can persist without having to
* duplicate translation logic to and from a `Query` object.
*/ o){
this.targetId = t, this.canonicalId = e, this.readTime = n, this.resumeToken = s, this.lastListenSequenceNumber = i, this.lastLimboFreeSnapshotVersion = r, this.query = o;
}
}
ks.store = "targets", /** Keys are automatically assigned via the targetId property. */ ks.keyPath = "targetId", /** The name of the queryTargets index. */ ks.queryTargetsIndexName = "queryTargetsIndex", /**
* The index of all canonicalIds to the targets that they match. This is not
* a unique mapping because canonicalId does not promise a unique name for all
* possible queries, so we append the targetId to make the mapping unique.
*/ ks.queryTargetsKeyPath = [
"canonicalId",
"targetId"
];
/**
* An object representing an association between a target and a document, or a
* sentinel row marking the last sequence number at which a document was used.
* Each document cached must have a corresponding sentinel row before lru
* garbage collection is enabled.
*
* The target associations and sentinel rows are co-located so that orphaned
* documents and their sequence numbers can be identified efficiently via a scan
* of this store.
*/ class $s {
constructor(/**
* The targetId identifying a target or 0 for a sentinel row.
*/ t, /**
* The path to the document, as encoded in the key.
*/ e, /**
* If this is a sentinel row, this should be the sequence number of the last
* time the document specified by `path` was used. Otherwise, it should be
* `undefined`.
*/ n){
this.targetId = t, this.path = e, this.sequenceNumber = n;
}
}
/** Name of the IndexedDb object store. */ $s.store = "targetDocuments", /** Keys are automatically assigned via the targetId, path properties. */ $s.keyPath = [
"targetId",
"path"
], /** The index name for the reverse index. */ $s.documentTargetsIndex = "documentTargetsIndex", /** We also need to create the reverse index for these properties. */ $s.documentTargetsKeyPath = [
"path",
"targetId"
];
/**
* A record of global state tracked across all Targets, tracked separately
* to avoid the need for extra indexes.
*
* This should be kept in-sync with the proto used in the iOS client.
*/ class Os {
constructor(/**
* The highest numbered target id across all targets.
*
* See DbTarget.targetId.
*/ t, /**
* The highest numbered lastListenSequenceNumber across all targets.
*
* See DbTarget.lastListenSequenceNumber.
*/ e, /**
* A global snapshot version representing the last consistent snapshot we
* received from the backend. This is monotonically increasing and any
* snapshots received from the backend prior to this version (e.g. for
* targets resumed with a resumeToken) should be suppressed (buffered)
* until the backend has caught up to this snapshot version again. This
* prevents our cache from ever going backwards in time.
*/ n, /**
* The number of targets persisted.
*/ s){
this.highestTargetId = t, this.highestListenSequenceNumber = e, this.lastRemoteSnapshotVersion = n, this.targetCount = s;
}
}
/**
* The key string used for the single object that exists in the
* DbTargetGlobal store.
*/ Os.key = "targetGlobalKey", Os.store = "targetGlobal";
/**
* An object representing an association between a Collection id (e.g. 'messages')
* to a parent path (e.g. '/chats/123') that contains it as a (sub)collection.
* This is used to efficiently find all collections to query when performing
* a Collection Group query.
*/ class Fs {
constructor(/**
* The collectionId (e.g. 'messages')
*/ t, /**
* The path to the parent (either a document location or an empty path for
* a root-level collection).
*/ e){
this.collectionId = t, this.parent = e;
}
}
/** Name of the IndexedDb object store. */ Fs.store = "collectionParents", /** Keys are automatically assigned via the collectionId, parent properties. */ Fs.keyPath = [
"collectionId",
"parent"
];
/**
* A record of the metadata state of each client.
*
* PORTING NOTE: This is used to synchronize multi-tab state and does not need
* to be ported to iOS or Android.
*/ class Ms {
constructor(// Note: Previous schema versions included a field
// "lastProcessedDocumentChangeId". Don't use anymore.
/** The auto-generated client id assigned at client startup. */ t, /** The last time this state was updated. */ e, /** Whether the client's network connection is enabled. */ n, /** Whether this client is running in a foreground tab. */ s){
this.clientId = t, this.updateTimeMs = e, this.networkEnabled = n, this.inForeground = s;
}
}
/** Name of the IndexedDb object store. */ Ms.store = "clientMetadata", /** Keys are automatically assigned via the clientId properties. */ Ms.keyPath = "clientId";
/**
* A object representing a bundle loaded by the SDK.
*/ class Ls {
constructor(/** The ID of the loaded bundle. */ t, /** The create time of the loaded bundle. */ e, /** The schema version of the loaded bundle. */ n){
this.bundleId = t, this.createTime = e, this.version = n;
}
}
/** Name of the IndexedDb object store. */ Ls.store = "bundles", Ls.keyPath = "bundleId";
/**
* A object representing a named query loaded by the SDK via a bundle.
*/ class Bs {
constructor(/** The name of the query. */ t, /** The read time of the results saved in the bundle from the named query. */ e, /** The query saved in the bundle. */ n){
this.name = t, this.readTime = e, this.bundledQuery = n;
}
}
/** Name of the IndexedDb object store. */ Bs.store = "namedQueries", Bs.keyPath = "name", vs.store, Vs.store, Ss.store, Ns.store, ks.store, Ps.store, Os.store, $s.store, Ms.store, xs.store, Fs.store, Ls.store, Bs.store;
// V2 is no longer usable (see comment at top of file)
// Visible for testing
/**
* A base class representing a persistence transaction, encapsulating both the
* transaction's sequence numbers as well as a list of onCommitted listeners.
*
* When you call Persistence.runTransaction(), it will create a transaction and
* pass it to your callback. You then pass it to any method that operates
* on persistence.
*/ class Ks {
constructor(){
this.onCommittedListeners = [];
}
addOnCommittedListener(t) {
this.onCommittedListeners.push(t);
}
raiseOnCommittedEvent() {
this.onCommittedListeners.forEach((t)=>t());
}
}
/**
* @license
* Copyright 2017 Google 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.
*/ /**
* PersistencePromise is essentially a re-implementation of Promise except
* it has a .next() method instead of .then() and .next() and .catch() callbacks
* are executed synchronously when a PersistencePromise resolves rather than
* asynchronously (Promise implementations use setImmediate() or similar).
*
* This is necessary to interoperate with IndexedDB which will automatically
* commit transactions if control is returned to the event loop without
* synchronously initiating another operation on the transaction.
*
* NOTE: .then() and .catch() only allow a single consumer, unlike normal
* Promises.
*/ class js {
constructor(t){
// NOTE: next/catchCallback will always point to our own wrapper functions,
// not the user's raw next() or catch() callbacks.
this.nextCallback = null, this.catchCallback = null, // When the operation resolves, we'll set result or error and mark isDone.
this.result = void 0, this.error = void 0, this.isDone = !1, // Set to true when .then() or .catch() are called and prevents additional
// chaining.
this.callbackAttached = !1, t((t)=>{
this.isDone = !0, this.result = t, this.nextCallback && // value should be defined unless T is Void, but we can't express
// that in the type system.
this.nextCallback(t);
}, (t)=>{
this.isDone = !0, this.error = t, this.catchCallback && this.catchCallback(t);
});
}
catch(t) {
return this.next(void 0, t);
}
next(t, e) {
return this.callbackAttached && L(), this.callbackAttached = !0, this.isDone ? this.error ? this.wrapFailure(e, this.error) : this.wrapSuccess(t, this.result) : new js((n, s)=>{
this.nextCallback = (e)=>{
this.wrapSuccess(t, e).next(n, s);
}, this.catchCallback = (t)=>{
this.wrapFailure(e, t).next(n, s);
};
});
}
toPromise() {
return new Promise((t, e)=>{
this.next(t, e);
});
}
wrapUserFunction(t) {
try {
const e = t();
return e instanceof js ? e : js.resolve(e);
} catch (t) {
return js.reject(t);
}
}
wrapSuccess(t, e) {
return t ? this.wrapUserFunction(()=>t(e)) : js.resolve(e);
}
wrapFailure(t, e) {
return t ? this.wrapUserFunction(()=>t(e)) : js.reject(e);
}
static resolve(t) {
return new js((e, n)=>{
e(t);
});
}
static reject(t) {
return new js((e, n)=>{
n(t);
});
}
static waitFor(// Accept all Promise types in waitFor().
// eslint-disable-next-line @typescript-eslint/no-explicit-any
t) {
return new js((e, n)=>{
let s = 0, i = 0, r = !1;
t.forEach((t)=>{
++s, t.next(()=>{
++i, r && i === s && e();
}, (t)=>n(t));
}), r = !0, i === s && e();
});
}
/**
* Given an array of predicate functions that asynchronously evaluate to a
* boolean, implements a short-circuiting `or` between the results. Predicates
* will be evaluated until one of them returns `true`, then stop. The final
* result will be whether any of them returned `true`.
*/ static or(t) {
let e = js.resolve(!1);
for (const n of t)e = e.next((t)=>t ? js.resolve(t) : n());
return e;
}
static forEach(t, e) {
const n = [];
return t.forEach((t, s)=>{
n.push(e.call(this, t, s));
}), this.waitFor(n);
}
}
/** Verifies whether `e` is an IndexedDbTransactionError. */ function Hs(t) {
// Use name equality, as instanceof checks on errors don't work with errors
// that wrap other errors.
return "IndexedDbTransactionError" === t.name;
}
/**
* @license
* Copyright 2017 Google 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.
*/ /**
* A batch of mutations that will be sent as one unit to the backend.
*/ class ni {
/**
* @param batchId - The unique ID of this mutation batch.
* @param localWriteTime - The original write time of this mutation.
* @param baseMutations - Mutations that are used to populate the base
* values when this mutation is applied locally. This can be used to locally
* overwrite values that are persisted in the remote document cache. Base
* mutations are never sent to the backend.
* @param mutations - The user-provided mutations in this mutation batch.
* User-provided mutations are applied both locally and remotely on the
* backend.
*/ constructor(t, e, n, s){
this.batchId = t, this.localWriteTime = e, this.baseMutations = n, this.mutations = s;
}
/**
* Applies all the mutations in this MutationBatch to the specified document
* to compute the state of the remote document
*
* @param document - The document to apply mutations to.
* @param batchResult - The result of applying the MutationBatch to the
* backend.
*/ applyToRemoteDocument(t, e) {
const n = e.mutationResults;
for(let e = 0; e < this.mutations.length; e++){
const s = this.mutations[e];
if (s.key.isEqual(t.key)) {
var n1;
n1 = n[e], s instanceof en ? function(t, e, n) {
// Unlike setMutationApplyToLocalView, if we're applying a mutation to a
// remote document the server has accepted the mutation so the precondition
// must have held.
const s = t.value.clone(), i = rn(t.fieldTransforms, e, n.transformResults);
s.setAll(i), e.convertToFoundDocument(n.version, s).setHasCommittedMutations();
}(s, t, n1) : s instanceof nn ? function(t, e, n) {
if (!ze(t.precondition, e)) // Since the mutation was not rejected, we know that the precondition
// matched on the backend. We therefore must not have the expected version
// of the document in our cache and convert to an UnknownDocument with a
// known updateTime.
return void e.convertToUnknownDocument(n.version);
const s = rn(t.fieldTransforms, e, n.transformResults), i = e.data;
i.setAll(sn(t)), i.setAll(s), e.convertToFoundDocument(n.version, i).setHasCommittedMutations();
}(s, t, n1) : function(t, e, n) {
// Unlike applyToLocalView, if we're applying a mutation to a remote
// document the server has accepted the mutation so the precondition must
// have held.
e.convertToNoDocument(n.version).setHasCommittedMutations();
}(0, t, n1);
}
}
}
/**
* Computes the local view of a document given all the mutations in this
* batch.
*
* @param document - The document to apply mutations to.
*/ applyToLocalView(t) {
// First, apply the base state. This allows us to apply non-idempotent
// transform against a consistent set of values.
for (const e of this.baseMutations)e.key.isEqual(t.key) && Ye(e, t, this.localWriteTime);
// Second, apply all user-provided mutations.
for (const e of this.mutations)e.key.isEqual(t.key) && Ye(e, t, this.localWriteTime);
}
/**
* Computes the local view for all provided documents given the mutations in
* this batch.
*/ applyToLocalDocumentSet(t) {
// TODO(mrschmidt): This implementation is O(n^2). If we apply the mutations
// directly (as done in `applyToLocalView()`), we can reduce the complexity
// to O(n).
this.mutations.forEach((e)=>{
const n = t.get(e.key);
// TODO(mutabledocuments): This method should take a MutableDocumentMap
// and we should remove this cast.
this.applyToLocalView(n), n.isValidDocument() || n.convertToNoDocument(rt.min());
});
}
keys() {
return this.mutations.reduce((t, e)=>t.add(e.key), Pn());
}
isEqual(t) {
return this.batchId === t.batchId && nt(this.mutations, t.mutations, (t, e)=>Ze(t, e)) && nt(this.baseMutations, t.baseMutations, (t, e)=>Ze(t, e));
}
}
/**
* @license
* Copyright 2017 Google 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.
*/ /**
* An immutable set of metadata that the local store tracks for each target.
*/ class ii {
constructor(/** The target being listened to. */ t, /**
* The target ID to which the target corresponds; Assigned by the
* LocalStore for user listens and by the SyncEngine for limbo watches.
*/ e, /** The purpose of the target. */ n, /**
* The sequence number of the last transaction during which this target data
* was modified.
*/ s, /** The latest snapshot version seen for this target. */ i = rt.min(), /**
* The maximum snapshot version at which the associated view
* contained no limbo documents.
*/ r = rt.min(), /**
* An opaque, server-assigned token that allows watching a target to be
* resumed after disconnecting without retransmitting all the data that
* matches the target. The resume token essentially identifies a point in
* time from which the server should resume sending results.
*/ o = _t.EMPTY_BYTE_STRING){
this.target = t, this.targetId = e, this.purpose = n, this.sequenceNumber = s, this.snapshotVersion = i, this.lastLimboFreeSnapshotVersion = r, this.resumeToken = o;
}
/** Creates a new target data instance with an updated sequence number. */ withSequenceNumber(t) {
return new ii(this.target, this.targetId, this.purpose, t, this.snapshotVersion, this.lastLimboFreeSnapshotVersion, this.resumeToken);
}
/**
* Creates a new target data instance with an updated resume token and
* snapshot version.
*/ withResumeToken(t, e) {
return new ii(this.target, this.targetId, this.purpose, this.sequenceNumber, e, this.lastLimboFreeSnapshotVersion, t);
}
/**
* Creates a new target data instance with an updated last limbo free
* snapshot version number.
*/ withLastLimboFreeSnapshotVersion(t) {
return new ii(this.target, this.targetId, this.purpose, this.sequenceNumber, this.snapshotVersion, t, this.resumeToken);
}
}
/**
* @license
* Copyright 2017 Google 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.
*/ /** Serializer for values stored in the LocalStore. */ class ri {
constructor(t){
this.Wt = t;
}
}
/**
* @license
* Copyright 2019 Google 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.
*/ /**
* An in-memory implementation of IndexManager.
*/ class pi {
constructor(){
this.Gt = new Ti();
}
addToCollectionParentIndex(t, e) {
return this.Gt.add(e), js.resolve();
}
getCollectionParents(t, e) {
return js.resolve(this.Gt.getEntries(e));
}
}
/**
* Internal implementation of the collection-parent index exposed by MemoryIndexManager.
* Also used for in-memory caching by IndexedDbIndexManager and initial index population
* in indexeddb_schema.ts
*/ class Ti {
constructor(){
this.index = {};
}
// Returns false if the entry already existed.
add(t) {
const e = t.lastSegment(), n = t.popLast(), s = this.index[e] || new gn(ht.comparator), i = !s.has(n);
return this.index[e] = s.add(n), i;
}
has(t) {
const e = t.lastSegment(), n = t.popLast(), s = this.index[e];
return s && s.has(n);
}
getEntries(t) {
return (this.index[t] || new gn(ht.comparator)).toArray();
}
}
class Ri {
constructor(// When we attempt to collect, we will only do so if the cache size is greater than this
// threshold. Passing `COLLECTION_DISABLED` here will cause collection to always be skipped.
t, // The percentage of sequence numbers that we will attempt to collect
e, // A cap on the total number of sequence numbers that will be collected. This prevents
// us from collecting a huge number of sequence numbers if the cache has grown very large.
n){
this.cacheSizeCollectionThreshold = t, this.percentileToCollect = e, this.maximumSequenceNumbersToCollect = n;
}
static withCacheSize(t) {
return new Ri(t, Ri.DEFAULT_COLLECTION_PERCENTILE, Ri.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT);
}
}
/**
* @license
* Copyright 2017 Google 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.
*/ /** A mutation queue for a specific user, backed by IndexedDB. */ Ri.DEFAULT_COLLECTION_PERCENTILE = 10, Ri.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT = 1e3, Ri.DEFAULT = new Ri(41943040, Ri.DEFAULT_COLLECTION_PERCENTILE, Ri.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT), Ri.DISABLED = new Ri(-1, 0, 0);
/**
* @license
* Copyright 2017 Google 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.
*/ /** Offset to ensure non-overlapping target ids. */ /**
* Generates monotonically increasing target IDs for sending targets to the
* watch stream.
*
* The client constructs two generators, one for the target cache, and one for
* for the sync engine (to generate limbo documents targets). These
* generators produce non-overlapping IDs (by using even and odd IDs
* respectively).
*
* By separating the target ID space, the query cache can generate target IDs
* that persist across client restarts, while sync engine can independently
* generate in-memory target IDs that are transient and can be reused after a
* restart.
*/ class Ni {
constructor(t){
this.ne = t;
}
next() {
return this.ne += 2, this.ne;
}
static se() {
// The target cache generator must return '2' in its first call to `next()`
// as there is no differentiation in the protocol layer between an unset
// number and the number '0'. If we were to sent a target with target ID
// '0', the backend would consider it unset and replace it with its own ID.
return new Ni(0);
}
static ie() {
// Sync engine assigns target IDs for limbo document detection.
return new Ni(-1);
}
}
/**
* @license
* Copyright 2017 Google 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.
*/ /**
* Verifies the error thrown by a LocalStore operation. If a LocalStore
* operation fails because the primary lease has been taken by another client,
* we ignore the error (the persistence layer will immediately call
* `applyPrimaryLease` to propagate the primary state change). All other errors
* are re-thrown.
*
* @param err - An error returned by a LocalStore operation.
* @returns A Promise that resolves after we recovered, or the original error.
*/ async function Fi(t) {
if (t.code !== K.FAILED_PRECONDITION || "The current tab is not in the required state to perform this operation. It might be necessary to refresh the browser tab." !== t.message) throw t;
$("LocalStore", "Unexpectedly lost primary lease");
}
/**
* @license
* Copyright 2017 Google 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.
*/ /**
* A map implementation that uses objects as keys. Objects must have an
* associated equals function and must be immutable. Entries in the map are
* stored together with the key being produced from the mapKeyFn. This map
* automatically handles collisions of keys.
*/ class ji {
constructor(t, e){
this.mapKeyFn = t, this.equalsFn = e, /**
* The inner map for a key/value pair. Due to the possibility of collisions we
* keep a list of entries that we do a linear search through to find an actual
* match. Note that collisions should be rare, so we still expect near
* constant time lookups in practice.
*/ this.inner = {};
}
/** Get a value for this key, or undefined if it does not exist. */ get(t) {
const e = this.mapKeyFn(t), n = this.inner[e];
if (void 0 !== n) {
for (const [e, s] of n)if (this.equalsFn(e, t)) return s;
}
}
has(t) {
return void 0 !== this.get(t);
}
/** Put this key and value in the map. */ set(t, e) {
const n = this.mapKeyFn(t), s = this.inner[n];
if (void 0 !== s) {
for(let n = 0; n < s.length; n++)if (this.equalsFn(s[n][0], t)) return void (s[n] = [
t,
e
]);
s.push([
t,
e
]);
} else this.inner[n] = [
[
t,
e
]
];
}
/**
* Remove this key from the map. Returns a boolean if anything was deleted.
*/ delete(t) {
const e = this.mapKeyFn(t), n = this.inner[e];
if (void 0 === n) return !1;
for(let s = 0; s < n.length; s++)if (this.equalsFn(n[s][0], t)) return 1 === n.length ? delete this.inner[e] : n.splice(s, 1), !0;
return !1;
}
forEach(t) {
ct(this.inner, (e, n)=>{
for (const [e, s] of n)t(e, s);
});
}
isEmpty() {
return function(t) {
for(const e in t)if (Object.prototype.hasOwnProperty.call(t, e)) return !1;
return !0;
}(this.inner);
}
}
/**
* @license
* Copyright 2017 Google 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.
*/ /**
* An in-memory buffer of entries to be written to a RemoteDocumentCache.
* It can be used to batch up a set of changes to be written to the cache, but
* additionally supports reading entries back with the `getEntry()` method,
* falling back to the underlying RemoteDocumentCache if no entry is
* buffered.
*
* Entries added to the cache *must* be read first. This is to facilitate
* calculating the size delta of the pending changes.
*
* PORTING NOTE: This class was implemented then removed from other platforms.
* If byte-counting ends up being needed on the other platforms, consider
* porting this class as part of that implementation work.
*/ class Qi {
constructor(){
// A mapping of document key to the new cache entry that should be written (or null if any
// existing cache entry should be removed).
this.changes = new ji((t)=>t.toString(), (t, e)=>t.isEqual(e)), this.changesApplied = !1;
}
getReadTime(t) {
const e = this.changes.get(t);
return e ? e.readTime : rt.min();
}
/**
* Buffers a `RemoteDocumentCache.addEntry()` call.
*
* You can only modify documents that have already been retrieved via
* `getEntry()/getEntries()` (enforced via IndexedDbs `apply()`).
*/ addEntry(t, e) {
this.assertNotApplied(), this.changes.set(t.key, {
document: t,
readTime: e
});
}
/**
* Buffers a `RemoteDocumentCache.removeEntry()` call.
*
* You can only remove documents that have already been retrieved via
* `getEntry()/getEntries()` (enforced via IndexedDbs `apply()`).
*/ removeEntry(t, e = null) {
this.assertNotApplied(), this.changes.set(t, {
document: Kt.newInvalidDocument(t),
readTime: e
});
}
/**
* Looks up an entry in the cache. The buffered changes will first be checked,
* and if no buffered change applies, this will forward to
* `RemoteDocumentCache.getEntry()`.
*
* @param transaction - The transaction in which to perform any persistence
* operations.
* @param documentKey - The key of the entry to look up.
* @returns The cached document or an invalid document if we have nothing
* cached.
*/ getEntry(t, e) {
this.assertNotApplied();
const n = this.changes.get(e);
return void 0 !== n ? js.resolve(n.document) : this.getFromCache(t, e);
}
/**
* Looks up several entries in the cache, forwarding to
* `RemoteDocumentCache.getEntry()`.
*
* @param transaction - The transaction in which to perform any persistence
* operations.
* @param documentKeys - The keys of the entries to look up.
* @returns A map of cached documents, indexed by key. If an entry cannot be
* found, the corresponding key will be mapped to an invalid document.
*/ getEntries(t, e) {
return this.getAllFromCache(t, e);
}
/**
* Applies buffered changes to the underlying RemoteDocumentCache, using
* the provided transaction.
*/ apply(t) {
return this.assertNotApplied(), this.changesApplied = !0, this.applyChanges(t);
}
/** Helper to assert this.changes is not null */ assertNotApplied() {}
}
/**
* @license
* Copyright 2017 Google 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.
*/ /**
* A readonly view of the local state of all documents we're tracking (i.e. we
* have a cached version in remoteDocumentCache or local mutations for the
* document). The view is computed by applying the mutations in the
* MutationQueue to the RemoteDocumentCache.
*/ class rr {
constructor(t, e, n){
this.He = t, this.In = e, this.Ht = n;
}
/**
* Get the local view of the document identified by `key`.
*
* @returns Local view of the document or null if we don't have any cached
* state for it.
*/ An(t, e) {
return this.In.getAllMutationBatchesAffectingDocumentKey(t, e).next((n)=>this.Rn(t, e, n));
}
/** Internal version of `getDocument` that allows reusing batches. */ Rn(t, e, n) {
return this.He.getEntry(t, e).next((t)=>{
for (const e of n)e.applyToLocalView(t);
return t;
});
}
// Returns the view of the given `docs` as they would appear after applying
// all mutations in the given `batches`.
bn(t, e) {
t.forEach((t, n)=>{
for (const t of e)t.applyToLocalView(n);
});
}
/**
* Gets the local view of the documents identified by `keys`.
*
* If we don't have cached state for a document in `keys`, a NoDocument will
* be stored for that key in the resulting set.
*/ Pn(t, e) {
return this.He.getEntries(t, e).next((e)=>this.vn(t, e).next(()=>e));
}
/**
* Applies the local view the given `baseDocs` without retrieving documents
* from the local store.
*/ vn(t, e) {
return this.In.getAllMutationBatchesAffectingDocumentKeys(t, e).next((t)=>this.bn(e, t));
}
/**
* Performs a query against the local view of all documents.
*
* @param transaction - The persistence transaction.
* @param query - The query to match documents against.
* @param sinceReadTime - If not set to SnapshotVersion.min(), return only
* documents that have been read since this snapshot version (exclusive).
*/ getDocumentsMatchingQuery(t, e, n) {
/**
* Returns whether the query matches a single document by path (rather than a
* collection).
*/ return Pt.isDocumentKey(e.path) && null === e.collectionGroup && 0 === e.filters.length ? this.Vn(t, e.path) : null !== e.collectionGroup ? this.Sn(t, e, n) : this.Dn(t, e, n);
}
Vn(t, e) {
// Just do a simple document lookup.
return this.An(t, new Pt(e)).next((t)=>{
let e = En;
return t.isFoundDocument() && (e = e.insert(t.key, t)), e;
});
}
Sn(t, e, n) {
const s = e.collectionGroup;
let i = En;
return this.Ht.getCollectionParents(t, s).next((r)=>js.forEach(r, (r)=>{
const o = new fe(r.child(s), /*collectionGroup=*/ null, /**
* Returns true if this query does not specify any query constraints that
* could remove results.
*/ e.explicitOrderBy.slice(), e.filters.slice(), e.limit, e.limitType, e.startAt, e.endAt);
return this.Dn(t, o, n).next((t)=>{
t.forEach((t, e)=>{
i = i.insert(t, e);
});
});
}).next(()=>i));
}
Dn(t, e, n) {
// Query the remote documents and overlay mutations.
let s, i;
return this.He.getDocumentsMatchingQuery(t, e, n).next((n)=>(s = n, this.In.getAllMutationBatchesAffectingQuery(t, e))).next((e)=>(i = e, this.Cn(t, i, s).next((t)=>{
for (const t1 of (s = t, i))for (const e of t1.mutations){
const n = e.key;
let i = s.get(n);
null == i && // Create invalid document to apply mutations on top of
(i = Kt.newInvalidDocument(n), s = s.insert(n, i)), Ye(e, i, t1.localWriteTime), i.isFoundDocument() || (s = s.remove(n));
}
}))).next(()=>// Finally, filter out any documents that don't actually match
// the query.
(s.forEach((t, n)=>{
Pe(e, n) || (s = s.remove(t));
}), s));
}
Cn(t, e, n) {
let s = Pn();
for (const t of e)for (const e of t.mutations)e instanceof nn && null === n.get(e.key) && (s = s.add(e.key));
let i = n;
return this.He.getEntries(t, s).next((t)=>(t.forEach((t, e)=>{
e.isFoundDocument() && (i = i.insert(t, e));
}), i));
}
}
/**
* @license
* Copyright 2017 Google 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.
*/ /**
* A set of changes to what documents are currently in view and out of view for
* a given query. These changes are sent to the LocalStore by the View (via
* the SyncEngine) and are used to pin / unpin documents as appropriate.
*/ class or {
constructor(t, e, n, s){
this.targetId = t, this.fromCache = e, this.Nn = n, this.xn = s;
}
static kn(t, e) {
let n = Pn(), s = Pn();
for (const t of e.docChanges)switch(t.type){
case 0 /* Added */ :
n = n.add(t.doc.key);
break;
case 1 /* Removed */ :
s = s.add(t.doc.key);
}
return new or(t, e.fromCache, n, s);
}
}
/**
* @license
* Copyright 2019 Google 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.
*/ /**
* A query engine that takes advantage of the target document mapping in the
* QueryCache. Query execution is optimized by only reading the documents that
* previously matched a query plus any documents that were edited after the
* query was last listened to.
*
* There are some cases when this optimization is not guaranteed to produce
* the same results as full collection scans. In these cases, query
* processing falls back to full scans. These cases are:
*
* - Limit queries where a document that matched the query previously no longer
* matches the query.
*
* - Limit queries where a document edit may cause the document to sort below
* another document that is in the local cache.
*
* - Queries that have never been CURRENT or free of limbo documents.
*/ class cr {
/** Sets the document view to query against. */ $n(t) {
this.On = t;
}
/** Returns all local documents matching the specified query. */ getDocumentsMatchingQuery(t, e, n, s) {
// Queries that match all documents don't benefit from using
// key-based lookups. It is more efficient to scan all documents in a
// collection, rather than to perform individual lookups.
return 0 === e.filters.length && null === e.limit && null == e.startAt && null == e.endAt && (0 === e.explicitOrderBy.length || 1 === e.explicitOrderBy.length && e.explicitOrderBy[0].field.isKeyField()) || n.isEqual(rt.min()) ? this.Fn(t, e) : this.On.Pn(t, s).next((i)=>{
const r = this.Mn(e, i);
return (_e(e) || me(e)) && this.Ln(e.limitType, r, s, n) ? this.Fn(t, e) : (x() <= _firebase_logger__WEBPACK_IMPORTED_MODULE_2__ /* .LogLevel.DEBUG */ .in.DEBUG && $("QueryEngine", "Re-using previous result from %s to execute query: %s", n.toString(), be(e)), this.On.getDocumentsMatchingQuery(t, e, n).next((t)=>// We merge `previousResults` into `updateResults`, since
// `updateResults` is already a DocumentMap. If a document is
// contained in both lists, then its contents are the same.
(r.forEach((e)=>{
t = t.insert(e.key, e);
}), t)));
});
// Queries that have never seen a snapshot without limbo free documents
// should also be run as a full collection scan.
}
/** Applies the query filter and sorting to the provided documents. */ Mn(t, e) {
// Sort the documents and re-apply the query filter since previously
// matching documents do not necessarily still match the query.
let n = new gn(ve(t));
return e.forEach((e, s)=>{
Pe(t, s) && (n = n.add(s));
}), n;
}
/**
* Determines if a limit query needs to be refilled from cache, making it
* ineligible for index-free execution.
*
* @param sortedPreviousResults - The documents that matched the query when it
* was last synchronized, sorted by the query's comparator.
* @param remoteKeys - The document keys that matched the query at the last
* snapshot.
* @param limboFreeSnapshotVersion - The version of the snapshot when the
* query was last synchronized.
*/ Ln(t, e, n, s) {
// The query needs to be refilled if a previously matching document no
// longer matches.
if (n.size !== e.size) return !0;
// Limit queries are not eligible for index-free query execution if there is
// a potential that an older document from cache now sorts before a document
// that was previously part of the limit. This, however, can only happen if
// the document at the edge of the limit goes out of limit.
// If a document that is not the limit boundary sorts differently,
// the boundary of the limit itself did not change and documents from cache
// will continue to be "rejected" by this boundary. Therefore, we can ignore
// any modifications that don't affect the last document.
const i = "F" /* First */ === t ? e.last() : e.first();
return !!i && (i.hasPendingWrites || i.version.compareTo(s) > 0);
}
Fn(t, e) {
return x() <= _firebase_logger__WEBPACK_IMPORTED_MODULE_2__ /* .LogLevel.DEBUG */ .in.DEBUG && $("QueryEngine", "Using full collection scan to execute query:", be(e)), this.On.getDocumentsMatchingQuery(t, e, rt.min());
}
}
/**
* @license
* Copyright 2020 Google 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.
*/ /**
* Implements `LocalStore` interface.
*
* Note: some field defined in this class might have public access level, but
* the class is not exported so they are only accessible from this module.
* This is useful to implement optional features (like bundles) in free
* functions, such that they are tree-shakeable.
*/ class ar {
constructor(/** Manages our in-memory or durable persistence. */ t, e, n, s){
this.persistence = t, this.Bn = e, this.N = s, /**
* Maps a targetID to data about its target.
*
* PORTING NOTE: We are using an immutable data structure on Web to make re-runs
* of `applyRemoteEvent()` idempotent.
*/ this.Un = new wn(et), /** Maps a target to its targetID. */ // TODO(wuandy): Evaluate if TargetId can be part of Target.
this.qn = new ji((t)=>Wt(t), zt), /**
* The read time of the last entry processed by `getNewDocumentChanges()`.
*
* PORTING NOTE: This is only used for multi-tab synchronization.
*/ this.Kn = rt.min(), this.In = t.getMutationQueue(n), this.jn = t.getRemoteDocumentCache(), this.ze = t.getTargetCache(), this.Qn = new rr(this.jn, this.In, this.persistence.getIndexManager()), this.Je = t.getBundleCache(), this.Bn.$n(this.Qn);
}
collectGarbage(t) {
return this.persistence.runTransaction("Collect garbage", "readwrite-primary", (e)=>t.collect(e, this.Un));
}
}
/**
* Tells the LocalStore that the currently authenticated user has changed.
*
* In response the local store switches the mutation queue to the new user and
* returns any resulting document changes.
*/ // PORTING NOTE: Android and iOS only return the documents affected by the
// change.
async function hr(t, e) {
let s = t.In, i = t.Qn;
const r = await t.persistence.runTransaction("Handle user change", "readonly", (t1)=>{
// Swap out the mutation queue, grabbing the pending mutation batches
// before and after.
let r;
return t.In.getAllMutationBatches(t1).next((o)=>(r = o, s = t.persistence.getMutationQueue(e), // Recreate our LocalDocumentsView using the new
// MutationQueue.
i = new rr(t.jn, s, t.persistence.getIndexManager()), s.getAllMutationBatches(t1))).next((e)=>{
const n = [], s = [];
// Union the old/new changed keys.
let o = Pn();
for (const t of r)for (const e of (n.push(t.batchId), t.mutations))o = o.add(e.key);
for (const t of e)for (const e of (s.push(t.batchId), t.mutations))o = o.add(e.key);
// Return the set of all (potentially) changed documents and the list
// of mutation batch IDs that were affected by change.
return i.Pn(t1, o).next((t)=>({
Wn: t,
removedBatchIds: n,
addedBatchIds: s
}));
});
});
return t.In = s, t.Qn = i, t.Bn.$n(t.Qn), r;
}
/**
* Removes mutations from the MutationQueue for the specified batch;
* LocalDocuments will be recalculated.
*
* @returns The resulting modified documents.
*/ /**
* Returns the last consistent snapshot processed (used by the RemoteStore to
* determine whether to buffer incoming snapshots from the backend).
*/ function fr(t) {
return t.persistence.runTransaction("Get last remote snapshot version", "readonly", (t1)=>t.ze.getLastRemoteSnapshotVersion(t1));
}
/**
* Returns the TargetData as seen by the LocalStore, including updates that may
* have not yet been persisted to the TargetCache.
*/ // Visible for testing.
/**
* Unpins all the documents associated with the given target. If
* `keepPersistedTargetData` is set to false and Eager GC enabled, the method
* directly removes the associated target data from the target cache.
*
* Releasing a non-existing `Target` is a no-op.
*/ // PORTING NOTE: `keepPersistedTargetData` is multi-tab only.
async function gr(t, e, n) {
const i = t.Un.get(e);
try {
n || await t.persistence.runTransaction("Release target", n ? "readwrite" : "readwrite-primary", (t1)=>t.persistence.referenceDelegate.removeTarget(t1, i));
} catch (t) {
if (!Hs(t)) throw t;
// All `releaseTarget` does is record the final metadata state for the
// target, but we've been recording this periodically during target
// activity. If we lose this write this could cause a very slight
// difference in the order of target deletion during GC, but we
// don't define exact LRU semantics so this is acceptable.
$("LocalStore", `Failed to update sequence numbers for target ${e}: ${t}`);
}
t.Un = t.Un.remove(e), t.qn.delete(i.target);
}
/**
* Runs the specified query against the local store and returns the results,
* potentially taking advantage of query data from previous executions (such
* as the set of remote keys).
*
* @param usePreviousResults - Whether results from previous executions can
* be used to optimize this query execution.
*/ function yr(t, e, n) {
let i = rt.min(), r = Pn();
return t.persistence.runTransaction("Execute query", "readonly", (t1)=>(function(t, e, n) {
const i = t.qn.get(n);
return void 0 !== i ? js.resolve(t.Un.get(i)) : t.ze.getTargetData(e, n);
})(t, t1, Ee(e)).next((e)=>{
if (e) return i = e.lastLimboFreeSnapshotVersion, t.ze.getMatchingKeysForTargetId(t1, e.targetId).next((t)=>{
r = t;
});
}).next(()=>t.Bn.getDocumentsMatchingQuery(t1, e, n ? i : rt.min(), n ? r : Pn())).next((t)=>({
documents: t,
Gn: r
})));
}
/**
* @license
* Copyright 2020 Google 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.
*/ class Rr {
constructor(t){
this.N = t, this.Yn = new Map(), this.Xn = new Map();
}
getBundleMetadata(t, e) {
return js.resolve(this.Yn.get(e));
}
saveBundleMetadata(t, e) {
return this.Yn.set(e.id, {
id: e.id,
version: e.version,
createTime: jn(e.createTime)
}), js.resolve();
}
getNamedQuery(t, e) {
return js.resolve(this.Xn.get(e));
}
saveNamedQuery(t, e) {
return this.Xn.set(e.name, {
name: e.name,
query: /**
* A helper function for figuring out what kind of query has been stored.
*/ /**
* Encodes a `BundledQuery` from bundle proto to a Query object.
*
* This reconstructs the original query used to build the bundle being loaded,
* including features exists only in SDKs (for example: limit-to-last).
*/ function(t) {
var e;
const e1 = function(t) {
var t1;
let e, e1 = function(t) {
const e = Wn(t);
// In v1beta1 queries for collections at the root did not have a trailing
// "/documents". In v1 all resource paths contain "/documents". Preserve the
// ability to read the v1beta1 form for compatibility with queries persisted
// in the local target cache.
return 4 === e.length ? ht.emptyPath() : Xn(e);
}(t.parent);
const n = t.structuredQuery, s = n.from ? n.from.length : 0;
let i = null;
if (s > 0) {
1 === s || L();
const t = n.from[0];
t.allDescendants ? i = t.collectionId : e1 = e1.child(t.collectionId);
}
let r = [];
n.where && (r = function hs(t) {
return t ? void 0 !== t.unaryFilter ? [
function(t) {
switch(t.unaryFilter.op){
case "IS_NAN":
const e = ms(t.unaryFilter.field);
return Jt.create(e, "==" /* EQUAL */ , {
doubleValue: NaN
});
case "IS_NULL":
const n = ms(t.unaryFilter.field);
return Jt.create(n, "==" /* EQUAL */ , {
nullValue: "NULL_VALUE"
});
case "IS_NOT_NAN":
const s = ms(t.unaryFilter.field);
return Jt.create(s, "!=" /* NOT_EQUAL */ , {
doubleValue: NaN
});
case "IS_NOT_NULL":
const i = ms(t.unaryFilter.field);
return Jt.create(i, "!=" /* NOT_EQUAL */ , {
nullValue: "NULL_VALUE"
});
default:
return L();
}
}(t)
] : void 0 !== t.fieldFilter ? [
Jt.create(ms(t.fieldFilter.field), function(t) {
switch(t){
case "EQUAL":
return "==" /* EQUAL */ ;
case "NOT_EQUAL":
return "!=" /* NOT_EQUAL */ ;
case "GREATER_THAN":
return ">" /* GREATER_THAN */ ;
case "GREATER_THAN_OR_EQUAL":
return ">=" /* GREATER_THAN_OR_EQUAL */ ;
case "LESS_THAN":
return "<" /* LESS_THAN */ ;
case "LESS_THAN_OR_EQUAL":
return "<=" /* LESS_THAN_OR_EQUAL */ ;
case "ARRAY_CONTAINS":
return "array-contains" /* ARRAY_CONTAINS */ ;
case "IN":
return "in" /* IN */ ;
case "NOT_IN":
return "not-in" /* NOT_IN */ ;
case "ARRAY_CONTAINS_ANY":
return "array-contains-any" /* ARRAY_CONTAINS_ANY */ ;
default:
return L();
}
}(t.fieldFilter.op), t.fieldFilter.value)
] : void 0 !== t.compositeFilter ? t.compositeFilter.filters.map((t)=>hs(t)).reduce((t, e)=>t.concat(e)) : L() : [];
}(n.where));
let o = [];
n.orderBy && (o = n.orderBy.map((t)=>new ae(ms(t.field), // visible for testing
function(t) {
switch(t){
case "ASCENDING":
return "asc" /* ASCENDING */ ;
case "DESCENDING":
return "desc" /* DESCENDING */ ;
default:
return;
}
}(// visible for testing
t.direction))));
let c = null;
n.limit && (c = At(e = "object" == typeof (t1 = n.limit) ? t1.value : t1) ? null : e);
let a = null;
n.startAt && (a = fs(n.startAt));
let u = null;
return n.endAt && (u = fs(n.endAt)), new fe(e1, i, o, r, c, "F" /* First */ , a, u);
}({
parent: t.parent,
structuredQuery: t.structuredQuery
});
return "LAST" === t.limitType ? (e = e1.limit, new fe(e1.path, e1.collectionGroup, e1.explicitOrderBy.slice(), e1.filters.slice(), e, "L" /* Last */ , e1.startAt, e1.endAt)) : e1;
}(e.bundledQuery),
readTime: jn(e.readTime)
}), js.resolve();
}
}
/**
* @license
* Copyright 2017 Google 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.
*/ /**
* A collection of references to a document from some kind of numbered entity
* (either a target ID or batch ID). As references are added to or removed from
* the set corresponding events are emitted to a registered garbage collector.
*
* Each reference is represented by a DocumentReference object. Each of them
* contains enough information to uniquely identify the reference. They are all
* stored primarily in a set sorted by key. A document is considered garbage if
* there's no references in that set (this can be efficiently checked thanks to
* sorting by key).
*
* ReferenceSet also keeps a secondary set that contains references sorted by
* IDs. This one is used to efficiently implement removal of all references by
* some target ID.
*/ class br {
constructor(){
// A set of outstanding references to a document sorted by key.
this.Zn = new gn(Pr.ts), // A set of outstanding references to a document sorted by target id.
this.es = new gn(Pr.ns);
}
/** Returns true if the reference set contains no references. */ isEmpty() {
return this.Zn.isEmpty();
}
/** Adds a reference to the given document key for the given ID. */ addReference(t, e) {
const n = new Pr(t, e);
this.Zn = this.Zn.add(n), this.es = this.es.add(n);
}
/** Add references to the given document keys for the given ID. */ ss(t, e) {
t.forEach((t)=>this.addReference(t, e));
}
/**
* Removes a reference to the given document key for the given
* ID.
*/ removeReference(t, e) {
this.rs(new Pr(t, e));
}
os(t, e) {
t.forEach((t)=>this.removeReference(t, e));
}
/**
* Clears all references with a given ID. Calls removeRef() for each key
* removed.
*/ cs(t) {
const e = new Pt(new ht([])), n = new Pr(e, t), s = new Pr(e, t + 1), i = [];
return this.es.forEachInRange([
n,
s
], (t)=>{
this.rs(t), i.push(t.key);
}), i;
}
us() {
this.Zn.forEach((t)=>this.rs(t));
}
rs(t) {
this.Zn = this.Zn.delete(t), this.es = this.es.delete(t);
}
hs(t) {
const e = new Pt(new ht([])), n = new Pr(e, t), s = new Pr(e, t + 1);
let i = Pn();
return this.es.forEachInRange([
n,
s
], (t)=>{
i = i.add(t.key);
}), i;
}
containsKey(t) {
const e = new Pr(t, 0), n = this.Zn.firstAfterOrEqual(e);
return null !== n && t.isEqual(n.key);
}
}
class Pr {
constructor(t, e){
this.key = t, this.ls = e;
}
/** Compare by key then by ID */ static ts(t, e) {
return Pt.comparator(t.key, e.key) || et(t.ls, e.ls);
}
/** Compare by ID then by key */ static ns(t, e) {
return et(t.ls, e.ls) || Pt.comparator(t.key, e.key);
}
}
/**
* @license
* Copyright 2017 Google 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.
*/ class vr {
constructor(t, e){
this.Ht = t, this.referenceDelegate = e, /**
* The set of all mutations that have been sent but not yet been applied to
* the backend.
*/ this.In = [], /** Next value to use when assigning sequential IDs to each mutation batch. */ this.fs = 1, /** An ordered mapping between documents and the mutations batch IDs. */ this.ds = new gn(Pr.ts);
}
checkEmpty(t) {
return js.resolve(0 === this.In.length);
}
addMutationBatch(t, e, n, s) {
const i = this.fs;
this.fs++, this.In.length > 0 && this.In[this.In.length - 1];
const r = new ni(i, e, n, s);
// Track references by document key and index collection parents.
for (const e of (this.In.push(r), s))this.ds = this.ds.add(new Pr(e.key, i)), this.Ht.addToCollectionParentIndex(t, e.key.path.popLast());
return js.resolve(r);
}
lookupMutationBatch(t, e) {
return js.resolve(this.ws(e));
}
getNextMutationBatchAfterBatchId(t, e) {
const s = this._s(e + 1), i = s < 0 ? 0 : s;
// The requested batchId may still be out of range so normalize it to the
// start of the queue.
return js.resolve(this.In.length > i ? this.In[i] : null);
}
getHighestUnacknowledgedBatchId() {
return js.resolve(0 === this.In.length ? -1 : this.fs - 1);
}
getAllMutationBatches(t) {
return js.resolve(this.In.slice());
}
getAllMutationBatchesAffectingDocumentKey(t, e) {
const n = new Pr(e, 0), s = new Pr(e, Number.POSITIVE_INFINITY), i = [];
return this.ds.forEachInRange([
n,
s
], (t)=>{
const e = this.ws(t.ls);
i.push(e);
}), js.resolve(i);
}
getAllMutationBatchesAffectingDocumentKeys(t, e) {
let n = new gn(et);
return e.forEach((t)=>{
const e = new Pr(t, 0), s = new Pr(t, Number.POSITIVE_INFINITY);
this.ds.forEachInRange([
e,
s
], (t)=>{
n = n.add(t.ls);
});
}), js.resolve(this.gs(n));
}
getAllMutationBatchesAffectingQuery(t, e) {
// Use the query path as a prefix for testing if a document matches the
// query.
const n = e.path, s = n.length + 1;
// Construct a document reference for actually scanning the index. Unlike
// the prefix the document key in this reference must have an even number of
// segments. The empty segment can be used a suffix of the query path
// because it precedes all other segments in an ordered traversal.
let i = n;
Pt.isDocumentKey(i) || (i = i.child(""));
const r = new Pr(new Pt(i), 0);
// Find unique batchIDs referenced by all documents potentially matching the
// query.
let o = new gn(et);
return this.ds.forEachWhile((t)=>{
const e = t.key.path;
return !!n.isPrefixOf(e) && // Rows with document keys more than one segment longer than the query
// path can't be matches. For example, a query on 'rooms' can't match
// the document /rooms/abc/messages/xyx.
// TODO(mcg): we'll need a different scanner when we implement
// ancestor queries.
(e.length === s && (o = o.add(t.ls)), !0);
}, r), js.resolve(this.gs(o));
}
gs(t) {
// Construct an array of matching batches, sorted by batchID to ensure that
// multiple mutations affecting the same document key are applied in order.
const e = [];
return t.forEach((t)=>{
const n = this.ws(t);
null !== n && e.push(n);
}), e;
}
removeMutationBatch(t, e) {
0 === this.ys(e.batchId, "removed") || L(), this.In.shift();
let n = this.ds;
return js.forEach(e.mutations, (s)=>{
const i = new Pr(s.key, e.batchId);
return n = n.delete(i), this.referenceDelegate.markPotentiallyOrphaned(t, s.key);
}).next(()=>{
this.ds = n;
});
}
te(t) {
// No-op since the memory mutation queue does not maintain a separate cache.
}
containsKey(t, e) {
const n = new Pr(e, 0), s = this.ds.firstAfterOrEqual(n);
return js.resolve(e.isEqual(s && s.key));
}
performConsistencyCheck(t) {
return this.In.length, js.resolve();
}
/**
* Finds the index of the given batchId in the mutation queue and asserts that
* the resulting index is within the bounds of the queue.
*
* @param batchId - The batchId to search for
* @param action - A description of what the caller is doing, phrased in passive
* form (e.g. "acknowledged" in a routine that acknowledges batches).
*/ ys(t, e) {
return this._s(t);
}
/**
* Finds the index of the given batchId in the mutation queue. This operation
* is O(1).
*
* @returns The computed index of the batch with the given batchId, based on
* the state of the queue. Note this index can be negative if the requested
* batchId has already been remvoed from the queue or past the end of the
* queue if the batchId is larger than the last added batch.
*/ _s(t) {
return 0 === this.In.length ? 0 : t - this.In[0].batchId;
}
/**
* A version of lookupMutationBatch that doesn't return a promise, this makes
* other functions that uses this code easier to read and more efficent.
*/ ws(t) {
const e = this._s(t);
return e < 0 || e >= this.In.length ? null : this.In[e];
}
}
/**
* @license
* Copyright 2017 Google 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.
*/ /**
* The memory-only RemoteDocumentCache for IndexedDb. To construct, invoke
* `newMemoryRemoteDocumentCache()`.
*/ class Vr {
/**
* @param sizer - Used to assess the size of a document. For eager GC, this is
* expected to just return 0 to avoid unnecessarily doing the work of
* calculating the size.
*/ constructor(t, e){
this.Ht = t, this.ps = e, /** Underlying cache of documents and their read times. */ this.docs = new wn(Pt.comparator), /** Size of all cached documents. */ this.size = 0;
}
/**
* Adds the supplied entry to the cache and updates the cache size as appropriate.
*
* All calls of `addEntry` are required to go through the RemoteDocumentChangeBuffer
* returned by `newChangeBuffer()`.
*/ addEntry(t, e, n) {
const s = e.key, i = this.docs.get(s), r = i ? i.size : 0, o = this.ps(e);
return this.docs = this.docs.insert(s, {
document: e.clone(),
size: o,
readTime: n
}), this.size += o - r, this.Ht.addToCollectionParentIndex(t, s.path.popLast());
}
/**
* Removes the specified entry from the cache and updates the cache size as appropriate.
*
* All calls of `removeEntry` are required to go through the RemoteDocumentChangeBuffer
* returned by `newChangeBuffer()`.
*/ removeEntry(t) {
const e = this.docs.get(t);
e && (this.docs = this.docs.remove(t), this.size -= e.size);
}
getEntry(t, e) {
const n = this.docs.get(e);
return js.resolve(n ? n.document.clone() : Kt.newInvalidDocument(e));
}
getEntries(t, e) {
let n = pn;
return e.forEach((t)=>{
const e = this.docs.get(t);
n = n.insert(t, e ? e.document.clone() : Kt.newInvalidDocument(t));
}), js.resolve(n);
}
getDocumentsMatchingQuery(t, e, n) {
let s = pn;
// Documents are ordered by key, so we can use a prefix scan to narrow down
// the documents we need to match the query against.
const i = new Pt(e.path.child("")), r = this.docs.getIteratorFrom(i);
for(; r.hasNext();){
const { key: t, value: { document: i, readTime: o } } = r.getNext();
if (!e.path.isPrefixOf(t.path)) break;
0 >= o.compareTo(n) || Pe(e, i) && (s = s.insert(i.key, i.clone()));
}
return js.resolve(s);
}
Ts(t, e) {
return js.forEach(this.docs, (t)=>e(t));
}
newChangeBuffer(t) {
// `trackRemovals` is ignores since the MemoryRemoteDocumentCache keeps
// a separate changelog and does not need special handling for removals.
return new Sr(this);
}
getSize(t) {
return js.resolve(this.size);
}
}
/**
* Creates a new memory-only RemoteDocumentCache.
*
* @param indexManager - A class that manages collection group indices.
* @param sizer - Used to assess the size of a document. For eager GC, this is
* expected to just return 0 to avoid unnecessarily doing the work of
* calculating the size.
*/ /**
* Handles the details of adding and updating documents in the MemoryRemoteDocumentCache.
*/ class Sr extends Qi {
constructor(t){
super(), this.Se = t;
}
applyChanges(t) {
const e = [];
return this.changes.forEach((n, s)=>{
s.document.isValidDocument() ? e.push(this.Se.addEntry(t, s.document, this.getReadTime(n))) : this.Se.removeEntry(n);
}), js.waitFor(e);
}
getFromCache(t, e) {
return this.Se.getEntry(t, e);
}
getAllFromCache(t, e) {
return this.Se.getEntries(t, e);
}
}
/**
* @license
* Copyright 2017 Google 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.
*/ class Dr {
constructor(t){
this.persistence = t, /**
* Maps a target to the data about that target
*/ this.Es = new ji((t)=>Wt(t), zt), /** The last received snapshot version. */ this.lastRemoteSnapshotVersion = rt.min(), /** The highest numbered target ID encountered. */ this.highestTargetId = 0, /** The highest sequence number encountered. */ this.Is = 0, /**
* A ordered bidirectional mapping between documents and the remote target
* IDs.
*/ this.As = new br(), this.targetCount = 0, this.Rs = Ni.se();
}
forEachTarget(t, e) {
return this.Es.forEach((t, n)=>e(n)), js.resolve();
}
getLastRemoteSnapshotVersion(t) {
return js.resolve(this.lastRemoteSnapshotVersion);
}
getHighestSequenceNumber(t) {
return js.resolve(this.Is);
}
allocateTargetId(t) {
return this.highestTargetId = this.Rs.next(), js.resolve(this.highestTargetId);
}
setTargetsMetadata(t, e, n) {
return n && (this.lastRemoteSnapshotVersion = n), e > this.Is && (this.Is = e), js.resolve();
}
ce(t) {
this.Es.set(t.target, t);
const e = t.targetId;
e > this.highestTargetId && (this.Rs = new Ni(e), this.highestTargetId = e), t.sequenceNumber > this.Is && (this.Is = t.sequenceNumber);
}
addTargetData(t, e) {
return this.ce(e), this.targetCount += 1, js.resolve();
}
updateTargetData(t, e) {
return this.ce(e), js.resolve();
}
removeTargetData(t, e) {
return this.Es.delete(e.target), this.As.cs(e.targetId), this.targetCount -= 1, js.resolve();
}
removeTargets(t, e, n) {
let s = 0;
const i = [];
return this.Es.forEach((r, o)=>{
o.sequenceNumber <= e && null === n.get(o.targetId) && (this.Es.delete(r), i.push(this.removeMatchingKeysForTargetId(t, o.targetId)), s++);
}), js.waitFor(i).next(()=>s);
}
getTargetCount(t) {
return js.resolve(this.targetCount);
}
getTargetData(t, e) {
const n = this.Es.get(e) || null;
return js.resolve(n);
}
addMatchingKeys(t, e, n) {
return this.As.ss(e, n), js.resolve();
}
removeMatchingKeys(t, e, n) {
this.As.os(e, n);
const s = this.persistence.referenceDelegate, i = [];
return s && e.forEach((e)=>{
i.push(s.markPotentiallyOrphaned(t, e));
}), js.waitFor(i);
}
removeMatchingKeysForTargetId(t, e) {
return this.As.cs(e), js.resolve();
}
getMatchingKeysForTargetId(t, e) {
const n = this.As.hs(e);
return js.resolve(n);
}
containsKey(t, e) {
return js.resolve(this.As.containsKey(e));
}
}
/**
* @license
* Copyright 2017 Google 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.
*/ /**
* A memory-backed instance of Persistence. Data is stored only in RAM and
* not persisted across sessions.
*/ class Cr {
/**
* The constructor accepts a factory for creating a reference delegate. This
* allows both the delegate and this instance to have strong references to
* each other without having nullable fields that would then need to be
* checked or asserted on every access.
*/ constructor(t, e){
this.bs = {}, this.Le = new X(0), this.Be = !1, this.Be = !0, this.referenceDelegate = t(this), this.ze = new Dr(this), this.Ht = new pi(), this.He = new Vr(this.Ht, (t)=>this.referenceDelegate.Ps(t)), this.N = new ri(e), this.Je = new Rr(this.N);
}
start() {
return Promise.resolve();
}
shutdown() {
// No durable state to ensure is closed on shutdown.
return this.Be = !1, Promise.resolve();
}
get started() {
return this.Be;
}
setDatabaseDeletedListener() {
// No op.
}
setNetworkEnabled() {
// No op.
}
getIndexManager() {
return this.Ht;
}
getMutationQueue(t) {
let e = this.bs[t.toKey()];
return e || (e = new vr(this.Ht, this.referenceDelegate), this.bs[t.toKey()] = e), e;
}
getTargetCache() {
return this.ze;
}
getRemoteDocumentCache() {
return this.He;
}
getBundleCache() {
return this.Je;
}
runTransaction(t, e, n) {
$("MemoryPersistence", "Starting transaction:", t);
const s = new Nr(this.Le.next());
return this.referenceDelegate.vs(), n(s).next((t)=>this.referenceDelegate.Vs(s).next(()=>t)).toPromise().then((t)=>(s.raiseOnCommittedEvent(), t));
}
Ss(t, e) {
return js.or(Object.values(this.bs).map((n)=>()=>n.containsKey(t, e)));
}
}
/**
* Memory persistence is not actually transactional, but future implementations
* may have transaction-scoped state.
*/ class Nr extends Ks {
constructor(t){
super(), this.currentSequenceNumber = t;
}
}
class xr {
constructor(t){
this.persistence = t, /** Tracks all documents that are active in Query views. */ this.Ds = new br(), /** The list of documents that are potentially GCed after each transaction. */ this.Cs = null;
}
static Ns(t) {
return new xr(t);
}
get xs() {
if (this.Cs) return this.Cs;
throw L();
}
addReference(t, e, n) {
return this.Ds.addReference(n, e), this.xs.delete(n.toString()), js.resolve();
}
removeReference(t, e, n) {
return this.Ds.removeReference(n, e), this.xs.add(n.toString()), js.resolve();
}
markPotentiallyOrphaned(t, e) {
return this.xs.add(e.toString()), js.resolve();
}
removeTarget(t, e) {
this.Ds.cs(e.targetId).forEach((t)=>this.xs.add(t.toString()));
const n = this.persistence.getTargetCache();
return n.getMatchingKeysForTargetId(t, e.targetId).next((t)=>{
t.forEach((t)=>this.xs.add(t.toString()));
}).next(()=>n.removeTargetData(t, e));
}
vs() {
this.Cs = new Set();
}
Vs(t) {
// Remove newly orphaned documents.
const e = this.persistence.getRemoteDocumentCache().newChangeBuffer();
return js.forEach(this.xs, (n)=>{
const s = Pt.fromPath(n);
return this.ks(t, s).next((t)=>{
t || e.removeEntry(s);
});
}).next(()=>(this.Cs = null, e.apply(t)));
}
updateLimboDocument(t, e) {
return this.ks(t, e).next((t)=>{
t ? this.xs.delete(e.toString()) : this.xs.add(e.toString());
});
}
Ps(t) {
// For eager GC, we don't care about the document size, there are no size thresholds.
return 0;
}
ks(t, e) {
return js.or([
()=>js.resolve(this.Ds.containsKey(e)),
()=>this.persistence.getTargetCache().containsKey(t, e),
()=>this.persistence.Ss(t, e)
]);
}
}
/**
* Metadata state of the local client. Unlike `RemoteClientState`, this class is
* mutable and keeps track of all pending mutations, which allows us to
* update the range of pending mutation batch IDs as new mutations are added or
* removed.
*
* The data in `LocalClientState` is not read from WebStorage and instead
* updated via its instance methods. The updated state can be serialized via
* `toWebStorageJSON()`.
*/ // Visible for testing.
class Ur {
constructor(){
this.activeTargetIds = vn;
}
Fs(t) {
this.activeTargetIds = this.activeTargetIds.add(t);
}
Ms(t) {
this.activeTargetIds = this.activeTargetIds.delete(t);
}
/**
* Converts this entry into a JSON-encoded format we can use for WebStorage.
* Does not encode `clientId` as it is part of the key in WebStorage.
*/ Os() {
return JSON.stringify({
activeTargetIds: this.activeTargetIds.toArray(),
updateTimeMs: Date.now()
});
}
}
class Kr {
constructor(){
this.yi = new Ur(), this.pi = {}, this.onlineStateHandler = null, this.sequenceNumberHandler = null;
}
addPendingMutation(t) {
// No op.
}
updateMutationState(t, e, n) {
// No op.
}
addLocalQueryTarget(t) {
return this.yi.Fs(t), this.pi[t] || "not-current";
}
updateQueryState(t, e, n) {
this.pi[t] = e;
}
removeLocalQueryTarget(t) {
this.yi.Ms(t);
}
isLocalQueryTarget(t) {
return this.yi.activeTargetIds.has(t);
}
clearQueryState(t) {
delete this.pi[t];
}
getAllActiveQueryTargets() {
return this.yi.activeTargetIds;
}
isActiveQueryTarget(t) {
return this.yi.activeTargetIds.has(t);
}
start() {
return this.yi = new Ur(), Promise.resolve();
}
handleUserChange(t, e, n) {
// No op.
}
setOnlineState(t) {
// No op.
}
shutdown() {}
writeSequenceNumber(t) {}
notifyBundleLoaded() {
// No op.
}
}
/**
* @license
* Copyright 2019 Google 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.
*/ class jr {
Ti(t) {
// No-op.
}
shutdown() {
// No-op.
}
}
/**
* @license
* Copyright 2019 Google 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.
*/ // References to `window` are guarded by BrowserConnectivityMonitor.isAvailable()
/* eslint-disable no-restricted-globals */ /**
* Browser implementation of ConnectivityMonitor.
*/ class Qr {
constructor(){
this.Ei = ()=>this.Ii(), this.Ai = ()=>this.Ri(), this.bi = [], this.Pi();
}
Ti(t) {
this.bi.push(t);
}
shutdown() {
window.removeEventListener("online", this.Ei), window.removeEventListener("offline", this.Ai);
}
Pi() {
window.addEventListener("online", this.Ei), window.addEventListener("offline", this.Ai);
}
Ii() {
for (const t of ($("ConnectivityMonitor", "Network connectivity changed: AVAILABLE"), this.bi))t(0 /* AVAILABLE */ );
}
Ri() {
for (const t of ($("ConnectivityMonitor", "Network connectivity changed: UNAVAILABLE"), this.bi))t(1 /* UNAVAILABLE */ );
}
// TODO(chenbrian): Consider passing in window either into this component or
// here for testing via FakeWindow.
/** Checks that all used attributes of window are available. */ static bt() {
return "undefined" != typeof window && void 0 !== window.addEventListener && void 0 !== window.removeEventListener;
}
}
/**
* @license
* Copyright 2020 Google 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.
*/ const Wr = {
BatchGetDocuments: "batchGet",
Commit: "commit",
RunQuery: "runQuery"
};
/**
* Maps RPC names to the corresponding REST endpoint name.
*
* We use array notation to avoid mangling.
*/ /**
* @license
* Copyright 2017 Google 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.
*/ /**
* Provides a simple helper class that implements the Stream interface to
* bridge to other implementations that are streams but do not implement the
* interface. The stream callbacks are invoked with the callOn... methods.
*/ class Gr {
constructor(t){
this.vi = t.vi, this.Vi = t.Vi;
}
Si(t) {
this.Di = t;
}
Ci(t) {
this.Ni = t;
}
onMessage(t) {
this.xi = t;
}
close() {
this.Vi();
}
send(t) {
this.vi(t);
}
ki() {
this.Di();
}
$i(t) {
this.Ni(t);
}
Oi(t) {
this.xi(t);
}
}
/**
* @license
* Copyright 2017 Google 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.
*/ class zr extends class {
constructor(t){
this.databaseInfo = t, this.databaseId = t.databaseId;
const e = t.ssl ? "https" : "http";
this.Fi = e + "://" + t.host, this.Mi = "projects/" + this.databaseId.projectId + "/databases/" + this.databaseId.database + "/documents";
}
Li(t, e, n, s) {
const i = this.Bi(t, e);
$("RestConnection", "Sending: ", i, n);
const r = {};
return this.Ui(r, s), this.qi(t, i, r, n).then((t)=>($("RestConnection", "Received: ", t), t), (e)=>{
throw F("RestConnection", `${t} failed with error: `, e, "url: ", i, "request:", n), e;
});
}
Ki(t, e, n, s) {
// The REST API automatically aggregates all of the streamed results, so we
// can just use the normal invoke() method.
return this.Li(t, e, n, s);
}
/**
* Modifies the headers for a request, adding any authorization token if
* present and any additional headers for the request.
*/ Ui(t, e) {
if (t["X-Goog-Api-Client"] = "gl-js/ fire/" + C, // Content-Type: text/plain will avoid preflight requests which might
// mess with CORS and redirects by proxies. If we add custom headers
// we will need to change this code to potentially use the $httpOverwrite
// parameter supported by ESF to avoid triggering preflight requests.
t["Content-Type"] = "text/plain", this.databaseInfo.appId && (t["X-Firebase-GMPID"] = this.databaseInfo.appId), e) for(const n in e.authHeaders)e.authHeaders.hasOwnProperty(n) && (t[n] = e.authHeaders[n]);
}
Bi(t, e) {
const n = Wr[t];
return `${this.Fi}/v1/${e}:${n}`;
}
} {
constructor(t){
super(t), this.forceLongPolling = t.forceLongPolling, this.autoDetectLongPolling = t.autoDetectLongPolling, this.useFetchStreams = t.useFetchStreams;
}
qi(t, e, n, s) {
return new Promise((i, r)=>{
const o = new _firebase_webchannel_wrapper__WEBPACK_IMPORTED_MODULE_4__ /* .XhrIo */ .JJ();
o.listenOnce(_firebase_webchannel_wrapper__WEBPACK_IMPORTED_MODULE_4__ /* .EventType.COMPLETE */ .tw.COMPLETE, ()=>{
try {
switch(o.getLastErrorCode()){
case _firebase_webchannel_wrapper__WEBPACK_IMPORTED_MODULE_4__ /* .ErrorCode.NO_ERROR */ .jK.NO_ERROR:
const e = o.getResponseJson();
$("Connection", "XHR received:", JSON.stringify(e)), i(e);
break;
case _firebase_webchannel_wrapper__WEBPACK_IMPORTED_MODULE_4__ /* .ErrorCode.TIMEOUT */ .jK.TIMEOUT:
$("Connection", 'RPC "' + t + '" timed out'), r(new j(K.DEADLINE_EXCEEDED, "Request time out"));
break;
case _firebase_webchannel_wrapper__WEBPACK_IMPORTED_MODULE_4__ /* .ErrorCode.HTTP_ERROR */ .jK.HTTP_ERROR:
const n = o.getStatus();
if ($("Connection", 'RPC "' + t + '" failed with status:', n, "response text:", o.getResponseText()), n > 0) {
const t = o.getResponseJson().error;
if (t && t.status && t.message) {
const e = function(t) {
const e = t.toLowerCase().replace(/_/g, "-");
return Object.values(K).indexOf(e) >= 0 ? e : K.UNKNOWN;
}(t.status);
r(new j(e, t.message));
} else r(new j(K.UNKNOWN, "Server responded with status " + o.getStatus()));
} else r(new j(K.UNAVAILABLE, "Connection failed."));
break;
default:
L();
}
} finally{
$("Connection", 'RPC "' + t + '" completed.');
}
});
const c = JSON.stringify(s);
o.send(e, "POST", c, n, 15);
});
}
ji(t, e) {
const n = [
this.Fi,
"/",
"google.firestore.v1.Firestore",
"/",
t,
"/channel"
], s = (0, _firebase_webchannel_wrapper__WEBPACK_IMPORTED_MODULE_4__ /* .createWebChannelTransport */ .UE)(), i = (0, _firebase_webchannel_wrapper__WEBPACK_IMPORTED_MODULE_4__ /* .getStatEventTarget */ .FJ)(), r = {
// Required for backend stickiness, routing behavior is based on this
// parameter.
httpSessionIdParam: "gsessionid",
initMessageHeaders: {},
messageUrlParams: {
// This param is used to improve routing and project isolation by the
// backend and must be included in every request.
database: `projects/${this.databaseId.projectId}/databases/${this.databaseId.database}`
},
sendRawJson: !0,
supportsCrossDomainXhr: !0,
internalChannelParams: {
// Override the default timeout (randomized between 10-20 seconds) since
// a large write batch on a slow internet connection may take a long
// time to send to the backend. Rather than have WebChannel impose a
// tight timeout which could lead to infinite timeouts and retries, we
// set it very large (5-10 minutes) and rely on the browser's builtin
// timeouts to kick in if the request isn't working.
forwardChannelRequestTimeoutMs: 6e5
},
forceLongPolling: this.forceLongPolling,
detectBufferingProxy: this.autoDetectLongPolling
};
this.useFetchStreams && (r.xmlHttpFactory = new _firebase_webchannel_wrapper__WEBPACK_IMPORTED_MODULE_4__ /* .FetchXmlHttpFactory */ .zI({})), this.Ui(r.initMessageHeaders, e), // Sending the custom headers we just added to request.initMessageHeaders
// (Authorization, etc.) will trigger the browser to make a CORS preflight
// request because the XHR will no longer meet the criteria for a "simple"
// CORS request:
// https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS#Simple_requests
// Therefore to avoid the CORS preflight request (an extra network
// roundtrip), we use the httpHeadersOverwriteParam option to specify that
// the headers should instead be encoded into a special "$httpHeaders" query
// parameter, which is recognized by the webchannel backend. This is
// formally defined here:
// https://github.com/google/closure-library/blob/b0e1815b13fb92a46d7c9b3c30de5d6a396a3245/closure/goog/net/rpc/httpcors.js#L32
// TODO(b/145624756): There is a backend bug where $httpHeaders isn't respected if the request
// doesn't have an Origin header. So we have to exclude a few browser environments that are
// known to (sometimes) not include an Origin. See
// https://github.com/firebase/firebase-js-sdk/issues/1491.
(0, _firebase_util__WEBPACK_IMPORTED_MODULE_3__ /* .isMobileCordova */ .uI)() || (0, _firebase_util__WEBPACK_IMPORTED_MODULE_3__ /* .isReactNative */ .b$)() || (0, _firebase_util__WEBPACK_IMPORTED_MODULE_3__ /* .isElectron */ .d)() || (0, _firebase_util__WEBPACK_IMPORTED_MODULE_3__ /* .isIE */ .w1)() || (0, _firebase_util__WEBPACK_IMPORTED_MODULE_3__ /* .isUWP */ .Mn)() || (0, _firebase_util__WEBPACK_IMPORTED_MODULE_3__ /* .isBrowserExtension */ .ru)() || (r.httpHeadersOverwriteParam = "$httpHeaders");
const o = n.join("");
$("Connection", "Creating WebChannel: " + o, r);
const c = s.createWebChannel(o, r);
// WebChannel supports sending the first message with the handshake - saving
// a network round trip. However, it will have to call send in the same
// JS event loop as open. In order to enforce this, we delay actually
// opening the WebChannel until send is called. Whether we have called
// open is tracked with this variable.
let a = !1, u = !1;
// A flag to determine whether the stream was closed (by us or through an
// error/close event) to avoid delivering multiple close events or sending
// on a closed stream
const h = new Gr({
vi: (t)=>{
u ? $("Connection", "Not sending because WebChannel is closed:", t) : (a || ($("Connection", "Opening WebChannel transport."), c.open(), a = !0), $("Connection", "WebChannel sending:", t), c.send(t));
},
Vi: ()=>c.close()
}), g = (t, e, n)=>{
// TODO(dimond): closure typing seems broken because WebChannel does
// not implement goog.events.Listenable
t.listen(e, (t)=>{
try {
n(t);
} catch (t) {
setTimeout(()=>{
throw t;
}, 0);
}
});
};
// Closure events are guarded and exceptions are swallowed, so catch any
// exception and rethrow using a setTimeout so they become visible again.
// Note that eventually this function could go away if we are confident
// enough the code is exception free.
return g(c, _firebase_webchannel_wrapper__WEBPACK_IMPORTED_MODULE_4__ /* .WebChannel.EventType.OPEN */ .ii.EventType.OPEN, ()=>{
u || $("Connection", "WebChannel transport opened.");
}), g(c, _firebase_webchannel_wrapper__WEBPACK_IMPORTED_MODULE_4__ /* .WebChannel.EventType.CLOSE */ .ii.EventType.CLOSE, ()=>{
u || (u = !0, $("Connection", "WebChannel transport closed"), h.$i());
}), g(c, _firebase_webchannel_wrapper__WEBPACK_IMPORTED_MODULE_4__ /* .WebChannel.EventType.ERROR */ .ii.EventType.ERROR, (t)=>{
u || (u = !0, F("Connection", "WebChannel transport errored:", t), h.$i(new j(K.UNAVAILABLE, "The operation could not be completed")));
}), g(c, _firebase_webchannel_wrapper__WEBPACK_IMPORTED_MODULE_4__ /* .WebChannel.EventType.MESSAGE */ .ii.EventType.MESSAGE, (t)=>{
var e;
if (!u) {
const n = t.data[0];
n || L();
// TODO(b/35143891): There is a bug in One Platform that caused errors
// (and only errors) to be wrapped in an extra array. To be forward
// compatible with the bug we need to check either condition. The latter
// can be removed once the fix has been rolled out.
// Use any because msgData.error is not typed.
const i = n.error || (null === (e = n[0]) || void 0 === e ? void 0 : e.error);
if (i) {
$("Connection", "WebChannel received error:", i);
// error.status will be a string like 'OK' or 'NOT_FOUND'.
const t = i.status;
let e = /**
* Maps an error Code from a GRPC status identifier like 'NOT_FOUND'.
*
* @returns The Code equivalent to the given status string or undefined if
* there is no match.
*/ function(t) {
// lookup by string
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const e = hn[t];
if (void 0 !== e) return dn(e);
}(t), n = i.message;
void 0 === e && (e = K.INTERNAL, n = "Unknown error status: " + t + " with message " + i.message), // Mark closed so no further events are propagated
u = !0, h.$i(new j(e, n)), c.close();
} else $("Connection", "WebChannel received:", n), h.Oi(n);
}
}), g(i, _firebase_webchannel_wrapper__WEBPACK_IMPORTED_MODULE_4__ /* .Event.STAT_EVENT */ .ju.STAT_EVENT, (t)=>{
t.stat === _firebase_webchannel_wrapper__WEBPACK_IMPORTED_MODULE_4__ /* .Stat.PROXY */ .kN.PROXY ? $("Connection", "Detected buffering proxy") : t.stat === _firebase_webchannel_wrapper__WEBPACK_IMPORTED_MODULE_4__ /* .Stat.NOPROXY */ .kN.NOPROXY && $("Connection", "Detected no buffering proxy");
}), setTimeout(()=>{
// Technically we could/should wait for the WebChannel opened event,
// but because we want to send the first message with the WebChannel
// handshake we pretend the channel opened here (asynchronously), and
// then delay the actual open until the first message is sent.
h.ki();
}, 0), h;
}
}
/** The Platform's 'document' implementation or null if not available. */ function Jr() {
// `document` is not always available, e.g. in ReactNative and WebWorkers.
// eslint-disable-next-line no-restricted-globals
return "undefined" != typeof document ? document : null;
}
/**
* An instance of the Platform's 'TextEncoder' implementation.
*/ /**
* A helper for running delayed tasks following an exponential backoff curve
* between attempts.
*
* Each delay is made up of a "base" delay which follows the exponential
* backoff curve, and a +/- 50% "jitter" that is calculated and added to the
* base delay. This prevents clients from accidentally synchronizing their
* delays causing spikes of load to the backend.
*/ class Xr {
constructor(/**
* The AsyncQueue to run backoff operations on.
*/ t, /**
* The ID to use when scheduling backoff operations on the AsyncQueue.
*/ e, /**
* The initial delay (used as the base delay on the first retry attempt).
* Note that jitter will still be applied, so the actual delay could be as
* little as 0.5*initialDelayMs.
*/ n = 1e3, /**
* The multiplier to use to determine the extended base delay after each
* attempt.
*/ s = 1.5, /**
* The maximum base delay after which no further backoff is performed.
* Note that jitter will still be applied, so the actual delay could be as
* much as 1.5*maxDelayMs.
*/ i = 6e4){
this.Oe = t, this.timerId = e, this.Qi = n, this.Wi = s, this.Gi = i, this.zi = 0, this.Hi = null, /** The last backoff attempt, as epoch milliseconds. */ this.Ji = Date.now(), this.reset();
}
/**
* Resets the backoff delay.
*
* The very next backoffAndWait() will have no delay. If it is called again
* (i.e. due to an error), initialDelayMs (plus jitter) will be used, and
* subsequent ones will increase according to the backoffFactor.
*/ reset() {
this.zi = 0;
}
/**
* Resets the backoff delay to the maximum delay (e.g. for use after a
* RESOURCE_EXHAUSTED error).
*/ Yi() {
this.zi = this.Gi;
}
/**
* Returns a promise that resolves after currentDelayMs, and increases the
* delay for any subsequent attempts. If there was a pending backoff operation
* already, it will be canceled.
*/ Xi(t) {
// Cancel any pending backoff operation.
this.cancel();
// First schedule using the current base (which may be 0 and should be
// honored as such).
const e = Math.floor(this.zi + this.Zi()), n = Math.max(0, Date.now() - this.Ji), s = Math.max(0, e - n);
// Guard against lastAttemptTime being in the future due to a clock change.
s > 0 && $("ExponentialBackoff", `Backing off for ${s} ms (base delay: ${this.zi} ms, delay with jitter: ${e} ms, last attempt: ${n} ms ago)`), this.Hi = this.Oe.enqueueAfterDelay(this.timerId, s, ()=>(this.Ji = Date.now(), t())), // Apply backoff factor to determine next delay and ensure it is within
// bounds.
this.zi *= this.Wi, this.zi < this.Qi && (this.zi = this.Qi), this.zi > this.Gi && (this.zi = this.Gi);
}
tr() {
null !== this.Hi && (this.Hi.skipDelay(), this.Hi = null);
}
cancel() {
null !== this.Hi && (this.Hi.cancel(), this.Hi = null);
}
/** Returns a random value in the range [-currentBaseMs/2, currentBaseMs/2] */ Zi() {
return (Math.random() - 0.5) * this.zi;
}
}
/**
* @license
* Copyright 2017 Google 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.
*/ /**
* A PersistentStream is an abstract base class that represents a streaming RPC
* to the Firestore backend. It's built on top of the connections own support
* for streaming RPCs, and adds several critical features for our clients:
*
* - Exponential backoff on failure
* - Authentication via CredentialsProvider
* - Dispatching all callbacks into the shared worker queue
* - Closing idle streams after 60 seconds of inactivity
*
* Subclasses of PersistentStream implement serialization of models to and
* from the JSON representation of the protocol buffers for a specific
* streaming RPC.
*
* ## Starting and Stopping
*
* Streaming RPCs are stateful and need to be start()ed before messages can
* be sent and received. The PersistentStream will call the onOpen() function
* of the listener once the stream is ready to accept requests.
*
* Should a start() fail, PersistentStream will call the registered onClose()
* listener with a FirestoreError indicating what went wrong.
*
* A PersistentStream can be started and stopped repeatedly.
*
* Generic types:
* SendType: The type of the outgoing message of the underlying
* connection stream
* ReceiveType: The type of the incoming message of the underlying
* connection stream
* ListenerType: The type of the listener that will be used for callbacks
*/ class Zr {
constructor(t, e, n, s, i, r, o){
this.Oe = t, this.er = n, this.nr = s, this.sr = i, this.credentialsProvider = r, this.listener = o, this.state = 0, /**
* A close count that's incremented every time the stream is closed; used by
* getCloseGuardedDispatcher() to invalidate callbacks that happen after
* close.
*/ this.ir = 0, this.rr = null, this.cr = null, this.stream = null, this.ar = new Xr(t, e);
}
/**
* Returns true if start() has been called and no error has occurred. True
* indicates the stream is open or in the process of opening (which
* encompasses respecting backoff, getting auth tokens, and starting the
* actual RPC). Use isOpen() to determine if the stream is open and ready for
* outbound requests.
*/ ur() {
return 1 /* Starting */ === this.state || 5 /* Backoff */ === this.state || this.hr();
}
/**
* Returns true if the underlying RPC is open (the onOpen() listener has been
* called) and the stream is ready for outbound requests.
*/ hr() {
return 2 /* Open */ === this.state || 3 /* Healthy */ === this.state;
}
/**
* Starts the RPC. Only allowed if isStarted() returns false. The stream is
* not immediately ready for use: onOpen() will be invoked when the RPC is
* ready for outbound requests, at which point isOpen() will return true.
*
* When start returns, isStarted() will return true.
*/ start() {
4 /* Error */ !== this.state ? this.auth() : this.lr();
}
/**
* Stops the RPC. This call is idempotent and allowed regardless of the
* current isStarted() state.
*
* When stop returns, isStarted() and isOpen() will both return false.
*/ async stop() {
this.ur() && await this.close(0 /* Initial */ );
}
/**
* After an error the stream will usually back off on the next attempt to
* start it. If the error warrants an immediate restart of the stream, the
* sender can use this to indicate that the receiver should not back off.
*
* Each error will call the onClose() listener. That function can decide to
* inhibit backoff if required.
*/ dr() {
this.state = 0, this.ar.reset();
}
/**
* Marks this stream as idle. If no further actions are performed on the
* stream for one minute, the stream will automatically close itself and
* notify the stream's onClose() handler with Status.OK. The stream will then
* be in a !isStarted() state, requiring the caller to start the stream again
* before further use.
*
* Only streams that are in state 'Open' can be marked idle, as all other
* states imply pending network operations.
*/ wr() {
// Starts the idle time if we are in state 'Open' and are not yet already
// running a timer (in which case the previous idle timeout still applies).
this.hr() && null === this.rr && (this.rr = this.Oe.enqueueAfterDelay(this.er, 6e4, ()=>this._r()));
}
/** Sends a message to the underlying stream. */ mr(t) {
this.gr(), this.stream.send(t);
}
/** Called by the idle timer when the stream should close due to inactivity. */ async _r() {
if (this.hr()) // When timing out an idle stream there's no reason to force the stream into backoff when
// it restarts so set the stream state to Initial instead of Error.
return this.close(0 /* Initial */ );
}
/** Marks the stream as active again. */ gr() {
this.rr && (this.rr.cancel(), this.rr = null);
}
/** Cancels the health check delayed operation. */ yr() {
this.cr && (this.cr.cancel(), this.cr = null);
}
/**
* Closes the stream and cleans up as necessary:
*
* * closes the underlying GRPC stream;
* * calls the onClose handler with the given 'error';
* * sets internal stream state to 'finalState';
* * adjusts the backoff timer based on the error
*
* A new stream can be opened by calling start().
*
* @param finalState - the intended state of the stream after closing.
* @param error - the error the connection was closed with.
*/ async close(t, e) {
// Cancel any outstanding timers (they're guaranteed not to execute).
this.gr(), this.yr(), this.ar.cancel(), // Invalidates any stream-related callbacks (e.g. from auth or the
// underlying stream), guaranteeing they won't execute.
this.ir++, 4 /* Error */ !== t ? this.ar.reset() : e && e.code === K.RESOURCE_EXHAUSTED ? (O(e.toString()), O("Using maximum backoff delay to prevent overloading the backend."), this.ar.Yi()) : e && e.code === K.UNAUTHENTICATED && 3 /* Healthy */ !== this.state && // "unauthenticated" error means the token was rejected. This should rarely
// happen since both Auth and AppCheck ensure a sufficient TTL when we
// request a token. If a user manually resets their system clock this can
// fail, however. In this case, we should get a Code.UNAUTHENTICATED error
// before we received the first message and we need to invalidate the token
// to ensure that we fetch a new token.
this.credentialsProvider.invalidateToken(), // Clean up the underlying stream because we are no longer interested in events.
null !== this.stream && (this.pr(), this.stream.close(), this.stream = null), // This state must be assigned before calling onClose() to allow the callback to
// inhibit backoff or otherwise manipulate the state in its non-started state.
this.state = t, // Notify the listener that the stream closed.
await this.listener.Ci(e);
}
/**
* Can be overridden to perform additional cleanup before the stream is closed.
* Calling super.tearDown() is not required.
*/ pr() {}
auth() {
this.state = 1 /* Starting */ ;
const t = this.Tr(this.ir), e = this.ir;
// TODO(mikelehen): Just use dispatchIfNotClosed, but see TODO below.
this.credentialsProvider.getToken().then((t)=>{
// Stream can be stopped while waiting for authentication.
// TODO(mikelehen): We really should just use dispatchIfNotClosed
// and let this dispatch onto the queue, but that opened a spec test can
// of worms that I don't want to deal with in this PR.
this.ir === e && // Normally we'd have to schedule the callback on the AsyncQueue.
// However, the following calls are safe to be called outside the
// AsyncQueue since they don't chain asynchronous calls
this.Er(t);
}, (e)=>{
t(()=>{
const t = new j(K.UNKNOWN, "Fetching auth token failed: " + e.message);
return this.Ir(t);
});
});
}
Er(t) {
const e = this.Tr(this.ir);
this.stream = this.Ar(t), this.stream.Si(()=>{
e(()=>(this.state = 2, this.cr = this.Oe.enqueueAfterDelay(this.nr, 1e4, ()=>(this.hr() && (this.state = 3), Promise.resolve())), this.listener.Si()));
}), this.stream.Ci((t)=>{
e(()=>this.Ir(t));
}), this.stream.onMessage((t)=>{
e(()=>this.onMessage(t));
});
}
lr() {
this.state = 5, this.ar.Xi(async ()=>{
this.state = 0, this.start();
});
}
// Visible for tests
Ir(t) {
// In theory the stream could close cleanly, however, in our current model
// we never expect this to happen because if we stop a stream ourselves,
// this callback will never be called. To prevent cases where we retry
// without a backoff accidentally, we set the stream to error in all cases.
return $("PersistentStream", `close with error: ${t}`), this.stream = null, this.close(4 /* Error */ , t);
}
/**
* Returns a "dispatcher" function that dispatches operations onto the
* AsyncQueue but only runs them if closeCount remains unchanged. This allows
* us to turn auth / stream callbacks into no-ops if the stream is closed /
* re-opened, etc.
*/ Tr(t) {
return (e)=>{
this.Oe.enqueueAndForget(()=>this.ir === t ? e() : ($("PersistentStream", "stream callback skipped by getCloseGuardedDispatcher."), Promise.resolve()));
};
}
}
/**
* A PersistentStream that implements the Listen RPC.
*
* Once the Listen stream has called the onOpen() listener, any number of
* listen() and unlisten() calls can be made to control what changes will be
* sent from the server for ListenResponses.
*/ class to extends Zr {
constructor(t, e, n, s, i){
super(t, "listen_stream_connection_backoff" /* ListenStreamConnectionBackoff */ , "listen_stream_idle" /* ListenStreamIdle */ , "health_check_timeout" /* HealthCheckTimeout */ , e, n, i), this.N = s;
}
Ar(t) {
return this.sr.ji("Listen", t);
}
onMessage(t) {
// A successful response means the stream is healthy
this.ar.reset();
const e = function(t, e) {
let n;
if ("targetChange" in e) {
var t1, e1;
e.targetChange;
// proto3 default value is unset in JSON (undefined), so use 'NO_CHANGE'
// if unset
const s = "NO_CHANGE" === (t1 = e.targetChange.targetChangeType || "NO_CHANGE") ? 0 /* NoChange */ : "ADD" === t1 ? 1 /* Added */ : "REMOVE" === t1 ? 2 /* Removed */ : "CURRENT" === t1 ? 3 /* Current */ : "RESET" === t1 ? 4 /* Reset */ : L(), i = e.targetChange.targetIds || [], r = (e1 = e.targetChange.resumeToken, t.D ? (void 0 === e1 || "string" == typeof e1 || L(), _t.fromBase64String(e1 || "")) : (void 0 === e1 || e1 instanceof Uint8Array || L(), _t.fromUint8Array(e1 || new Uint8Array()))), o = e.targetChange.cause;
n = new xn(s, i, r, o && new j(void 0 === /**
* Returns a value for a number (or null) that's appropriate to put into
* a google.protobuf.Int32Value proto.
* DO NOT USE THIS FOR ANYTHING ELSE.
* This method cheats. It's typed as returning "number" because that's what
* our generated proto interfaces say Int32Value must be. But GRPC actually
* expects a { value: <number> } struct.
*/ o.code ? K.UNKNOWN : dn(o.code), o.message || "") || null);
} else if ("documentChange" in e) {
e.documentChange;
const s = e.documentChange;
s.document, s.document.name, s.document.updateTime;
const i = zn(t, s.document.name), r = jn(s.document.updateTime), o = new Ut({
mapValue: {
fields: s.document.fields
}
}), c = Kt.newFoundDocument(i, r, o);
n = new Cn(s.targetIds || [], s.removedTargetIds || [], c.key, c);
} else if ("documentDelete" in e) {
e.documentDelete;
const s = e.documentDelete;
s.document;
const i = zn(t, s.document), r = s.readTime ? jn(s.readTime) : rt.min(), o = Kt.newNoDocument(i, r);
n = new Cn([], s.removedTargetIds || [], o.key, o);
} else if ("documentRemove" in e) {
e.documentRemove;
const s = e.documentRemove;
s.document;
const i = zn(t, s.document);
n = new Cn([], s.removedTargetIds || [], i, null);
} else {
if (!("filter" in e)) return L();
{
e.filter;
const t = e.filter;
t.targetId;
const i = new un(t.count || 0);
n = new Nn(t.targetId, i);
}
}
return n;
}(this.N, t), n = function(t) {
// We have only reached a consistent snapshot for the entire stream if there
// is a read_time set and it applies to all targets (i.e. the list of
// targets is empty). The backend is guaranteed to send such responses.
if (!("targetChange" in t)) return rt.min();
const e = t.targetChange;
return e.targetIds && e.targetIds.length ? rt.min() : e.readTime ? jn(e.readTime) : rt.min();
}(t);
return this.listener.Rr(e, n);
}
/**
* Registers interest in the results of the given target. If the target
* includes a resumeToken it will be included in the request. Results that
* affect the target will be streamed back as WatchChange messages that
* reference the targetId.
*/ br(t) {
const e = {};
e.database = Yn(this.N), e.addTarget = function(t, e) {
var e1, e2;
let n;
const s = e.target;
return (n = Ht(s) ? {
documents: {
documents: [
Hn(t, s.path)
]
}
} : {
query: function(t, e) {
var e1;
// Dissect the path into parent, collectionId, and optional key filter.
const n = {
structuredQuery: {}
}, s = e.path;
null !== e.collectionGroup ? (n.parent = Hn(t, s), n.structuredQuery.from = [
{
collectionId: e.collectionGroup,
allDescendants: !0
}
]) : (n.parent = Hn(t, s.popLast()), n.structuredQuery.from = [
{
collectionId: s.lastSegment()
}
]);
const i = function(t) {
if (0 === t.length) return;
const e = t.map((t)=>// visible for testing
(function(t) {
if ("==" /* EQUAL */ === t.op) {
if (Mt(t.value)) return {
unaryFilter: {
field: _s(t.field),
op: "IS_NAN"
}
};
if (Ft(t.value)) return {
unaryFilter: {
field: _s(t.field),
op: "IS_NULL"
}
};
} else if ("!=" /* NOT_EQUAL */ === t.op) {
if (Mt(t.value)) return {
unaryFilter: {
field: _s(t.field),
op: "IS_NOT_NAN"
}
};
if (Ft(t.value)) return {
unaryFilter: {
field: _s(t.field),
op: "IS_NOT_NULL"
}
};
}
return {
fieldFilter: {
field: _s(t.field),
op: Ln[t.op],
value: t.value
}
};
})(t));
return 1 === e.length ? e[0] : {
compositeFilter: {
op: "AND",
filters: e
}
};
}(e.filters);
i && (n.structuredQuery.where = i);
const r = function(t) {
if (0 !== t.length) return t.map((t)=>({
field: _s(t.field),
direction: Mn[t.dir]
}));
}(e.orderBy);
r && (n.structuredQuery.orderBy = r);
const o = (e1 = e.limit, /**
* Returns a number (or null) from a google.protobuf.Int32Value proto.
*/ t.D || At(e1) ? e1 : {
value: e1
});
return null !== o && (n.structuredQuery.limit = o), e.startAt && (n.structuredQuery.startAt = ls(e.startAt)), e.endAt && (n.structuredQuery.endAt = ls(e.endAt)), n;
}(t, s)
}).targetId = e.targetId, e.resumeToken.approximateByteSize() > 0 ? (e1 = e.resumeToken, n.resumeToken = t.D ? e1.toBase64() : e1.toUint8Array()) : e.snapshotVersion.compareTo(rt.min()) > 0 && (e2 = e.snapshotVersion.toTimestamp(), // TODO(wuandy): Consider removing above check because it is most likely true.
// Right now, many tests depend on this behaviour though (leaving min() out
// of serialization).
n.readTime = t.D ? `${new Date(1e3 * e2.seconds).toISOString().replace(/\.\d*/, "").replace("Z", "")}.${("000000000" + e2.nanoseconds).slice(-9)}Z` : {
seconds: "" + e2.seconds,
nanos: e2.nanoseconds
}), n;
}(this.N, t);
const n = function(t, e) {
const n = function(t, e) {
switch(e){
case 0 /* Listen */ :
return null;
case 1 /* ExistenceFilterMismatch */ :
return "existence-filter-mismatch";
case 2 /* LimboResolution */ :
return "limbo-document";
default:
return L();
}
}(0, e.purpose);
return null == n ? null : {
"goog-listen-tags": n
};
}(this.N, t);
n && (e.labels = n), this.mr(e);
}
/**
* Unregisters interest in the results of the target associated with the
* given targetId.
*/ Pr(t) {
const e = {};
e.database = Yn(this.N), e.removeTarget = t, this.mr(e);
}
}
/**
* @license
* Copyright 2017 Google 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.
*/ /**
* Datastore and its related methods are a wrapper around the external Google
* Cloud Datastore grpc API, which provides an interface that is more convenient
* for the rest of the client SDK architecture to consume.
*/ /**
* An implementation of Datastore that exposes additional state for internal
* consumption.
*/ class no extends class {
} {
constructor(t, e, n){
super(), this.credentials = t, this.sr = e, this.N = n, this.kr = !1;
}
$r() {
if (this.kr) throw new j(K.FAILED_PRECONDITION, "The client has already been terminated.");
}
/** Gets an auth token and invokes the provided RPC. */ Li(t, e, n) {
return this.$r(), this.credentials.getToken().then((s)=>this.sr.Li(t, e, n, s)).catch((t)=>{
throw "FirebaseError" === t.name ? (t.code === K.UNAUTHENTICATED && this.credentials.invalidateToken(), t) : new j(K.UNKNOWN, t.toString());
});
}
/** Gets an auth token and invokes the provided RPC with streamed results. */ Ki(t, e, n) {
return this.$r(), this.credentials.getToken().then((s)=>this.sr.Ki(t, e, n, s)).catch((t)=>{
throw "FirebaseError" === t.name ? (t.code === K.UNAUTHENTICATED && this.credentials.invalidateToken(), t) : new j(K.UNKNOWN, t.toString());
});
}
terminate() {
this.kr = !0;
}
}
// TODO(firestorexp): Make sure there is only one Datastore instance per
// firestore-exp client.
/**
* A component used by the RemoteStore to track the OnlineState (that is,
* whether or not the client as a whole should be considered to be online or
* offline), implementing the appropriate heuristics.
*
* In particular, when the client is trying to connect to the backend, we
* allow up to MAX_WATCH_STREAM_FAILURES within ONLINE_STATE_TIMEOUT_MS for
* a connection to succeed. If we have too many failures or the timeout elapses,
* then we set the OnlineState to Offline, and the client will behave as if
* it is offline (get()s will return cached data, etc.).
*/ class so {
constructor(t, e){
this.asyncQueue = t, this.onlineStateHandler = e, /** The current OnlineState. */ this.state = "Unknown", /**
* A count of consecutive failures to open the stream. If it reaches the
* maximum defined by MAX_WATCH_STREAM_FAILURES, we'll set the OnlineState to
* Offline.
*/ this.Or = 0, /**
* A timer that elapses after ONLINE_STATE_TIMEOUT_MS, at which point we
* transition from OnlineState.Unknown to OnlineState.Offline without waiting
* for the stream to actually fail (MAX_WATCH_STREAM_FAILURES times).
*/ this.Fr = null, /**
* Whether the client should log a warning message if it fails to connect to
* the backend (initially true, cleared after a successful stream, or if we've
* logged the message already).
*/ this.Mr = !0;
}
/**
* Called by RemoteStore when a watch stream is started (including on each
* backoff attempt).
*
* If this is the first attempt, it sets the OnlineState to Unknown and starts
* the onlineStateTimer.
*/ Lr() {
0 === this.Or && (this.Br("Unknown" /* Unknown */ ), this.Fr = this.asyncQueue.enqueueAfterDelay("online_state_timeout" /* OnlineStateTimeout */ , 1e4, ()=>(this.Fr = null, this.Ur("Backend didn't respond within 10 seconds."), this.Br("Offline" /* Offline */ ), Promise.resolve())));
}
/**
* Updates our OnlineState as appropriate after the watch stream reports a
* failure. The first failure moves us to the 'Unknown' state. We then may
* allow multiple failures (based on MAX_WATCH_STREAM_FAILURES) before we
* actually transition to the 'Offline' state.
*/ qr(t) {
"Online" /* Online */ === this.state ? this.Br("Unknown" /* Unknown */ ) : (this.Or++, this.Or >= 1 && (this.Kr(), this.Ur(`Connection failed 1 times. Most recent error: ${t.toString()}`), this.Br("Offline" /* Offline */ )));
}
/**
* Explicitly sets the OnlineState to the specified state.
*
* Note that this resets our timers / failure counters, etc. used by our
* Offline heuristics, so must not be used in place of
* handleWatchStreamStart() and handleWatchStreamFailure().
*/ set(t) {
this.Kr(), this.Or = 0, "Online" /* Online */ === t && // We've connected to watch at least once. Don't warn the developer
// about being offline going forward.
(this.Mr = !1), this.Br(t);
}
Br(t) {
t !== this.state && (this.state = t, this.onlineStateHandler(t));
}
Ur(t) {
const e = `Could not reach Cloud Firestore backend. ${t}\nThis typically indicates that your device does not have a healthy Internet connection at the moment. The client will operate in offline mode until it is able to successfully connect to the backend.`;
this.Mr ? (O(e), this.Mr = !1) : $("OnlineStateTracker", e);
}
Kr() {
null !== this.Fr && (this.Fr.cancel(), this.Fr = null);
}
}
/**
* @license
* Copyright 2017 Google 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.
*/ class io {
constructor(/**
* The local store, used to fill the write pipeline with outbound mutations.
*/ t, /** The client-side proxy for interacting with the backend. */ e, n, s, i){
this.localStore = t, this.datastore = e, this.asyncQueue = n, this.remoteSyncer = {}, /**
* A list of up to MAX_PENDING_WRITES writes that we have fetched from the
* LocalStore via fillWritePipeline() and have or will send to the write
* stream.
*
* Whenever writePipeline.length > 0 the RemoteStore will attempt to start or
* restart the write stream. When the stream is established the writes in the
* pipeline will be sent in order.
*
* Writes remain in writePipeline until they are acknowledged by the backend
* and thus will automatically be re-sent if the stream is interrupted /
* restarted before they're acknowledged.
*
* Write responses from the backend are linked to their originating request
* purely based on order, and so we can just shift() writes from the front of
* the writePipeline as we receive responses.
*/ this.jr = [], /**
* A mapping of watched targets that the client cares about tracking and the
* user has explicitly called a 'listen' for this target.
*
* These targets may or may not have been sent to or acknowledged by the
* server. On re-establishing the listen stream, these targets should be sent
* to the server. The targets removed with unlistens are removed eagerly
* without waiting for confirmation from the listen stream.
*/ this.Qr = new Map(), /**
* A set of reasons for why the RemoteStore may be offline. If empty, the
* RemoteStore may start its network connections.
*/ this.Wr = new Set(), /**
* Event handlers that get called when the network is disabled or enabled.
*
* PORTING NOTE: These functions are used on the Web client to create the
* underlying streams (to support tree-shakeable streams). On Android and iOS,
* the streams are created during construction of RemoteStore.
*/ this.Gr = [], this.zr = i, this.zr.Ti((t)=>{
n.enqueueAndForget(async ()=>{
// Porting Note: Unlike iOS, `restartNetwork()` is called even when the
// network becomes unreachable as we don't have any other way to tear
// down our streams.
wo(this) && ($("RemoteStore", "Restarting streams for network reachability change."), await async function(t) {
t.Wr.add(4 /* ConnectivityChange */ ), await oo(t), t.Hr.set("Unknown" /* Unknown */ ), t.Wr.delete(4 /* ConnectivityChange */ ), await ro(t);
}(this));
});
}), this.Hr = new so(n, s);
}
}
async function ro(t) {
if (wo(t)) for (const e of t.Gr)await e(/* enabled= */ !0);
}
/**
* Temporarily disables the network. The network can be re-enabled using
* enableNetwork().
*/ async function oo(t) {
for (const e of t.Gr)await e(/* enabled= */ !1);
}
/**
* Starts new listen for the given target. Uses resume token if provided. It
* is a no-op if the target of given `TargetData` is already being listened to.
*/ function co(t, e) {
t.Qr.has(e.targetId) || // Mark this as something the client is currently listening for.
(t.Qr.set(e.targetId, e), fo(t) ? lo(t) : Co(t).hr() && uo(t, e));
}
/**
* Removes the listen from server. It is a no-op if the given target id is
* not being listened to.
*/ function ao(t, e) {
const s = Co(t);
t.Qr.delete(e), s.hr() && ho(t, e), 0 === t.Qr.size && (s.hr() ? s.wr() : wo(t) && // Revert to OnlineState.Unknown if the watch stream is not open and we
// have no listeners, since without any listens to send we cannot
// confirm if the stream is healthy and upgrade to OnlineState.Online.
t.Hr.set("Unknown" /* Unknown */ ));
}
/**
* We need to increment the the expected number of pending responses we're due
* from watch so we wait for the ack to process any messages from this target.
*/ function uo(t, e) {
t.Jr.Y(e.targetId), Co(t).br(e);
}
/**
* We need to increment the expected number of pending responses we're due
* from watch so we wait for the removal on the server before we process any
* messages from this target.
*/ function ho(t, e) {
t.Jr.Y(e), Co(t).Pr(e);
}
function lo(t) {
t.Jr = new $n({
getRemoteKeysForTarget: (e)=>t.remoteSyncer.getRemoteKeysForTarget(e),
Tt: (e)=>t.Qr.get(e) || null
}), Co(t).start(), t.Hr.Lr();
}
/**
* Returns whether the watch stream should be started because it's necessary
* and has not yet been started.
*/ function fo(t) {
return wo(t) && !Co(t).ur() && t.Qr.size > 0;
}
function wo(t) {
return 0 === t.Wr.size;
}
async function mo(t) {
t.Qr.forEach((e, n)=>{
uo(t, e);
});
}
async function go(t, e) {
t.Jr = void 0, // If we still need the watch stream, retry the connection.
fo(t) ? (t.Hr.qr(e), lo(t)) : // The online state is set to unknown because there is no active attempt
// at establishing a connection
t.Hr.set("Unknown" /* Unknown */ );
}
async function yo(t, e, n) {
if (// Mark the client as online since we got a message from the server
t.Hr.set("Online" /* Online */ ), e instanceof xn && 2 /* Removed */ === e.state && e.cause) // There was an error on a target, don't wait for a consistent snapshot
// to raise events
try {
await /** Handles an error on a target */ async function(t, e) {
const n = e.cause;
// A watched target might have been removed already.
for (const s of e.targetIds)t.Qr.has(s) && (await t.remoteSyncer.rejectListen(s, n), t.Qr.delete(s), t.Jr.removeTarget(s));
}(/**
* Attempts to fill our write pipeline with writes from the LocalStore.
*
* Called internally to bootstrap or refill the write pipeline and by
* SyncEngine whenever there are new mutations to process.
*
* Starts the write stream if necessary.
*/ t, e);
} catch (n) {
$("RemoteStore", "Failed to remove targets %s: %s ", e.targetIds.join(","), n), await po(t, n);
}
else if (e instanceof Cn ? t.Jr.rt(e) : e instanceof Nn ? t.Jr.ft(e) : t.Jr.at(e), !n.isEqual(rt.min())) try {
const e = await fr(t.localStore);
n.compareTo(e) >= 0 && // We have received a target change with a global snapshot if the snapshot
// version is not equal to SnapshotVersion.min().
await /**
* Takes a batch of changes from the Datastore, repackages them as a
* RemoteEvent, and passes that on to the listener, which is typically the
* SyncEngine.
*/ function(t, e) {
const n = t.Jr._t(e);
// Update in-memory resume tokens. LocalStore will update the
// persistent view of these when applying the completed RemoteEvent.
return n.targetChanges.forEach((n, s)=>{
if (n.resumeToken.approximateByteSize() > 0) {
const i = t.Qr.get(s);
// A watched target might have been removed already.
i && t.Qr.set(s, i.withResumeToken(n.resumeToken, e));
}
}), // Re-establish listens for the targets that have been invalidated by
// existence filter mismatches.
n.targetMismatches.forEach((e)=>{
const n = t.Qr.get(e);
if (!n) // A watched target might have been removed already.
return;
// Clear the resume token for the target, since we're in a known mismatch
// state.
t.Qr.set(e, n.withResumeToken(_t.EMPTY_BYTE_STRING, n.snapshotVersion)), // Cause a hard reset by unwatching and rewatching immediately, but
// deliberately don't send a resume token so that we get a full update.
ho(t, e);
// Mark the target we send as being on behalf of an existence filter
// mismatch, but don't actually retain that in listenTargets. This ensures
// that we flag the first re-listen this way without impacting future
// listens of this target (that might happen e.g. on reconnect).
const s = new ii(n.target, e, 1 /* ExistenceFilterMismatch */ , n.sequenceNumber);
uo(t, s);
}), t.remoteSyncer.applyRemoteEvent(n);
}(t, n);
} catch (e) {
$("RemoteStore", "Failed to raise snapshot:", e), await po(t, e);
}
}
/**
* Recovery logic for IndexedDB errors that takes the network offline until
* `op` succeeds. Retries are scheduled with backoff using
* `enqueueRetryable()`. If `op()` is not provided, IndexedDB access is
* validated via a generic operation.
*
* The returned Promise is resolved once the network is disabled and before
* any retry attempt.
*/ async function po(t, e, n) {
if (!Hs(e)) throw e;
t.Wr.add(1 /* IndexedDbFailed */ ), // Disable network and raise offline snapshots
await oo(t), t.Hr.set("Offline" /* Offline */ ), n || // Use a simple read operation to determine if IndexedDB recovered.
// Ideally, we would expose a health check directly on SimpleDb, but
// RemoteStore only has access to persistence through LocalStore.
(n = ()=>fr(t.localStore)), // Probe IndexedDB periodically and re-enable network
t.asyncQueue.enqueueRetryable(async ()=>{
$("RemoteStore", "Retrying IndexedDB access"), await n(), t.Wr.delete(1 /* IndexedDbFailed */ ), await ro(t);
});
}
/**
* Toggles the network state when the client gains or loses its primary lease.
*/ async function Do(t, e) {
e ? (t.Wr.delete(2 /* IsSecondary */ ), await ro(t)) : e || (t.Wr.add(2 /* IsSecondary */ ), await oo(t), t.Hr.set("Unknown" /* Unknown */ ));
}
/**
* If not yet initialized, registers the WatchStream and its network state
* callback with `remoteStoreImpl`. Returns the existing stream if one is
* already available.
*
* PORTING NOTE: On iOS and Android, the WatchStream gets registered on startup.
* This is not done on Web to allow it to be tree-shaken.
*/ function Co(t) {
var t1, e, n;
return t.Yr || // Create stream (but note that it is not started yet).
(t1 = /**
* @license
* Copyright 2018 Google 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.
*/ t.datastore, e = t.asyncQueue, n = {
Si: mo.bind(null, t),
Ci: go.bind(null, t),
Rr: yo.bind(null, t)
}, t1.$r(), t.Yr = new to(e, t1.sr, t1.credentials, t1.N, n), t.Gr.push(async (e)=>{
e ? (t.Yr.dr(), fo(t) ? lo(t) : t.Hr.set("Unknown" /* Unknown */ )) : (await t.Yr.stop(), t.Jr = void 0);
})), t.Yr;
}
/**
* @license
* Copyright 2017 Google 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.
*/ /**
* Represents an operation scheduled to be run in the future on an AsyncQueue.
*
* It is created via DelayedOperation.createAndSchedule().
*
* Supports cancellation (via cancel()) and early execution (via skipDelay()).
*
* Note: We implement `PromiseLike` instead of `Promise`, as the `Promise` type
* in newer versions of TypeScript defines `finally`, which is not available in
* IE.
*/ class xo {
constructor(t, e, n, s, i){
this.asyncQueue = t, this.timerId = e, this.targetTimeMs = n, this.op = s, this.removalCallback = i, this.deferred = new Q(), this.then = this.deferred.promise.then.bind(this.deferred.promise), // It's normal for the deferred promise to be canceled (due to cancellation)
// and so we attach a dummy catch callback to avoid
// 'UnhandledPromiseRejectionWarning' log spam.
this.deferred.promise.catch((t)=>{});
}
/**
* Creates and returns a DelayedOperation that has been scheduled to be
* executed on the provided asyncQueue after the provided delayMs.
*
* @param asyncQueue - The queue to schedule the operation on.
* @param id - A Timer ID identifying the type of operation this is.
* @param delayMs - The delay (ms) before the operation should be scheduled.
* @param op - The operation to run.
* @param removalCallback - A callback to be called synchronously once the
* operation is executed or canceled, notifying the AsyncQueue to remove it
* from its delayedOperations list.
* PORTING NOTE: This exists to prevent making removeDelayedOperation() and
* the DelayedOperation class public.
*/ static createAndSchedule(t, e, n, s, i) {
const o = new xo(t, e, Date.now() + n, s, i);
return o.start(n), o;
}
/**
* Starts the timer. This is called immediately after construction by
* createAndSchedule().
*/ start(t) {
this.timerHandle = setTimeout(()=>this.handleDelayElapsed(), t);
}
/**
* Queues the operation to run immediately (if it hasn't already been run or
* canceled).
*/ skipDelay() {
return this.handleDelayElapsed();
}
/**
* Cancels the operation if it hasn't already been executed or canceled. The
* promise will be rejected.
*
* As long as the operation has not yet been run, calling cancel() provides a
* guarantee that the operation will not be run.
*/ cancel(t) {
null !== this.timerHandle && (this.clearTimeout(), this.deferred.reject(new j(K.CANCELLED, "Operation cancelled" + (t ? ": " + t : ""))));
}
handleDelayElapsed() {
this.asyncQueue.enqueueAndForget(()=>null !== this.timerHandle ? (this.clearTimeout(), this.op().then((t)=>this.deferred.resolve(t))) : Promise.resolve());
}
clearTimeout() {
null !== this.timerHandle && (this.removalCallback(this), clearTimeout(this.timerHandle), this.timerHandle = null);
}
}
/**
* Returns a FirestoreError that can be surfaced to the user if the provided
* error is an IndexedDbTransactionError. Re-throws the error otherwise.
*/ function ko(t, e) {
if (O("AsyncQueue", `${e}: ${t}`), Hs(t)) return new j(K.UNAVAILABLE, `${e}: ${t}`);
throw t;
}
/**
* @license
* Copyright 2017 Google 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.
*/ /**
* DocumentSet is an immutable (copy-on-write) collection that holds documents
* in order specified by the provided comparator. We always add a document key
* comparator on top of what is provided to guarantee document equality based on
* the key.
*/ class $o {
/** The default ordering is by key if the comparator is omitted */ constructor(t){
// We are adding document key comparator to the end as it's the only
// guaranteed unique property of a document.
this.comparator = t ? (e, n)=>t(e, n) || Pt.comparator(e.key, n.key) : (t, e)=>Pt.comparator(t.key, e.key), this.keyedMap = En, this.sortedSet = new wn(this.comparator);
}
/**
* Returns an empty copy of the existing DocumentSet, using the same
* comparator.
*/ static emptySet(t) {
return new $o(t.comparator);
}
has(t) {
return null != this.keyedMap.get(t);
}
get(t) {
return this.keyedMap.get(t);
}
first() {
return this.sortedSet.minKey();
}
last() {
return this.sortedSet.maxKey();
}
isEmpty() {
return this.sortedSet.isEmpty();
}
/**
* Returns the index of the provided key in the document set, or -1 if the
* document key is not present in the set;
*/ indexOf(t) {
const e = this.keyedMap.get(t);
return e ? this.sortedSet.indexOf(e) : -1;
}
get size() {
return this.sortedSet.size;
}
/** Iterates documents in order defined by "comparator" */ forEach(t) {
this.sortedSet.inorderTraversal((e, n)=>(t(e), !1));
}
/** Inserts or updates a document with the same key */ add(t) {
// First remove the element if we have it.
const e = this.delete(t.key);
return e.copy(e.keyedMap.insert(t.key, t), e.sortedSet.insert(t, null));
}
/** Deletes a document with a given key */ delete(t) {
const e = this.get(t);
return e ? this.copy(this.keyedMap.remove(t), this.sortedSet.remove(e)) : this;
}
isEqual(t) {
if (!(t instanceof $o) || this.size !== t.size) return !1;
const e = this.sortedSet.getIterator(), n = t.sortedSet.getIterator();
for(; e.hasNext();){
const t = e.getNext().key, s = n.getNext().key;
if (!t.isEqual(s)) return !1;
}
return !0;
}
toString() {
const t = [];
return this.forEach((e)=>{
t.push(e.toString());
}), 0 === t.length ? "DocumentSet ()" : "DocumentSet (\n " + t.join(" \n") + "\n)";
}
copy(t, e) {
const n = new $o();
return n.comparator = this.comparator, n.keyedMap = t, n.sortedSet = e, n;
}
}
/**
* @license
* Copyright 2017 Google 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.
*/ /**
* DocumentChangeSet keeps track of a set of changes to docs in a query, merging
* duplicate events for the same doc.
*/ class Oo {
constructor(){
this.Zr = new wn(Pt.comparator);
}
track(t) {
const e = t.doc.key, n = this.Zr.get(e);
n ? 0 /* Added */ !== t.type && 3 /* Metadata */ === n.type ? this.Zr = this.Zr.insert(e, t) : 3 /* Metadata */ === t.type && 1 /* Removed */ !== n.type ? this.Zr = this.Zr.insert(e, {
type: n.type,
doc: t.doc
}) : 2 /* Modified */ === t.type && 2 /* Modified */ === n.type ? this.Zr = this.Zr.insert(e, {
type: 2 /* Modified */ ,
doc: t.doc
}) : 2 /* Modified */ === t.type && 0 /* Added */ === n.type ? this.Zr = this.Zr.insert(e, {
type: 0 /* Added */ ,
doc: t.doc
}) : 1 /* Removed */ === t.type && 0 /* Added */ === n.type ? this.Zr = this.Zr.remove(e) : 1 /* Removed */ === t.type && 2 /* Modified */ === n.type ? this.Zr = this.Zr.insert(e, {
type: 1 /* Removed */ ,
doc: n.doc
}) : 0 /* Added */ === t.type && 1 /* Removed */ === n.type ? this.Zr = this.Zr.insert(e, {
type: 2 /* Modified */ ,
doc: t.doc
}) : // Added->Added
// Removed->Removed
// Modified->Added
// Removed->Modified
// Metadata->Added
// Removed->Metadata
L() : this.Zr = this.Zr.insert(e, t);
}
eo() {
const t = [];
return this.Zr.inorderTraversal((e, n)=>{
t.push(n);
}), t;
}
}
class Fo {
constructor(t, e, n, s, i, r, o, c){
this.query = t, this.docs = e, this.oldDocs = n, this.docChanges = s, this.mutatedKeys = i, this.fromCache = r, this.syncStateChanged = o, this.excludesMetadataChanges = c;
}
/** Returns a view snapshot as if all documents in the snapshot were added. */ static fromInitialDocuments(t, e, n, s) {
const i = [];
return e.forEach((t)=>{
i.push({
type: 0 /* Added */ ,
doc: t
});
}), new Fo(t, e, $o.emptySet(e), i, n, s, /* syncStateChanged= */ !0, /* excludesMetadataChanges= */ !1);
}
get hasPendingWrites() {
return !this.mutatedKeys.isEmpty();
}
isEqual(t) {
if (!(this.fromCache === t.fromCache && this.syncStateChanged === t.syncStateChanged && this.mutatedKeys.isEqual(t.mutatedKeys) && Ae(this.query, t.query) && this.docs.isEqual(t.docs) && this.oldDocs.isEqual(t.oldDocs))) return !1;
const e = this.docChanges, n = t.docChanges;
if (e.length !== n.length) return !1;
for(let t = 0; t < e.length; t++)if (e[t].type !== n[t].type || !e[t].doc.isEqual(n[t].doc)) return !1;
return !0;
}
}
/**
* @license
* Copyright 2017 Google 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.
*/ /**
* Holds the listeners and the last received ViewSnapshot for a query being
* tracked by EventManager.
*/ class Mo {
constructor(){
this.no = void 0, this.listeners = [];
}
}
class Lo {
constructor(){
this.queries = new ji((t)=>Re(t), Ae), this.onlineState = "Unknown", this.so = new Set();
}
}
async function Bo(t, e) {
const s = e.query;
let i = !1, r = t.queries.get(s);
if (r || (i = !0, r = new Mo()), i) try {
r.no = await t.onListen(s);
} catch (t) {
const n = ko(t, `Initialization of query '${be(e.query)}' failed`);
return void e.onError(n);
}
t.queries.set(s, r), r.listeners.push(e), // Run global snapshot listeners if a consistent snapshot has been emitted.
e.io(t.onlineState), r.no && e.ro(r.no) && jo(t);
}
async function Uo(t, e) {
const s = e.query;
let i = !1;
const r = t.queries.get(s);
if (r) {
const t = r.listeners.indexOf(e);
t >= 0 && (r.listeners.splice(t, 1), i = 0 === r.listeners.length);
}
if (i) return t.queries.delete(s), t.onUnlisten(s);
}
function qo(t, e) {
let s = !1;
for (const t1 of e){
const e = t1.query, i = t.queries.get(e);
if (i) {
for (const e of i.listeners)e.ro(t1) && (s = !0);
i.no = t1;
}
}
s && jo(t);
}
function Ko(t, e, n) {
const i = t.queries.get(e);
if (i) for (const t of i.listeners)t.onError(n);
// Remove all listeners. NOTE: We don't need to call syncEngine.unlisten()
// after an error.
t.queries.delete(e);
}
// Call all global snapshot listeners that have been set.
function jo(t) {
t.so.forEach((t)=>{
t.next();
});
}
/**
* QueryListener takes a series of internal view snapshots and determines
* when to raise the event.
*
* It uses an Observer to dispatch events.
*/ class Qo {
constructor(t, e, n){
this.query = t, this.oo = e, /**
* Initial snapshots (e.g. from cache) may not be propagated to the wrapped
* observer. This flag is set to true once we've actually raised an event.
*/ this.co = !1, this.ao = null, this.onlineState = "Unknown", this.options = n || {};
}
/**
* Applies the new ViewSnapshot to this listener, raising a user-facing event
* if applicable (depending on what changed, whether the user has opted into
* metadata-only changes, etc.). Returns true if a user-facing event was
* indeed raised.
*/ ro(t) {
if (!this.options.includeMetadataChanges) {
// Remove the metadata only changes.
const e = [];
for (const n of t.docChanges)3 /* Metadata */ !== n.type && e.push(n);
t = new Fo(t.query, t.docs, t.oldDocs, e, t.mutatedKeys, t.fromCache, t.syncStateChanged, /* excludesMetadataChanges= */ !0);
}
let e = !1;
return this.co ? this.uo(t) && (this.oo.next(t), e = !0) : this.ho(t, this.onlineState) && (this.lo(t), e = !0), this.ao = t, e;
}
onError(t) {
this.oo.error(t);
}
/** Returns whether a snapshot was raised. */ io(t) {
this.onlineState = t;
let e = !1;
return this.ao && !this.co && this.ho(this.ao, t) && (this.lo(this.ao), e = !0), e;
}
ho(t, e) {
return(// Always raise the first event when we're synced
!t.fromCache || (!this.options.fo || "Offline" /* Offline */ === e) && (!t.docs.isEmpty() || "Offline" /* Offline */ === e));
// Raise data from cache if we have any documents or we are offline
}
uo(t) {
// We don't need to handle includeDocumentMetadataChanges here because
// the Metadata only changes have already been stripped out if needed.
// At this point the only changes we will see are the ones we should
// propagate.
if (t.docChanges.length > 0) return !0;
const e = this.ao && this.ao.hasPendingWrites !== t.hasPendingWrites;
return !(!t.syncStateChanged && !e) && !0 === this.options.includeMetadataChanges;
// Generally we should have hit one of the cases above, but it's possible
// to get here if there were only metadata docChanges and they got
// stripped out.
}
lo(t) {
t = Fo.fromInitialDocuments(t.query, t.docs, t.mutatedKeys, t.fromCache), this.co = !0, this.oo.next(t);
}
}
/**
* Returns a `LoadBundleTaskProgress` representing the progress that the loading
* has succeeded.
*/ /**
* @license
* Copyright 2017 Google 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.
*/ class Jo {
constructor(t){
this.key = t;
}
}
class Yo {
constructor(t){
this.key = t;
}
}
/**
* View is responsible for computing the final merged truth of what docs are in
* a query. It gets notified of local and remote changes to docs, and applies
* the query filters and limits to determine the most correct possible results.
*/ class Xo {
constructor(t, /** Documents included in the remote target */ e){
this.query = t, this.po = e, this.To = null, /**
* A flag whether the view is current with the backend. A view is considered
* current after it has seen the current flag from the backend and did not
* lose consistency within the watch stream (e.g. because of an existence
* filter mismatch).
*/ this.current = !1, /** Documents in the view but not in the remote target */ this.Eo = Pn(), /** Document Keys that have local changes */ this.mutatedKeys = Pn(), this.Io = ve(t), this.Ao = new $o(this.Io);
}
/**
* The set of remote documents that the server has told us belongs to the target associated with
* this view.
*/ get Ro() {
return this.po;
}
/**
* Iterates over a set of doc changes, applies the query limit, and computes
* what the new results should be, what the changes were, and whether we may
* need to go back to the local cache for more results. Does not make any
* changes to the view.
* @param docChanges - The doc changes to apply to this view.
* @param previousChanges - If this is being called with a refill, then start
* with this set of docs and changes instead of the current view.
* @returns a new set of docs, changes, and refill flag.
*/ bo(t, e) {
const n = e ? e.Po : new Oo(), s = e ? e.Ao : this.Ao;
let i = e ? e.mutatedKeys : this.mutatedKeys, r = s, o = !1;
// Track the last doc in a (full) limit. This is necessary, because some
// update (a delete, or an update moving a doc past the old limit) might
// mean there is some other document in the local cache that either should
// come (1) between the old last limit doc and the new last document, in the
// case of updates, or (2) after the new last document, in the case of
// deletes. So we keep this doc at the old limit to compare the updates to.
// Note that this should never get used in a refill (when previousChanges is
// set), because there will only be adds -- no deletes or updates.
const c = _e(this.query) && s.size === this.query.limit ? s.last() : null, a = me(this.query) && s.size === this.query.limit ? s.first() : null;
// Drop documents out to meet limit/limitToLast requirement.
if (t.inorderTraversal((t, e)=>{
const u = s.get(t), h = Pe(this.query, e) ? e : null, l = !!u && this.mutatedKeys.has(u.key), f = !!h && (h.hasLocalMutations || // We only consider committed mutations for documents that were
// mutated during the lifetime of the view.
this.mutatedKeys.has(h.key) && h.hasCommittedMutations);
let d = !1;
u && h ? u.data.isEqual(h.data) ? l !== f && (n.track({
type: 3 /* Metadata */ ,
doc: h
}), d = !0) : this.vo(u, h) || (n.track({
type: 2 /* Modified */ ,
doc: h
}), d = !0, (c && this.Io(h, c) > 0 || a && 0 > this.Io(h, a)) && // This doc moved from inside the limit to outside the limit.
// That means there may be some other doc in the local cache
// that should be included instead.
(o = !0)) : !u && h ? (n.track({
type: 0 /* Added */ ,
doc: h
}), d = !0) : u && !h && (n.track({
type: 1 /* Removed */ ,
doc: u
}), d = !0, (c || a) && // A doc was removed from a full limit query. We'll need to
// requery from the local cache to see if we know about some other
// doc that should be in the results.
(o = !0)), d && (h ? (r = r.add(h), i = f ? i.add(t) : i.delete(t)) : (r = r.delete(t), i = i.delete(t)));
}), _e(this.query) || me(this.query)) for(; r.size > this.query.limit;){
const t = _e(this.query) ? r.last() : r.first();
r = r.delete(t.key), i = i.delete(t.key), n.track({
type: 1 /* Removed */ ,
doc: t
});
}
return {
Ao: r,
Po: n,
Ln: o,
mutatedKeys: i
};
}
vo(t, e) {
// We suppress the initial change event for documents that were modified as
// part of a write acknowledgment (e.g. when the value of a server transform
// is applied) as Watch will send us the same document again.
// By suppressing the event, we only raise two user visible events (one with
// `hasPendingWrites` and the final state of the document) instead of three
// (one with `hasPendingWrites`, the modified document with
// `hasPendingWrites` and the final state of the document).
return t.hasLocalMutations && e.hasCommittedMutations && !e.hasLocalMutations;
}
/**
* Updates the view with the given ViewDocumentChanges and optionally updates
* limbo docs and sync state from the provided target change.
* @param docChanges - The set of changes to make to the view's docs.
* @param updateLimboDocuments - Whether to update limbo documents based on
* this change.
* @param targetChange - A target change to apply for computing limbo docs and
* sync state.
* @returns A new ViewChange with the given docs, changes, and sync state.
*/ // PORTING NOTE: The iOS/Android clients always compute limbo document changes.
applyChanges(t, e, n) {
const s = this.Ao;
this.Ao = t.Ao, this.mutatedKeys = t.mutatedKeys;
// Sort changes based on type and query comparator
const i = t.Po.eo();
i.sort((t, e)=>(function(t, e) {
const n = (t)=>{
switch(t){
case 0 /* Added */ :
return 1;
case 2 /* Modified */ :
case 3 /* Metadata */ :
// A metadata change is converted to a modified change at the public
// api layer. Since we sort by document key and then change type,
// metadata and modified changes must be sorted equivalently.
return 2;
case 1 /* Removed */ :
return 0;
default:
return L();
}
};
return n(t) - n(e);
})(/**
* @license
* Copyright 2020 Google 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.
*/ t.type, e.type) || this.Io(t.doc, e.doc)), this.Vo(n);
const r = e ? this.So() : [], o = 0 === this.Eo.size && this.current ? 1 /* Synced */ : 0 /* Local */ , c = o !== this.To;
return (this.To = o, 0 !== i.length || c) ? {
snapshot: new Fo(this.query, t.Ao, s, i, t.mutatedKeys, 0 /* Local */ === o, c, /* excludesMetadataChanges= */ !1),
Do: r
} : {
Do: r
};
}
/**
* Applies an OnlineState change to the view, potentially generating a
* ViewChange if the view's syncState changes as a result.
*/ io(t) {
return this.current && "Offline" /* Offline */ === t ? // to refresh our syncState and generate a ViewChange as appropriate. We
// are guaranteed to get a new TargetChange that sets `current` back to
// true once the client is back online.
(this.current = !1, this.applyChanges({
Ao: this.Ao,
Po: new Oo(),
mutatedKeys: this.mutatedKeys,
Ln: !1
}, /* updateLimboDocuments= */ !1)) : {
Do: []
};
}
/**
* Returns whether the doc for the given key should be in limbo.
*/ Co(t) {
// If the remote end says it's part of this query, it's not in limbo.
return !this.po.has(t) && // The local store doesn't think it's a result, so it shouldn't be in limbo.
!!this.Ao.has(t) && !this.Ao.get(t).hasLocalMutations;
}
/**
* Updates syncedDocuments, current, and limbo docs based on the given change.
* Returns the list of changes to which docs are in limbo.
*/ Vo(t) {
t && (t.addedDocuments.forEach((t)=>this.po = this.po.add(t)), t.modifiedDocuments.forEach((t)=>{}), t.removedDocuments.forEach((t)=>this.po = this.po.delete(t)), this.current = t.current);
}
So() {
// We can only determine limbo documents when we're in-sync with the server.
if (!this.current) return [];
// TODO(klimt): Do this incrementally so that it's not quadratic when
// updating many documents.
const t = this.Eo;
this.Eo = Pn(), this.Ao.forEach((t)=>{
this.Co(t.key) && (this.Eo = this.Eo.add(t.key));
});
// Diff the new limbo docs with the old limbo docs.
const e = [];
return t.forEach((t)=>{
this.Eo.has(t) || e.push(new Yo(t));
}), this.Eo.forEach((n)=>{
t.has(n) || e.push(new Jo(n));
}), e;
}
/**
* Update the in-memory state of the current view with the state read from
* persistence.
*
* We update the query view whenever a client's primary status changes:
* - When a client transitions from primary to secondary, it can miss
* LocalStorage updates and its query views may temporarily not be
* synchronized with the state on disk.
* - For secondary to primary transitions, the client needs to update the list
* of `syncedDocuments` since secondary clients update their query views
* based purely on synthesized RemoteEvents.
*
* @param queryResult.documents - The documents that match the query according
* to the LocalStore.
* @param queryResult.remoteKeys - The keys of the documents that match the
* query according to the backend.
*
* @returns The ViewChange that resulted from this synchronization.
*/ // PORTING NOTE: Multi-tab only.
No(t) {
this.po = t.Gn, this.Eo = Pn();
const e = this.bo(t.documents);
return this.applyChanges(e, /*updateLimboDocuments=*/ !0);
}
/**
* Returns a view snapshot as if this query was just listened to. Contains
* a document add for every existing document and the `fromCache` and
* `hasPendingWrites` status of the already established view.
*/ // PORTING NOTE: Multi-tab only.
xo() {
return Fo.fromInitialDocuments(this.query, this.Ao, this.mutatedKeys, 0 /* Local */ === this.To);
}
}
/**
* QueryView contains all of the data that SyncEngine needs to keep track of for
* a particular query.
*/ class Zo {
constructor(/**
* The query itself.
*/ t, /**
* The target number created by the client that is used in the watch
* stream to identify this query.
*/ e, /**
* The view is responsible for computing the final merged truth of what
* docs are in the query. It gets notified of local and remote changes,
* and applies the query filters and limits to determine the most correct
* possible results.
*/ n){
this.query = t, this.targetId = e, this.view = n;
}
}
/** Tracks a limbo resolution. */ class tc {
constructor(t){
this.key = t, /**
* Set to true once we've received a document. This is used in
* getRemoteKeysForTarget() and ultimately used by WatchChangeAggregator to
* decide whether it needs to manufacture a delete event for the target once
* the target is CURRENT.
*/ this.ko = !1;
}
}
/**
* An implementation of `SyncEngine` coordinating with other parts of SDK.
*
* The parts of SyncEngine that act as a callback to RemoteStore need to be
* registered individually. This is done in `syncEngineWrite()` and
* `syncEngineListen()` (as well as `applyPrimaryState()`) as these methods
* serve as entry points to RemoteStore's functionality.
*
* Note: some field defined in this class might have public access level, but
* the class is not exported so they are only accessible from this module.
* This is useful to implement optional features (like bundles) in free
* functions, such that they are tree-shakeable.
*/ class ec {
constructor(t, e, n, // PORTING NOTE: Manages state synchronization in multi-tab environments.
s, i, r){
this.localStore = t, this.remoteStore = e, this.eventManager = n, this.sharedClientState = s, this.currentUser = i, this.maxConcurrentLimboResolutions = r, this.$o = {}, this.Oo = new ji((t)=>Re(t), Ae), this.Fo = new Map(), /**
* The keys of documents that are in limbo for which we haven't yet started a
* limbo resolution query. The strings in this set are the result of calling
* `key.path.canonicalString()` where `key` is a `DocumentKey` object.
*
* The `Set` type was chosen because it provides efficient lookup and removal
* of arbitrary elements and it also maintains insertion order, providing the
* desired queue-like FIFO semantics.
*/ this.Mo = new Set(), /**
* Keeps track of the target ID for each document that is in limbo with an
* active target.
*/ this.Lo = new wn(Pt.comparator), /**
* Keeps track of the information about an active limbo resolution for each
* active target ID that was started for the purpose of limbo resolution.
*/ this.Bo = new Map(), this.Uo = new br(), /** Stores user completion handlers, indexed by User and BatchId. */ this.qo = {}, /** Stores user callbacks waiting for all pending writes to be acknowledged. */ this.Ko = new Map(), this.jo = Ni.ie(), this.onlineState = "Unknown", // The primary state is set to `true` or `false` immediately after Firestore
// startup. In the interim, a client should only be considered primary if
// `isPrimary` is true.
this.Qo = void 0;
}
get isPrimaryClient() {
return !0 === this.Qo;
}
}
/**
* Initiates the new listen, resolves promise when listen enqueued to the
* server. All the subsequent view snapshots or errors are sent to the
* subscribed handlers. Returns the initial snapshot.
*/ async function nc(t, e) {
var t1, e1;
let s, i;
const n = (t.remoteStore.remoteSyncer.applyRemoteEvent = oc.bind(null, t), t.remoteStore.remoteSyncer.getRemoteKeysForTarget = Ec.bind(null, t), t.remoteStore.remoteSyncer.rejectListen = ac.bind(null, t), t.$o.Rr = qo.bind(null, t.eventManager), t.$o.Go = Ko.bind(null, t.eventManager), t), r = n.Oo.get(e);
if (r) // PORTING NOTE: With Multi-Tab Web, it is possible that a query view
// already exists when EventManager calls us for the first time. This
// happens when the primary tab is already listening to this query on
// behalf of another tab and the user of the primary also starts listening
// to the query. EventManager will not have an assigned target ID in this
// case and calls `listen` to obtain this ID.
s = r.targetId, n.sharedClientState.addLocalQueryTarget(s), i = r.view.xo();
else {
const t = await (t1 = n.localStore, e1 = Ee(e), t1.persistence.runTransaction("Allocate target", "readwrite", (t)=>{
let s;
return t1.ze.getTargetData(t, e1).next((i)=>i ? // previous targetID.
// TODO(mcg): freshen last accessed date?
(s = i, js.resolve(s)) : t1.ze.allocateTargetId(t).next((i)=>(s = new ii(e1, i, 0 /* Listen */ , t.currentSequenceNumber), t1.ze.addTargetData(t, s).next(()=>s))));
}).then((t)=>{
// If Multi-Tab is enabled, the existing target data may be newer than
// the in-memory data
const s = t1.Un.get(t.targetId);
return (null === s || t.snapshotVersion.compareTo(s.snapshotVersion) > 0) && (t1.Un = t1.Un.insert(t.targetId, t), t1.qn.set(e1, t.targetId)), t;
})), r = n.sharedClientState.addLocalQueryTarget(t.targetId);
s = t.targetId, i = await sc(n, e, s, "current" === r), n.isPrimaryClient && co(n.remoteStore, t);
}
return i;
}
/**
* Registers a view for a previously unknown query and computes its initial
* snapshot.
*/ async function sc(t, e, n, s) {
// PORTING NOTE: On Web only, we inject the code that registers new Limbo
// targets based on view changes. This allows us to only depend on Limbo
// changes when user code includes queries.
t.Wo = (e, n, s)=>(async function(t, e, n, s) {
let i = e.view.bo(n);
i.Ln && // The query has a limit and some docs were removed, so we need
// to re-run the query against the local store to make sure we
// didn't lose any good docs that had been past the limit.
(i = await yr(t.localStore, e.query, /* usePreviousResults= */ !1).then(({ documents: t })=>e.view.bo(t, i)));
const r = s && s.targetChanges.get(e.targetId), o = e.view.applyChanges(i, /* updateLimboDocuments= */ t.isPrimaryClient, r);
return mc(t, e.targetId, o.Do), o.snapshot;
})(t, e, n, s);
const i = await yr(t.localStore, e, /* usePreviousResults= */ !0), r = new Xo(e, i.Gn), o = r.bo(i.documents), c = Dn.createSynthesizedTargetChangeForCurrentChange(n, s && "Offline" /* Offline */ !== t.onlineState), a = r.applyChanges(o, /* updateLimboDocuments= */ t.isPrimaryClient, c);
mc(t, n, a.Do);
const u = new Zo(e, n, r);
return t.Oo.set(e, u), t.Fo.has(n) ? t.Fo.get(n).push(e) : t.Fo.set(n, [
e
]), a.snapshot;
}
/** Stops listening to the query. */ async function ic(t, e) {
const s = t.Oo.get(e), i = t.Fo.get(s.targetId);
if (i.length > 1) return t.Fo.set(s.targetId, i.filter((t)=>!Ae(t, e))), void t.Oo.delete(e);
// No other queries are mapped to the target, clean up the query and the target.
t.isPrimaryClient ? (// We need to remove the local query target first to allow us to verify
// whether any other client is still interested in this target.
t.sharedClientState.removeLocalQueryTarget(s.targetId), t.sharedClientState.isActiveQueryTarget(s.targetId) || await gr(t.localStore, s.targetId, /*keepPersistedTargetData=*/ !1).then(()=>{
t.sharedClientState.clearQueryState(s.targetId), ao(t.remoteStore, s.targetId), wc(t, s.targetId);
}).catch(Fi)) : (wc(t, s.targetId), await gr(t.localStore, s.targetId, /*keepPersistedTargetData=*/ !0));
}
/**
* Applies one remote event to the sync engine, notifying any views of the
* changes, and releasing any pending mutation batches that would become
* visible because of the snapshot version the remote event contains.
*/ async function oc(t, e) {
try {
const t1 = await /**
* Updates the "ground-state" (remote) documents. We assume that the remote
* event reflects any write batches that have been acknowledged or rejected
* (i.e. we do not re-apply local mutations to updates from this event).
*
* LocalDocuments are re-calculated if there are remaining mutations in the
* queue.
*/ function(t, e) {
const s = e.snapshotVersion;
let i = t.Un;
return t.persistence.runTransaction("Apply remote event", "readwrite-primary", (t1)=>{
var n, // TODO(wuandy): We could add `readTime` to MaybeDocument instead to remove
// this parameter.
i1;
let r;
const r1 = t.jn.newChangeBuffer({
trackRemovals: !0
});
// Reset newTargetDataByTargetMap in case this transaction gets re-run.
i = t.Un;
const o = [];
e.targetChanges.forEach((e, r)=>{
const c = i.get(r);
if (!c) return;
// Only update the remote keys if the target is still active. This
// ensures that we can persist the updated target data along with
// the updated assignment.
o.push(t.ze.removeMatchingKeys(t1, e.removedDocuments, r).next(()=>t.ze.addMatchingKeys(t1, e.addedDocuments, r)));
const a = e.resumeToken;
// Update the resume token if the change includes one.
if (a.approximateByteSize() > 0) {
const u = c.withResumeToken(a, s).withSequenceNumber(t1.currentSequenceNumber);
i = i.insert(r, u), u.resumeToken.approximateByteSize() > 0 || L(), (0 === /**
* Notifies local store of the changed views to locally pin documents.
*/ c.resumeToken.approximateByteSize() || u.snapshotVersion.toMicroseconds() - c.snapshotVersion.toMicroseconds() >= 3e8 || e.addedDocuments.size + e.modifiedDocuments.size + e.removedDocuments.size > 0) && o.push(t.ze.updateTargetData(t1, u));
}
});
let c = pn;
// HACK: The only reason we allow a null snapshot version is so that we
// can synthesize remote events when we get permission denied errors while
// trying to resolve the state of a locally cached document that is in
// limbo.
if (e.documentUpdates.forEach((s, i)=>{
e.resolvedLimboDocuments.has(s) && o.push(t.persistence.referenceDelegate.updateLimboDocument(t1, s));
}), // Each loop iteration only affects its "own" doc, so it's safe to get all the remote
// documents in advance in a single call.
o.push((n = e.documentUpdates, i1 = void 0, r = Pn(), n.forEach((t)=>r = r.add(t)), r1.getEntries(t1, r).next((t)=>{
let r = pn;
return n.forEach((n, o)=>{
const c = t.get(n), a = (null == i1 ? void 0 : i1.get(n)) || s;
// Note: The order of the steps below is important, since we want
// to ensure that rejected limbo resolutions (which fabricate
// NoDocuments with SnapshotVersion.min()) never add documents to
// cache.
o.isNoDocument() && o.version.isEqual(rt.min()) ? // events. We remove these documents from cache since we lost
// access.
(r1.removeEntry(n, a), r = r.insert(n, o)) : !c.isValidDocument() || o.version.compareTo(c.version) > 0 || 0 === o.version.compareTo(c.version) && c.hasPendingWrites ? (r1.addEntry(o, a), r = r.insert(n, o)) : $("LocalStore", "Ignoring outdated watch update for ", n, ". Current version:", c.version, " Watch version:", o.version);
}), r;
})).next((t)=>{
c = t;
})), !s.isEqual(rt.min())) {
const e = t.ze.getLastRemoteSnapshotVersion(t1).next((e)=>t.ze.setTargetsMetadata(t1, t1.currentSequenceNumber, s));
o.push(e);
}
return js.waitFor(o).next(()=>r1.apply(t1)).next(()=>t.Qn.vn(t1, c)).next(()=>c);
}).then((t1)=>(t.Un = i, t1));
}(t.localStore, e);
// Update `receivedDocument` as appropriate for any limbo targets.
e.targetChanges.forEach((t1, e)=>{
const s = t.Bo.get(e);
s && // Since this is a limbo resolution lookup, it's for a single document
// and it could be added, modified, or removed, but not a combination.
(t1.addedDocuments.size + t1.modifiedDocuments.size + t1.removedDocuments.size <= 1 || L(), t1.addedDocuments.size > 0 ? s.ko = !0 : t1.modifiedDocuments.size > 0 ? s.ko || L() : t1.removedDocuments.size > 0 && (s.ko || L(), s.ko = !1));
}), await pc(t, t1, e);
} catch (t) {
await Fi(t);
}
}
/**
* Applies an OnlineState change to the sync engine and notifies any views of
* the change.
*/ function cc(t, e, n) {
var t1;
// If we are the secondary client, we explicitly ignore the remote store's
// online state (the local client may go offline, even though the primary
// tab remains online) and only apply the primary tab's online state from
// SharedClientState.
if (t.isPrimaryClient && 0 /* RemoteStore */ === n || !t.isPrimaryClient && 1 /* SharedClientState */ === n) {
let s;
const t2 = [];
t.Oo.forEach((n, s)=>{
const i = s.view.io(e);
i.snapshot && t2.push(i.snapshot);
}), (t1 = t.eventManager).onlineState = e, s = !1, t1.queries.forEach((t, n)=>{
// Run global snapshot listeners if a consistent snapshot has been emitted.
for (const t of n.listeners)t.io(e) && (s = !0);
}), s && jo(t1), t2.length && t.$o.Rr(t2), t.onlineState = e, t.isPrimaryClient && t.sharedClientState.setOnlineState(e);
}
}
/**
* Rejects the listen for the given targetID. This can be triggered by the
* backend for any active target.
*
* @param syncEngine - The sync engine implementation.
* @param targetId - The targetID corresponds to one previously initiated by the
* user as part of TargetData passed to listen() on RemoteStore.
* @param err - A description of the condition that has forced the rejection.
* Nearly always this will be an indication that the user is no longer
* authorized to see the data matching the target.
*/ async function ac(t, e, n) {
// PORTING NOTE: Multi-tab only.
t.sharedClientState.updateQueryState(e, "rejected", n);
const i = t.Bo.get(e), r = i && i.key;
if (r) {
// TODO(klimt): We really only should do the following on permission
// denied errors, but we don't have the cause code here.
// It's a limbo doc. Create a synthetic event saying it was deleted.
// This is kind of a hack. Ideally, we would have a method in the local
// store to purge a document. However, it would be tricky to keep all of
// the local store's invariants with another method.
let t1 = new wn(Pt.comparator);
t1 = t1.insert(r, Kt.newNoDocument(r, rt.min()));
const n = Pn().add(r), i = new Sn(rt.min(), /* targetChanges= */ new Map(), /* targetMismatches= */ new gn(et), t1, n);
await oc(t, i), // Since this query failed, we won't want to manually unlisten to it.
// We only remove it from bookkeeping after we successfully applied the
// RemoteEvent. If `applyRemoteEvent()` throws, we want to re-listen to
// this query when the RemoteStore restarts the Watch stream, which should
// re-trigger the target failure.
t.Lo = t.Lo.remove(r), t.Bo.delete(e), yc(t);
} else await gr(t.localStore, e, /* keepPersistedTargetData */ !1).then(()=>wc(t, e, n)).catch(Fi);
}
function wc(t, e, n = null) {
for (const s of (t.sharedClientState.removeLocalQueryTarget(e), t.Fo.get(e)))t.Oo.delete(s), n && t.$o.Go(s, n);
t.Fo.delete(e), t.isPrimaryClient && t.Uo.cs(e).forEach((e)=>{
t.Uo.containsKey(e) || // We removed the last reference for this key
_c(t, e);
});
}
function _c(t, e) {
t.Mo.delete(e.path.canonicalString());
// It's possible that the target already got removed because the query failed. In that case,
// the key won't exist in `limboTargetsByKey`. Only do the cleanup if we still have the target.
const n = t.Lo.get(e);
null !== n && (ao(t.remoteStore, n), t.Lo = t.Lo.remove(e), t.Bo.delete(n), yc(t));
}
function mc(t, e, n) {
for (const s of n)s instanceof Jo ? (t.Uo.addReference(s.key, e), function(t, e) {
const n = e.key, s = n.path.canonicalString();
t.Lo.get(n) || t.Mo.has(s) || ($("SyncEngine", "New document in limbo: " + n), t.Mo.add(s), yc(t));
}(t, s)) : s instanceof Yo ? ($("SyncEngine", "Document no longer in limbo: " + s.key), t.Uo.removeReference(s.key, e), t.Uo.containsKey(s.key) || // We removed the last reference for this key
_c(t, s.key)) : L();
}
/**
* Starts listens for documents in limbo that are enqueued for resolution,
* subject to a maximum number of concurrent resolutions.
*
* Without bounding the number of concurrent resolutions, the server can fail
* with "resource exhausted" errors which can lead to pathological client
* behavior as seen in https://github.com/firebase/firebase-js-sdk/issues/2683.
*/ function yc(t) {
for(; t.Mo.size > 0 && t.Lo.size < t.maxConcurrentLimboResolutions;){
const e = t.Mo.values().next().value;
t.Mo.delete(e);
const n = new Pt(ht.fromString(e)), s = t.jo.next();
t.Bo.set(s, new tc(n)), t.Lo = t.Lo.insert(n, s), co(t.remoteStore, new ii(Ee(new fe(n.path)), s, 2 /* LimboResolution */ , X.T));
}
}
async function pc(t, e, n) {
const i = [], r = [], o = [];
t.Oo.isEmpty() || (t.Oo.forEach((t1, c)=>{
o.push(t.Wo(c, e, n).then((t1)=>{
if (t1) {
t.isPrimaryClient && t.sharedClientState.updateQueryState(c.targetId, t1.fromCache ? "not-current" : "current"), i.push(t1);
const e = or.kn(c.targetId, t1);
r.push(e);
}
}));
}), await Promise.all(o), t.$o.Rr(i), await async function(t, e) {
try {
await t.persistence.runTransaction("notifyLocalViewChanges", "readwrite", (t1)=>js.forEach(e, (e)=>js.forEach(e.Nn, (s)=>t.persistence.referenceDelegate.addReference(t1, e.targetId, s)).next(()=>js.forEach(e.xn, (s)=>t.persistence.referenceDelegate.removeReference(t1, e.targetId, s)))));
} catch (t) {
if (!Hs(t)) throw t;
// If `notifyLocalViewChanges` fails, we did not advance the sequence
// number for the documents that were included in this transaction.
// This might trigger them to be deleted earlier than they otherwise
// would have, but it should not invalidate the integrity of the data.
$("LocalStore", "Failed to update sequence numbers: " + t);
}
for (const t1 of e){
const e = t1.targetId;
if (!t1.fromCache) {
const t1 = t.Un.get(e), s = t1.snapshotVersion, i = t1.withLastLimboFreeSnapshotVersion(s);
// Advance the last limbo free snapshot version
t.Un = t.Un.insert(e, i);
}
}
}(t.localStore, r));
}
async function Tc(t, e) {
if (!t.currentUser.isEqual(e)) {
$("SyncEngine", "User change. New user:", e.toKey());
const t1 = await hr(t.localStore, e);
t.currentUser = e, t.Ko.forEach((t)=>{
t.forEach((t)=>{
t.reject(new j(K.CANCELLED, "'waitForPendingWrites' promise is rejected due to a user change."));
});
}), t.Ko.clear(), // TODO(b/114226417): Consider calling this only in the primary tab.
t.sharedClientState.handleUserChange(e, t1.removedBatchIds, t1.addedBatchIds), await pc(t, t1.Wn);
}
}
function Ec(t, e) {
const s = t.Bo.get(e);
if (s && s.ko) return Pn().add(s.key);
{
let t1 = Pn();
const s = t.Fo.get(e);
if (!s) return t1;
for (const e of s){
const s = t.Oo.get(e);
t1 = t1.unionWith(s.view.Ro);
}
return t1;
}
}
class kc {
constructor(){
this.synchronizeTabs = !1;
}
async initialize(t) {
this.N = new Bn(t.databaseInfo.databaseId, /* useProto3Json= */ !0), this.sharedClientState = this.Ho(t), this.persistence = this.Jo(t), await this.persistence.start(), this.gcScheduler = this.Yo(t), this.localStore = this.Xo(t);
}
Yo(t) {
return null;
}
Xo(t) {
return new ar(this.persistence, new cr(), t.initialUser, this.N);
}
Jo(t) {
return new Cr(xr.Ns, this.N);
}
Ho(t) {
return new Kr();
}
async terminate() {
this.gcScheduler && this.gcScheduler.stop(), await this.sharedClientState.shutdown(), await this.persistence.shutdown();
}
}
/**
* Initializes and wires the components that are needed to interface with the
* network.
*/ class Fc {
async initialize(t, e) {
this.localStore || (this.localStore = t.localStore, this.sharedClientState = t.sharedClientState, this.datastore = this.createDatastore(e), this.remoteStore = this.createRemoteStore(e), this.eventManager = this.createEventManager(e), this.syncEngine = this.createSyncEngine(e, /* startAsPrimary=*/ !t.synchronizeTabs), this.sharedClientState.onlineStateHandler = (t)=>cc(this.syncEngine, t, 1 /* SharedClientState */ ), this.remoteStore.remoteSyncer.handleCredentialChange = Tc.bind(null, this.syncEngine), await Do(this.remoteStore, this.syncEngine.isPrimaryClient));
}
createEventManager(t) {
return new Lo();
}
createDatastore(t) {
const e = new Bn(t.databaseInfo.databaseId, !0), n = new zr(t.databaseInfo);
/** Return the Platform-specific connectivity monitor. */ return new no(t.credentials, n, e);
}
createRemoteStore(t) {
return new io(this.localStore, this.datastore, t.asyncQueue, (t)=>cc(this.syncEngine, t, 0 /* RemoteStore */ ), Qr.bt() ? new Qr() : new jr());
/** Re-enables the network. Idempotent. */ }
createSyncEngine(t, e) {
return function(t, e, n, // PORTING NOTE: Manages state synchronization in multi-tab environments.
s, i, r, o) {
const c = new ec(t, e, n, s, i, r);
return o && (c.Qo = !0), c;
}(this.localStore, this.remoteStore, this.eventManager, this.sharedClientState, t.initialUser, t.maxConcurrentLimboResolutions, e);
}
terminate() {
return async function(t) {
$("RemoteStore", "RemoteStore shutting down."), t.Wr.add(5 /* Shutdown */ ), await oo(t), t.zr.shutdown(), // Set the OnlineState to Unknown (rather than Offline) to avoid potentially
// triggering spurious listener events with cached data, etc.
t.Hr.set("Unknown" /* Unknown */ );
}(this.remoteStore);
}
}
/**
* @license
* Copyright 2020 Google 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.
*/ /**
* On web, a `ReadableStream` is wrapped around by a `ByteStreamReader`.
*/ /**
* @license
* Copyright 2017 Google 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.
*/ /*
* A wrapper implementation of Observer<T> that will dispatch events
* asynchronously. To allow immediate silencing, a mute call is added which
* causes events scheduled to no longer be raised.
*/ class Lc {
constructor(t){
this.observer = t, /**
* When set to true, will not raise future events. Necessary to deal with
* async detachment of listener.
*/ this.muted = !1;
}
next(t) {
this.observer.next && this.tc(this.observer.next, t);
}
error(t) {
this.observer.error ? this.tc(this.observer.error, t) : console.error("Uncaught Error in snapshot listener:", t);
}
ec() {
this.muted = !0;
}
tc(t, e) {
this.muted || setTimeout(()=>{
this.muted || t(e);
}, 0);
}
}
/**
* @license
* Copyright 2017 Google 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.
*/ /**
* FirestoreClient is a top-level class that constructs and owns all of the
* pieces of the client SDK architecture. It is responsible for creating the
* async queue that is shared by all of the other components in the system.
*/ class Kc {
constructor(t, /**
* Asynchronous queue responsible for all of our internal processing. When
* we get incoming work from the user (via public API) or the network
* (incoming GRPC messages), we should always schedule onto this queue.
* This ensures all of our work is properly serialized (e.g. we don't
* start processing a new operation while the previous one is waiting for
* an async I/O to complete).
*/ e, n){
this.credentials = t, this.asyncQueue = e, this.databaseInfo = n, this.user = D.UNAUTHENTICATED, this.clientId = tt.I(), this.credentialListener = ()=>Promise.resolve(), this.credentials.start(e, async (t)=>{
$("FirestoreClient", "Received user=", t.uid), await this.credentialListener(t), this.user = t;
});
}
async getConfiguration() {
return {
asyncQueue: this.asyncQueue,
databaseInfo: this.databaseInfo,
clientId: this.clientId,
credentials: this.credentials,
initialUser: this.user,
maxConcurrentLimboResolutions: 100
};
}
setCredentialChangeListener(t) {
this.credentialListener = t;
}
/**
* Checks that the client has not been terminated. Ensures that other methods on
* this class cannot be called after the client is terminated.
*/ verifyNotTerminated() {
if (this.asyncQueue.isShuttingDown) throw new j(K.FAILED_PRECONDITION, "The client has already been terminated.");
}
terminate() {
this.asyncQueue.enterRestrictedMode();
const t = new Q();
return this.asyncQueue.enqueueAndForgetEvenWhileRestricted(async ()=>{
try {
this.onlineComponents && await this.onlineComponents.terminate(), this.offlineComponents && await this.offlineComponents.terminate(), // The credentials provider must be terminated after shutting down the
// RemoteStore as it will prevent the RemoteStore from retrieving auth
// tokens.
this.credentials.shutdown(), t.resolve();
} catch (e) {
const n = ko(e, "Failed to shutdown persistence");
t.reject(n);
}
}), t.promise;
}
}
async function jc(t, e) {
t.asyncQueue.verifyOperationInProgress(), $("FirestoreClient", "Initializing OfflineComponentProvider");
const n = await t.getConfiguration();
await e.initialize(n);
let s = n.initialUser;
t.setCredentialChangeListener(async (t)=>{
s.isEqual(t) || (await hr(e.localStore, t), s = t);
}), // When a user calls clearPersistence() in one client, all other clients
// need to be terminated to allow the delete to succeed.
e.persistence.setDatabaseDeletedListener(()=>t.terminate()), t.offlineComponents = e;
}
async function Qc(t, e) {
t.asyncQueue.verifyOperationInProgress();
const n = await Wc(t);
$("FirestoreClient", "Initializing OnlineComponentProvider");
const s = await t.getConfiguration();
await e.initialize(n, s), // The CredentialChangeListener of the online component provider takes
// precedence over the offline component provider.
t.setCredentialChangeListener((t)=>(async function(t, e) {
t.asyncQueue.verifyOperationInProgress(), $("RemoteStore", "RemoteStore received new credentials");
const s = wo(t);
// Tear down and re-create our network streams. This will ensure we get a
// fresh auth token for the new user and re-fill the write pipeline with
// new mutations from the LocalStore (since mutations are per-user).
t.Wr.add(3 /* CredentialChange */ ), await oo(t), s && // Don't set the network status to Unknown if we are offline.
t.Hr.set("Unknown" /* Unknown */ ), await t.remoteSyncer.handleCredentialChange(e), t.Wr.delete(3 /* CredentialChange */ ), await ro(t);
})(e.remoteStore, t)), t.onlineComponents = e;
}
async function Wc(t) {
return t.offlineComponents || ($("FirestoreClient", "Using default OfflineComponentProvider"), await jc(t, new kc())), t.offlineComponents;
}
async function Gc(t) {
return t.onlineComponents || ($("FirestoreClient", "Using default OnlineComponentProvider"), await Qc(t, new Fc())), t.onlineComponents;
}
async function Xc(t) {
const e = await Gc(t), n = e.eventManager;
return n.onListen = nc.bind(null, e.syncEngine), n.onUnlisten = ic.bind(null, e.syncEngine), n;
}
class ua {
/**
* Constructs a DatabaseInfo using the provided host, databaseId and
* persistenceKey.
*
* @param databaseId - The database to use.
* @param appId - The Firebase App Id.
* @param persistenceKey - A unique identifier for this Firestore's local
* storage (used in conjunction with the databaseId).
* @param host - The Firestore backend host to connect to.
* @param ssl - Whether to use SSL when connecting.
* @param forceLongPolling - Whether to use the forceLongPolling option
* when using WebChannel as the network transport.
* @param autoDetectLongPolling - Whether to use the detectBufferingProxy
* option when using WebChannel as the network transport.
* @param useFetchStreams Whether to use the Fetch API instead of
* XMLHTTPRequest
*/ constructor(t, e, n, s, i, r, o, c){
this.databaseId = t, this.appId = e, this.persistenceKey = n, this.host = s, this.ssl = i, this.forceLongPolling = r, this.autoDetectLongPolling = o, this.useFetchStreams = c;
}
}
/** The default database name for a project. */ /**
* Represents the database ID a Firestore client is associated with.
* @internal
*/ class ha {
constructor(t, e){
this.projectId = t, this.database = e || "(default)";
}
get isDefaultDatabase() {
return "(default)" === this.database;
}
isEqual(t) {
return t instanceof ha && t.projectId === this.projectId && t.database === this.database;
}
}
/**
* @license
* Copyright 2020 Google 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.
*/ const la = new Map();
/**
* Validates that `path` refers to a collection (indicated by the fact it
* contains an odd numbers of segments).
*/ function _a(t) {
if (Pt.isDocumentKey(t)) throw new j(K.INVALID_ARGUMENT, `Invalid collection reference. Collection references must have an odd number of segments, but ${t} has ${t.length}.`);
}
function ga(t, // eslint-disable-next-line @typescript-eslint/no-explicit-any
e) {
if ("_delegate" in t && // Unwrap Compat types
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(t = t._delegate), !(t instanceof e)) {
if (e.name === t.constructor.name) throw new j(K.INVALID_ARGUMENT, "Type does not match the expected instance. Did you pass a reference from a different Firestore SDK?");
{
const n = /**
* Returns true if it's a non-null object without a custom prototype
* (i.e. excludes Array, Date, etc.).
*/ /** Returns a string describing the type / value of the provided input. */ function(t) {
if (void 0 === t) return "undefined";
if (null === t) return "null";
if ("string" == typeof t) return t.length > 20 && (t = `${t.substring(0, 20)}...`), JSON.stringify(t);
if ("number" == typeof t || "boolean" == typeof t) return "" + t;
if ("object" == typeof t) {
if (t instanceof Array) return "an array";
{
var t1;
const e = (t1 = /**
* Casts `obj` to `T`, optionally unwrapping Compat types to expose the
* underlying instance. Throws if `obj` is not an instance of `T`.
*
* This cast is used in the Lite and Full SDK to verify instance types for
* arguments passed to the public API.
* @internal
*/ t).constructor ? t1.constructor.name : null;
return e ? `a custom ${e} object` : "an object";
}
}
return "function" == typeof t ? "a function" : L();
}(t);
throw new j(K.INVALID_ARGUMENT, `Expected type '${e.name}', but it was: ${n}`);
}
}
return t;
}
/**
* @license
* Copyright 2020 Google 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.
*/ // settings() defaults:
/**
* A concrete type describing all the values that can be applied via a
* user-supplied `FirestoreSettings` object. This is a separate type so that
* defaults can be supplied and the value can be checked for equality.
*/ class pa {
constructor(t){
var e;
if (void 0 === t.host) {
if (void 0 !== t.ssl) throw new j(K.INVALID_ARGUMENT, "Can't provide ssl option if host option is not set");
this.host = "firestore.googleapis.com", this.ssl = !0;
} else this.host = t.host, this.ssl = null === (e = t.ssl) || void 0 === e || e;
if (this.credentials = t.credentials, this.ignoreUndefinedProperties = !!t.ignoreUndefinedProperties, void 0 === t.cacheSizeBytes) this.cacheSizeBytes = 41943040;
else {
if (-1 !== t.cacheSizeBytes && t.cacheSizeBytes < 1048576) throw new j(K.INVALID_ARGUMENT, "cacheSizeBytes must be at least 1048576");
this.cacheSizeBytes = t.cacheSizeBytes;
}
this.experimentalForceLongPolling = !!t.experimentalForceLongPolling, this.experimentalAutoDetectLongPolling = !!t.experimentalAutoDetectLongPolling, this.useFetchStreams = !!t.useFetchStreams, /**
* Validates that two boolean options are not set at the same time.
* @internal
*/ function(t, e, n, s) {
if (!0 === e && !0 === s) throw new j(K.INVALID_ARGUMENT, `${t} and ${n} cannot be used together.`);
}("experimentalForceLongPolling", t.experimentalForceLongPolling, "experimentalAutoDetectLongPolling", t.experimentalAutoDetectLongPolling);
}
isEqual(t) {
return this.host === t.host && this.ssl === t.ssl && this.credentials === t.credentials && this.cacheSizeBytes === t.cacheSizeBytes && this.experimentalForceLongPolling === t.experimentalForceLongPolling && this.experimentalAutoDetectLongPolling === t.experimentalAutoDetectLongPolling && this.ignoreUndefinedProperties === t.ignoreUndefinedProperties && this.useFetchStreams === t.useFetchStreams;
}
}
/**
* @license
* Copyright 2020 Google 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.
*/ /**
* The Cloud Firestore service interface.
*
* Do not call this constructor directly. Instead, use {@link getFirestore}.
*/ class Ta {
/** @hideconstructor */ constructor(t, e){
this._credentials = e, /**
* Whether it's a Firestore or Firestore Lite instance.
*/ this.type = "firestore-lite", this._persistenceKey = "(lite)", this._settings = new pa({}), this._settingsFrozen = !1, t instanceof ha ? this._databaseId = t : (this._app = t, this._databaseId = function(t) {
if (!Object.prototype.hasOwnProperty.apply(t.options, [
"projectId"
])) throw new j(K.INVALID_ARGUMENT, '"projectId" not provided in firebase.initializeApp.');
return new ha(t.options.projectId);
}(/**
* Modify this instance to communicate with the Cloud Firestore emulator.
*
* Note: This must be called before this instance has been used to do any
* operations.
*
* @param firestore - The `Firestore` instance to configure to connect to the
* emulator.
* @param host - the emulator host (ex: localhost).
* @param port - the emulator port (ex: 9000).
* @param options.mockUserToken - the mock auth token to use for unit testing
* Security Rules.
*/ t));
}
/**
* The {@link @firebase/app#FirebaseApp} associated with this `Firestore` service
* instance.
*/ get app() {
if (!this._app) throw new j(K.FAILED_PRECONDITION, "Firestore was not initialized using the Firebase SDK. 'app' is not available");
return this._app;
}
get _initialized() {
return this._settingsFrozen;
}
get _terminated() {
return void 0 !== this._terminateTask;
}
_setSettings(t) {
if (this._settingsFrozen) throw new j(K.FAILED_PRECONDITION, "Firestore has already been started and its settings can no longer be changed. You can only modify settings before calling any other methods on a Firestore object.");
this._settings = new pa(t), void 0 !== t.credentials && (this._credentials = function(t) {
if (!t) return new G();
switch(t.type){
case "gapi":
const e = t.client;
// Make sure this really is a Gapi client.
return "object" == typeof e && null !== e && e.auth && e.auth.getAuthHeaderValueForFirstParty || L(), new Y(e, t.sessionIndex || "0", t.iamToken || null);
case "provider":
return t.client;
default:
throw new j(K.INVALID_ARGUMENT, "makeCredentialsProvider failed due to invalid credential type");
}
}(t.credentials));
}
_getSettings() {
return this._settings;
}
_freezeSettings() {
return this._settingsFrozen = !0, this._settings;
}
_delete() {
return this._terminateTask || (this._terminateTask = this._terminate()), this._terminateTask;
}
/** Returns a JSON-serializable representation of this `Firestore` instance. */ toJSON() {
return {
app: this._app,
databaseId: this._databaseId,
settings: this._settings
};
}
/**
* Terminates all components used by this client. Subclasses can override
* this method to clean up their own dependencies, but must also call this
* method.
*
* Only ever called once.
*/ _terminate() {
/**
* Removes all components associated with the provided instance. Must be called
* when the `Firestore` instance is terminated.
*/ return function(t) {
const e = la.get(t);
e && ($("ComponentProvider", "Removing Datastore"), la.delete(t), e.terminate());
}(this), Promise.resolve();
}
}
/**
* @license
* Copyright 2020 Google 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.
*/ /**
* A `DocumentReference` refers to a document location in a Firestore database
* and can be used to write, read, or listen to the location. The document at
* the referenced location may or may not exist.
*/ class Ia {
/** @hideconstructor */ constructor(t, /**
* If provided, the `FirestoreDataConverter` associated with this instance.
*/ e, n){
this.converter = e, this._key = n, /** The type of this Firestore reference. */ this.type = "document", this.firestore = t;
}
get _path() {
return this._key.path;
}
/**
* The document's identifier within its collection.
*/ get id() {
return this._key.path.lastSegment();
}
/**
* A string representing the path of the referenced document (relative
* to the root of the database).
*/ get path() {
return this._key.path.canonicalString();
}
/**
* The collection this `DocumentReference` belongs to.
*/ get parent() {
return new Ra(this.firestore, this.converter, this._key.path.popLast());
}
withConverter(t) {
return new Ia(this.firestore, t, this._key);
}
}
/**
* A `Query` refers to a query which you can read or listen to. You can also
* construct refined `Query` objects by adding filters and ordering.
*/ class Aa {
// This is the lite version of the Query class in the main SDK.
/** @hideconstructor protected */ constructor(t, /**
* If provided, the `FirestoreDataConverter` associated with this instance.
*/ e, n){
this.converter = e, this._query = n, /** The type of this Firestore reference. */ this.type = "query", this.firestore = t;
}
withConverter(t) {
return new Aa(this.firestore, t, this._query);
}
}
/**
* A `CollectionReference` object can be used for adding documents, getting
* document references, and querying for documents (using {@link query}).
*/ class Ra extends Aa {
/** @hideconstructor */ constructor(t, e, n){
super(t, e, new fe(n)), this._path = n, /** The type of this Firestore reference. */ this.type = "collection";
}
/** The collection's identifier. */ get id() {
return this._query.path.lastSegment();
}
/**
* A string representing the path of the referenced collection (relative
* to the root of the database).
*/ get path() {
return this._query.path.canonicalString();
}
/**
* A reference to the containing `DocumentReference` if this is a
* subcollection. If this isn't a subcollection, the reference is null.
*/ get parent() {
const t = this._path.popLast();
return t.isEmpty() ? null : new Ia(this.firestore, /* converter= */ null, new Pt(t));
}
withConverter(t) {
return new Ra(this.firestore, t, this._path);
}
}
function ba(t, e, ...n) {
if (t = (0, _firebase_util__WEBPACK_IMPORTED_MODULE_3__ /* .getModularInstance */ .m9)(t), /**
* An instance map that ensures only one Datastore exists per Firestore
* instance.
*/ /**
* @license
* Copyright 2017 Google 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.
*/ function(t, e, n) {
if (!n) throw new j(K.INVALID_ARGUMENT, `Function ${t}() cannot be called with an empty ${e}.`);
}("collection", "path", e), t instanceof Ta) {
const s = ht.fromString(e, ...n);
return _a(s), new Ra(t, /* converter= */ null, s);
}
{
if (!(t instanceof Ia || t instanceof Ra)) throw new j(K.INVALID_ARGUMENT, "Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore");
const s = t._path.child(ht.fromString(e, ...n));
return _a(s), new Ra(t.firestore, /* converter= */ null, s);
}
}
/**
* @license
* Copyright 2020 Google 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.
*/ class Da {
constructor(){
// The last promise in the queue.
this._c = Promise.resolve(), // A list of retryable operations. Retryable operations are run in order and
// retried with backoff.
this.mc = [], // Is this AsyncQueue being shut down? Once it is set to true, it will not
// be changed again.
this.gc = !1, // Operations scheduled to be queued in the future. Operations are
// automatically removed after they are run or canceled.
this.yc = [], // visible for testing
this.Tc = null, // Flag set while there's an outstanding AsyncQueue operation, used for
// assertion sanity-checks.
this.Ec = !1, // Enabled during shutdown on Safari to prevent future access to IndexedDB.
this.Ic = !1, // List of TimerIds to fast-forward delays for.
this.Ac = [], // Backoff timer used to schedule retries for retryable operations
this.ar = new Xr(this, "async_queue_retry" /* AsyncQueueRetry */ ), // Visibility handler that triggers an immediate retry of all retryable
// operations. Meant to speed up recovery when we regain file system access
// after page comes into foreground.
this.Rc = ()=>{
const t = Jr();
t && $("AsyncQueue", "Visibility state changed to " + t.visibilityState), this.ar.tr();
};
const t = Jr();
t && "function" == typeof t.addEventListener && t.addEventListener("visibilitychange", this.Rc);
}
get isShuttingDown() {
return this.gc;
}
/**
* Adds a new operation to the queue without waiting for it to complete (i.e.
* we ignore the Promise result).
*/ enqueueAndForget(t) {
// eslint-disable-next-line @typescript-eslint/no-floating-promises
this.enqueue(t);
}
enqueueAndForgetEvenWhileRestricted(t) {
this.bc(), // eslint-disable-next-line @typescript-eslint/no-floating-promises
this.Pc(t);
}
enterRestrictedMode(t) {
if (!this.gc) {
this.gc = !0, this.Ic = t || !1;
const e = Jr();
e && "function" == typeof e.removeEventListener && e.removeEventListener("visibilitychange", this.Rc);
}
}
enqueue(t) {
if (this.bc(), this.gc) // Return a Promise which never resolves.
return new Promise(()=>{});
// Create a deferred Promise that we can return to the callee. This
// allows us to return a "hanging Promise" only to the callee and still
// advance the queue even when the operation is not run.
const e = new Q();
return this.Pc(()=>this.gc && this.Ic ? Promise.resolve() : (t().then(e.resolve, e.reject), e.promise)).then(()=>e.promise);
}
enqueueRetryable(t) {
this.enqueueAndForget(()=>(this.mc.push(t), this.vc()));
}
/**
* Runs the next operation from the retryable queue. If the operation fails,
* reschedules with backoff.
*/ async vc() {
if (0 !== this.mc.length) {
try {
await this.mc[0](), this.mc.shift(), this.ar.reset();
} catch (t) {
if (!Hs(t)) throw t;
// Failure will be handled by AsyncQueue
$("AsyncQueue", "Operation failed with retryable error: " + t);
}
this.mc.length > 0 && // If there are additional operations, we re-schedule `retryNextOp()`.
// This is necessary to run retryable operations that failed during
// their initial attempt since we don't know whether they are already
// enqueued. If, for example, `op1`, `op2`, `op3` are enqueued and `op1`
// needs to be re-run, we will run `op1`, `op1`, `op2` using the
// already enqueued calls to `retryNextOp()`. `op3()` will then run in the
// call scheduled here.
// Since `backoffAndRun()` cancels an existing backoff and schedules a
// new backoff on every call, there is only ever a single additional
// operation in the queue.
this.ar.Xi(()=>this.vc());
}
}
Pc(t) {
const e = this._c.then(()=>(this.Ec = !0, t().catch((t)=>{
let e;
// Re-throw the error so that this.tail becomes a rejected Promise and
// all further attempts to chain (via .then) will just short-circuit
// and return the rejected Promise.
throw this.Tc = t, this.Ec = !1, O("INTERNAL UNHANDLED ERROR: ", (e = /**
* @license
* Copyright 2017 Google 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.
*/ t.message || "", t.stack && (e = t.stack.includes(t.message) ? t.stack : t.message + "\n" + t.stack), e)), t;
}).then((t)=>(this.Ec = !1, t))));
return this._c = e, e;
}
enqueueAfterDelay(t, e, n) {
this.bc(), // Fast-forward delays for timerIds that have been overriden.
this.Ac.indexOf(t) > -1 && (e = 0);
const s = xo.createAndSchedule(this, t, e, n, (t)=>this.Vc(t));
return this.yc.push(s), s;
}
bc() {
this.Tc && L();
}
verifyOperationInProgress() {}
/**
* Waits until all currently queued tasks are finished executing. Delayed
* operations are not run.
*/ async Sc() {
// Operations in the queue prior to draining may have enqueued additional
// operations. Keep draining the queue until the tail is no longer advanced,
// which indicates that no more new operations were enqueued and that all
// operations were executed.
let t;
do t = this._c, await t;
while (t !== this._c)
}
/**
* For Tests: Determine if a delayed operation with a particular TimerId
* exists.
*/ Dc(t) {
for (const e of this.yc)if (e.timerId === t) return !0;
return !1;
}
/**
* For Tests: Runs some or all delayed operations early.
*
* @param lastTimerId - Delayed operations up to and including this TimerId
* will be drained. Pass TimerId.All to run all delayed operations.
* @returns a Promise that resolves once all operations have been run.
*/ Cc(t) {
// Note that draining may generate more delayed ops, so we do that first.
return this.Sc().then(()=>{
for (const e of (// Run ops in the same order they'd run if they ran naturally.
this.yc.sort((t, e)=>t.targetTimeMs - e.targetTimeMs), this.yc))if (e.skipDelay(), "all" /* All */ !== t && e.timerId === t) break;
return this.Sc();
});
}
/**
* For Tests: Skip all subsequent delays for a timer id.
*/ Nc(t) {
this.Ac.push(t);
}
/** Called once a DelayedOperation is run or canceled. */ Vc(t) {
// NOTE: indexOf / slice are O(n), but delayedOperations is expected to be small.
const e = this.yc.indexOf(t);
this.yc.splice(e, 1);
}
}
/**
* The Cloud Firestore service interface.
*
* Do not call this constructor directly. Instead, use {@link getFirestore}.
*/ class ka extends Ta {
/** @hideconstructor */ constructor(t, e){
super(t, e), /**
* Whether it's a {@link Firestore} or Firestore Lite instance.
*/ this.type = "firestore", this._queue = new Da(), this._persistenceKey = "name" in t ? t.name : "[DEFAULT]";
}
_terminate() {
return this._firestoreClient || // The client must be initialized to ensure that all subsequent API
// usage throws an exception.
Ma(this), this._firestoreClient.terminate();
}
}
function Ma(t) {
var e;
const n = t._freezeSettings(), s = new ua(t._databaseId, (null === (e = t._app) || void 0 === e ? void 0 : e.options.appId) || "", t._persistenceKey, n.host, n.ssl, n.experimentalForceLongPolling, n.experimentalAutoDetectLongPolling, n.useFetchStreams);
t._firestoreClient = new Kc(t._credentials, t._queue, s);
}
/**
* @license
* Copyright 2020 Google 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.
*/ /**
* @license
* Copyright 2020 Google 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.
*/ /**
* A `FieldPath` refers to a field in a document. The path may consist of a
* single field name (referring to a top-level field in the document), or a
* list of field names (referring to a nested field in the document).
*
* Create a `FieldPath` by providing field names. If more than one field
* name is provided, the path will point to a nested field in a document.
*/ class Ja {
/**
* Creates a `FieldPath` from the provided field names. If more than one field
* name is provided, the path will point to a nested field in a document.
*
* @param fieldNames - A list of field names.
*/ constructor(...t){
for(let e = 0; e < t.length; ++e)if (0 === t[e].length) throw new j(K.INVALID_ARGUMENT, "Invalid field name at argument $(i + 1). Field names must not be empty.");
this._internalPath = new ft(t);
}
/**
* Returns true if this `FieldPath` is equal to the provided one.
*
* @param other - The `FieldPath` to compare against.
* @returns true if this `FieldPath` is equal to the provided one.
*/ isEqual(t) {
return this._internalPath.isEqual(t._internalPath);
}
}
/**
* @license
* Copyright 2020 Google 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.
*/ /**
* An immutable object representing an array of bytes.
*/ class Xa {
/** @hideconstructor */ constructor(t){
this._byteString = t;
}
/**
* Creates a new `Bytes` object from the given Base64 string, converting it to
* bytes.
*
* @param base64 - The Base64 string used to create the `Bytes` object.
*/ static fromBase64String(t) {
try {
return new Xa(_t.fromBase64String(t));
} catch (t) {
throw new j(K.INVALID_ARGUMENT, "Failed to construct data from Base64 string: " + t);
}
}
/**
* Creates a new `Bytes` object from the given Uint8Array.
*
* @param array - The Uint8Array used to create the `Bytes` object.
*/ static fromUint8Array(t) {
return new Xa(_t.fromUint8Array(t));
}
/**
* Returns the underlying bytes as a Base64-encoded string.
*
* @returns The Base64-encoded string created from the `Bytes` object.
*/ toBase64() {
return this._byteString.toBase64();
}
/**
* Returns the underlying bytes in a new `Uint8Array`.
*
* @returns The Uint8Array created from the `Bytes` object.
*/ toUint8Array() {
return this._byteString.toUint8Array();
}
/**
* Returns a string representation of the `Bytes` object.
*
* @returns A string representation of the `Bytes` object.
*/ toString() {
return "Bytes(base64: " + this.toBase64() + ")";
}
/**
* Returns true if this `Bytes` object is equal to the provided one.
*
* @param other - The `Bytes` object to compare against.
* @returns true if this `Bytes` object is equal to the provided one.
*/ isEqual(t) {
return this._byteString.isEqual(t._byteString);
}
}
/**
* @license
* Copyright 2017 Google 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.
*/ /**
* An immutable object representing a geographic location in Firestore. The
* location is represented as latitude/longitude pair.
*
* Latitude values are in the range of [-90, 90].
* Longitude values are in the range of [-180, 180].
*/ class tu {
/**
* Creates a new immutable `GeoPoint` object with the provided latitude and
* longitude values.
* @param latitude - The latitude as number between -90 and 90.
* @param longitude - The longitude as number between -180 and 180.
*/ constructor(t, e){
if (!isFinite(t) || t < -90 || t > 90) throw new j(K.INVALID_ARGUMENT, "Latitude must be a number between -90 and 90, but was: " + t);
if (!isFinite(e) || e < -180 || e > 180) throw new j(K.INVALID_ARGUMENT, "Longitude must be a number between -180 and 180, but was: " + e);
this._lat = t, this._long = e;
}
/**
* The latitude of this `GeoPoint` instance.
*/ get latitude() {
return this._lat;
}
/**
* The longitude of this `GeoPoint` instance.
*/ get longitude() {
return this._long;
}
/**
* Returns true if this `GeoPoint` is equal to the provided one.
*
* @param other - The `GeoPoint` to compare against.
* @returns true if this `GeoPoint` is equal to the provided one.
*/ isEqual(t) {
return this._lat === t._lat && this._long === t._long;
}
/** Returns a JSON-serializable representation of this GeoPoint. */ toJSON() {
return {
latitude: this._lat,
longitude: this._long
};
}
/**
* Actually private to JS consumers of our API, so this function is prefixed
* with an underscore.
*/ _compareTo(t) {
return et(this._lat, t._lat) || et(this._long, t._long);
}
}
/**
* Matches any characters in a field path string that are reserved.
*/ const Au = RegExp("[~\\*/\\[\\]]");
function bu(t, e, n, s, i) {
const r = s && !s.isEmpty(), o = void 0 !== i;
let c = `Function ${e}() called with invalid data`;
n && (c += " (via `toFirestore()`)"), c += ". ";
let a = "";
return (r || o) && (a += " (found", r && (a += ` in field ${s}`), o && (a += ` in document ${i}`), a += ")"), new j(K.INVALID_ARGUMENT, c + t + a);
}
/**
* @license
* Copyright 2020 Google 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.
*/ /**
* A `DocumentSnapshot` contains data read from a document in your Firestore
* database. The data can be extracted with `.data()` or `.get(<field>)` to
* get a specific field.
*
* For a `DocumentSnapshot` that points to a non-existing document, any data
* access will return 'undefined'. You can use the `exists()` method to
* explicitly verify a document's existence.
*/ class vu {
// Note: This class is stripped down version of the DocumentSnapshot in
// the legacy SDK. The changes are:
// - No support for SnapshotMetadata.
// - No support for SnapshotOptions.
/** @hideconstructor protected */ constructor(t, e, n, s, i){
this._firestore = t, this._userDataWriter = e, this._key = n, this._document = s, this._converter = i;
}
/** Property of the `DocumentSnapshot` that provides the document's ID. */ get id() {
return this._key.path.lastSegment();
}
/**
* The `DocumentReference` for the document included in the `DocumentSnapshot`.
*/ get ref() {
return new Ia(this._firestore, this._converter, this._key);
}
/**
* Signals whether or not the document at the snapshot's location exists.
*
* @returns true if the document exists.
*/ exists() {
return null !== this._document;
}
/**
* Retrieves all fields in the document as an `Object`. Returns `undefined` if
* the document doesn't exist.
*
* @returns An `Object` containing all fields in the document or `undefined`
* if the document doesn't exist.
*/ data() {
if (this._document) {
if (this._converter) {
// We only want to use the converter and create a new DocumentSnapshot
// if a converter has been provided.
const t = new Vu(this._firestore, this._userDataWriter, this._key, this._document, /* converter= */ null);
return this._converter.fromFirestore(t);
}
return this._userDataWriter.convertValue(this._document.data.value);
}
}
/**
* Retrieves the field specified by `fieldPath`. Returns `undefined` if the
* document or field doesn't exist.
*
* @param fieldPath - The path (for example 'foo' or 'foo.bar') to a specific
* field.
* @returns The data at the specified field location or undefined if no such
* field exists in the document.
*/ // We are using `any` here to avoid an explicit cast by our users.
// eslint-disable-next-line @typescript-eslint/no-explicit-any
get(t) {
if (this._document) {
const e = this._document.data.field(Su("DocumentSnapshot.get", t));
if (null !== e) return this._userDataWriter.convertValue(e);
}
}
}
/**
* A `QueryDocumentSnapshot` contains data read from a document in your
* Firestore database as part of a query. The document is guaranteed to exist
* and its data can be extracted with `.data()` or `.get(<field>)` to get a
* specific field.
*
* A `QueryDocumentSnapshot` offers the same API surface as a
* `DocumentSnapshot`. Since query results contain only existing documents, the
* `exists` property will always be true and `data()` will never return
* 'undefined'.
*/ class Vu extends vu {
/**
* Retrieves all fields in the document as an `Object`.
*
* @override
* @returns An `Object` containing all fields in the document.
*/ data() {
return super.data();
}
}
/**
* Helper that calls `fromDotSeparatedString()` but wraps any error thrown.
*/ function Su(t, e) {
return "string" == typeof e ? /**
* Wraps fromDotSeparatedString with an error message about the method that
* was thrown.
* @param methodName - The publicly visible method name
* @param path - The dot-separated string form of a field path which will be
* split on dots.
* @param targetDoc - The document against which the field path will be
* evaluated.
*/ function(t, e, n) {
if (e.search(Au) >= 0) throw bu(`Invalid field path (${e}). Paths must not contain '~', '*', '/', '[', or ']'`, t, /* hasConverter= */ !1, /* path= */ void 0, void 0);
try {
return new Ja(...e.split("."))._internalPath;
} catch (s) {
throw bu(`Invalid field path (${e}). Paths must not be empty, begin with '.', end with '.', or contain '..'`, t, /* hasConverter= */ !1, /* path= */ void 0, void 0);
}
}(t, e) : e instanceof Ja ? e._internalPath : e._delegate._internalPath;
}
/**
* @license
* Copyright 2020 Google 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.
*/ /**
* Metadata about a snapshot, describing the state of the snapshot.
*/ class Du {
/** @hideconstructor */ constructor(t, e){
this.hasPendingWrites = t, this.fromCache = e;
}
/**
* Returns true if this `SnapshotMetadata` is equal to the provided one.
*
* @param other - The `SnapshotMetadata` to compare against.
* @returns true if this `SnapshotMetadata` is equal to the provided one.
*/ isEqual(t) {
return this.hasPendingWrites === t.hasPendingWrites && this.fromCache === t.fromCache;
}
}
/**
* A `DocumentSnapshot` contains data read from a document in your Firestore
* database. The data can be extracted with `.data()` or `.get(<field>)` to
* get a specific field.
*
* For a `DocumentSnapshot` that points to a non-existing document, any data
* access will return 'undefined'. You can use the `exists()` method to
* explicitly verify a document's existence.
*/ class Cu extends vu {
/** @hideconstructor protected */ constructor(t, e, n, s, i, r){
super(t, e, n, s, r), this._firestore = t, this._firestoreImpl = t, this.metadata = i;
}
/**
* Property of the `DocumentSnapshot` that signals whether or not the data
* exists. True if the document exists.
*/ exists() {
return super.exists();
}
/**
* Retrieves all fields in the document as an `Object`. Returns `undefined` if
* the document doesn't exist.
*
* By default, `FieldValue.serverTimestamp()` values that have not yet been
* set to their final value will be returned as `null`. You can override
* this by passing an options object.
*
* @param options - An options object to configure how data is retrieved from
* the snapshot (for example the desired behavior for server timestamps that
* have not yet been set to their final value).
* @returns An `Object` containing all fields in the document or `undefined` if
* the document doesn't exist.
*/ data(t = {}) {
if (this._document) {
if (this._converter) {
// We only want to use the converter and create a new DocumentSnapshot
// if a converter has been provided.
const e = new Nu(this._firestore, this._userDataWriter, this._key, this._document, this.metadata, /* converter= */ null);
return this._converter.fromFirestore(e, t);
}
return this._userDataWriter.convertValue(this._document.data.value, t.serverTimestamps);
}
}
/**
* Retrieves the field specified by `fieldPath`. Returns `undefined` if the
* document or field doesn't exist.
*
* By default, a `FieldValue.serverTimestamp()` that has not yet been set to
* its final value will be returned as `null`. You can override this by
* passing an options object.
*
* @param fieldPath - The path (for example 'foo' or 'foo.bar') to a specific
* field.
* @param options - An options object to configure how the field is retrieved
* from the snapshot (for example the desired behavior for server timestamps
* that have not yet been set to their final value).
* @returns The data at the specified field location or undefined if no such
* field exists in the document.
*/ // We are using `any` here to avoid an explicit cast by our users.
// eslint-disable-next-line @typescript-eslint/no-explicit-any
get(t, e = {}) {
if (this._document) {
const n = this._document.data.field(Su("DocumentSnapshot.get", t));
if (null !== n) return this._userDataWriter.convertValue(n, e.serverTimestamps);
}
}
}
/**
* A `QueryDocumentSnapshot` contains data read from a document in your
* Firestore database as part of a query. The document is guaranteed to exist
* and its data can be extracted with `.data()` or `.get(<field>)` to get a
* specific field.
*
* A `QueryDocumentSnapshot` offers the same API surface as a
* `DocumentSnapshot`. Since query results contain only existing documents, the
* `exists` property will always be true and `data()` will never return
* 'undefined'.
*/ class Nu extends Cu {
/**
* Retrieves all fields in the document as an `Object`.
*
* By default, `FieldValue.serverTimestamp()` values that have not yet been
* set to their final value will be returned as `null`. You can override
* this by passing an options object.
*
* @override
* @param options - An options object to configure how data is retrieved from
* the snapshot (for example the desired behavior for server timestamps that
* have not yet been set to their final value).
* @returns An `Object` containing all fields in the document.
*/ data(t = {}) {
return super.data(t);
}
}
/**
* A `QuerySnapshot` contains zero or more `DocumentSnapshot` objects
* representing the results of a query. The documents can be accessed as an
* array via the `docs` property or enumerated using the `forEach` method. The
* number of documents can be determined via the `empty` and `size`
* properties.
*/ class xu {
/** @hideconstructor */ constructor(t, e, n, s){
this._firestore = t, this._userDataWriter = e, this._snapshot = s, this.metadata = new Du(s.hasPendingWrites, s.fromCache), this.query = n;
}
/** An array of all the documents in the `QuerySnapshot`. */ get docs() {
const t = [];
return this.forEach((e)=>t.push(e)), t;
}
/** The number of documents in the `QuerySnapshot`. */ get size() {
return this._snapshot.docs.size;
}
/** True if there are no documents in the `QuerySnapshot`. */ get empty() {
return 0 === this.size;
}
/**
* Enumerates all of the documents in the `QuerySnapshot`.
*
* @param callback - A callback to be called with a `QueryDocumentSnapshot` for
* each document in the snapshot.
* @param thisArg - The `this` binding for the callback.
*/ forEach(t, e) {
this._snapshot.docs.forEach((n)=>{
t.call(e, new Nu(this._firestore, this._userDataWriter, n.key, n, new Du(this._snapshot.mutatedKeys.has(n.key), this._snapshot.fromCache), this.query.converter));
});
}
/**
* Returns an array of the documents changes since the last snapshot. If this
* is the first snapshot, all documents will be in the list as 'added'
* changes.
*
* @param options - `SnapshotListenOptions` that control whether metadata-only
* changes (i.e. only `DocumentSnapshot.metadata` changed) should trigger
* snapshot events.
*/ docChanges(t = {}) {
const e = !!t.includeMetadataChanges;
if (e && this._snapshot.excludesMetadataChanges) throw new j(K.INVALID_ARGUMENT, "To include metadata changes with your document changes, you must also pass { includeMetadataChanges:true } to onSnapshot().");
return this._cachedChanges && this._cachedChangesIncludeMetadataChanges === e || (this._cachedChanges = /** Calculates the array of `DocumentChange`s for a given `ViewSnapshot`. */ function(t, e) {
if (t._snapshot.oldDocs.isEmpty()) {
let e = 0;
return t._snapshot.docChanges.map((n)=>({
type: "added",
doc: new Nu(t._firestore, t._userDataWriter, n.doc.key, n.doc, new Du(t._snapshot.mutatedKeys.has(n.doc.key), t._snapshot.fromCache), t.query.converter),
oldIndex: -1,
newIndex: e++
}));
}
{
// A `DocumentSet` that is updated incrementally as changes are applied to use
// to lookup the index of a document.
let n = t._snapshot.oldDocs;
return t._snapshot.docChanges.filter((t)=>e || 3 /* Metadata */ !== t.type).map((e)=>{
const s = new Nu(t._firestore, t._userDataWriter, e.doc.key, e.doc, new Du(t._snapshot.mutatedKeys.has(e.doc.key), t._snapshot.fromCache), t.query.converter);
let i = -1, r = -1;
return 0 /* Added */ !== e.type && (i = n.indexOf(e.doc.key), n = n.delete(e.doc.key)), 1 /* Removed */ !== e.type && (r = (n = n.add(e.doc)).indexOf(e.doc.key)), {
type: function(t) {
switch(t){
case 0 /* Added */ :
return "added";
case 2 /* Modified */ :
case 3 /* Metadata */ :
return "modified";
case 1 /* Removed */ :
return "removed";
default:
return L();
}
}(e.type),
doc: s,
oldIndex: i,
newIndex: r
};
});
}
}(this, e), this._cachedChangesIncludeMetadataChanges = e), this._cachedChanges;
}
}
/**
* @license
* Copyright 2020 Google 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.
*/ /**
* Converts Firestore's internal types to the JavaScript types that we expose
* to the user.
*
* @internal
*/ class nh {
convertValue(t, e = "none") {
switch(vt(t)){
case 0 /* NullValue */ :
return null;
case 1 /* BooleanValue */ :
return t.booleanValue;
case 2 /* NumberValue */ :
return yt(t.integerValue || t.doubleValue);
case 3 /* TimestampValue */ :
return this.convertTimestamp(t.timestampValue);
case 4 /* ServerTimestampValue */ :
return this.convertServerTimestamp(t, e);
case 5 /* StringValue */ :
return t.stringValue;
case 6 /* BlobValue */ :
return this.convertBytes(pt(t.bytesValue));
case 7 /* RefValue */ :
return this.convertReference(t.referenceValue);
case 8 /* GeoPointValue */ :
return this.convertGeoPoint(t.geoPointValue);
case 9 /* ArrayValue */ :
return this.convertArray(t.arrayValue, e);
case 10 /* ObjectValue */ :
return this.convertObject(t.mapValue, e);
default:
throw L();
}
}
convertObject(t, e) {
const n = {};
return ct(t.fields, (t, s)=>{
n[t] = this.convertValue(s, e);
}), n;
}
convertGeoPoint(t) {
return new tu(yt(t.latitude), yt(t.longitude));
}
convertArray(t, e) {
return (t.values || []).map((t)=>this.convertValue(t, e));
}
convertServerTimestamp(t, e) {
switch(e){
case "previous":
const n = /**
* Creates a new ServerTimestamp proto value (using the internal format).
*/ /**
* Returns the value of the field before this ServerTimestamp was set.
*
* Preserving the previous values allows the user to display the last resoled
* value until the backend responds with the timestamp.
*/ function Et(t) {
const e = t.mapValue.fields.__previous_value__;
return Tt(e) ? Et(e) : e;
}(t);
return null == n ? null : this.convertValue(n, e);
case "estimate":
return this.convertTimestamp(It(t));
default:
return null;
}
}
convertTimestamp(t) {
const e = gt(t);
return new it(e.seconds, e.nanos);
}
convertDocumentKey(t, e) {
const n = ht.fromString(t);
Ts(n) || L();
const s = new ha(n.get(1), n.get(3)), i = new Pt(n.popFirst(5));
return s.isEqual(e) || // TODO(b/64130202): Somehow support foreign references.
O(`Document ${i} contains a document reference within a different database (${s.projectId}/${s.database}) which is not supported. It will be treated as a reference in the current database (${e.projectId}/${e.database}) instead.`), i;
}
}
class ah extends nh {
constructor(t){
super(), this.firestore = t;
}
convertBytes(t) {
return new Xa(t);
}
convertReference(t) {
const e = this.convertDocumentKey(t, this.firestore._databaseId);
return new Ia(this.firestore, /* converter= */ null, e);
}
}
/**
* Executes the query and returns the results as a `QuerySnapshot`.
*
* Note: `getDocs()` attempts to provide up-to-date data when possible by
* waiting for data from the server, but it may return cached data or fail if
* you are offline and the server cannot be reached. To specify this behavior,
* invoke {@link getDocsFromCache} or {@link getDocsFromServer}.
*
* @returns A `Promise` that will be resolved with the results of the query.
*/ function lh(t) {
t = ga(t, Aa);
const e = ga(t.firestore, ka), n = (e._firestoreClient || Ma(e), e._firestoreClient.verifyNotTerminated(), e._firestoreClient), s = new ah(e);
return(/**
* @license
* Copyright 2020 Google 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.
*/ function(t) {
if (me(t) && 0 === t.explicitOrderBy.length) throw new j(K.UNIMPLEMENTED, "limitToLast() queries require specifying at least one orderBy() clause");
}(t._query), (function(t, e, n = {}) {
const s = new Q();
return t.asyncQueue.enqueueAndForget(async ()=>(function(t, e, n, s, i) {
const o = new Qo(n, new Lc({
next: (n)=>{
// Remove query first before passing event to user to avoid
// user actions affecting the now stale query.
e.enqueueAndForget(()=>Uo(t, o)), n.fromCache && "server" === s.source ? i.reject(new j(K.UNAVAILABLE, 'Failed to get documents from server. (However, these documents may exist in the local cache. Run again without setting source to "server" to retrieve the cached documents.)')) : i.resolve(n);
},
error: (t)=>i.reject(t)
}), {
includeMetadataChanges: !0,
fo: !0
});
return Bo(t, o);
})(await Xc(t), t.asyncQueue, e, n, s)), s.promise;
})(n, t._query).then((n)=>new xu(e, s, t, n)));
}
/**
* Cloud Firestore
*
* @packageDocumentation
*/ !function(t, e = !0) {
C = _firebase_app__WEBPACK_IMPORTED_MODULE_0__ /* .SDK_VERSION */ .Jn, (0, _firebase_app__WEBPACK_IMPORTED_MODULE_0__ /* ._registerComponent */ .Xd)(new _firebase_component__WEBPACK_IMPORTED_MODULE_1__ /* .Component */ .wA("firestore", (t, { options: n })=>{
const i = new ka(t.getProvider("app").getImmediate(), new H(t.getProvider("auth-internal")));
return n = Object.assign({
useFetchStreams: e
}, n), i._setSettings(n), i;
}, "PUBLIC" /* PUBLIC */ )), (0, _firebase_app__WEBPACK_IMPORTED_MODULE_0__ /* .registerVersion */ .KN)(S, "3.3.0", void 0), // BUILD_TARGET will be replaced by values like esm5, esm2017, cjs5, etc during the compilation
(0, _firebase_app__WEBPACK_IMPORTED_MODULE_0__ /* .registerVersion */ .KN)(S, "3.3.0", "esm2017");
}();
//# sourceMappingURL=index.esm2017.js.map
/***/ }
}
]);
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_minifier/tests/fixture/issues/firebase/2/input.js | JavaScript | export function treeSubTree(tree, pathObj) {
// TODO: Require pathObj to be Path?
let path = pathObj instanceof Path ? pathObj : new Path(pathObj);
let child = tree,
next = pathGetFront(path);
while (next !== null) {
const childNode = safeGet(child.node.children, next) || {
children: {},
childCount: 0,
};
child = new Tree(next, child, childNode);
path = pathPopFront(path);
next = pathGetFront(path);
}
return child;
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_minifier/tests/fixture/issues/firebase/2/output.js | JavaScript | export function treeSubTree(tree, pathObj) {
// TODO: Require pathObj to be Path?
let path = pathObj instanceof Path ? pathObj : new Path(pathObj), child = tree, next = pathGetFront(path);
for(; null !== next;){
const childNode = safeGet(child.node.children, next) || {
children: {},
childCount: 0
};
child = new Tree(next, child, childNode), next = pathGetFront(path = pathPopFront(path));
}
return child;
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_minifier/tests/fixture/issues/framer-motion/1/input.js | JavaScript | // `resolveVariantFromProps` in framer-motion
// https://github.com/motiondivision/motion/blob/ecd97f7dce8954be300aa73ab6a96208437941c5/packages/framer-motion/src/render/utils/resolve-variants.ts#L31-L72
export function resolveVariantFromProps(props, definition, custom, visualElement) {
if (typeof definition === "function") {
const [current, velocity] = getValueState(visualElement)
definition = definition(
custom !== undefined ? custom : props.custom,
current,
velocity
)
}
if (typeof definition === "string") {
definition = props.variants && props.variants[definition]
}
if (typeof definition === "function") {
const [current, velocity] = getValueState(visualElement)
definition = definition(
custom !== undefined ? custom : props.custom,
current,
velocity
)
}
return definition
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_minifier/tests/fixture/issues/framer-motion/1/output.js | JavaScript | // `resolveVariantFromProps` in framer-motion
// https://github.com/motiondivision/motion/blob/ecd97f7dce8954be300aa73ab6a96208437941c5/packages/framer-motion/src/render/utils/resolve-variants.ts#L31-L72
export function resolveVariantFromProps(props, definition, custom, visualElement) {
if ("function" == typeof definition) {
const [current, velocity] = getValueState(visualElement);
definition = definition(void 0 !== custom ? custom : props.custom, current, velocity);
}
if ("string" == typeof definition && (definition = props.variants && props.variants[definition]), "function" == typeof definition) {
const [current, velocity] = getValueState(visualElement);
definition = definition(void 0 !== custom ? custom : props.custom, current, velocity);
}
return definition;
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_minifier/tests/fixture/issues/issue-2604/1/input.js | JavaScript | push({
"": function () {
(function () {
function za() {
if (/$/)
try {
return eval(a);
} catch (b) {}
}
function Rb(a) {
return p() ? JSON : za();
}
h.get = function (a) {
return null == a ? null : Rb(a);
};
})();
},
"App.jsx": function () {
var shadowmap_pars_vertex = "";
var shadowmap_vertex = "";
var shadowmask_pars_fragment = "";
var skinbase_vertex = "";
var skinning_pars_vertex = "";
var skinning_vertex = "";
var skinnormal_vertex = "";
var specularmap_fragment = "";
var specularmap_pars_fragment = "";
var tonemapping_fragment = "";
var tonemapping_pars_fragment = "";
var uv_pars_fragment = "";
var uv_pars_vertex = "";
var uv_vertex = "";
var uv2_pars_fragment = "";
var uv2_pars_vertex = "";
var uv2_vertex = "";
var worldpos_vertex = "";
var cube_frag = "";
var cube_vert = "";
var depth_frag = "";
var depth_vert = "";
var distanceRGBA_frag = "";
var distanceRGBA_vert = "";
var equirect_frag = "";
var equirect_vert = "";
var linedashed_frag = "";
var linedashed_vert = "";
var meshphong_frag = "";
var meshphong_vert = "";
var ShaderChunk = {
shadowmap_pars_vertex: shadowmap_pars_vertex,
shadowmap_vertex: shadowmap_vertex,
shadowmask_pars_fragment: shadowmask_pars_fragment,
skinbase_vertex: skinbase_vertex,
skinning_pars_vertex: skinning_pars_vertex,
skinning_vertex: skinning_vertex,
skinnormal_vertex: skinnormal_vertex,
specularmap_fragment: specularmap_fragment,
specularmap_pars_fragment: specularmap_pars_fragment,
tonemapping_fragment: tonemapping_fragment,
tonemapping_pars_fragment: tonemapping_pars_fragment,
uv_pars_fragment: uv_pars_fragment,
uv_pars_vertex: uv_pars_vertex,
uv_vertex: uv_vertex,
uv2_pars_fragment: uv2_pars_fragment,
uv2_pars_vertex: uv2_pars_vertex,
uv2_vertex: uv2_vertex,
worldpos_vertex: worldpos_vertex,
cube_frag: cube_frag,
cube_vert: cube_vert,
depth_frag: depth_frag,
depth_vert: depth_vert,
distanceRGBA_frag: distanceRGBA_frag,
distanceRGBA_vert: distanceRGBA_vert,
equirect_frag: equirect_frag,
equirect_vert: equirect_vert,
linedashed_frag: linedashed_frag,
linedashed_vert: linedashed_vert,
meshphong_frag: meshphong_frag,
};
ShaderLib.physical = {
x: ShaderChunk.meshphysical_frag,
};
},
});
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_minifier/tests/fixture/issues/issue-2604/1/output.js | JavaScript | push({
"": function() {
!function() {
function za() {
try {
return eval(a);
} catch (b) {}
}
function Rb(a1) {
return p() ? JSON : za();
}
h.get = function(a1) {
return null == a1 ? null : Rb(a1);
};
}();
},
"App.jsx": function() {
var ShaderChunk = {
shadowmap_pars_vertex: "",
shadowmap_vertex: "",
shadowmask_pars_fragment: "",
skinbase_vertex: "",
skinning_pars_vertex: "",
skinning_vertex: "",
skinnormal_vertex: "",
specularmap_fragment: "",
specularmap_pars_fragment: "",
tonemapping_fragment: "",
tonemapping_pars_fragment: "",
uv_pars_fragment: "",
uv_pars_vertex: "",
uv_vertex: "",
uv2_pars_fragment: "",
uv2_pars_vertex: "",
uv2_vertex: "",
worldpos_vertex: "",
cube_frag: "",
cube_vert: "",
depth_frag: "",
depth_vert: "",
distanceRGBA_frag: "",
distanceRGBA_vert: "",
equirect_frag: "",
equirect_vert: "",
linedashed_frag: "",
linedashed_vert: "",
meshphong_frag: ""
};
ShaderLib.physical = {
x: ShaderChunk.meshphysical_frag
};
}
});
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_minifier/tests/fixture/issues/lit_comparisons/input.js | JavaScript | const a = 3;
const b = 4;
const c = "3";
const d = "4";
const e = {};
const f = {};
const g = true;
const h = false;
const j = null;
console.log(a === b, c === d, e === f, g === h, h === j);
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_minifier/tests/fixture/issues/lit_comparisons/output.js | JavaScript | const h = false;
console.log(false, false, ({}) == {}, false, false);
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_minifier/tests/fixture/issues/moment/1/input.js | JavaScript | //! moment.js
//! version : 2.29.1
//! authors : Tim Wood, Iskren Chernev, Moment.js contributors
//! license : MIT
//! momentjs.com
(function (global, factory) {
typeof exports === "object" && typeof module !== "undefined"
? (module.exports = factory())
: typeof define === "function" && define.amd
? define(factory)
: (global.moment = factory());
})(this, function () {
"use strict";
var hookCallback;
function hooks() {
return hookCallback.apply(null, arguments);
}
// This is done to register the method called with moment()
// without creating circular dependencies.
function setHookCallback(callback) {
hookCallback = callback;
}
function isArray(input) {
return (
input instanceof Array ||
Object.prototype.toString.call(input) === "[object Array]"
);
}
function isObject(input) {
// IE8 will treat undefined and null as object if it wasn't for
// input != null
return (
input != null &&
Object.prototype.toString.call(input) === "[object Object]"
);
}
function hasOwnProp(a, b) {
return Object.prototype.hasOwnProperty.call(a, b);
}
function isObjectEmpty(obj) {
if (Object.getOwnPropertyNames) {
return Object.getOwnPropertyNames(obj).length === 0;
} else {
var k;
for (k in obj) {
if (hasOwnProp(obj, k)) {
return false;
}
}
return true;
}
}
function isUndefined(input) {
return input === void 0;
}
function isNumber(input) {
return (
typeof input === "number" ||
Object.prototype.toString.call(input) === "[object Number]"
);
}
function isDate(input) {
return (
input instanceof Date ||
Object.prototype.toString.call(input) === "[object Date]"
);
}
function map(arr, fn) {
var res = [],
i;
for (i = 0; i < arr.length; ++i) {
res.push(fn(arr[i], i));
}
return res;
}
function extend(a, b) {
for (var i in b) {
if (hasOwnProp(b, i)) {
a[i] = b[i];
}
}
if (hasOwnProp(b, "toString")) {
a.toString = b.toString;
}
if (hasOwnProp(b, "valueOf")) {
a.valueOf = b.valueOf;
}
return a;
}
function createUTC(input, format, locale, strict) {
return createLocalOrUTC(input, format, locale, strict, true).utc();
}
function defaultParsingFlags() {
// We need to deep clone this object.
return {
empty: false,
unusedTokens: [],
unusedInput: [],
overflow: -2,
charsLeftOver: 0,
nullInput: false,
invalidEra: null,
invalidMonth: null,
invalidFormat: false,
userInvalidated: false,
iso: false,
parsedDateParts: [],
era: null,
meridiem: null,
rfc2822: false,
weekdayMismatch: false,
};
}
function getParsingFlags(m) {
if (m._pf == null) {
m._pf = defaultParsingFlags();
}
return m._pf;
}
var some;
if (Array.prototype.some) {
some = Array.prototype.some;
} else {
some = function (fun) {
var t = Object(this),
len = t.length >>> 0,
i;
for (i = 0; i < len; i++) {
if (i in t && fun.call(this, t[i], i, t)) {
return true;
}
}
return false;
};
}
function isValid(m) {
if (m._isValid == null) {
var flags = getParsingFlags(m),
parsedParts = some.call(flags.parsedDateParts, function (i) {
return i != null;
}),
isNowValid =
!isNaN(m._d.getTime()) &&
flags.overflow < 0 &&
!flags.empty &&
!flags.invalidEra &&
!flags.invalidMonth &&
!flags.invalidWeekday &&
!flags.weekdayMismatch &&
!flags.nullInput &&
!flags.invalidFormat &&
!flags.userInvalidated &&
(!flags.meridiem || (flags.meridiem && parsedParts));
if (m._strict) {
isNowValid =
isNowValid &&
flags.charsLeftOver === 0 &&
flags.unusedTokens.length === 0 &&
flags.bigHour === undefined;
}
if (Object.isFrozen == null || !Object.isFrozen(m)) {
m._isValid = isNowValid;
} else {
return isNowValid;
}
}
return m._isValid;
}
function createInvalid(flags) {
var m = createUTC(NaN);
if (flags != null) {
extend(getParsingFlags(m), flags);
} else {
getParsingFlags(m).userInvalidated = true;
}
return m;
}
// Plugins that add properties should also add the key here (null value),
// so we can properly clone ourselves.
var momentProperties = (hooks.momentProperties = []),
updateInProgress = false;
function copyConfig(to, from) {
var i, prop, val;
if (!isUndefined(from._isAMomentObject)) {
to._isAMomentObject = from._isAMomentObject;
}
if (!isUndefined(from._i)) {
to._i = from._i;
}
if (!isUndefined(from._f)) {
to._f = from._f;
}
if (!isUndefined(from._l)) {
to._l = from._l;
}
if (!isUndefined(from._strict)) {
to._strict = from._strict;
}
if (!isUndefined(from._tzm)) {
to._tzm = from._tzm;
}
if (!isUndefined(from._isUTC)) {
to._isUTC = from._isUTC;
}
if (!isUndefined(from._offset)) {
to._offset = from._offset;
}
if (!isUndefined(from._pf)) {
to._pf = getParsingFlags(from);
}
if (!isUndefined(from._locale)) {
to._locale = from._locale;
}
if (momentProperties.length > 0) {
for (i = 0; i < momentProperties.length; i++) {
prop = momentProperties[i];
val = from[prop];
if (!isUndefined(val)) {
to[prop] = val;
}
}
}
return to;
}
// Moment prototype object
function Moment(config) {
copyConfig(this, config);
this._d = new Date(config._d != null ? config._d.getTime() : NaN);
if (!this.isValid()) {
this._d = new Date(NaN);
}
// Prevent infinite loop in case updateOffset creates new moment
// objects.
if (updateInProgress === false) {
updateInProgress = true;
hooks.updateOffset(this);
updateInProgress = false;
}
}
function isMoment(obj) {
return (
obj instanceof Moment ||
(obj != null && obj._isAMomentObject != null)
);
}
function warn(msg) {
if (
hooks.suppressDeprecationWarnings === false &&
typeof console !== "undefined" &&
console.warn
) {
console.warn("Deprecation warning: " + msg);
}
}
function deprecate(msg, fn) {
var firstTime = true;
return extend(function () {
if (hooks.deprecationHandler != null) {
hooks.deprecationHandler(null, msg);
}
if (firstTime) {
var args = [],
arg,
i,
key;
for (i = 0; i < arguments.length; i++) {
arg = "";
if (typeof arguments[i] === "object") {
arg += "\n[" + i + "] ";
for (key in arguments[0]) {
if (hasOwnProp(arguments[0], key)) {
arg += key + ": " + arguments[0][key] + ", ";
}
}
arg = arg.slice(0, -2); // Remove trailing comma and space
} else {
arg = arguments[i];
}
args.push(arg);
}
warn(
msg +
"\nArguments: " +
Array.prototype.slice.call(args).join("") +
"\n" +
new Error().stack
);
firstTime = false;
}
return fn.apply(this, arguments);
}, fn);
}
var deprecations = {};
function deprecateSimple(name, msg) {
if (hooks.deprecationHandler != null) {
hooks.deprecationHandler(name, msg);
}
if (!deprecations[name]) {
warn(msg);
deprecations[name] = true;
}
}
hooks.suppressDeprecationWarnings = false;
hooks.deprecationHandler = null;
function isFunction(input) {
return (
(typeof Function !== "undefined" && input instanceof Function) ||
Object.prototype.toString.call(input) === "[object Function]"
);
}
function set(config) {
var prop, i;
for (i in config) {
if (hasOwnProp(config, i)) {
prop = config[i];
if (isFunction(prop)) {
this[i] = prop;
} else {
this["_" + i] = prop;
}
}
}
this._config = config;
// Lenient ordinal parsing accepts just a number in addition to
// number + (possibly) stuff coming from _dayOfMonthOrdinalParse.
// TODO: Remove "ordinalParse" fallback in next major release.
this._dayOfMonthOrdinalParseLenient = new RegExp(
(this._dayOfMonthOrdinalParse.source || this._ordinalParse.source) +
"|" +
/\d{1,2}/.source
);
}
function mergeConfigs(parentConfig, childConfig) {
var res = extend({}, parentConfig),
prop;
for (prop in childConfig) {
if (hasOwnProp(childConfig, prop)) {
if (
isObject(parentConfig[prop]) &&
isObject(childConfig[prop])
) {
res[prop] = {};
extend(res[prop], parentConfig[prop]);
extend(res[prop], childConfig[prop]);
} else if (childConfig[prop] != null) {
res[prop] = childConfig[prop];
} else {
delete res[prop];
}
}
}
for (prop in parentConfig) {
if (
hasOwnProp(parentConfig, prop) &&
!hasOwnProp(childConfig, prop) &&
isObject(parentConfig[prop])
) {
// make sure changes to properties don't modify parent config
res[prop] = extend({}, res[prop]);
}
}
return res;
}
function Locale(config) {
if (config != null) {
this.set(config);
}
}
var keys;
if (Object.keys) {
keys = Object.keys;
} else {
keys = function (obj) {
var i,
res = [];
for (i in obj) {
if (hasOwnProp(obj, i)) {
res.push(i);
}
}
return res;
};
}
var defaultCalendar = {
sameDay: "[Today at] LT",
nextDay: "[Tomorrow at] LT",
nextWeek: "dddd [at] LT",
lastDay: "[Yesterday at] LT",
lastWeek: "[Last] dddd [at] LT",
sameElse: "L",
};
function calendar(key, mom, now) {
var output = this._calendar[key] || this._calendar["sameElse"];
return isFunction(output) ? output.call(mom, now) : output;
}
function zeroFill(number, targetLength, forceSign) {
var absNumber = "" + Math.abs(number),
zerosToFill = targetLength - absNumber.length,
sign = number >= 0;
return (
(sign ? (forceSign ? "+" : "") : "-") +
Math.pow(10, Math.max(0, zerosToFill)).toString().substr(1) +
absNumber
);
}
var formattingTokens =
/(\[[^\[]*\])|(\\)?([Hh]mm(ss)?|Mo|MM?M?M?|Do|DDDo|DD?D?D?|ddd?d?|do?|w[o|w]?|W[o|W]?|Qo?|N{1,5}|YYYYYY|YYYYY|YYYY|YY|y{2,4}|yo?|gg(ggg?)?|GG(GGG?)?|e|E|a|A|hh?|HH?|kk?|mm?|ss?|S{1,9}|x|X|zz?|ZZ?|.)/g,
localFormattingTokens = /(\[[^\[]*\])|(\\)?(LTS|LT|LL?L?L?|l{1,4})/g,
formatFunctions = {},
formatTokenFunctions = {};
// token: 'M'
// padded: ['MM', 2]
// ordinal: 'Mo'
// callback: function () { this.month() + 1 }
function addFormatToken(token, padded, ordinal, callback) {
var func = callback;
if (typeof callback === "string") {
func = function () {
return this[callback]();
};
}
if (token) {
formatTokenFunctions[token] = func;
}
if (padded) {
formatTokenFunctions[padded[0]] = function () {
return zeroFill(
func.apply(this, arguments),
padded[1],
padded[2]
);
};
}
if (ordinal) {
formatTokenFunctions[ordinal] = function () {
return this.localeData().ordinal(
func.apply(this, arguments),
token
);
};
}
}
function removeFormattingTokens(input) {
if (input.match(/\[[\s\S]/)) {
return input.replace(/^\[|\]$/g, "");
}
return input.replace(/\\/g, "");
}
function makeFormatFunction(format) {
var array = format.match(formattingTokens),
i,
length;
for (i = 0, length = array.length; i < length; i++) {
if (formatTokenFunctions[array[i]]) {
array[i] = formatTokenFunctions[array[i]];
} else {
array[i] = removeFormattingTokens(array[i]);
}
}
return function (mom) {
var output = "",
i;
for (i = 0; i < length; i++) {
output += isFunction(array[i])
? array[i].call(mom, format)
: array[i];
}
return output;
};
}
// format date using native date object
function formatMoment(m, format) {
if (!m.isValid()) {
return m.localeData().invalidDate();
}
format = expandFormat(format, m.localeData());
formatFunctions[format] =
formatFunctions[format] || makeFormatFunction(format);
return formatFunctions[format](m);
}
function expandFormat(format, locale) {
var i = 5;
function replaceLongDateFormatTokens(input) {
return locale.longDateFormat(input) || input;
}
localFormattingTokens.lastIndex = 0;
while (i >= 0 && localFormattingTokens.test(format)) {
format = format.replace(
localFormattingTokens,
replaceLongDateFormatTokens
);
localFormattingTokens.lastIndex = 0;
i -= 1;
}
return format;
}
var defaultLongDateFormat = {
LTS: "h:mm:ss A",
LT: "h:mm A",
L: "MM/DD/YYYY",
LL: "MMMM D, YYYY",
LLL: "MMMM D, YYYY h:mm A",
LLLL: "dddd, MMMM D, YYYY h:mm A",
};
function longDateFormat(key) {
var format = this._longDateFormat[key],
formatUpper = this._longDateFormat[key.toUpperCase()];
if (format || !formatUpper) {
return format;
}
this._longDateFormat[key] = formatUpper
.match(formattingTokens)
.map(function (tok) {
if (
tok === "MMMM" ||
tok === "MM" ||
tok === "DD" ||
tok === "dddd"
) {
return tok.slice(1);
}
return tok;
})
.join("");
return this._longDateFormat[key];
}
var defaultInvalidDate = "Invalid date";
function invalidDate() {
return this._invalidDate;
}
var defaultOrdinal = "%d",
defaultDayOfMonthOrdinalParse = /\d{1,2}/;
function ordinal(number) {
return this._ordinal.replace("%d", number);
}
var defaultRelativeTime = {
future: "in %s",
past: "%s ago",
s: "a few seconds",
ss: "%d seconds",
m: "a minute",
mm: "%d minutes",
h: "an hour",
hh: "%d hours",
d: "a day",
dd: "%d days",
w: "a week",
ww: "%d weeks",
M: "a month",
MM: "%d months",
y: "a year",
yy: "%d years",
};
function relativeTime(number, withoutSuffix, string, isFuture) {
var output = this._relativeTime[string];
return isFunction(output)
? output(number, withoutSuffix, string, isFuture)
: output.replace(/%d/i, number);
}
function pastFuture(diff, output) {
var format = this._relativeTime[diff > 0 ? "future" : "past"];
return isFunction(format)
? format(output)
: format.replace(/%s/i, output);
}
var aliases = {};
function addUnitAlias(unit, shorthand) {
var lowerCase = unit.toLowerCase();
aliases[lowerCase] =
aliases[lowerCase + "s"] =
aliases[shorthand] =
unit;
}
function normalizeUnits(units) {
return typeof units === "string"
? aliases[units] || aliases[units.toLowerCase()]
: undefined;
}
function normalizeObjectUnits(inputObject) {
var normalizedInput = {},
normalizedProp,
prop;
for (prop in inputObject) {
if (hasOwnProp(inputObject, prop)) {
normalizedProp = normalizeUnits(prop);
if (normalizedProp) {
normalizedInput[normalizedProp] = inputObject[prop];
}
}
}
return normalizedInput;
}
var priorities = {};
function addUnitPriority(unit, priority) {
priorities[unit] = priority;
}
function getPrioritizedUnits(unitsObj) {
var units = [],
u;
for (u in unitsObj) {
if (hasOwnProp(unitsObj, u)) {
units.push({ unit: u, priority: priorities[u] });
}
}
units.sort(function (a, b) {
return a.priority - b.priority;
});
return units;
}
function isLeapYear(year) {
return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;
}
function absFloor(number) {
if (number < 0) {
// -0 -> 0
return Math.ceil(number) || 0;
} else {
return Math.floor(number);
}
}
function toInt(argumentForCoercion) {
var coercedNumber = +argumentForCoercion,
value = 0;
if (coercedNumber !== 0 && isFinite(coercedNumber)) {
value = absFloor(coercedNumber);
}
return value;
}
function makeGetSet(unit, keepTime) {
return function (value) {
if (value != null) {
set$1(this, unit, value);
hooks.updateOffset(this, keepTime);
return this;
} else {
return get(this, unit);
}
};
}
function get(mom, unit) {
return mom.isValid()
? mom._d["get" + (mom._isUTC ? "UTC" : "") + unit]()
: NaN;
}
function set$1(mom, unit, value) {
if (mom.isValid() && !isNaN(value)) {
if (
unit === "FullYear" &&
isLeapYear(mom.year()) &&
mom.month() === 1 &&
mom.date() === 29
) {
value = toInt(value);
mom._d["set" + (mom._isUTC ? "UTC" : "") + unit](
value,
mom.month(),
daysInMonth(value, mom.month())
);
} else {
mom._d["set" + (mom._isUTC ? "UTC" : "") + unit](value);
}
}
}
// MOMENTS
function stringGet(units) {
units = normalizeUnits(units);
if (isFunction(this[units])) {
return this[units]();
}
return this;
}
function stringSet(units, value) {
if (typeof units === "object") {
units = normalizeObjectUnits(units);
var prioritized = getPrioritizedUnits(units),
i;
for (i = 0; i < prioritized.length; i++) {
this[prioritized[i].unit](units[prioritized[i].unit]);
}
} else {
units = normalizeUnits(units);
if (isFunction(this[units])) {
return this[units](value);
}
}
return this;
}
var match1 = /\d/, // 0 - 9
match2 = /\d\d/, // 00 - 99
match3 = /\d{3}/, // 000 - 999
match4 = /\d{4}/, // 0000 - 9999
match6 = /[+-]?\d{6}/, // -999999 - 999999
match1to2 = /\d\d?/, // 0 - 99
match3to4 = /\d\d\d\d?/, // 999 - 9999
match5to6 = /\d\d\d\d\d\d?/, // 99999 - 999999
match1to3 = /\d{1,3}/, // 0 - 999
match1to4 = /\d{1,4}/, // 0 - 9999
match1to6 = /[+-]?\d{1,6}/, // -999999 - 999999
matchUnsigned = /\d+/, // 0 - inf
matchSigned = /[+-]?\d+/, // -inf - inf
matchOffset = /Z|[+-]\d\d:?\d\d/gi, // +00:00 -00:00 +0000 -0000 or Z
matchShortOffset = /Z|[+-]\d\d(?::?\d\d)?/gi, // +00 -00 +00:00 -00:00 +0000 -0000 or Z
matchTimestamp = /[+-]?\d+(\.\d{1,3})?/, // 123456789 123456789.123
// any word (or two) characters or numbers including two/three word month in arabic.
// includes scottish gaelic two word and hyphenated months
matchWord =
/[0-9]{0,256}['a-z\u00A0-\u05FF\u0700-\uD7FF\uF900-\uFDCF\uFDF0-\uFF07\uFF10-\uFFEF]{1,256}|[\u0600-\u06FF\/]{1,256}(\s*?[\u0600-\u06FF]{1,256}){1,2}/i,
regexes;
regexes = {};
function addRegexToken(token, regex, strictRegex) {
regexes[token] = isFunction(regex)
? regex
: function (isStrict, localeData) {
return isStrict && strictRegex ? strictRegex : regex;
};
}
function getParseRegexForToken(token, config) {
if (!hasOwnProp(regexes, token)) {
return new RegExp(unescapeFormat(token));
}
return regexes[token](config._strict, config._locale);
}
// Code from http://stackoverflow.com/questions/3561493/is-there-a-regexp-escape-function-in-javascript
function unescapeFormat(s) {
return regexEscape(
s
.replace("\\", "")
.replace(
/\\(\[)|\\(\])|\[([^\]\[]*)\]|\\(.)/g,
function (matched, p1, p2, p3, p4) {
return p1 || p2 || p3 || p4;
}
)
);
}
function regexEscape(s) {
return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, "\\$&");
}
var tokens = {};
function addParseToken(token, callback) {
var i,
func = callback;
if (typeof token === "string") {
token = [token];
}
if (isNumber(callback)) {
func = function (input, array) {
array[callback] = toInt(input);
};
}
for (i = 0; i < token.length; i++) {
tokens[token[i]] = func;
}
}
function addWeekParseToken(token, callback) {
addParseToken(token, function (input, array, config, token) {
config._w = config._w || {};
callback(input, config._w, config, token);
});
}
function addTimeToArrayFromToken(token, input, config) {
if (input != null && hasOwnProp(tokens, token)) {
tokens[token](input, config._a, config, token);
}
}
var YEAR = 0,
MONTH = 1,
DATE = 2,
HOUR = 3,
MINUTE = 4,
SECOND = 5,
MILLISECOND = 6,
WEEK = 7,
WEEKDAY = 8;
function mod(n, x) {
return ((n % x) + x) % x;
}
var indexOf;
if (Array.prototype.indexOf) {
indexOf = Array.prototype.indexOf;
} else {
indexOf = function (o) {
// I know
var i;
for (i = 0; i < this.length; ++i) {
if (this[i] === o) {
return i;
}
}
return -1;
};
}
function daysInMonth(year, month) {
if (isNaN(year) || isNaN(month)) {
return NaN;
}
var modMonth = mod(month, 12);
year += (month - modMonth) / 12;
return modMonth === 1
? isLeapYear(year)
? 29
: 28
: 31 - ((modMonth % 7) % 2);
}
// FORMATTING
addFormatToken("M", ["MM", 2], "Mo", function () {
return this.month() + 1;
});
addFormatToken("MMM", 0, 0, function (format) {
return this.localeData().monthsShort(this, format);
});
addFormatToken("MMMM", 0, 0, function (format) {
return this.localeData().months(this, format);
});
// ALIASES
addUnitAlias("month", "M");
// PRIORITY
addUnitPriority("month", 8);
// PARSING
addRegexToken("M", match1to2);
addRegexToken("MM", match1to2, match2);
addRegexToken("MMM", function (isStrict, locale) {
return locale.monthsShortRegex(isStrict);
});
addRegexToken("MMMM", function (isStrict, locale) {
return locale.monthsRegex(isStrict);
});
addParseToken(["M", "MM"], function (input, array) {
array[MONTH] = toInt(input) - 1;
});
addParseToken(["MMM", "MMMM"], function (input, array, config, token) {
var month = config._locale.monthsParse(input, token, config._strict);
// if we didn't find a month name, mark the date as invalid.
if (month != null) {
array[MONTH] = month;
} else {
getParsingFlags(config).invalidMonth = input;
}
});
// LOCALES
var defaultLocaleMonths =
"January_February_March_April_May_June_July_August_September_October_November_December".split(
"_"
),
defaultLocaleMonthsShort =
"Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec".split("_"),
MONTHS_IN_FORMAT = /D[oD]?(\[[^\[\]]*\]|\s)+MMMM?/,
defaultMonthsShortRegex = matchWord,
defaultMonthsRegex = matchWord;
function localeMonths(m, format) {
if (!m) {
return isArray(this._months)
? this._months
: this._months["standalone"];
}
return isArray(this._months)
? this._months[m.month()]
: this._months[
(this._months.isFormat || MONTHS_IN_FORMAT).test(format)
? "format"
: "standalone"
][m.month()];
}
function localeMonthsShort(m, format) {
if (!m) {
return isArray(this._monthsShort)
? this._monthsShort
: this._monthsShort["standalone"];
}
return isArray(this._monthsShort)
? this._monthsShort[m.month()]
: this._monthsShort[
MONTHS_IN_FORMAT.test(format) ? "format" : "standalone"
][m.month()];
}
function handleStrictParse(monthName, format, strict) {
var i,
ii,
mom,
llc = monthName.toLocaleLowerCase();
if (!this._monthsParse) {
// this is not used
this._monthsParse = [];
this._longMonthsParse = [];
this._shortMonthsParse = [];
for (i = 0; i < 12; ++i) {
mom = createUTC([2000, i]);
this._shortMonthsParse[i] = this.monthsShort(
mom,
""
).toLocaleLowerCase();
this._longMonthsParse[i] = this.months(
mom,
""
).toLocaleLowerCase();
}
}
if (strict) {
if (format === "MMM") {
ii = indexOf.call(this._shortMonthsParse, llc);
return ii !== -1 ? ii : null;
} else {
ii = indexOf.call(this._longMonthsParse, llc);
return ii !== -1 ? ii : null;
}
} else {
if (format === "MMM") {
ii = indexOf.call(this._shortMonthsParse, llc);
if (ii !== -1) {
return ii;
}
ii = indexOf.call(this._longMonthsParse, llc);
return ii !== -1 ? ii : null;
} else {
ii = indexOf.call(this._longMonthsParse, llc);
if (ii !== -1) {
return ii;
}
ii = indexOf.call(this._shortMonthsParse, llc);
return ii !== -1 ? ii : null;
}
}
}
function localeMonthsParse(monthName, format, strict) {
var i, mom, regex;
if (this._monthsParseExact) {
return handleStrictParse.call(this, monthName, format, strict);
}
if (!this._monthsParse) {
this._monthsParse = [];
this._longMonthsParse = [];
this._shortMonthsParse = [];
}
// TODO: add sorting
// Sorting makes sure if one month (or abbr) is a prefix of another
// see sorting in computeMonthsParse
for (i = 0; i < 12; i++) {
// make the regex if we don't have it already
mom = createUTC([2000, i]);
if (strict && !this._longMonthsParse[i]) {
this._longMonthsParse[i] = new RegExp(
"^" + this.months(mom, "").replace(".", "") + "$",
"i"
);
this._shortMonthsParse[i] = new RegExp(
"^" + this.monthsShort(mom, "").replace(".", "") + "$",
"i"
);
}
if (!strict && !this._monthsParse[i]) {
regex =
"^" +
this.months(mom, "") +
"|^" +
this.monthsShort(mom, "");
this._monthsParse[i] = new RegExp(regex.replace(".", ""), "i");
}
// test the regex
if (
strict &&
format === "MMMM" &&
this._longMonthsParse[i].test(monthName)
) {
return i;
} else if (
strict &&
format === "MMM" &&
this._shortMonthsParse[i].test(monthName)
) {
return i;
} else if (!strict && this._monthsParse[i].test(monthName)) {
return i;
}
}
}
// MOMENTS
function setMonth(mom, value) {
var dayOfMonth;
if (!mom.isValid()) {
// No op
return mom;
}
if (typeof value === "string") {
if (/^\d+$/.test(value)) {
value = toInt(value);
} else {
value = mom.localeData().monthsParse(value);
// TODO: Another silent failure?
if (!isNumber(value)) {
return mom;
}
}
}
dayOfMonth = Math.min(mom.date(), daysInMonth(mom.year(), value));
mom._d["set" + (mom._isUTC ? "UTC" : "") + "Month"](value, dayOfMonth);
return mom;
}
function getSetMonth(value) {
if (value != null) {
setMonth(this, value);
hooks.updateOffset(this, true);
return this;
} else {
return get(this, "Month");
}
}
function getDaysInMonth() {
return daysInMonth(this.year(), this.month());
}
function monthsShortRegex(isStrict) {
if (this._monthsParseExact) {
if (!hasOwnProp(this, "_monthsRegex")) {
computeMonthsParse.call(this);
}
if (isStrict) {
return this._monthsShortStrictRegex;
} else {
return this._monthsShortRegex;
}
} else {
if (!hasOwnProp(this, "_monthsShortRegex")) {
this._monthsShortRegex = defaultMonthsShortRegex;
}
return this._monthsShortStrictRegex && isStrict
? this._monthsShortStrictRegex
: this._monthsShortRegex;
}
}
function monthsRegex(isStrict) {
if (this._monthsParseExact) {
if (!hasOwnProp(this, "_monthsRegex")) {
computeMonthsParse.call(this);
}
if (isStrict) {
return this._monthsStrictRegex;
} else {
return this._monthsRegex;
}
} else {
if (!hasOwnProp(this, "_monthsRegex")) {
this._monthsRegex = defaultMonthsRegex;
}
return this._monthsStrictRegex && isStrict
? this._monthsStrictRegex
: this._monthsRegex;
}
}
function computeMonthsParse() {
function cmpLenRev(a, b) {
return b.length - a.length;
}
var shortPieces = [],
longPieces = [],
mixedPieces = [],
i,
mom;
for (i = 0; i < 12; i++) {
// make the regex if we don't have it already
mom = createUTC([2000, i]);
shortPieces.push(this.monthsShort(mom, ""));
longPieces.push(this.months(mom, ""));
mixedPieces.push(this.months(mom, ""));
mixedPieces.push(this.monthsShort(mom, ""));
}
// Sorting makes sure if one month (or abbr) is a prefix of another it
// will match the longer piece.
shortPieces.sort(cmpLenRev);
longPieces.sort(cmpLenRev);
mixedPieces.sort(cmpLenRev);
for (i = 0; i < 12; i++) {
shortPieces[i] = regexEscape(shortPieces[i]);
longPieces[i] = regexEscape(longPieces[i]);
}
for (i = 0; i < 24; i++) {
mixedPieces[i] = regexEscape(mixedPieces[i]);
}
this._monthsRegex = new RegExp("^(" + mixedPieces.join("|") + ")", "i");
this._monthsShortRegex = this._monthsRegex;
this._monthsStrictRegex = new RegExp(
"^(" + longPieces.join("|") + ")",
"i"
);
this._monthsShortStrictRegex = new RegExp(
"^(" + shortPieces.join("|") + ")",
"i"
);
}
// FORMATTING
addFormatToken("Y", 0, 0, function () {
var y = this.year();
return y <= 9999 ? zeroFill(y, 4) : "+" + y;
});
addFormatToken(0, ["YY", 2], 0, function () {
return this.year() % 100;
});
addFormatToken(0, ["YYYY", 4], 0, "year");
addFormatToken(0, ["YYYYY", 5], 0, "year");
addFormatToken(0, ["YYYYYY", 6, true], 0, "year");
// ALIASES
addUnitAlias("year", "y");
// PRIORITIES
addUnitPriority("year", 1);
// PARSING
addRegexToken("Y", matchSigned);
addRegexToken("YY", match1to2, match2);
addRegexToken("YYYY", match1to4, match4);
addRegexToken("YYYYY", match1to6, match6);
addRegexToken("YYYYYY", match1to6, match6);
addParseToken(["YYYYY", "YYYYYY"], YEAR);
addParseToken("YYYY", function (input, array) {
array[YEAR] =
input.length === 2 ? hooks.parseTwoDigitYear(input) : toInt(input);
});
addParseToken("YY", function (input, array) {
array[YEAR] = hooks.parseTwoDigitYear(input);
});
addParseToken("Y", function (input, array) {
array[YEAR] = parseInt(input, 10);
});
// HELPERS
function daysInYear(year) {
return isLeapYear(year) ? 366 : 365;
}
// HOOKS
hooks.parseTwoDigitYear = function (input) {
return toInt(input) + (toInt(input) > 68 ? 1900 : 2000);
};
// MOMENTS
var getSetYear = makeGetSet("FullYear", true);
function getIsLeapYear() {
return isLeapYear(this.year());
}
function createDate(y, m, d, h, M, s, ms) {
// can't just apply() to create a date:
// https://stackoverflow.com/q/181348
var date;
// the date constructor remaps years 0-99 to 1900-1999
if (y < 100 && y >= 0) {
// preserve leap years using a full 400 year cycle, then reset
date = new Date(y + 400, m, d, h, M, s, ms);
if (isFinite(date.getFullYear())) {
date.setFullYear(y);
}
} else {
date = new Date(y, m, d, h, M, s, ms);
}
return date;
}
function createUTCDate(y) {
var date, args;
// the Date.UTC function remaps years 0-99 to 1900-1999
if (y < 100 && y >= 0) {
args = Array.prototype.slice.call(arguments);
// preserve leap years using a full 400 year cycle, then reset
args[0] = y + 400;
date = new Date(Date.UTC.apply(null, args));
if (isFinite(date.getUTCFullYear())) {
date.setUTCFullYear(y);
}
} else {
date = new Date(Date.UTC.apply(null, arguments));
}
return date;
}
// start-of-first-week - start-of-year
function firstWeekOffset(year, dow, doy) {
var // first-week day -- which january is always in the first week (4 for iso, 1 for other)
fwd = 7 + dow - doy,
// first-week day local weekday -- which local weekday is fwd
fwdlw = (7 + createUTCDate(year, 0, fwd).getUTCDay() - dow) % 7;
return -fwdlw + fwd - 1;
}
// https://en.wikipedia.org/wiki/ISO_week_date#Calculating_a_date_given_the_year.2C_week_number_and_weekday
function dayOfYearFromWeeks(year, week, weekday, dow, doy) {
var localWeekday = (7 + weekday - dow) % 7,
weekOffset = firstWeekOffset(year, dow, doy),
dayOfYear = 1 + 7 * (week - 1) + localWeekday + weekOffset,
resYear,
resDayOfYear;
if (dayOfYear <= 0) {
resYear = year - 1;
resDayOfYear = daysInYear(resYear) + dayOfYear;
} else if (dayOfYear > daysInYear(year)) {
resYear = year + 1;
resDayOfYear = dayOfYear - daysInYear(year);
} else {
resYear = year;
resDayOfYear = dayOfYear;
}
return {
year: resYear,
dayOfYear: resDayOfYear,
};
}
function weekOfYear(mom, dow, doy) {
var weekOffset = firstWeekOffset(mom.year(), dow, doy),
week = Math.floor((mom.dayOfYear() - weekOffset - 1) / 7) + 1,
resWeek,
resYear;
if (week < 1) {
resYear = mom.year() - 1;
resWeek = week + weeksInYear(resYear, dow, doy);
} else if (week > weeksInYear(mom.year(), dow, doy)) {
resWeek = week - weeksInYear(mom.year(), dow, doy);
resYear = mom.year() + 1;
} else {
resYear = mom.year();
resWeek = week;
}
return {
week: resWeek,
year: resYear,
};
}
function weeksInYear(year, dow, doy) {
var weekOffset = firstWeekOffset(year, dow, doy),
weekOffsetNext = firstWeekOffset(year + 1, dow, doy);
return (daysInYear(year) - weekOffset + weekOffsetNext) / 7;
}
// FORMATTING
addFormatToken("w", ["ww", 2], "wo", "week");
addFormatToken("W", ["WW", 2], "Wo", "isoWeek");
// ALIASES
addUnitAlias("week", "w");
addUnitAlias("isoWeek", "W");
// PRIORITIES
addUnitPriority("week", 5);
addUnitPriority("isoWeek", 5);
// PARSING
addRegexToken("w", match1to2);
addRegexToken("ww", match1to2, match2);
addRegexToken("W", match1to2);
addRegexToken("WW", match1to2, match2);
addWeekParseToken(
["w", "ww", "W", "WW"],
function (input, week, config, token) {
week[token.substr(0, 1)] = toInt(input);
}
);
// HELPERS
// LOCALES
function localeWeek(mom) {
return weekOfYear(mom, this._week.dow, this._week.doy).week;
}
var defaultLocaleWeek = {
dow: 0, // Sunday is the first day of the week.
doy: 6, // The week that contains Jan 6th is the first week of the year.
};
function localeFirstDayOfWeek() {
return this._week.dow;
}
function localeFirstDayOfYear() {
return this._week.doy;
}
// MOMENTS
function getSetWeek(input) {
var week = this.localeData().week(this);
return input == null ? week : this.add((input - week) * 7, "d");
}
function getSetISOWeek(input) {
var week = weekOfYear(this, 1, 4).week;
return input == null ? week : this.add((input - week) * 7, "d");
}
// FORMATTING
addFormatToken("d", 0, "do", "day");
addFormatToken("dd", 0, 0, function (format) {
return this.localeData().weekdaysMin(this, format);
});
addFormatToken("ddd", 0, 0, function (format) {
return this.localeData().weekdaysShort(this, format);
});
addFormatToken("dddd", 0, 0, function (format) {
return this.localeData().weekdays(this, format);
});
addFormatToken("e", 0, 0, "weekday");
addFormatToken("E", 0, 0, "isoWeekday");
// ALIASES
addUnitAlias("day", "d");
addUnitAlias("weekday", "e");
addUnitAlias("isoWeekday", "E");
// PRIORITY
addUnitPriority("day", 11);
addUnitPriority("weekday", 11);
addUnitPriority("isoWeekday", 11);
// PARSING
addRegexToken("d", match1to2);
addRegexToken("e", match1to2);
addRegexToken("E", match1to2);
addRegexToken("dd", function (isStrict, locale) {
return locale.weekdaysMinRegex(isStrict);
});
addRegexToken("ddd", function (isStrict, locale) {
return locale.weekdaysShortRegex(isStrict);
});
addRegexToken("dddd", function (isStrict, locale) {
return locale.weekdaysRegex(isStrict);
});
addWeekParseToken(
["dd", "ddd", "dddd"],
function (input, week, config, token) {
var weekday = config._locale.weekdaysParse(
input,
token,
config._strict
);
// if we didn't get a weekday name, mark the date as invalid
if (weekday != null) {
week.d = weekday;
} else {
getParsingFlags(config).invalidWeekday = input;
}
}
);
addWeekParseToken(["d", "e", "E"], function (input, week, config, token) {
week[token] = toInt(input);
});
// HELPERS
function parseWeekday(input, locale) {
if (typeof input !== "string") {
return input;
}
if (!isNaN(input)) {
return parseInt(input, 10);
}
input = locale.weekdaysParse(input);
if (typeof input === "number") {
return input;
}
return null;
}
function parseIsoWeekday(input, locale) {
if (typeof input === "string") {
return locale.weekdaysParse(input) % 7 || 7;
}
return isNaN(input) ? null : input;
}
// LOCALES
function shiftWeekdays(ws, n) {
return ws.slice(n, 7).concat(ws.slice(0, n));
}
var defaultLocaleWeekdays =
"Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split(
"_"
),
defaultLocaleWeekdaysShort = "Sun_Mon_Tue_Wed_Thu_Fri_Sat".split("_"),
defaultLocaleWeekdaysMin = "Su_Mo_Tu_We_Th_Fr_Sa".split("_"),
defaultWeekdaysRegex = matchWord,
defaultWeekdaysShortRegex = matchWord,
defaultWeekdaysMinRegex = matchWord;
function localeWeekdays(m, format) {
var weekdays = isArray(this._weekdays)
? this._weekdays
: this._weekdays[
m && m !== true && this._weekdays.isFormat.test(format)
? "format"
: "standalone"
];
return m === true
? shiftWeekdays(weekdays, this._week.dow)
: m
? weekdays[m.day()]
: weekdays;
}
function localeWeekdaysShort(m) {
return m === true
? shiftWeekdays(this._weekdaysShort, this._week.dow)
: m
? this._weekdaysShort[m.day()]
: this._weekdaysShort;
}
function localeWeekdaysMin(m) {
return m === true
? shiftWeekdays(this._weekdaysMin, this._week.dow)
: m
? this._weekdaysMin[m.day()]
: this._weekdaysMin;
}
function handleStrictParse$1(weekdayName, format, strict) {
var i,
ii,
mom,
llc = weekdayName.toLocaleLowerCase();
if (!this._weekdaysParse) {
this._weekdaysParse = [];
this._shortWeekdaysParse = [];
this._minWeekdaysParse = [];
for (i = 0; i < 7; ++i) {
mom = createUTC([2000, 1]).day(i);
this._minWeekdaysParse[i] = this.weekdaysMin(
mom,
""
).toLocaleLowerCase();
this._shortWeekdaysParse[i] = this.weekdaysShort(
mom,
""
).toLocaleLowerCase();
this._weekdaysParse[i] = this.weekdays(
mom,
""
).toLocaleLowerCase();
}
}
if (strict) {
if (format === "dddd") {
ii = indexOf.call(this._weekdaysParse, llc);
return ii !== -1 ? ii : null;
} else if (format === "ddd") {
ii = indexOf.call(this._shortWeekdaysParse, llc);
return ii !== -1 ? ii : null;
} else {
ii = indexOf.call(this._minWeekdaysParse, llc);
return ii !== -1 ? ii : null;
}
} else {
if (format === "dddd") {
ii = indexOf.call(this._weekdaysParse, llc);
if (ii !== -1) {
return ii;
}
ii = indexOf.call(this._shortWeekdaysParse, llc);
if (ii !== -1) {
return ii;
}
ii = indexOf.call(this._minWeekdaysParse, llc);
return ii !== -1 ? ii : null;
} else if (format === "ddd") {
ii = indexOf.call(this._shortWeekdaysParse, llc);
if (ii !== -1) {
return ii;
}
ii = indexOf.call(this._weekdaysParse, llc);
if (ii !== -1) {
return ii;
}
ii = indexOf.call(this._minWeekdaysParse, llc);
return ii !== -1 ? ii : null;
} else {
ii = indexOf.call(this._minWeekdaysParse, llc);
if (ii !== -1) {
return ii;
}
ii = indexOf.call(this._weekdaysParse, llc);
if (ii !== -1) {
return ii;
}
ii = indexOf.call(this._shortWeekdaysParse, llc);
return ii !== -1 ? ii : null;
}
}
}
function localeWeekdaysParse(weekdayName, format, strict) {
var i, mom, regex;
if (this._weekdaysParseExact) {
return handleStrictParse$1.call(this, weekdayName, format, strict);
}
if (!this._weekdaysParse) {
this._weekdaysParse = [];
this._minWeekdaysParse = [];
this._shortWeekdaysParse = [];
this._fullWeekdaysParse = [];
}
for (i = 0; i < 7; i++) {
// make the regex if we don't have it already
mom = createUTC([2000, 1]).day(i);
if (strict && !this._fullWeekdaysParse[i]) {
this._fullWeekdaysParse[i] = new RegExp(
"^" + this.weekdays(mom, "").replace(".", "\\.?") + "$",
"i"
);
this._shortWeekdaysParse[i] = new RegExp(
"^" +
this.weekdaysShort(mom, "").replace(".", "\\.?") +
"$",
"i"
);
this._minWeekdaysParse[i] = new RegExp(
"^" + this.weekdaysMin(mom, "").replace(".", "\\.?") + "$",
"i"
);
}
if (!this._weekdaysParse[i]) {
regex =
"^" +
this.weekdays(mom, "") +
"|^" +
this.weekdaysShort(mom, "") +
"|^" +
this.weekdaysMin(mom, "");
this._weekdaysParse[i] = new RegExp(
regex.replace(".", ""),
"i"
);
}
// test the regex
if (
strict &&
format === "dddd" &&
this._fullWeekdaysParse[i].test(weekdayName)
) {
return i;
} else if (
strict &&
format === "ddd" &&
this._shortWeekdaysParse[i].test(weekdayName)
) {
return i;
} else if (
strict &&
format === "dd" &&
this._minWeekdaysParse[i].test(weekdayName)
) {
return i;
} else if (!strict && this._weekdaysParse[i].test(weekdayName)) {
return i;
}
}
}
// MOMENTS
function getSetDayOfWeek(input) {
if (!this.isValid()) {
return input != null ? this : NaN;
}
var day = this._isUTC ? this._d.getUTCDay() : this._d.getDay();
if (input != null) {
input = parseWeekday(input, this.localeData());
return this.add(input - day, "d");
} else {
return day;
}
}
function getSetLocaleDayOfWeek(input) {
if (!this.isValid()) {
return input != null ? this : NaN;
}
var weekday = (this.day() + 7 - this.localeData()._week.dow) % 7;
return input == null ? weekday : this.add(input - weekday, "d");
}
function getSetISODayOfWeek(input) {
if (!this.isValid()) {
return input != null ? this : NaN;
}
// behaves the same as moment#day except
// as a getter, returns 7 instead of 0 (1-7 range instead of 0-6)
// as a setter, sunday should belong to the previous week.
if (input != null) {
var weekday = parseIsoWeekday(input, this.localeData());
return this.day(this.day() % 7 ? weekday : weekday - 7);
} else {
return this.day() || 7;
}
}
function weekdaysRegex(isStrict) {
if (this._weekdaysParseExact) {
if (!hasOwnProp(this, "_weekdaysRegex")) {
computeWeekdaysParse.call(this);
}
if (isStrict) {
return this._weekdaysStrictRegex;
} else {
return this._weekdaysRegex;
}
} else {
if (!hasOwnProp(this, "_weekdaysRegex")) {
this._weekdaysRegex = defaultWeekdaysRegex;
}
return this._weekdaysStrictRegex && isStrict
? this._weekdaysStrictRegex
: this._weekdaysRegex;
}
}
function weekdaysShortRegex(isStrict) {
if (this._weekdaysParseExact) {
if (!hasOwnProp(this, "_weekdaysRegex")) {
computeWeekdaysParse.call(this);
}
if (isStrict) {
return this._weekdaysShortStrictRegex;
} else {
return this._weekdaysShortRegex;
}
} else {
if (!hasOwnProp(this, "_weekdaysShortRegex")) {
this._weekdaysShortRegex = defaultWeekdaysShortRegex;
}
return this._weekdaysShortStrictRegex && isStrict
? this._weekdaysShortStrictRegex
: this._weekdaysShortRegex;
}
}
function weekdaysMinRegex(isStrict) {
if (this._weekdaysParseExact) {
if (!hasOwnProp(this, "_weekdaysRegex")) {
computeWeekdaysParse.call(this);
}
if (isStrict) {
return this._weekdaysMinStrictRegex;
} else {
return this._weekdaysMinRegex;
}
} else {
if (!hasOwnProp(this, "_weekdaysMinRegex")) {
this._weekdaysMinRegex = defaultWeekdaysMinRegex;
}
return this._weekdaysMinStrictRegex && isStrict
? this._weekdaysMinStrictRegex
: this._weekdaysMinRegex;
}
}
function computeWeekdaysParse() {
function cmpLenRev(a, b) {
return b.length - a.length;
}
var minPieces = [],
shortPieces = [],
longPieces = [],
mixedPieces = [],
i,
mom,
minp,
shortp,
longp;
for (i = 0; i < 7; i++) {
// make the regex if we don't have it already
mom = createUTC([2000, 1]).day(i);
minp = regexEscape(this.weekdaysMin(mom, ""));
shortp = regexEscape(this.weekdaysShort(mom, ""));
longp = regexEscape(this.weekdays(mom, ""));
minPieces.push(minp);
shortPieces.push(shortp);
longPieces.push(longp);
mixedPieces.push(minp);
mixedPieces.push(shortp);
mixedPieces.push(longp);
}
// Sorting makes sure if one weekday (or abbr) is a prefix of another it
// will match the longer piece.
minPieces.sort(cmpLenRev);
shortPieces.sort(cmpLenRev);
longPieces.sort(cmpLenRev);
mixedPieces.sort(cmpLenRev);
this._weekdaysRegex = new RegExp(
"^(" + mixedPieces.join("|") + ")",
"i"
);
this._weekdaysShortRegex = this._weekdaysRegex;
this._weekdaysMinRegex = this._weekdaysRegex;
this._weekdaysStrictRegex = new RegExp(
"^(" + longPieces.join("|") + ")",
"i"
);
this._weekdaysShortStrictRegex = new RegExp(
"^(" + shortPieces.join("|") + ")",
"i"
);
this._weekdaysMinStrictRegex = new RegExp(
"^(" + minPieces.join("|") + ")",
"i"
);
}
// FORMATTING
function hFormat() {
return this.hours() % 12 || 12;
}
function kFormat() {
return this.hours() || 24;
}
addFormatToken("H", ["HH", 2], 0, "hour");
addFormatToken("h", ["hh", 2], 0, hFormat);
addFormatToken("k", ["kk", 2], 0, kFormat);
addFormatToken("hmm", 0, 0, function () {
return "" + hFormat.apply(this) + zeroFill(this.minutes(), 2);
});
addFormatToken("hmmss", 0, 0, function () {
return (
"" +
hFormat.apply(this) +
zeroFill(this.minutes(), 2) +
zeroFill(this.seconds(), 2)
);
});
addFormatToken("Hmm", 0, 0, function () {
return "" + this.hours() + zeroFill(this.minutes(), 2);
});
addFormatToken("Hmmss", 0, 0, function () {
return (
"" +
this.hours() +
zeroFill(this.minutes(), 2) +
zeroFill(this.seconds(), 2)
);
});
function meridiem(token, lowercase) {
addFormatToken(token, 0, 0, function () {
return this.localeData().meridiem(
this.hours(),
this.minutes(),
lowercase
);
});
}
meridiem("a", true);
meridiem("A", false);
// ALIASES
addUnitAlias("hour", "h");
// PRIORITY
addUnitPriority("hour", 13);
// PARSING
function matchMeridiem(isStrict, locale) {
return locale._meridiemParse;
}
addRegexToken("a", matchMeridiem);
addRegexToken("A", matchMeridiem);
addRegexToken("H", match1to2);
addRegexToken("h", match1to2);
addRegexToken("k", match1to2);
addRegexToken("HH", match1to2, match2);
addRegexToken("hh", match1to2, match2);
addRegexToken("kk", match1to2, match2);
addRegexToken("hmm", match3to4);
addRegexToken("hmmss", match5to6);
addRegexToken("Hmm", match3to4);
addRegexToken("Hmmss", match5to6);
addParseToken(["H", "HH"], HOUR);
addParseToken(["k", "kk"], function (input, array, config) {
var kInput = toInt(input);
array[HOUR] = kInput === 24 ? 0 : kInput;
});
addParseToken(["a", "A"], function (input, array, config) {
config._isPm = config._locale.isPM(input);
config._meridiem = input;
});
addParseToken(["h", "hh"], function (input, array, config) {
array[HOUR] = toInt(input);
getParsingFlags(config).bigHour = true;
});
addParseToken("hmm", function (input, array, config) {
var pos = input.length - 2;
array[HOUR] = toInt(input.substr(0, pos));
array[MINUTE] = toInt(input.substr(pos));
getParsingFlags(config).bigHour = true;
});
addParseToken("hmmss", function (input, array, config) {
var pos1 = input.length - 4,
pos2 = input.length - 2;
array[HOUR] = toInt(input.substr(0, pos1));
array[MINUTE] = toInt(input.substr(pos1, 2));
array[SECOND] = toInt(input.substr(pos2));
getParsingFlags(config).bigHour = true;
});
addParseToken("Hmm", function (input, array, config) {
var pos = input.length - 2;
array[HOUR] = toInt(input.substr(0, pos));
array[MINUTE] = toInt(input.substr(pos));
});
addParseToken("Hmmss", function (input, array, config) {
var pos1 = input.length - 4,
pos2 = input.length - 2;
array[HOUR] = toInt(input.substr(0, pos1));
array[MINUTE] = toInt(input.substr(pos1, 2));
array[SECOND] = toInt(input.substr(pos2));
});
// LOCALES
function localeIsPM(input) {
// IE8 Quirks Mode & IE7 Standards Mode do not allow accessing strings like arrays
// Using charAt should be more compatible.
return (input + "").toLowerCase().charAt(0) === "p";
}
var defaultLocaleMeridiemParse = /[ap]\.?m?\.?/i,
// Setting the hour should keep the time, because the user explicitly
// specified which hour they want. So trying to maintain the same hour (in
// a new timezone) makes sense. Adding/subtracting hours does not follow
// this rule.
getSetHour = makeGetSet("Hours", true);
function localeMeridiem(hours, minutes, isLower) {
if (hours > 11) {
return isLower ? "pm" : "PM";
} else {
return isLower ? "am" : "AM";
}
}
var baseConfig = {
calendar: defaultCalendar,
longDateFormat: defaultLongDateFormat,
invalidDate: defaultInvalidDate,
ordinal: defaultOrdinal,
dayOfMonthOrdinalParse: defaultDayOfMonthOrdinalParse,
relativeTime: defaultRelativeTime,
months: defaultLocaleMonths,
monthsShort: defaultLocaleMonthsShort,
week: defaultLocaleWeek,
weekdays: defaultLocaleWeekdays,
weekdaysMin: defaultLocaleWeekdaysMin,
weekdaysShort: defaultLocaleWeekdaysShort,
meridiemParse: defaultLocaleMeridiemParse,
};
// internal storage for locale config files
var locales = {},
localeFamilies = {},
globalLocale;
function commonPrefix(arr1, arr2) {
var i,
minl = Math.min(arr1.length, arr2.length);
for (i = 0; i < minl; i += 1) {
if (arr1[i] !== arr2[i]) {
return i;
}
}
return minl;
}
function normalizeLocale(key) {
return key ? key.toLowerCase().replace("_", "-") : key;
}
// pick the locale from the array
// try ['en-au', 'en-gb'] as 'en-au', 'en-gb', 'en', as in move through the list trying each
// substring from most specific to least, but move to the next array item if it's a more specific variant than the current root
function chooseLocale(names) {
var i = 0,
j,
next,
locale,
split;
while (i < names.length) {
split = normalizeLocale(names[i]).split("-");
j = split.length;
next = normalizeLocale(names[i + 1]);
next = next ? next.split("-") : null;
while (j > 0) {
locale = loadLocale(split.slice(0, j).join("-"));
if (locale) {
return locale;
}
if (
next &&
next.length >= j &&
commonPrefix(split, next) >= j - 1
) {
//the next array item is better than a shallower substring of this one
break;
}
j--;
}
i++;
}
return globalLocale;
}
function loadLocale(name) {
var oldLocale = null,
aliasedRequire;
// TODO: Find a better way to register and load all the locales in Node
if (
locales[name] === undefined &&
typeof module !== "undefined" &&
module &&
module.exports
) {
try {
oldLocale = globalLocale._abbr;
aliasedRequire = require;
aliasedRequire("./locale/" + name);
getSetGlobalLocale(oldLocale);
} catch (e) {
// mark as not found to avoid repeating expensive file require call causing high CPU
// when trying to find en-US, en_US, en-us for every format call
locales[name] = null; // null means not found
}
}
return locales[name];
}
// This function will load locale and then set the global locale. If
// no arguments are passed in, it will simply return the current global
// locale key.
function getSetGlobalLocale(key, values) {
var data;
if (key) {
if (isUndefined(values)) {
data = getLocale(key);
} else {
data = defineLocale(key, values);
}
if (data) {
// moment.duration._locale = moment._locale = data;
globalLocale = data;
} else {
if (typeof console !== "undefined" && console.warn) {
//warn user if arguments are passed but the locale could not be set
console.warn(
"Locale " +
key +
" not found. Did you forget to load it?"
);
}
}
}
return globalLocale._abbr;
}
function defineLocale(name, config) {
if (config !== null) {
var locale,
parentConfig = baseConfig;
config.abbr = name;
if (locales[name] != null) {
deprecateSimple(
"defineLocaleOverride",
"use moment.updateLocale(localeName, config) to change " +
"an existing locale. moment.defineLocale(localeName, " +
"config) should only be used for creating a new locale " +
"See http://momentjs.com/guides/#/warnings/define-locale/ for more info."
);
parentConfig = locales[name]._config;
} else if (config.parentLocale != null) {
if (locales[config.parentLocale] != null) {
parentConfig = locales[config.parentLocale]._config;
} else {
locale = loadLocale(config.parentLocale);
if (locale != null) {
parentConfig = locale._config;
} else {
if (!localeFamilies[config.parentLocale]) {
localeFamilies[config.parentLocale] = [];
}
localeFamilies[config.parentLocale].push({
name: name,
config: config,
});
return null;
}
}
}
locales[name] = new Locale(mergeConfigs(parentConfig, config));
if (localeFamilies[name]) {
localeFamilies[name].forEach(function (x) {
defineLocale(x.name, x.config);
});
}
// backwards compat for now: also set the locale
// make sure we set the locale AFTER all child locales have been
// created, so we won't end up with the child locale set.
getSetGlobalLocale(name);
return locales[name];
} else {
// useful for testing
delete locales[name];
return null;
}
}
function updateLocale(name, config) {
if (config != null) {
var locale,
tmpLocale,
parentConfig = baseConfig;
if (locales[name] != null && locales[name].parentLocale != null) {
// Update existing child locale in-place to avoid memory-leaks
locales[name].set(mergeConfigs(locales[name]._config, config));
} else {
// MERGE
tmpLocale = loadLocale(name);
if (tmpLocale != null) {
parentConfig = tmpLocale._config;
}
config = mergeConfigs(parentConfig, config);
if (tmpLocale == null) {
// updateLocale is called for creating a new locale
// Set abbr so it will have a name (getters return
// undefined otherwise).
config.abbr = name;
}
locale = new Locale(config);
locale.parentLocale = locales[name];
locales[name] = locale;
}
// backwards compat for now: also set the locale
getSetGlobalLocale(name);
} else {
// pass null for config to unupdate, useful for tests
if (locales[name] != null) {
if (locales[name].parentLocale != null) {
locales[name] = locales[name].parentLocale;
if (name === getSetGlobalLocale()) {
getSetGlobalLocale(name);
}
} else if (locales[name] != null) {
delete locales[name];
}
}
}
return locales[name];
}
// returns locale data
function getLocale(key) {
var locale;
if (key && key._locale && key._locale._abbr) {
key = key._locale._abbr;
}
if (!key) {
return globalLocale;
}
if (!isArray(key)) {
//short-circuit everything else
locale = loadLocale(key);
if (locale) {
return locale;
}
key = [key];
}
return chooseLocale(key);
}
function listLocales() {
return keys(locales);
}
function checkOverflow(m) {
var overflow,
a = m._a;
if (a && getParsingFlags(m).overflow === -2) {
overflow =
a[MONTH] < 0 || a[MONTH] > 11
? MONTH
: a[DATE] < 1 || a[DATE] > daysInMonth(a[YEAR], a[MONTH])
? DATE
: a[HOUR] < 0 ||
a[HOUR] > 24 ||
(a[HOUR] === 24 &&
(a[MINUTE] !== 0 ||
a[SECOND] !== 0 ||
a[MILLISECOND] !== 0))
? HOUR
: a[MINUTE] < 0 || a[MINUTE] > 59
? MINUTE
: a[SECOND] < 0 || a[SECOND] > 59
? SECOND
: a[MILLISECOND] < 0 || a[MILLISECOND] > 999
? MILLISECOND
: -1;
if (
getParsingFlags(m)._overflowDayOfYear &&
(overflow < YEAR || overflow > DATE)
) {
overflow = DATE;
}
if (getParsingFlags(m)._overflowWeeks && overflow === -1) {
overflow = WEEK;
}
if (getParsingFlags(m)._overflowWeekday && overflow === -1) {
overflow = WEEKDAY;
}
getParsingFlags(m).overflow = overflow;
}
return m;
}
// iso 8601 regex
// 0000-00-00 0000-W00 or 0000-W00-0 + T + 00 or 00:00 or 00:00:00 or 00:00:00.000 + +00:00 or +0000 or +00)
var extendedIsoRegex =
/^\s*((?:[+-]\d{6}|\d{4})-(?:\d\d-\d\d|W\d\d-\d|W\d\d|\d\d\d|\d\d))(?:(T| )(\d\d(?::\d\d(?::\d\d(?:[.,]\d+)?)?)?)([+-]\d\d(?::?\d\d)?|\s*Z)?)?$/,
basicIsoRegex =
/^\s*((?:[+-]\d{6}|\d{4})(?:\d\d\d\d|W\d\d\d|W\d\d|\d\d\d|\d\d|))(?:(T| )(\d\d(?:\d\d(?:\d\d(?:[.,]\d+)?)?)?)([+-]\d\d(?::?\d\d)?|\s*Z)?)?$/,
tzRegex = /Z|[+-]\d\d(?::?\d\d)?/,
isoDates = [
["YYYYYY-MM-DD", /[+-]\d{6}-\d\d-\d\d/],
["YYYY-MM-DD", /\d{4}-\d\d-\d\d/],
["GGGG-[W]WW-E", /\d{4}-W\d\d-\d/],
["GGGG-[W]WW", /\d{4}-W\d\d/, false],
["YYYY-DDD", /\d{4}-\d{3}/],
["YYYY-MM", /\d{4}-\d\d/, false],
["YYYYYYMMDD", /[+-]\d{10}/],
["YYYYMMDD", /\d{8}/],
["GGGG[W]WWE", /\d{4}W\d{3}/],
["GGGG[W]WW", /\d{4}W\d{2}/, false],
["YYYYDDD", /\d{7}/],
["YYYYMM", /\d{6}/, false],
["YYYY", /\d{4}/, false],
],
// iso time formats and regexes
isoTimes = [
["HH:mm:ss.SSSS", /\d\d:\d\d:\d\d\.\d+/],
["HH:mm:ss,SSSS", /\d\d:\d\d:\d\d,\d+/],
["HH:mm:ss", /\d\d:\d\d:\d\d/],
["HH:mm", /\d\d:\d\d/],
["HHmmss.SSSS", /\d\d\d\d\d\d\.\d+/],
["HHmmss,SSSS", /\d\d\d\d\d\d,\d+/],
["HHmmss", /\d\d\d\d\d\d/],
["HHmm", /\d\d\d\d/],
["HH", /\d\d/],
],
aspNetJsonRegex = /^\/?Date\((-?\d+)/i,
// RFC 2822 regex: For details see https://tools.ietf.org/html/rfc2822#section-3.3
rfc2822 =
/^(?:(Mon|Tue|Wed|Thu|Fri|Sat|Sun),?\s)?(\d{1,2})\s(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s(\d{2,4})\s(\d\d):(\d\d)(?::(\d\d))?\s(?:(UT|GMT|[ECMP][SD]T)|([Zz])|([+-]\d{4}))$/,
obsOffsets = {
UT: 0,
GMT: 0,
EDT: -4 * 60,
EST: -5 * 60,
CDT: -5 * 60,
CST: -6 * 60,
MDT: -6 * 60,
MST: -7 * 60,
PDT: -7 * 60,
PST: -8 * 60,
};
// date from iso format
function configFromISO(config) {
var i,
l,
string = config._i,
match = extendedIsoRegex.exec(string) || basicIsoRegex.exec(string),
allowTime,
dateFormat,
timeFormat,
tzFormat;
if (match) {
getParsingFlags(config).iso = true;
for (i = 0, l = isoDates.length; i < l; i++) {
if (isoDates[i][1].exec(match[1])) {
dateFormat = isoDates[i][0];
allowTime = isoDates[i][2] !== false;
break;
}
}
if (dateFormat == null) {
config._isValid = false;
return;
}
if (match[3]) {
for (i = 0, l = isoTimes.length; i < l; i++) {
if (isoTimes[i][1].exec(match[3])) {
// match[2] should be 'T' or space
timeFormat = (match[2] || " ") + isoTimes[i][0];
break;
}
}
if (timeFormat == null) {
config._isValid = false;
return;
}
}
if (!allowTime && timeFormat != null) {
config._isValid = false;
return;
}
if (match[4]) {
if (tzRegex.exec(match[4])) {
tzFormat = "Z";
} else {
config._isValid = false;
return;
}
}
config._f = dateFormat + (timeFormat || "") + (tzFormat || "");
configFromStringAndFormat(config);
} else {
config._isValid = false;
}
}
function extractFromRFC2822Strings(
yearStr,
monthStr,
dayStr,
hourStr,
minuteStr,
secondStr
) {
var result = [
untruncateYear(yearStr),
defaultLocaleMonthsShort.indexOf(monthStr),
parseInt(dayStr, 10),
parseInt(hourStr, 10),
parseInt(minuteStr, 10),
];
if (secondStr) {
result.push(parseInt(secondStr, 10));
}
return result;
}
function untruncateYear(yearStr) {
var year = parseInt(yearStr, 10);
if (year <= 49) {
return 2000 + year;
} else if (year <= 999) {
return 1900 + year;
}
return year;
}
function preprocessRFC2822(s) {
// Remove comments and folding whitespace and replace multiple-spaces with a single space
return s
.replace(/\([^)]*\)|[\n\t]/g, " ")
.replace(/(\s\s+)/g, " ")
.replace(/^\s\s*/, "")
.replace(/\s\s*$/, "");
}
function checkWeekday(weekdayStr, parsedInput, config) {
if (weekdayStr) {
// TODO: Replace the vanilla JS Date object with an independent day-of-week check.
var weekdayProvided =
defaultLocaleWeekdaysShort.indexOf(weekdayStr),
weekdayActual = new Date(
parsedInput[0],
parsedInput[1],
parsedInput[2]
).getDay();
if (weekdayProvided !== weekdayActual) {
getParsingFlags(config).weekdayMismatch = true;
config._isValid = false;
return false;
}
}
return true;
}
function calculateOffset(obsOffset, militaryOffset, numOffset) {
if (obsOffset) {
return obsOffsets[obsOffset];
} else if (militaryOffset) {
// the only allowed military tz is Z
return 0;
} else {
var hm = parseInt(numOffset, 10),
m = hm % 100,
h = (hm - m) / 100;
return h * 60 + m;
}
}
// date and time from ref 2822 format
function configFromRFC2822(config) {
var match = rfc2822.exec(preprocessRFC2822(config._i)),
parsedArray;
if (match) {
parsedArray = extractFromRFC2822Strings(
match[4],
match[3],
match[2],
match[5],
match[6],
match[7]
);
if (!checkWeekday(match[1], parsedArray, config)) {
return;
}
config._a = parsedArray;
config._tzm = calculateOffset(match[8], match[9], match[10]);
config._d = createUTCDate.apply(null, config._a);
config._d.setUTCMinutes(config._d.getUTCMinutes() - config._tzm);
getParsingFlags(config).rfc2822 = true;
} else {
config._isValid = false;
}
}
// date from 1) ASP.NET, 2) ISO, 3) RFC 2822 formats, or 4) optional fallback if parsing isn't strict
function configFromString(config) {
var matched = aspNetJsonRegex.exec(config._i);
if (matched !== null) {
config._d = new Date(+matched[1]);
return;
}
configFromISO(config);
if (config._isValid === false) {
delete config._isValid;
} else {
return;
}
configFromRFC2822(config);
if (config._isValid === false) {
delete config._isValid;
} else {
return;
}
if (config._strict) {
config._isValid = false;
} else {
// Final attempt, use Input Fallback
hooks.createFromInputFallback(config);
}
}
hooks.createFromInputFallback = deprecate(
"value provided is not in a recognized RFC2822 or ISO format. moment construction falls back to js Date(), " +
"which is not reliable across all browsers and versions. Non RFC2822/ISO date formats are " +
"discouraged. Please refer to http://momentjs.com/guides/#/warnings/js-date/ for more info.",
function (config) {
config._d = new Date(config._i + (config._useUTC ? " UTC" : ""));
}
);
// Pick the first defined of two or three arguments.
function defaults(a, b, c) {
if (a != null) {
return a;
}
if (b != null) {
return b;
}
return c;
}
function currentDateArray(config) {
// hooks is actually the exported moment object
var nowValue = new Date(hooks.now());
if (config._useUTC) {
return [
nowValue.getUTCFullYear(),
nowValue.getUTCMonth(),
nowValue.getUTCDate(),
];
}
return [
nowValue.getFullYear(),
nowValue.getMonth(),
nowValue.getDate(),
];
}
// convert an array to a date.
// the array should mirror the parameters below
// note: all values past the year are optional and will default to the lowest possible value.
// [year, month, day , hour, minute, second, millisecond]
function configFromArray(config) {
var i,
date,
input = [],
currentDate,
expectedWeekday,
yearToUse;
if (config._d) {
return;
}
currentDate = currentDateArray(config);
//compute day of the year from weeks and weekdays
if (config._w && config._a[DATE] == null && config._a[MONTH] == null) {
dayOfYearFromWeekInfo(config);
}
//if the day of the year is set, figure out what it is
if (config._dayOfYear != null) {
yearToUse = defaults(config._a[YEAR], currentDate[YEAR]);
if (
config._dayOfYear > daysInYear(yearToUse) ||
config._dayOfYear === 0
) {
getParsingFlags(config)._overflowDayOfYear = true;
}
date = createUTCDate(yearToUse, 0, config._dayOfYear);
config._a[MONTH] = date.getUTCMonth();
config._a[DATE] = date.getUTCDate();
}
// Default to current date.
// * if no year, month, day of month are given, default to today
// * if day of month is given, default month and year
// * if month is given, default only year
// * if year is given, don't default anything
for (i = 0; i < 3 && config._a[i] == null; ++i) {
config._a[i] = input[i] = currentDate[i];
}
// Zero out whatever was not defaulted, including time
for (; i < 7; i++) {
config._a[i] = input[i] =
config._a[i] == null ? (i === 2 ? 1 : 0) : config._a[i];
}
// Check for 24:00:00.000
if (
config._a[HOUR] === 24 &&
config._a[MINUTE] === 0 &&
config._a[SECOND] === 0 &&
config._a[MILLISECOND] === 0
) {
config._nextDay = true;
config._a[HOUR] = 0;
}
config._d = (config._useUTC ? createUTCDate : createDate).apply(
null,
input
);
expectedWeekday = config._useUTC
? config._d.getUTCDay()
: config._d.getDay();
// Apply timezone offset from input. The actual utcOffset can be changed
// with parseZone.
if (config._tzm != null) {
config._d.setUTCMinutes(config._d.getUTCMinutes() - config._tzm);
}
if (config._nextDay) {
config._a[HOUR] = 24;
}
// check for mismatching day of week
if (
config._w &&
typeof config._w.d !== "undefined" &&
config._w.d !== expectedWeekday
) {
getParsingFlags(config).weekdayMismatch = true;
}
}
function dayOfYearFromWeekInfo(config) {
var w,
weekYear,
week,
weekday,
dow,
doy,
temp,
weekdayOverflow,
curWeek;
w = config._w;
if (w.GG != null || w.W != null || w.E != null) {
dow = 1;
doy = 4;
// TODO: We need to take the current isoWeekYear, but that depends on
// how we interpret now (local, utc, fixed offset). So create
// a now version of current config (take local/utc/offset flags, and
// create now).
weekYear = defaults(
w.GG,
config._a[YEAR],
weekOfYear(createLocal(), 1, 4).year
);
week = defaults(w.W, 1);
weekday = defaults(w.E, 1);
if (weekday < 1 || weekday > 7) {
weekdayOverflow = true;
}
} else {
dow = config._locale._week.dow;
doy = config._locale._week.doy;
curWeek = weekOfYear(createLocal(), dow, doy);
weekYear = defaults(w.gg, config._a[YEAR], curWeek.year);
// Default to current week.
week = defaults(w.w, curWeek.week);
if (w.d != null) {
// weekday -- low day numbers are considered next week
weekday = w.d;
if (weekday < 0 || weekday > 6) {
weekdayOverflow = true;
}
} else if (w.e != null) {
// local weekday -- counting starts from beginning of week
weekday = w.e + dow;
if (w.e < 0 || w.e > 6) {
weekdayOverflow = true;
}
} else {
// default to beginning of week
weekday = dow;
}
}
if (week < 1 || week > weeksInYear(weekYear, dow, doy)) {
getParsingFlags(config)._overflowWeeks = true;
} else if (weekdayOverflow != null) {
getParsingFlags(config)._overflowWeekday = true;
} else {
temp = dayOfYearFromWeeks(weekYear, week, weekday, dow, doy);
config._a[YEAR] = temp.year;
config._dayOfYear = temp.dayOfYear;
}
}
// constant that refers to the ISO standard
hooks.ISO_8601 = function () {};
// constant that refers to the RFC 2822 form
hooks.RFC_2822 = function () {};
// date from string and format string
function configFromStringAndFormat(config) {
// TODO: Move this to another part of the creation flow to prevent circular deps
if (config._f === hooks.ISO_8601) {
configFromISO(config);
return;
}
if (config._f === hooks.RFC_2822) {
configFromRFC2822(config);
return;
}
config._a = [];
getParsingFlags(config).empty = true;
// This array is used to make a Date, either with `new Date` or `Date.UTC`
var string = "" + config._i,
i,
parsedInput,
tokens,
token,
skipped,
stringLength = string.length,
totalParsedInputLength = 0,
era;
tokens =
expandFormat(config._f, config._locale).match(formattingTokens) ||
[];
for (i = 0; i < tokens.length; i++) {
token = tokens[i];
parsedInput = (string.match(getParseRegexForToken(token, config)) ||
[])[0];
if (parsedInput) {
skipped = string.substr(0, string.indexOf(parsedInput));
if (skipped.length > 0) {
getParsingFlags(config).unusedInput.push(skipped);
}
string = string.slice(
string.indexOf(parsedInput) + parsedInput.length
);
totalParsedInputLength += parsedInput.length;
}
// don't parse if it's not a known token
if (formatTokenFunctions[token]) {
if (parsedInput) {
getParsingFlags(config).empty = false;
} else {
getParsingFlags(config).unusedTokens.push(token);
}
addTimeToArrayFromToken(token, parsedInput, config);
} else if (config._strict && !parsedInput) {
getParsingFlags(config).unusedTokens.push(token);
}
}
// add remaining unparsed input length to the string
getParsingFlags(config).charsLeftOver =
stringLength - totalParsedInputLength;
if (string.length > 0) {
getParsingFlags(config).unusedInput.push(string);
}
// clear _12h flag if hour is <= 12
if (
config._a[HOUR] <= 12 &&
getParsingFlags(config).bigHour === true &&
config._a[HOUR] > 0
) {
getParsingFlags(config).bigHour = undefined;
}
getParsingFlags(config).parsedDateParts = config._a.slice(0);
getParsingFlags(config).meridiem = config._meridiem;
// handle meridiem
config._a[HOUR] = meridiemFixWrap(
config._locale,
config._a[HOUR],
config._meridiem
);
// handle era
era = getParsingFlags(config).era;
if (era !== null) {
config._a[YEAR] = config._locale.erasConvertYear(
era,
config._a[YEAR]
);
}
configFromArray(config);
checkOverflow(config);
}
function meridiemFixWrap(locale, hour, meridiem) {
var isPm;
if (meridiem == null) {
// nothing to do
return hour;
}
if (locale.meridiemHour != null) {
return locale.meridiemHour(hour, meridiem);
} else if (locale.isPM != null) {
// Fallback
isPm = locale.isPM(meridiem);
if (isPm && hour < 12) {
hour += 12;
}
if (!isPm && hour === 12) {
hour = 0;
}
return hour;
} else {
// this is not supposed to happen
return hour;
}
}
// date from string and array of format strings
function configFromStringAndArray(config) {
var tempConfig,
bestMoment,
scoreToBeat,
i,
currentScore,
validFormatFound,
bestFormatIsValid = false;
if (config._f.length === 0) {
getParsingFlags(config).invalidFormat = true;
config._d = new Date(NaN);
return;
}
for (i = 0; i < config._f.length; i++) {
currentScore = 0;
validFormatFound = false;
tempConfig = copyConfig({}, config);
if (config._useUTC != null) {
tempConfig._useUTC = config._useUTC;
}
tempConfig._f = config._f[i];
configFromStringAndFormat(tempConfig);
if (isValid(tempConfig)) {
validFormatFound = true;
}
// if there is any input that was not parsed add a penalty for that format
currentScore += getParsingFlags(tempConfig).charsLeftOver;
//or tokens
currentScore +=
getParsingFlags(tempConfig).unusedTokens.length * 10;
getParsingFlags(tempConfig).score = currentScore;
if (!bestFormatIsValid) {
if (
scoreToBeat == null ||
currentScore < scoreToBeat ||
validFormatFound
) {
scoreToBeat = currentScore;
bestMoment = tempConfig;
if (validFormatFound) {
bestFormatIsValid = true;
}
}
} else {
if (currentScore < scoreToBeat) {
scoreToBeat = currentScore;
bestMoment = tempConfig;
}
}
}
extend(config, bestMoment || tempConfig);
}
function configFromObject(config) {
if (config._d) {
return;
}
var i = normalizeObjectUnits(config._i),
dayOrDate = i.day === undefined ? i.date : i.day;
config._a = map(
[
i.year,
i.month,
dayOrDate,
i.hour,
i.minute,
i.second,
i.millisecond,
],
function (obj) {
return obj && parseInt(obj, 10);
}
);
configFromArray(config);
}
function createFromConfig(config) {
var res = new Moment(checkOverflow(prepareConfig(config)));
if (res._nextDay) {
// Adding is smart enough around DST
res.add(1, "d");
res._nextDay = undefined;
}
return res;
}
function prepareConfig(config) {
var input = config._i,
format = config._f;
config._locale = config._locale || getLocale(config._l);
if (input === null || (format === undefined && input === "")) {
return createInvalid({ nullInput: true });
}
if (typeof input === "string") {
config._i = input = config._locale.preparse(input);
}
if (isMoment(input)) {
return new Moment(checkOverflow(input));
} else if (isDate(input)) {
config._d = input;
} else if (isArray(format)) {
configFromStringAndArray(config);
} else if (format) {
configFromStringAndFormat(config);
} else {
configFromInput(config);
}
if (!isValid(config)) {
config._d = null;
}
return config;
}
function configFromInput(config) {
var input = config._i;
if (isUndefined(input)) {
config._d = new Date(hooks.now());
} else if (isDate(input)) {
config._d = new Date(input.valueOf());
} else if (typeof input === "string") {
configFromString(config);
} else if (isArray(input)) {
config._a = map(input.slice(0), function (obj) {
return parseInt(obj, 10);
});
configFromArray(config);
} else if (isObject(input)) {
configFromObject(config);
} else if (isNumber(input)) {
// from milliseconds
config._d = new Date(input);
} else {
hooks.createFromInputFallback(config);
}
}
function createLocalOrUTC(input, format, locale, strict, isUTC) {
var c = {};
if (format === true || format === false) {
strict = format;
format = undefined;
}
if (locale === true || locale === false) {
strict = locale;
locale = undefined;
}
if (
(isObject(input) && isObjectEmpty(input)) ||
(isArray(input) && input.length === 0)
) {
input = undefined;
}
// object construction must be done this way.
// https://github.com/moment/moment/issues/1423
c._isAMomentObject = true;
c._useUTC = c._isUTC = isUTC;
c._l = locale;
c._i = input;
c._f = format;
c._strict = strict;
return createFromConfig(c);
}
function createLocal(input, format, locale, strict) {
return createLocalOrUTC(input, format, locale, strict, false);
}
var prototypeMin = deprecate(
"moment().min is deprecated, use moment.max instead. http://momentjs.com/guides/#/warnings/min-max/",
function () {
var other = createLocal.apply(null, arguments);
if (this.isValid() && other.isValid()) {
return other < this ? this : other;
} else {
return createInvalid();
}
}
),
prototypeMax = deprecate(
"moment().max is deprecated, use moment.min instead. http://momentjs.com/guides/#/warnings/min-max/",
function () {
var other = createLocal.apply(null, arguments);
if (this.isValid() && other.isValid()) {
return other > this ? this : other;
} else {
return createInvalid();
}
}
);
// Pick a moment m from moments so that m[fn](other) is true for all
// other. This relies on the function fn to be transitive.
//
// moments should either be an array of moment objects or an array, whose
// first element is an array of moment objects.
function pickBy(fn, moments) {
var res, i;
if (moments.length === 1 && isArray(moments[0])) {
moments = moments[0];
}
if (!moments.length) {
return createLocal();
}
res = moments[0];
for (i = 1; i < moments.length; ++i) {
if (!moments[i].isValid() || moments[i][fn](res)) {
res = moments[i];
}
}
return res;
}
// TODO: Use [].sort instead?
function min() {
var args = [].slice.call(arguments, 0);
return pickBy("isBefore", args);
}
function max() {
var args = [].slice.call(arguments, 0);
return pickBy("isAfter", args);
}
var now = function () {
return Date.now ? Date.now() : +new Date();
};
var ordering = [
"year",
"quarter",
"month",
"week",
"day",
"hour",
"minute",
"second",
"millisecond",
];
function isDurationValid(m) {
var key,
unitHasDecimal = false,
i;
for (key in m) {
if (
hasOwnProp(m, key) &&
!(
indexOf.call(ordering, key) !== -1 &&
(m[key] == null || !isNaN(m[key]))
)
) {
return false;
}
}
for (i = 0; i < ordering.length; ++i) {
if (m[ordering[i]]) {
if (unitHasDecimal) {
return false; // only allow non-integers for smallest unit
}
if (parseFloat(m[ordering[i]]) !== toInt(m[ordering[i]])) {
unitHasDecimal = true;
}
}
}
return true;
}
function isValid$1() {
return this._isValid;
}
function createInvalid$1() {
return createDuration(NaN);
}
function Duration(duration) {
var normalizedInput = normalizeObjectUnits(duration),
years = normalizedInput.year || 0,
quarters = normalizedInput.quarter || 0,
months = normalizedInput.month || 0,
weeks = normalizedInput.week || normalizedInput.isoWeek || 0,
days = normalizedInput.day || 0,
hours = normalizedInput.hour || 0,
minutes = normalizedInput.minute || 0,
seconds = normalizedInput.second || 0,
milliseconds = normalizedInput.millisecond || 0;
this._isValid = isDurationValid(normalizedInput);
// representation for dateAddRemove
this._milliseconds =
+milliseconds +
seconds * 1e3 + // 1000
minutes * 6e4 + // 1000 * 60
hours * 1000 * 60 * 60; //using 1000 * 60 * 60 instead of 36e5 to avoid floating point rounding errors https://github.com/moment/moment/issues/2978
// Because of dateAddRemove treats 24 hours as different from a
// day when working around DST, we need to store them separately
this._days = +days + weeks * 7;
// It is impossible to translate months into days without knowing
// which months you are are talking about, so we have to store
// it separately.
this._months = +months + quarters * 3 + years * 12;
this._data = {};
this._locale = getLocale();
this._bubble();
}
function isDuration(obj) {
return obj instanceof Duration;
}
function absRound(number) {
if (number < 0) {
return Math.round(-1 * number) * -1;
} else {
return Math.round(number);
}
}
// compare two arrays, return the number of differences
function compareArrays(array1, array2, dontConvert) {
var len = Math.min(array1.length, array2.length),
lengthDiff = Math.abs(array1.length - array2.length),
diffs = 0,
i;
for (i = 0; i < len; i++) {
if (
(dontConvert && array1[i] !== array2[i]) ||
(!dontConvert && toInt(array1[i]) !== toInt(array2[i]))
) {
diffs++;
}
}
return diffs + lengthDiff;
}
// FORMATTING
function offset(token, separator) {
addFormatToken(token, 0, 0, function () {
var offset = this.utcOffset(),
sign = "+";
if (offset < 0) {
offset = -offset;
sign = "-";
}
return (
sign +
zeroFill(~~(offset / 60), 2) +
separator +
zeroFill(~~offset % 60, 2)
);
});
}
offset("Z", ":");
offset("ZZ", "");
// PARSING
addRegexToken("Z", matchShortOffset);
addRegexToken("ZZ", matchShortOffset);
addParseToken(["Z", "ZZ"], function (input, array, config) {
config._useUTC = true;
config._tzm = offsetFromString(matchShortOffset, input);
});
// HELPERS
// timezone chunker
// '+10:00' > ['10', '00']
// '-1530' > ['-15', '30']
var chunkOffset = /([\+\-]|\d\d)/gi;
function offsetFromString(matcher, string) {
var matches = (string || "").match(matcher),
chunk,
parts,
minutes;
if (matches === null) {
return null;
}
chunk = matches[matches.length - 1] || [];
parts = (chunk + "").match(chunkOffset) || ["-", 0, 0];
minutes = +(parts[1] * 60) + toInt(parts[2]);
return minutes === 0 ? 0 : parts[0] === "+" ? minutes : -minutes;
}
// Return a moment from input, that is local/utc/zone equivalent to model.
function cloneWithOffset(input, model) {
var res, diff;
if (model._isUTC) {
res = model.clone();
diff =
(isMoment(input) || isDate(input)
? input.valueOf()
: createLocal(input).valueOf()) - res.valueOf();
// Use low-level api, because this fn is low-level api.
res._d.setTime(res._d.valueOf() + diff);
hooks.updateOffset(res, false);
return res;
} else {
return createLocal(input).local();
}
}
function getDateOffset(m) {
// On Firefox.24 Date#getTimezoneOffset returns a floating point.
// https://github.com/moment/moment/pull/1871
return -Math.round(m._d.getTimezoneOffset());
}
// HOOKS
// This function will be called whenever a moment is mutated.
// It is intended to keep the offset in sync with the timezone.
hooks.updateOffset = function () {};
// MOMENTS
// keepLocalTime = true means only change the timezone, without
// affecting the local hour. So 5:31:26 +0300 --[utcOffset(2, true)]-->
// 5:31:26 +0200 It is possible that 5:31:26 doesn't exist with offset
// +0200, so we adjust the time as needed, to be valid.
//
// Keeping the time actually adds/subtracts (one hour)
// from the actual represented time. That is why we call updateOffset
// a second time. In case it wants us to change the offset again
// _changeInProgress == true case, then we have to adjust, because
// there is no such time in the given timezone.
function getSetOffset(input, keepLocalTime, keepMinutes) {
var offset = this._offset || 0,
localAdjust;
if (!this.isValid()) {
return input != null ? this : NaN;
}
if (input != null) {
if (typeof input === "string") {
input = offsetFromString(matchShortOffset, input);
if (input === null) {
return this;
}
} else if (Math.abs(input) < 16 && !keepMinutes) {
input = input * 60;
}
if (!this._isUTC && keepLocalTime) {
localAdjust = getDateOffset(this);
}
this._offset = input;
this._isUTC = true;
if (localAdjust != null) {
this.add(localAdjust, "m");
}
if (offset !== input) {
if (!keepLocalTime || this._changeInProgress) {
addSubtract(
this,
createDuration(input - offset, "m"),
1,
false
);
} else if (!this._changeInProgress) {
this._changeInProgress = true;
hooks.updateOffset(this, true);
this._changeInProgress = null;
}
}
return this;
} else {
return this._isUTC ? offset : getDateOffset(this);
}
}
function getSetZone(input, keepLocalTime) {
if (input != null) {
if (typeof input !== "string") {
input = -input;
}
this.utcOffset(input, keepLocalTime);
return this;
} else {
return -this.utcOffset();
}
}
function setOffsetToUTC(keepLocalTime) {
return this.utcOffset(0, keepLocalTime);
}
function setOffsetToLocal(keepLocalTime) {
if (this._isUTC) {
this.utcOffset(0, keepLocalTime);
this._isUTC = false;
if (keepLocalTime) {
this.subtract(getDateOffset(this), "m");
}
}
return this;
}
function setOffsetToParsedOffset() {
if (this._tzm != null) {
this.utcOffset(this._tzm, false, true);
} else if (typeof this._i === "string") {
var tZone = offsetFromString(matchOffset, this._i);
if (tZone != null) {
this.utcOffset(tZone);
} else {
this.utcOffset(0, true);
}
}
return this;
}
function hasAlignedHourOffset(input) {
if (!this.isValid()) {
return false;
}
input = input ? createLocal(input).utcOffset() : 0;
return (this.utcOffset() - input) % 60 === 0;
}
function isDaylightSavingTime() {
return (
this.utcOffset() > this.clone().month(0).utcOffset() ||
this.utcOffset() > this.clone().month(5).utcOffset()
);
}
function isDaylightSavingTimeShifted() {
if (!isUndefined(this._isDSTShifted)) {
return this._isDSTShifted;
}
var c = {},
other;
copyConfig(c, this);
c = prepareConfig(c);
if (c._a) {
other = c._isUTC ? createUTC(c._a) : createLocal(c._a);
this._isDSTShifted =
this.isValid() && compareArrays(c._a, other.toArray()) > 0;
} else {
this._isDSTShifted = false;
}
return this._isDSTShifted;
}
function isLocal() {
return this.isValid() ? !this._isUTC : false;
}
function isUtcOffset() {
return this.isValid() ? this._isUTC : false;
}
function isUtc() {
return this.isValid() ? this._isUTC && this._offset === 0 : false;
}
// ASP.NET json date format regex
var aspNetRegex = /^(-|\+)?(?:(\d*)[. ])?(\d+):(\d+)(?::(\d+)(\.\d*)?)?$/,
// from http://docs.closure-library.googlecode.com/git/closure_goog_date_date.js.source.html
// somewhat more in line with 4.4.3.2 2004 spec, but allows decimal anywhere
// and further modified to allow for strings containing both week and day
isoRegex =
/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/;
function createDuration(input, key) {
var duration = input,
// matching against regexp is expensive, do it on demand
match = null,
sign,
ret,
diffRes;
if (isDuration(input)) {
duration = {
ms: input._milliseconds,
d: input._days,
M: input._months,
};
} else if (isNumber(input) || !isNaN(+input)) {
duration = {};
if (key) {
duration[key] = +input;
} else {
duration.milliseconds = +input;
}
} else if ((match = aspNetRegex.exec(input))) {
sign = match[1] === "-" ? -1 : 1;
duration = {
y: 0,
d: toInt(match[DATE]) * sign,
h: toInt(match[HOUR]) * sign,
m: toInt(match[MINUTE]) * sign,
s: toInt(match[SECOND]) * sign,
ms: toInt(absRound(match[MILLISECOND] * 1000)) * sign, // the millisecond decimal point is included in the match
};
} else if ((match = isoRegex.exec(input))) {
sign = match[1] === "-" ? -1 : 1;
duration = {
y: parseIso(match[2], sign),
M: parseIso(match[3], sign),
w: parseIso(match[4], sign),
d: parseIso(match[5], sign),
h: parseIso(match[6], sign),
m: parseIso(match[7], sign),
s: parseIso(match[8], sign),
};
} else if (duration == null) {
// checks for null or undefined
duration = {};
} else if (
typeof duration === "object" &&
("from" in duration || "to" in duration)
) {
diffRes = momentsDifference(
createLocal(duration.from),
createLocal(duration.to)
);
duration = {};
duration.ms = diffRes.milliseconds;
duration.M = diffRes.months;
}
ret = new Duration(duration);
if (isDuration(input) && hasOwnProp(input, "_locale")) {
ret._locale = input._locale;
}
if (isDuration(input) && hasOwnProp(input, "_isValid")) {
ret._isValid = input._isValid;
}
return ret;
}
createDuration.fn = Duration.prototype;
createDuration.invalid = createInvalid$1;
function parseIso(inp, sign) {
// We'd normally use ~~inp for this, but unfortunately it also
// converts floats to ints.
// inp may be undefined, so careful calling replace on it.
var res = inp && parseFloat(inp.replace(",", "."));
// apply sign while we're at it
return (isNaN(res) ? 0 : res) * sign;
}
function positiveMomentsDifference(base, other) {
var res = {};
res.months =
other.month() - base.month() + (other.year() - base.year()) * 12;
if (base.clone().add(res.months, "M").isAfter(other)) {
--res.months;
}
res.milliseconds = +other - +base.clone().add(res.months, "M");
return res;
}
function momentsDifference(base, other) {
var res;
if (!(base.isValid() && other.isValid())) {
return { milliseconds: 0, months: 0 };
}
other = cloneWithOffset(other, base);
if (base.isBefore(other)) {
res = positiveMomentsDifference(base, other);
} else {
res = positiveMomentsDifference(other, base);
res.milliseconds = -res.milliseconds;
res.months = -res.months;
}
return res;
}
// TODO: remove 'name' arg after deprecation is removed
function createAdder(direction, name) {
return function (val, period) {
var dur, tmp;
//invert the arguments, but complain about it
if (period !== null && !isNaN(+period)) {
deprecateSimple(
name,
"moment()." +
name +
"(period, number) is deprecated. Please use moment()." +
name +
"(number, period). " +
"See http://momentjs.com/guides/#/warnings/add-inverted-param/ for more info."
);
tmp = val;
val = period;
period = tmp;
}
dur = createDuration(val, period);
addSubtract(this, dur, direction);
return this;
};
}
function addSubtract(mom, duration, isAdding, updateOffset) {
var milliseconds = duration._milliseconds,
days = absRound(duration._days),
months = absRound(duration._months);
if (!mom.isValid()) {
// No op
return;
}
updateOffset = updateOffset == null ? true : updateOffset;
if (months) {
setMonth(mom, get(mom, "Month") + months * isAdding);
}
if (days) {
set$1(mom, "Date", get(mom, "Date") + days * isAdding);
}
if (milliseconds) {
mom._d.setTime(mom._d.valueOf() + milliseconds * isAdding);
}
if (updateOffset) {
hooks.updateOffset(mom, days || months);
}
}
var add = createAdder(1, "add"),
subtract = createAdder(-1, "subtract");
function isString(input) {
return typeof input === "string" || input instanceof String;
}
// type MomentInput = Moment | Date | string | number | (number | string)[] | MomentInputObject | void; // null | undefined
function isMomentInput(input) {
return (
isMoment(input) ||
isDate(input) ||
isString(input) ||
isNumber(input) ||
isNumberOrStringArray(input) ||
isMomentInputObject(input) ||
input === null ||
input === undefined
);
}
function isMomentInputObject(input) {
var objectTest = isObject(input) && !isObjectEmpty(input),
propertyTest = false,
properties = [
"years",
"year",
"y",
"months",
"month",
"M",
"days",
"day",
"d",
"dates",
"date",
"D",
"hours",
"hour",
"h",
"minutes",
"minute",
"m",
"seconds",
"second",
"s",
"milliseconds",
"millisecond",
"ms",
],
i,
property;
for (i = 0; i < properties.length; i += 1) {
property = properties[i];
propertyTest = propertyTest || hasOwnProp(input, property);
}
return objectTest && propertyTest;
}
function isNumberOrStringArray(input) {
var arrayTest = isArray(input),
dataTypeTest = false;
if (arrayTest) {
dataTypeTest =
input.filter(function (item) {
return !isNumber(item) && isString(input);
}).length === 0;
}
return arrayTest && dataTypeTest;
}
function isCalendarSpec(input) {
var objectTest = isObject(input) && !isObjectEmpty(input),
propertyTest = false,
properties = [
"sameDay",
"nextDay",
"lastDay",
"nextWeek",
"lastWeek",
"sameElse",
],
i,
property;
for (i = 0; i < properties.length; i += 1) {
property = properties[i];
propertyTest = propertyTest || hasOwnProp(input, property);
}
return objectTest && propertyTest;
}
function getCalendarFormat(myMoment, now) {
var diff = myMoment.diff(now, "days", true);
return diff < -6
? "sameElse"
: diff < -1
? "lastWeek"
: diff < 0
? "lastDay"
: diff < 1
? "sameDay"
: diff < 2
? "nextDay"
: diff < 7
? "nextWeek"
: "sameElse";
}
function calendar$1(time, formats) {
// Support for single parameter, formats only overload to the calendar function
if (arguments.length === 1) {
if (!arguments[0]) {
time = undefined;
formats = undefined;
} else if (isMomentInput(arguments[0])) {
time = arguments[0];
formats = undefined;
} else if (isCalendarSpec(arguments[0])) {
formats = arguments[0];
time = undefined;
}
}
// We want to compare the start of today, vs this.
// Getting start-of-today depends on whether we're local/utc/offset or not.
var now = time || createLocal(),
sod = cloneWithOffset(now, this).startOf("day"),
format = hooks.calendarFormat(this, sod) || "sameElse",
output =
formats &&
(isFunction(formats[format])
? formats[format].call(this, now)
: formats[format]);
return this.format(
output || this.localeData().calendar(format, this, createLocal(now))
);
}
function clone() {
return new Moment(this);
}
function isAfter(input, units) {
var localInput = isMoment(input) ? input : createLocal(input);
if (!(this.isValid() && localInput.isValid())) {
return false;
}
units = normalizeUnits(units) || "millisecond";
if (units === "millisecond") {
return this.valueOf() > localInput.valueOf();
} else {
return localInput.valueOf() < this.clone().startOf(units).valueOf();
}
}
function isBefore(input, units) {
var localInput = isMoment(input) ? input : createLocal(input);
if (!(this.isValid() && localInput.isValid())) {
return false;
}
units = normalizeUnits(units) || "millisecond";
if (units === "millisecond") {
return this.valueOf() < localInput.valueOf();
} else {
return this.clone().endOf(units).valueOf() < localInput.valueOf();
}
}
function isBetween(from, to, units, inclusivity) {
var localFrom = isMoment(from) ? from : createLocal(from),
localTo = isMoment(to) ? to : createLocal(to);
if (!(this.isValid() && localFrom.isValid() && localTo.isValid())) {
return false;
}
inclusivity = inclusivity || "()";
return (
(inclusivity[0] === "("
? this.isAfter(localFrom, units)
: !this.isBefore(localFrom, units)) &&
(inclusivity[1] === ")"
? this.isBefore(localTo, units)
: !this.isAfter(localTo, units))
);
}
function isSame(input, units) {
var localInput = isMoment(input) ? input : createLocal(input),
inputMs;
if (!(this.isValid() && localInput.isValid())) {
return false;
}
units = normalizeUnits(units) || "millisecond";
if (units === "millisecond") {
return this.valueOf() === localInput.valueOf();
} else {
inputMs = localInput.valueOf();
return (
this.clone().startOf(units).valueOf() <= inputMs &&
inputMs <= this.clone().endOf(units).valueOf()
);
}
}
function isSameOrAfter(input, units) {
return this.isSame(input, units) || this.isAfter(input, units);
}
function isSameOrBefore(input, units) {
return this.isSame(input, units) || this.isBefore(input, units);
}
function diff(input, units, asFloat) {
var that, zoneDelta, output;
if (!this.isValid()) {
return NaN;
}
that = cloneWithOffset(input, this);
if (!that.isValid()) {
return NaN;
}
zoneDelta = (that.utcOffset() - this.utcOffset()) * 6e4;
units = normalizeUnits(units);
switch (units) {
case "year":
output = monthDiff(this, that) / 12;
break;
case "month":
output = monthDiff(this, that);
break;
case "quarter":
output = monthDiff(this, that) / 3;
break;
case "second":
output = (this - that) / 1e3;
break; // 1000
case "minute":
output = (this - that) / 6e4;
break; // 1000 * 60
case "hour":
output = (this - that) / 36e5;
break; // 1000 * 60 * 60
case "day":
output = (this - that - zoneDelta) / 864e5;
break; // 1000 * 60 * 60 * 24, negate dst
case "week":
output = (this - that - zoneDelta) / 6048e5;
break; // 1000 * 60 * 60 * 24 * 7, negate dst
default:
output = this - that;
}
return asFloat ? output : absFloor(output);
}
function monthDiff(a, b) {
if (a.date() < b.date()) {
// end-of-month calculations work correct when the start month has more
// days than the end month.
return -monthDiff(b, a);
}
// difference in months
var wholeMonthDiff =
(b.year() - a.year()) * 12 + (b.month() - a.month()),
// b is in (anchor - 1 month, anchor + 1 month)
anchor = a.clone().add(wholeMonthDiff, "months"),
anchor2,
adjust;
if (b - anchor < 0) {
anchor2 = a.clone().add(wholeMonthDiff - 1, "months");
// linear across the month
adjust = (b - anchor) / (anchor - anchor2);
} else {
anchor2 = a.clone().add(wholeMonthDiff + 1, "months");
// linear across the month
adjust = (b - anchor) / (anchor2 - anchor);
}
//check for negative zero, return zero if negative zero
return -(wholeMonthDiff + adjust) || 0;
}
hooks.defaultFormat = "YYYY-MM-DDTHH:mm:ssZ";
hooks.defaultFormatUtc = "YYYY-MM-DDTHH:mm:ss[Z]";
function toString() {
return this.clone()
.locale("en")
.format("ddd MMM DD YYYY HH:mm:ss [GMT]ZZ");
}
function toISOString(keepOffset) {
if (!this.isValid()) {
return null;
}
var utc = keepOffset !== true,
m = utc ? this.clone().utc() : this;
if (m.year() < 0 || m.year() > 9999) {
return formatMoment(
m,
utc
? "YYYYYY-MM-DD[T]HH:mm:ss.SSS[Z]"
: "YYYYYY-MM-DD[T]HH:mm:ss.SSSZ"
);
}
if (isFunction(Date.prototype.toISOString)) {
// native implementation is ~50x faster, use it when we can
if (utc) {
return this.toDate().toISOString();
} else {
return new Date(this.valueOf() + this.utcOffset() * 60 * 1000)
.toISOString()
.replace("Z", formatMoment(m, "Z"));
}
}
return formatMoment(
m,
utc ? "YYYY-MM-DD[T]HH:mm:ss.SSS[Z]" : "YYYY-MM-DD[T]HH:mm:ss.SSSZ"
);
}
/**
* Return a human readable representation of a moment that can
* also be evaluated to get a new moment which is the same
*
* @link https://nodejs.org/dist/latest/docs/api/util.html#util_custom_inspect_function_on_objects
*/
function inspect() {
if (!this.isValid()) {
return "moment.invalid(/* " + this._i + " */)";
}
var func = "moment",
zone = "",
prefix,
year,
datetime,
suffix;
if (!this.isLocal()) {
func = this.utcOffset() === 0 ? "moment.utc" : "moment.parseZone";
zone = "Z";
}
prefix = "[" + func + '("]';
year = 0 <= this.year() && this.year() <= 9999 ? "YYYY" : "YYYYYY";
datetime = "-MM-DD[T]HH:mm:ss.SSS";
suffix = zone + '[")]';
return this.format(prefix + year + datetime + suffix);
}
function format(inputString) {
if (!inputString) {
inputString = this.isUtc()
? hooks.defaultFormatUtc
: hooks.defaultFormat;
}
var output = formatMoment(this, inputString);
return this.localeData().postformat(output);
}
function from(time, withoutSuffix) {
if (
this.isValid() &&
((isMoment(time) && time.isValid()) || createLocal(time).isValid())
) {
return createDuration({ to: this, from: time })
.locale(this.locale())
.humanize(!withoutSuffix);
} else {
return this.localeData().invalidDate();
}
}
function fromNow(withoutSuffix) {
return this.from(createLocal(), withoutSuffix);
}
function to(time, withoutSuffix) {
if (
this.isValid() &&
((isMoment(time) && time.isValid()) || createLocal(time).isValid())
) {
return createDuration({ from: this, to: time })
.locale(this.locale())
.humanize(!withoutSuffix);
} else {
return this.localeData().invalidDate();
}
}
function toNow(withoutSuffix) {
return this.to(createLocal(), withoutSuffix);
}
// If passed a locale key, it will set the locale for this
// instance. Otherwise, it will return the locale configuration
// variables for this instance.
function locale(key) {
var newLocaleData;
if (key === undefined) {
return this._locale._abbr;
} else {
newLocaleData = getLocale(key);
if (newLocaleData != null) {
this._locale = newLocaleData;
}
return this;
}
}
var lang = deprecate(
"moment().lang() is deprecated. Instead, use moment().localeData() to get the language configuration. Use moment().locale() to change languages.",
function (key) {
if (key === undefined) {
return this.localeData();
} else {
return this.locale(key);
}
}
);
function localeData() {
return this._locale;
}
var MS_PER_SECOND = 1000,
MS_PER_MINUTE = 60 * MS_PER_SECOND,
MS_PER_HOUR = 60 * MS_PER_MINUTE,
MS_PER_400_YEARS = (365 * 400 + 97) * 24 * MS_PER_HOUR;
// actual modulo - handles negative numbers (for dates before 1970):
function mod$1(dividend, divisor) {
return ((dividend % divisor) + divisor) % divisor;
}
function localStartOfDate(y, m, d) {
// the date constructor remaps years 0-99 to 1900-1999
if (y < 100 && y >= 0) {
// preserve leap years using a full 400 year cycle, then reset
return new Date(y + 400, m, d) - MS_PER_400_YEARS;
} else {
return new Date(y, m, d).valueOf();
}
}
function utcStartOfDate(y, m, d) {
// Date.UTC remaps years 0-99 to 1900-1999
if (y < 100 && y >= 0) {
// preserve leap years using a full 400 year cycle, then reset
return Date.UTC(y + 400, m, d) - MS_PER_400_YEARS;
} else {
return Date.UTC(y, m, d);
}
}
function startOf(units) {
var time, startOfDate;
units = normalizeUnits(units);
if (units === undefined || units === "millisecond" || !this.isValid()) {
return this;
}
startOfDate = this._isUTC ? utcStartOfDate : localStartOfDate;
switch (units) {
case "year":
time = startOfDate(this.year(), 0, 1);
break;
case "quarter":
time = startOfDate(
this.year(),
this.month() - (this.month() % 3),
1
);
break;
case "month":
time = startOfDate(this.year(), this.month(), 1);
break;
case "week":
time = startOfDate(
this.year(),
this.month(),
this.date() - this.weekday()
);
break;
case "isoWeek":
time = startOfDate(
this.year(),
this.month(),
this.date() - (this.isoWeekday() - 1)
);
break;
case "day":
case "date":
time = startOfDate(this.year(), this.month(), this.date());
break;
case "hour":
time = this._d.valueOf();
time -= mod$1(
time + (this._isUTC ? 0 : this.utcOffset() * MS_PER_MINUTE),
MS_PER_HOUR
);
break;
case "minute":
time = this._d.valueOf();
time -= mod$1(time, MS_PER_MINUTE);
break;
case "second":
time = this._d.valueOf();
time -= mod$1(time, MS_PER_SECOND);
break;
}
this._d.setTime(time);
hooks.updateOffset(this, true);
return this;
}
function endOf(units) {
var time, startOfDate;
units = normalizeUnits(units);
if (units === undefined || units === "millisecond" || !this.isValid()) {
return this;
}
startOfDate = this._isUTC ? utcStartOfDate : localStartOfDate;
switch (units) {
case "year":
time = startOfDate(this.year() + 1, 0, 1) - 1;
break;
case "quarter":
time =
startOfDate(
this.year(),
this.month() - (this.month() % 3) + 3,
1
) - 1;
break;
case "month":
time = startOfDate(this.year(), this.month() + 1, 1) - 1;
break;
case "week":
time =
startOfDate(
this.year(),
this.month(),
this.date() - this.weekday() + 7
) - 1;
break;
case "isoWeek":
time =
startOfDate(
this.year(),
this.month(),
this.date() - (this.isoWeekday() - 1) + 7
) - 1;
break;
case "day":
case "date":
time =
startOfDate(this.year(), this.month(), this.date() + 1) - 1;
break;
case "hour":
time = this._d.valueOf();
time +=
MS_PER_HOUR -
mod$1(
time +
(this._isUTC
? 0
: this.utcOffset() * MS_PER_MINUTE),
MS_PER_HOUR
) -
1;
break;
case "minute":
time = this._d.valueOf();
time += MS_PER_MINUTE - mod$1(time, MS_PER_MINUTE) - 1;
break;
case "second":
time = this._d.valueOf();
time += MS_PER_SECOND - mod$1(time, MS_PER_SECOND) - 1;
break;
}
this._d.setTime(time);
hooks.updateOffset(this, true);
return this;
}
function valueOf() {
return this._d.valueOf() - (this._offset || 0) * 60000;
}
function unix() {
return Math.floor(this.valueOf() / 1000);
}
function toDate() {
return new Date(this.valueOf());
}
function toArray() {
var m = this;
return [
m.year(),
m.month(),
m.date(),
m.hour(),
m.minute(),
m.second(),
m.millisecond(),
];
}
function toObject() {
var m = this;
return {
years: m.year(),
months: m.month(),
date: m.date(),
hours: m.hours(),
minutes: m.minutes(),
seconds: m.seconds(),
milliseconds: m.milliseconds(),
};
}
function toJSON() {
// new Date(NaN).toJSON() === null
return this.isValid() ? this.toISOString() : null;
}
function isValid$2() {
return isValid(this);
}
function parsingFlags() {
return extend({}, getParsingFlags(this));
}
function invalidAt() {
return getParsingFlags(this).overflow;
}
function creationData() {
return {
input: this._i,
format: this._f,
locale: this._locale,
isUTC: this._isUTC,
strict: this._strict,
};
}
addFormatToken("N", 0, 0, "eraAbbr");
addFormatToken("NN", 0, 0, "eraAbbr");
addFormatToken("NNN", 0, 0, "eraAbbr");
addFormatToken("NNNN", 0, 0, "eraName");
addFormatToken("NNNNN", 0, 0, "eraNarrow");
addFormatToken("y", ["y", 1], "yo", "eraYear");
addFormatToken("y", ["yy", 2], 0, "eraYear");
addFormatToken("y", ["yyy", 3], 0, "eraYear");
addFormatToken("y", ["yyyy", 4], 0, "eraYear");
addRegexToken("N", matchEraAbbr);
addRegexToken("NN", matchEraAbbr);
addRegexToken("NNN", matchEraAbbr);
addRegexToken("NNNN", matchEraName);
addRegexToken("NNNNN", matchEraNarrow);
addParseToken(
["N", "NN", "NNN", "NNNN", "NNNNN"],
function (input, array, config, token) {
var era = config._locale.erasParse(input, token, config._strict);
if (era) {
getParsingFlags(config).era = era;
} else {
getParsingFlags(config).invalidEra = input;
}
}
);
addRegexToken("y", matchUnsigned);
addRegexToken("yy", matchUnsigned);
addRegexToken("yyy", matchUnsigned);
addRegexToken("yyyy", matchUnsigned);
addRegexToken("yo", matchEraYearOrdinal);
addParseToken(["y", "yy", "yyy", "yyyy"], YEAR);
addParseToken(["yo"], function (input, array, config, token) {
var match;
if (config._locale._eraYearOrdinalRegex) {
match = input.match(config._locale._eraYearOrdinalRegex);
}
if (config._locale.eraYearOrdinalParse) {
array[YEAR] = config._locale.eraYearOrdinalParse(input, match);
} else {
array[YEAR] = parseInt(input, 10);
}
});
function localeEras(m, format) {
var i,
l,
date,
eras = this._eras || getLocale("en")._eras;
for (i = 0, l = eras.length; i < l; ++i) {
switch (typeof eras[i].since) {
case "string":
// truncate time
date = hooks(eras[i].since).startOf("day");
eras[i].since = date.valueOf();
break;
}
switch (typeof eras[i].until) {
case "undefined":
eras[i].until = +Infinity;
break;
case "string":
// truncate time
date = hooks(eras[i].until).startOf("day").valueOf();
eras[i].until = date.valueOf();
break;
}
}
return eras;
}
function localeErasParse(eraName, format, strict) {
var i,
l,
eras = this.eras(),
name,
abbr,
narrow;
eraName = eraName.toUpperCase();
for (i = 0, l = eras.length; i < l; ++i) {
name = eras[i].name.toUpperCase();
abbr = eras[i].abbr.toUpperCase();
narrow = eras[i].narrow.toUpperCase();
if (strict) {
switch (format) {
case "N":
case "NN":
case "NNN":
if (abbr === eraName) {
return eras[i];
}
break;
case "NNNN":
if (name === eraName) {
return eras[i];
}
break;
case "NNNNN":
if (narrow === eraName) {
return eras[i];
}
break;
}
} else if ([name, abbr, narrow].indexOf(eraName) >= 0) {
return eras[i];
}
}
}
function localeErasConvertYear(era, year) {
var dir = era.since <= era.until ? +1 : -1;
if (year === undefined) {
return hooks(era.since).year();
} else {
return hooks(era.since).year() + (year - era.offset) * dir;
}
}
function getEraName() {
var i,
l,
val,
eras = this.localeData().eras();
for (i = 0, l = eras.length; i < l; ++i) {
// truncate time
val = this.clone().startOf("day").valueOf();
if (eras[i].since <= val && val <= eras[i].until) {
return eras[i].name;
}
if (eras[i].until <= val && val <= eras[i].since) {
return eras[i].name;
}
}
return "";
}
function getEraNarrow() {
var i,
l,
val,
eras = this.localeData().eras();
for (i = 0, l = eras.length; i < l; ++i) {
// truncate time
val = this.clone().startOf("day").valueOf();
if (eras[i].since <= val && val <= eras[i].until) {
return eras[i].narrow;
}
if (eras[i].until <= val && val <= eras[i].since) {
return eras[i].narrow;
}
}
return "";
}
function getEraAbbr() {
var i,
l,
val,
eras = this.localeData().eras();
for (i = 0, l = eras.length; i < l; ++i) {
// truncate time
val = this.clone().startOf("day").valueOf();
if (eras[i].since <= val && val <= eras[i].until) {
return eras[i].abbr;
}
if (eras[i].until <= val && val <= eras[i].since) {
return eras[i].abbr;
}
}
return "";
}
function getEraYear() {
var i,
l,
dir,
val,
eras = this.localeData().eras();
for (i = 0, l = eras.length; i < l; ++i) {
dir = eras[i].since <= eras[i].until ? +1 : -1;
// truncate time
val = this.clone().startOf("day").valueOf();
if (
(eras[i].since <= val && val <= eras[i].until) ||
(eras[i].until <= val && val <= eras[i].since)
) {
return (
(this.year() - hooks(eras[i].since).year()) * dir +
eras[i].offset
);
}
}
return this.year();
}
function erasNameRegex(isStrict) {
if (!hasOwnProp(this, "_erasNameRegex")) {
computeErasParse.call(this);
}
return isStrict ? this._erasNameRegex : this._erasRegex;
}
function erasAbbrRegex(isStrict) {
if (!hasOwnProp(this, "_erasAbbrRegex")) {
computeErasParse.call(this);
}
return isStrict ? this._erasAbbrRegex : this._erasRegex;
}
function erasNarrowRegex(isStrict) {
if (!hasOwnProp(this, "_erasNarrowRegex")) {
computeErasParse.call(this);
}
return isStrict ? this._erasNarrowRegex : this._erasRegex;
}
function matchEraAbbr(isStrict, locale) {
return locale.erasAbbrRegex(isStrict);
}
function matchEraName(isStrict, locale) {
return locale.erasNameRegex(isStrict);
}
function matchEraNarrow(isStrict, locale) {
return locale.erasNarrowRegex(isStrict);
}
function matchEraYearOrdinal(isStrict, locale) {
return locale._eraYearOrdinalRegex || matchUnsigned;
}
function computeErasParse() {
var abbrPieces = [],
namePieces = [],
narrowPieces = [],
mixedPieces = [],
i,
l,
eras = this.eras();
for (i = 0, l = eras.length; i < l; ++i) {
namePieces.push(regexEscape(eras[i].name));
abbrPieces.push(regexEscape(eras[i].abbr));
narrowPieces.push(regexEscape(eras[i].narrow));
mixedPieces.push(regexEscape(eras[i].name));
mixedPieces.push(regexEscape(eras[i].abbr));
mixedPieces.push(regexEscape(eras[i].narrow));
}
this._erasRegex = new RegExp("^(" + mixedPieces.join("|") + ")", "i");
this._erasNameRegex = new RegExp(
"^(" + namePieces.join("|") + ")",
"i"
);
this._erasAbbrRegex = new RegExp(
"^(" + abbrPieces.join("|") + ")",
"i"
);
this._erasNarrowRegex = new RegExp(
"^(" + narrowPieces.join("|") + ")",
"i"
);
}
// FORMATTING
addFormatToken(0, ["gg", 2], 0, function () {
return this.weekYear() % 100;
});
addFormatToken(0, ["GG", 2], 0, function () {
return this.isoWeekYear() % 100;
});
function addWeekYearFormatToken(token, getter) {
addFormatToken(0, [token, token.length], 0, getter);
}
addWeekYearFormatToken("gggg", "weekYear");
addWeekYearFormatToken("ggggg", "weekYear");
addWeekYearFormatToken("GGGG", "isoWeekYear");
addWeekYearFormatToken("GGGGG", "isoWeekYear");
// ALIASES
addUnitAlias("weekYear", "gg");
addUnitAlias("isoWeekYear", "GG");
// PRIORITY
addUnitPriority("weekYear", 1);
addUnitPriority("isoWeekYear", 1);
// PARSING
addRegexToken("G", matchSigned);
addRegexToken("g", matchSigned);
addRegexToken("GG", match1to2, match2);
addRegexToken("gg", match1to2, match2);
addRegexToken("GGGG", match1to4, match4);
addRegexToken("gggg", match1to4, match4);
addRegexToken("GGGGG", match1to6, match6);
addRegexToken("ggggg", match1to6, match6);
addWeekParseToken(
["gggg", "ggggg", "GGGG", "GGGGG"],
function (input, week, config, token) {
week[token.substr(0, 2)] = toInt(input);
}
);
addWeekParseToken(["gg", "GG"], function (input, week, config, token) {
week[token] = hooks.parseTwoDigitYear(input);
});
// MOMENTS
function getSetWeekYear(input) {
return getSetWeekYearHelper.call(
this,
input,
this.week(),
this.weekday(),
this.localeData()._week.dow,
this.localeData()._week.doy
);
}
function getSetISOWeekYear(input) {
return getSetWeekYearHelper.call(
this,
input,
this.isoWeek(),
this.isoWeekday(),
1,
4
);
}
function getISOWeeksInYear() {
return weeksInYear(this.year(), 1, 4);
}
function getISOWeeksInISOWeekYear() {
return weeksInYear(this.isoWeekYear(), 1, 4);
}
function getWeeksInYear() {
var weekInfo = this.localeData()._week;
return weeksInYear(this.year(), weekInfo.dow, weekInfo.doy);
}
function getWeeksInWeekYear() {
var weekInfo = this.localeData()._week;
return weeksInYear(this.weekYear(), weekInfo.dow, weekInfo.doy);
}
function getSetWeekYearHelper(input, week, weekday, dow, doy) {
var weeksTarget;
if (input == null) {
return weekOfYear(this, dow, doy).year;
} else {
weeksTarget = weeksInYear(input, dow, doy);
if (week > weeksTarget) {
week = weeksTarget;
}
return setWeekAll.call(this, input, week, weekday, dow, doy);
}
}
function setWeekAll(weekYear, week, weekday, dow, doy) {
var dayOfYearData = dayOfYearFromWeeks(
weekYear,
week,
weekday,
dow,
doy
),
date = createUTCDate(
dayOfYearData.year,
0,
dayOfYearData.dayOfYear
);
this.year(date.getUTCFullYear());
this.month(date.getUTCMonth());
this.date(date.getUTCDate());
return this;
}
// FORMATTING
addFormatToken("Q", 0, "Qo", "quarter");
// ALIASES
addUnitAlias("quarter", "Q");
// PRIORITY
addUnitPriority("quarter", 7);
// PARSING
addRegexToken("Q", match1);
addParseToken("Q", function (input, array) {
array[MONTH] = (toInt(input) - 1) * 3;
});
// MOMENTS
function getSetQuarter(input) {
return input == null
? Math.ceil((this.month() + 1) / 3)
: this.month((input - 1) * 3 + (this.month() % 3));
}
// FORMATTING
addFormatToken("D", ["DD", 2], "Do", "date");
// ALIASES
addUnitAlias("date", "D");
// PRIORITY
addUnitPriority("date", 9);
// PARSING
addRegexToken("D", match1to2);
addRegexToken("DD", match1to2, match2);
addRegexToken("Do", function (isStrict, locale) {
// TODO: Remove "ordinalParse" fallback in next major release.
return isStrict
? locale._dayOfMonthOrdinalParse || locale._ordinalParse
: locale._dayOfMonthOrdinalParseLenient;
});
addParseToken(["D", "DD"], DATE);
addParseToken("Do", function (input, array) {
array[DATE] = toInt(input.match(match1to2)[0]);
});
// MOMENTS
var getSetDayOfMonth = makeGetSet("Date", true);
// FORMATTING
addFormatToken("DDD", ["DDDD", 3], "DDDo", "dayOfYear");
// ALIASES
addUnitAlias("dayOfYear", "DDD");
// PRIORITY
addUnitPriority("dayOfYear", 4);
// PARSING
addRegexToken("DDD", match1to3);
addRegexToken("DDDD", match3);
addParseToken(["DDD", "DDDD"], function (input, array, config) {
config._dayOfYear = toInt(input);
});
// HELPERS
// MOMENTS
function getSetDayOfYear(input) {
var dayOfYear =
Math.round(
(this.clone().startOf("day") - this.clone().startOf("year")) /
864e5
) + 1;
return input == null ? dayOfYear : this.add(input - dayOfYear, "d");
}
// FORMATTING
addFormatToken("m", ["mm", 2], 0, "minute");
// ALIASES
addUnitAlias("minute", "m");
// PRIORITY
addUnitPriority("minute", 14);
// PARSING
addRegexToken("m", match1to2);
addRegexToken("mm", match1to2, match2);
addParseToken(["m", "mm"], MINUTE);
// MOMENTS
var getSetMinute = makeGetSet("Minutes", false);
// FORMATTING
addFormatToken("s", ["ss", 2], 0, "second");
// ALIASES
addUnitAlias("second", "s");
// PRIORITY
addUnitPriority("second", 15);
// PARSING
addRegexToken("s", match1to2);
addRegexToken("ss", match1to2, match2);
addParseToken(["s", "ss"], SECOND);
// MOMENTS
var getSetSecond = makeGetSet("Seconds", false);
// FORMATTING
addFormatToken("S", 0, 0, function () {
return ~~(this.millisecond() / 100);
});
addFormatToken(0, ["SS", 2], 0, function () {
return ~~(this.millisecond() / 10);
});
addFormatToken(0, ["SSS", 3], 0, "millisecond");
addFormatToken(0, ["SSSS", 4], 0, function () {
return this.millisecond() * 10;
});
addFormatToken(0, ["SSSSS", 5], 0, function () {
return this.millisecond() * 100;
});
addFormatToken(0, ["SSSSSS", 6], 0, function () {
return this.millisecond() * 1000;
});
addFormatToken(0, ["SSSSSSS", 7], 0, function () {
return this.millisecond() * 10000;
});
addFormatToken(0, ["SSSSSSSS", 8], 0, function () {
return this.millisecond() * 100000;
});
addFormatToken(0, ["SSSSSSSSS", 9], 0, function () {
return this.millisecond() * 1000000;
});
// ALIASES
addUnitAlias("millisecond", "ms");
// PRIORITY
addUnitPriority("millisecond", 16);
// PARSING
addRegexToken("S", match1to3, match1);
addRegexToken("SS", match1to3, match2);
addRegexToken("SSS", match1to3, match3);
var token, getSetMillisecond;
for (token = "SSSS"; token.length <= 9; token += "S") {
addRegexToken(token, matchUnsigned);
}
function parseMs(input, array) {
array[MILLISECOND] = toInt(("0." + input) * 1000);
}
for (token = "S"; token.length <= 9; token += "S") {
addParseToken(token, parseMs);
}
getSetMillisecond = makeGetSet("Milliseconds", false);
// FORMATTING
addFormatToken("z", 0, 0, "zoneAbbr");
addFormatToken("zz", 0, 0, "zoneName");
// MOMENTS
function getZoneAbbr() {
return this._isUTC ? "UTC" : "";
}
function getZoneName() {
return this._isUTC ? "Coordinated Universal Time" : "";
}
var proto = Moment.prototype;
proto.add = add;
proto.calendar = calendar$1;
proto.clone = clone;
proto.diff = diff;
proto.endOf = endOf;
proto.format = format;
proto.from = from;
proto.fromNow = fromNow;
proto.to = to;
proto.toNow = toNow;
proto.get = stringGet;
proto.invalidAt = invalidAt;
proto.isAfter = isAfter;
proto.isBefore = isBefore;
proto.isBetween = isBetween;
proto.isSame = isSame;
proto.isSameOrAfter = isSameOrAfter;
proto.isSameOrBefore = isSameOrBefore;
proto.isValid = isValid$2;
proto.lang = lang;
proto.locale = locale;
proto.localeData = localeData;
proto.max = prototypeMax;
proto.min = prototypeMin;
proto.parsingFlags = parsingFlags;
proto.set = stringSet;
proto.startOf = startOf;
proto.subtract = subtract;
proto.toArray = toArray;
proto.toObject = toObject;
proto.toDate = toDate;
proto.toISOString = toISOString;
proto.inspect = inspect;
if (typeof Symbol !== "undefined" && Symbol.for != null) {
proto[Symbol.for("nodejs.util.inspect.custom")] = function () {
return "Moment<" + this.format() + ">";
};
}
proto.toJSON = toJSON;
proto.toString = toString;
proto.unix = unix;
proto.valueOf = valueOf;
proto.creationData = creationData;
proto.eraName = getEraName;
proto.eraNarrow = getEraNarrow;
proto.eraAbbr = getEraAbbr;
proto.eraYear = getEraYear;
proto.year = getSetYear;
proto.isLeapYear = getIsLeapYear;
proto.weekYear = getSetWeekYear;
proto.isoWeekYear = getSetISOWeekYear;
proto.quarter = proto.quarters = getSetQuarter;
proto.month = getSetMonth;
proto.daysInMonth = getDaysInMonth;
proto.week = proto.weeks = getSetWeek;
proto.isoWeek = proto.isoWeeks = getSetISOWeek;
proto.weeksInYear = getWeeksInYear;
proto.weeksInWeekYear = getWeeksInWeekYear;
proto.isoWeeksInYear = getISOWeeksInYear;
proto.isoWeeksInISOWeekYear = getISOWeeksInISOWeekYear;
proto.date = getSetDayOfMonth;
proto.day = proto.days = getSetDayOfWeek;
proto.weekday = getSetLocaleDayOfWeek;
proto.isoWeekday = getSetISODayOfWeek;
proto.dayOfYear = getSetDayOfYear;
proto.hour = proto.hours = getSetHour;
proto.minute = proto.minutes = getSetMinute;
proto.second = proto.seconds = getSetSecond;
proto.millisecond = proto.milliseconds = getSetMillisecond;
proto.utcOffset = getSetOffset;
proto.utc = setOffsetToUTC;
proto.local = setOffsetToLocal;
proto.parseZone = setOffsetToParsedOffset;
proto.hasAlignedHourOffset = hasAlignedHourOffset;
proto.isDST = isDaylightSavingTime;
proto.isLocal = isLocal;
proto.isUtcOffset = isUtcOffset;
proto.isUtc = isUtc;
proto.isUTC = isUtc;
proto.zoneAbbr = getZoneAbbr;
proto.zoneName = getZoneName;
proto.dates = deprecate(
"dates accessor is deprecated. Use date instead.",
getSetDayOfMonth
);
proto.months = deprecate(
"months accessor is deprecated. Use month instead",
getSetMonth
);
proto.years = deprecate(
"years accessor is deprecated. Use year instead",
getSetYear
);
proto.zone = deprecate(
"moment().zone is deprecated, use moment().utcOffset instead. http://momentjs.com/guides/#/warnings/zone/",
getSetZone
);
proto.isDSTShifted = deprecate(
"isDSTShifted is deprecated. See http://momentjs.com/guides/#/warnings/dst-shifted/ for more information",
isDaylightSavingTimeShifted
);
function createUnix(input) {
return createLocal(input * 1000);
}
function createInZone() {
return createLocal.apply(null, arguments).parseZone();
}
function preParsePostFormat(string) {
return string;
}
var proto$1 = Locale.prototype;
proto$1.calendar = calendar;
proto$1.longDateFormat = longDateFormat;
proto$1.invalidDate = invalidDate;
proto$1.ordinal = ordinal;
proto$1.preparse = preParsePostFormat;
proto$1.postformat = preParsePostFormat;
proto$1.relativeTime = relativeTime;
proto$1.pastFuture = pastFuture;
proto$1.set = set;
proto$1.eras = localeEras;
proto$1.erasParse = localeErasParse;
proto$1.erasConvertYear = localeErasConvertYear;
proto$1.erasAbbrRegex = erasAbbrRegex;
proto$1.erasNameRegex = erasNameRegex;
proto$1.erasNarrowRegex = erasNarrowRegex;
proto$1.months = localeMonths;
proto$1.monthsShort = localeMonthsShort;
proto$1.monthsParse = localeMonthsParse;
proto$1.monthsRegex = monthsRegex;
proto$1.monthsShortRegex = monthsShortRegex;
proto$1.week = localeWeek;
proto$1.firstDayOfYear = localeFirstDayOfYear;
proto$1.firstDayOfWeek = localeFirstDayOfWeek;
proto$1.weekdays = localeWeekdays;
proto$1.weekdaysMin = localeWeekdaysMin;
proto$1.weekdaysShort = localeWeekdaysShort;
proto$1.weekdaysParse = localeWeekdaysParse;
proto$1.weekdaysRegex = weekdaysRegex;
proto$1.weekdaysShortRegex = weekdaysShortRegex;
proto$1.weekdaysMinRegex = weekdaysMinRegex;
proto$1.isPM = localeIsPM;
proto$1.meridiem = localeMeridiem;
function get$1(format, index, field, setter) {
var locale = getLocale(),
utc = createUTC().set(setter, index);
return locale[field](utc, format);
}
function listMonthsImpl(format, index, field) {
if (isNumber(format)) {
index = format;
format = undefined;
}
format = format || "";
if (index != null) {
return get$1(format, index, field, "month");
}
var i,
out = [];
for (i = 0; i < 12; i++) {
out[i] = get$1(format, i, field, "month");
}
return out;
}
// ()
// (5)
// (fmt, 5)
// (fmt)
// (true)
// (true, 5)
// (true, fmt, 5)
// (true, fmt)
function listWeekdaysImpl(localeSorted, format, index, field) {
if (typeof localeSorted === "boolean") {
if (isNumber(format)) {
index = format;
format = undefined;
}
format = format || "";
} else {
format = localeSorted;
index = format;
localeSorted = false;
if (isNumber(format)) {
index = format;
format = undefined;
}
format = format || "";
}
var locale = getLocale(),
shift = localeSorted ? locale._week.dow : 0,
i,
out = [];
if (index != null) {
return get$1(format, (index + shift) % 7, field, "day");
}
for (i = 0; i < 7; i++) {
out[i] = get$1(format, (i + shift) % 7, field, "day");
}
return out;
}
function listMonths(format, index) {
return listMonthsImpl(format, index, "months");
}
function listMonthsShort(format, index) {
return listMonthsImpl(format, index, "monthsShort");
}
function listWeekdays(localeSorted, format, index) {
return listWeekdaysImpl(localeSorted, format, index, "weekdays");
}
function listWeekdaysShort(localeSorted, format, index) {
return listWeekdaysImpl(localeSorted, format, index, "weekdaysShort");
}
function listWeekdaysMin(localeSorted, format, index) {
return listWeekdaysImpl(localeSorted, format, index, "weekdaysMin");
}
getSetGlobalLocale("en", {
eras: [
{
since: "0001-01-01",
until: +Infinity,
offset: 1,
name: "Anno Domini",
narrow: "AD",
abbr: "AD",
},
{
since: "0000-12-31",
until: -Infinity,
offset: 1,
name: "Before Christ",
narrow: "BC",
abbr: "BC",
},
],
dayOfMonthOrdinalParse: /\d{1,2}(th|st|nd|rd)/,
ordinal: function (number) {
var b = number % 10,
output =
toInt((number % 100) / 10) === 1
? "th"
: b === 1
? "st"
: b === 2
? "nd"
: b === 3
? "rd"
: "th";
return number + output;
},
});
// Side effect imports
hooks.lang = deprecate(
"moment.lang is deprecated. Use moment.locale instead.",
getSetGlobalLocale
);
hooks.langData = deprecate(
"moment.langData is deprecated. Use moment.localeData instead.",
getLocale
);
var mathAbs = Math.abs;
function abs() {
var data = this._data;
this._milliseconds = mathAbs(this._milliseconds);
this._days = mathAbs(this._days);
this._months = mathAbs(this._months);
data.milliseconds = mathAbs(data.milliseconds);
data.seconds = mathAbs(data.seconds);
data.minutes = mathAbs(data.minutes);
data.hours = mathAbs(data.hours);
data.months = mathAbs(data.months);
data.years = mathAbs(data.years);
return this;
}
function addSubtract$1(duration, input, value, direction) {
var other = createDuration(input, value);
duration._milliseconds += direction * other._milliseconds;
duration._days += direction * other._days;
duration._months += direction * other._months;
return duration._bubble();
}
// supports only 2.0-style add(1, 's') or add(duration)
function add$1(input, value) {
return addSubtract$1(this, input, value, 1);
}
// supports only 2.0-style subtract(1, 's') or subtract(duration)
function subtract$1(input, value) {
return addSubtract$1(this, input, value, -1);
}
function absCeil(number) {
if (number < 0) {
return Math.floor(number);
} else {
return Math.ceil(number);
}
}
function bubble() {
var milliseconds = this._milliseconds,
days = this._days,
months = this._months,
data = this._data,
seconds,
minutes,
hours,
years,
monthsFromDays;
// if we have a mix of positive and negative values, bubble down first
// check: https://github.com/moment/moment/issues/2166
if (
!(
(milliseconds >= 0 && days >= 0 && months >= 0) ||
(milliseconds <= 0 && days <= 0 && months <= 0)
)
) {
milliseconds += absCeil(monthsToDays(months) + days) * 864e5;
days = 0;
months = 0;
}
// The following code bubbles up values, see the tests for
// examples of what that means.
data.milliseconds = milliseconds % 1000;
seconds = absFloor(milliseconds / 1000);
data.seconds = seconds % 60;
minutes = absFloor(seconds / 60);
data.minutes = minutes % 60;
hours = absFloor(minutes / 60);
data.hours = hours % 24;
days += absFloor(hours / 24);
// convert days to months
monthsFromDays = absFloor(daysToMonths(days));
months += monthsFromDays;
days -= absCeil(monthsToDays(monthsFromDays));
// 12 months -> 1 year
years = absFloor(months / 12);
months %= 12;
data.days = days;
data.months = months;
data.years = years;
return this;
}
function daysToMonths(days) {
// 400 years have 146097 days (taking into account leap year rules)
// 400 years have 12 months === 4800
return (days * 4800) / 146097;
}
function monthsToDays(months) {
// the reverse of daysToMonths
return (months * 146097) / 4800;
}
function as(units) {
if (!this.isValid()) {
return NaN;
}
var days,
months,
milliseconds = this._milliseconds;
units = normalizeUnits(units);
if (units === "month" || units === "quarter" || units === "year") {
days = this._days + milliseconds / 864e5;
months = this._months + daysToMonths(days);
switch (units) {
case "month":
return months;
case "quarter":
return months / 3;
case "year":
return months / 12;
}
} else {
// handle milliseconds separately because of floating point math errors (issue #1867)
days = this._days + Math.round(monthsToDays(this._months));
switch (units) {
case "week":
return days / 7 + milliseconds / 6048e5;
case "day":
return days + milliseconds / 864e5;
case "hour":
return days * 24 + milliseconds / 36e5;
case "minute":
return days * 1440 + milliseconds / 6e4;
case "second":
return days * 86400 + milliseconds / 1000;
// Math.floor prevents floating point math errors here
case "millisecond":
return Math.floor(days * 864e5) + milliseconds;
default:
throw new Error("Unknown unit " + units);
}
}
}
// TODO: Use this.as('ms')?
function valueOf$1() {
if (!this.isValid()) {
return NaN;
}
return (
this._milliseconds +
this._days * 864e5 +
(this._months % 12) * 2592e6 +
toInt(this._months / 12) * 31536e6
);
}
function makeAs(alias) {
return function () {
return this.as(alias);
};
}
var asMilliseconds = makeAs("ms"),
asSeconds = makeAs("s"),
asMinutes = makeAs("m"),
asHours = makeAs("h"),
asDays = makeAs("d"),
asWeeks = makeAs("w"),
asMonths = makeAs("M"),
asQuarters = makeAs("Q"),
asYears = makeAs("y");
function clone$1() {
return createDuration(this);
}
function get$2(units) {
units = normalizeUnits(units);
return this.isValid() ? this[units + "s"]() : NaN;
}
function makeGetter(name) {
return function () {
return this.isValid() ? this._data[name] : NaN;
};
}
var milliseconds = makeGetter("milliseconds"),
seconds = makeGetter("seconds"),
minutes = makeGetter("minutes"),
hours = makeGetter("hours"),
days = makeGetter("days"),
months = makeGetter("months"),
years = makeGetter("years");
function weeks() {
return absFloor(this.days() / 7);
}
var round = Math.round,
thresholds = {
ss: 44, // a few seconds to seconds
s: 45, // seconds to minute
m: 45, // minutes to hour
h: 22, // hours to day
d: 26, // days to month/week
w: null, // weeks to month
M: 11, // months to year
};
// helper function for moment.fn.from, moment.fn.fromNow, and moment.duration.fn.humanize
function substituteTimeAgo(
string,
number,
withoutSuffix,
isFuture,
locale
) {
return locale.relativeTime(
number || 1,
!!withoutSuffix,
string,
isFuture
);
}
function relativeTime$1(posNegDuration, withoutSuffix, thresholds, locale) {
var duration = createDuration(posNegDuration).abs(),
seconds = round(duration.as("s")),
minutes = round(duration.as("m")),
hours = round(duration.as("h")),
days = round(duration.as("d")),
months = round(duration.as("M")),
weeks = round(duration.as("w")),
years = round(duration.as("y")),
a =
(seconds <= thresholds.ss && ["s", seconds]) ||
(seconds < thresholds.s && ["ss", seconds]) ||
(minutes <= 1 && ["m"]) ||
(minutes < thresholds.m && ["mm", minutes]) ||
(hours <= 1 && ["h"]) ||
(hours < thresholds.h && ["hh", hours]) ||
(days <= 1 && ["d"]) ||
(days < thresholds.d && ["dd", days]);
if (thresholds.w != null) {
a =
a ||
(weeks <= 1 && ["w"]) ||
(weeks < thresholds.w && ["ww", weeks]);
}
a = a ||
(months <= 1 && ["M"]) ||
(months < thresholds.M && ["MM", months]) ||
(years <= 1 && ["y"]) || ["yy", years];
a[2] = withoutSuffix;
a[3] = +posNegDuration > 0;
a[4] = locale;
return substituteTimeAgo.apply(null, a);
}
// This function allows you to set the rounding function for relative time strings
function getSetRelativeTimeRounding(roundingFunction) {
if (roundingFunction === undefined) {
return round;
}
if (typeof roundingFunction === "function") {
round = roundingFunction;
return true;
}
return false;
}
// This function allows you to set a threshold for relative time strings
function getSetRelativeTimeThreshold(threshold, limit) {
if (thresholds[threshold] === undefined) {
return false;
}
if (limit === undefined) {
return thresholds[threshold];
}
thresholds[threshold] = limit;
if (threshold === "s") {
thresholds.ss = limit - 1;
}
return true;
}
function humanize(argWithSuffix, argThresholds) {
if (!this.isValid()) {
return this.localeData().invalidDate();
}
var withSuffix = false,
th = thresholds,
locale,
output;
if (typeof argWithSuffix === "object") {
argThresholds = argWithSuffix;
argWithSuffix = false;
}
if (typeof argWithSuffix === "boolean") {
withSuffix = argWithSuffix;
}
if (typeof argThresholds === "object") {
th = Object.assign({}, thresholds, argThresholds);
if (argThresholds.s != null && argThresholds.ss == null) {
th.ss = argThresholds.s - 1;
}
}
locale = this.localeData();
output = relativeTime$1(this, !withSuffix, th, locale);
if (withSuffix) {
output = locale.pastFuture(+this, output);
}
return locale.postformat(output);
}
var abs$1 = Math.abs;
function sign(x) {
return (x > 0) - (x < 0) || +x;
}
function toISOString$1() {
// for ISO strings we do not use the normal bubbling rules:
// * milliseconds bubble up until they become hours
// * days do not bubble at all
// * months bubble up until they become years
// This is because there is no context-free conversion between hours and days
// (think of clock changes)
// and also not between days and months (28-31 days per month)
if (!this.isValid()) {
return this.localeData().invalidDate();
}
var seconds = abs$1(this._milliseconds) / 1000,
days = abs$1(this._days),
months = abs$1(this._months),
minutes,
hours,
years,
s,
total = this.asSeconds(),
totalSign,
ymSign,
daysSign,
hmsSign;
if (!total) {
// this is the same as C#'s (Noda) and python (isodate)...
// but not other JS (goog.date)
return "P0D";
}
// 3600 seconds -> 60 minutes -> 1 hour
minutes = absFloor(seconds / 60);
hours = absFloor(minutes / 60);
seconds %= 60;
minutes %= 60;
// 12 months -> 1 year
years = absFloor(months / 12);
months %= 12;
// inspired by https://github.com/dordille/moment-isoduration/blob/master/moment.isoduration.js
s = seconds ? seconds.toFixed(3).replace(/\.?0+$/, "") : "";
totalSign = total < 0 ? "-" : "";
ymSign = sign(this._months) !== sign(total) ? "-" : "";
daysSign = sign(this._days) !== sign(total) ? "-" : "";
hmsSign = sign(this._milliseconds) !== sign(total) ? "-" : "";
return (
totalSign +
"P" +
(years ? ymSign + years + "Y" : "") +
(months ? ymSign + months + "M" : "") +
(days ? daysSign + days + "D" : "") +
(hours || minutes || seconds ? "T" : "") +
(hours ? hmsSign + hours + "H" : "") +
(minutes ? hmsSign + minutes + "M" : "") +
(seconds ? hmsSign + s + "S" : "")
);
}
var proto$2 = Duration.prototype;
proto$2.isValid = isValid$1;
proto$2.abs = abs;
proto$2.add = add$1;
proto$2.subtract = subtract$1;
proto$2.as = as;
proto$2.asMilliseconds = asMilliseconds;
proto$2.asSeconds = asSeconds;
proto$2.asMinutes = asMinutes;
proto$2.asHours = asHours;
proto$2.asDays = asDays;
proto$2.asWeeks = asWeeks;
proto$2.asMonths = asMonths;
proto$2.asQuarters = asQuarters;
proto$2.asYears = asYears;
proto$2.valueOf = valueOf$1;
proto$2._bubble = bubble;
proto$2.clone = clone$1;
proto$2.get = get$2;
proto$2.milliseconds = milliseconds;
proto$2.seconds = seconds;
proto$2.minutes = minutes;
proto$2.hours = hours;
proto$2.days = days;
proto$2.weeks = weeks;
proto$2.months = months;
proto$2.years = years;
proto$2.humanize = humanize;
proto$2.toISOString = toISOString$1;
proto$2.toString = toISOString$1;
proto$2.toJSON = toISOString$1;
proto$2.locale = locale;
proto$2.localeData = localeData;
proto$2.toIsoString = deprecate(
"toIsoString() is deprecated. Please use toISOString() instead (notice the capitals)",
toISOString$1
);
proto$2.lang = lang;
// FORMATTING
addFormatToken("X", 0, 0, "unix");
addFormatToken("x", 0, 0, "valueOf");
// PARSING
addRegexToken("x", matchSigned);
addRegexToken("X", matchTimestamp);
addParseToken("X", function (input, array, config) {
config._d = new Date(parseFloat(input) * 1000);
});
addParseToken("x", function (input, array, config) {
config._d = new Date(toInt(input));
});
//! moment.js
hooks.version = "2.29.1";
setHookCallback(createLocal);
hooks.fn = proto;
hooks.min = min;
hooks.max = max;
hooks.now = now;
hooks.utc = createUTC;
hooks.unix = createUnix;
hooks.months = listMonths;
hooks.isDate = isDate;
hooks.locale = getSetGlobalLocale;
hooks.invalid = createInvalid;
hooks.duration = createDuration;
hooks.isMoment = isMoment;
hooks.weekdays = listWeekdays;
hooks.parseZone = createInZone;
hooks.localeData = getLocale;
hooks.isDuration = isDuration;
hooks.monthsShort = listMonthsShort;
hooks.weekdaysMin = listWeekdaysMin;
hooks.defineLocale = defineLocale;
hooks.updateLocale = updateLocale;
hooks.locales = listLocales;
hooks.weekdaysShort = listWeekdaysShort;
hooks.normalizeUnits = normalizeUnits;
hooks.relativeTimeRounding = getSetRelativeTimeRounding;
hooks.relativeTimeThreshold = getSetRelativeTimeThreshold;
hooks.calendarFormat = getCalendarFormat;
hooks.prototype = proto;
// currently HTML5 input type only supports 24-hour formats
hooks.HTML5_FMT = {
DATETIME_LOCAL: "YYYY-MM-DDTHH:mm", // <input type="datetime-local" />
DATETIME_LOCAL_SECONDS: "YYYY-MM-DDTHH:mm:ss", // <input type="datetime-local" step="1" />
DATETIME_LOCAL_MS: "YYYY-MM-DDTHH:mm:ss.SSS", // <input type="datetime-local" step="0.001" />
DATE: "YYYY-MM-DD", // <input type="date" />
TIME: "HH:mm", // <input type="time" />
TIME_SECONDS: "HH:mm:ss", // <input type="time" step="1" />
TIME_MS: "HH:mm:ss.SSS", // <input type="time" step="0.001" />
WEEK: "GGGG-[W]WW", // <input type="week" />
MONTH: "YYYY-MM", // <input type="month" />
};
return hooks;
});
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_minifier/tests/fixture/issues/moment/1/output.js | JavaScript | !//! moment.js
//! version : 2.29.1
//! authors : Tim Wood, Iskren Chernev, Moment.js contributors
//! license : MIT
//! momentjs.com
function(global, factory) {
"object" == typeof exports && "undefined" != typeof module ? module.exports = factory() : "function" == typeof define && define.amd ? define(factory) : global.moment = factory();
}(this, function() {
"use strict";
function hooks() {
return hookCallback.apply(null, arguments);
}
function isArray(input) {
return input instanceof Array || "[object Array]" === Object.prototype.toString.call(input);
}
function isObject(input) {
// IE8 will treat undefined and null as object if it wasn't for
// input != null
return null != input && "[object Object]" === Object.prototype.toString.call(input);
}
function hasOwnProp(a, b) {
return Object.prototype.hasOwnProperty.call(a, b);
}
function isObjectEmpty(obj) {
var k;
if (Object.getOwnPropertyNames) return 0 === Object.getOwnPropertyNames(obj).length;
for(k in obj)if (hasOwnProp(obj, k)) return !1;
return !0;
}
function isUndefined(input) {
return void 0 === input;
}
function isNumber(input) {
return "number" == typeof input || "[object Number]" === Object.prototype.toString.call(input);
}
function isDate(input) {
return input instanceof Date || "[object Date]" === Object.prototype.toString.call(input);
}
function map(arr, fn) {
var i, res = [];
for(i = 0; i < arr.length; ++i)res.push(fn(arr[i], i));
return res;
}
function extend(a, b) {
for(var i in b)hasOwnProp(b, i) && (a[i] = b[i]);
return hasOwnProp(b, "toString") && (a.toString = b.toString), hasOwnProp(b, "valueOf") && (a.valueOf = b.valueOf), a;
}
function createUTC(input, format, locale, strict) {
return createLocalOrUTC(input, format, locale, strict, !0).utc();
}
function getParsingFlags(m) {
return null == m._pf && (m._pf = {
empty: !1,
unusedTokens: [],
unusedInput: [],
overflow: -2,
charsLeftOver: 0,
nullInput: !1,
invalidEra: null,
invalidMonth: null,
invalidFormat: !1,
userInvalidated: !1,
iso: !1,
parsedDateParts: [],
era: null,
meridiem: null,
rfc2822: !1,
weekdayMismatch: !1
}), m._pf;
}
function isValid(m) {
if (null == m._isValid) {
var flags = getParsingFlags(m), parsedParts = some.call(flags.parsedDateParts, function(i) {
return null != i;
}), isNowValid = !isNaN(m._d.getTime()) && flags.overflow < 0 && !flags.empty && !flags.invalidEra && !flags.invalidMonth && !flags.invalidWeekday && !flags.weekdayMismatch && !flags.nullInput && !flags.invalidFormat && !flags.userInvalidated && (!flags.meridiem || flags.meridiem && parsedParts);
if (m._strict && (isNowValid = isNowValid && 0 === flags.charsLeftOver && 0 === flags.unusedTokens.length && void 0 === flags.bigHour), null != Object.isFrozen && Object.isFrozen(m)) return isNowValid;
m._isValid = isNowValid;
}
return m._isValid;
}
function createInvalid(flags) {
var m = createUTC(NaN);
return null != flags ? extend(getParsingFlags(m), flags) : getParsingFlags(m).userInvalidated = !0, m;
}
some = Array.prototype.some ? Array.prototype.some : function(fun) {
var i, t = Object(this), len = t.length >>> 0;
for(i = 0; i < len; i++)if (i in t && fun.call(this, t[i], i, t)) return !0;
return !1;
};
// Plugins that add properties should also add the key here (null value),
// so we can properly clone ourselves.
var token, getSetMillisecond, momentProperties = hooks.momentProperties = [], updateInProgress = !1;
function copyConfig(to, from) {
var i, prop, val;
if (isUndefined(from._isAMomentObject) || (to._isAMomentObject = from._isAMomentObject), isUndefined(from._i) || (to._i = from._i), isUndefined(from._f) || (to._f = from._f), isUndefined(from._l) || (to._l = from._l), isUndefined(from._strict) || (to._strict = from._strict), isUndefined(from._tzm) || (to._tzm = from._tzm), isUndefined(from._isUTC) || (to._isUTC = from._isUTC), isUndefined(from._offset) || (to._offset = from._offset), isUndefined(from._pf) || (to._pf = getParsingFlags(from)), isUndefined(from._locale) || (to._locale = from._locale), momentProperties.length > 0) for(i = 0; i < momentProperties.length; i++)isUndefined(val = from[prop = momentProperties[i]]) || (to[prop] = val);
return to;
}
// Moment prototype object
function Moment(config) {
copyConfig(this, config), this._d = new Date(null != config._d ? config._d.getTime() : NaN), this.isValid() || (this._d = new Date(NaN)), !1 === updateInProgress && (updateInProgress = !0, hooks.updateOffset(this), updateInProgress = !1);
}
function isMoment(obj) {
return obj instanceof Moment || null != obj && null != obj._isAMomentObject;
}
function warn(msg) {
!1 === hooks.suppressDeprecationWarnings && "undefined" != typeof console && console.warn && console.warn("Deprecation warning: " + msg);
}
function deprecate(msg, fn) {
var firstTime = !0;
return extend(function() {
if (null != hooks.deprecationHandler && hooks.deprecationHandler(null, msg), firstTime) {
var arg, i, key, args = [];
for(i = 0; i < arguments.length; i++){
if (arg = "", "object" == typeof arguments[i]) {
for(key in arg += "\n[" + i + "] ", arguments[0])hasOwnProp(arguments[0], key) && (arg += key + ": " + arguments[0][key] + ", ");
arg = arg.slice(0, -2);
} else arg = arguments[i];
args.push(arg);
}
warn(msg + "\nArguments: " + Array.prototype.slice.call(args).join("") + "\n" + Error().stack), firstTime = !1;
}
return fn.apply(this, arguments);
}, fn);
}
var deprecations = {};
function deprecateSimple(name, msg) {
null != hooks.deprecationHandler && hooks.deprecationHandler(name, msg), deprecations[name] || (warn(msg), deprecations[name] = !0);
}
function isFunction(input) {
return "undefined" != typeof Function && input instanceof Function || "[object Function]" === Object.prototype.toString.call(input);
}
function mergeConfigs(parentConfig, childConfig) {
var prop, res = extend({}, parentConfig);
for(prop in childConfig)hasOwnProp(childConfig, prop) && (isObject(parentConfig[prop]) && isObject(childConfig[prop]) ? (res[prop] = {}, extend(res[prop], parentConfig[prop]), extend(res[prop], childConfig[prop])) : null != childConfig[prop] ? res[prop] = childConfig[prop] : delete res[prop]);
for(prop in parentConfig)hasOwnProp(parentConfig, prop) && !hasOwnProp(childConfig, prop) && isObject(parentConfig[prop]) && // make sure changes to properties don't modify parent config
(res[prop] = extend({}, res[prop]));
return res;
}
function Locale(config) {
null != config && this.set(config);
}
function zeroFill(number, targetLength, forceSign) {
var absNumber = "" + Math.abs(number);
return (number >= 0 ? forceSign ? "+" : "" : "-") + Math.pow(10, Math.max(0, targetLength - absNumber.length)).toString().substr(1) + absNumber;
}
hooks.suppressDeprecationWarnings = !1, hooks.deprecationHandler = null, keys = Object.keys ? Object.keys : function(obj) {
var i, res = [];
for(i in obj)hasOwnProp(obj, i) && res.push(i);
return res;
};
var formattingTokens = /(\[[^\[]*\])|(\\)?([Hh]mm(ss)?|Mo|MM?M?M?|Do|DDDo|DD?D?D?|ddd?d?|do?|w[o|w]?|W[o|W]?|Qo?|N{1,5}|YYYYYY|YYYYY|YYYY|YY|y{2,4}|yo?|gg(ggg?)?|GG(GGG?)?|e|E|a|A|hh?|HH?|kk?|mm?|ss?|S{1,9}|x|X|zz?|ZZ?|.)/g, localFormattingTokens = /(\[[^\[]*\])|(\\)?(LTS|LT|LL?L?L?|l{1,4})/g, formatFunctions = {}, formatTokenFunctions = {};
// token: 'M'
// padded: ['MM', 2]
// ordinal: 'Mo'
// callback: function () { this.month() + 1 }
function addFormatToken(token, padded, ordinal, callback) {
var func = callback;
"string" == typeof callback && (func = function() {
return this[callback]();
}), token && (formatTokenFunctions[token] = func), padded && (formatTokenFunctions[padded[0]] = function() {
return zeroFill(func.apply(this, arguments), padded[1], padded[2]);
}), ordinal && (formatTokenFunctions[ordinal] = function() {
return this.localeData().ordinal(func.apply(this, arguments), token);
});
}
// format date using native date object
function formatMoment(m, format) {
return m.isValid() ? (formatFunctions[format = expandFormat(format, m.localeData())] = formatFunctions[format] || function(format) {
var input, i, length, array = format.match(formattingTokens);
for(i = 0, length = array.length; i < length; i++)formatTokenFunctions[array[i]] ? array[i] = formatTokenFunctions[array[i]] : array[i] = (input = array[i]).match(/\[[\s\S]/) ? input.replace(/^\[|\]$/g, "") : input.replace(/\\/g, "");
return function(mom) {
var i, output = "";
for(i = 0; i < length; i++)output += isFunction(array[i]) ? array[i].call(mom, format) : array[i];
return output;
};
}(format), formatFunctions[format](m)) : m.localeData().invalidDate();
}
function expandFormat(format, locale) {
var i = 5;
function replaceLongDateFormatTokens(input) {
return locale.longDateFormat(input) || input;
}
for(localFormattingTokens.lastIndex = 0; i >= 0 && localFormattingTokens.test(format);)format = format.replace(localFormattingTokens, replaceLongDateFormatTokens), localFormattingTokens.lastIndex = 0, i -= 1;
return format;
}
var aliases = {};
function addUnitAlias(unit, shorthand) {
var lowerCase = unit.toLowerCase();
aliases[lowerCase] = aliases[lowerCase + "s"] = aliases[shorthand] = unit;
}
function normalizeUnits(units) {
return "string" == typeof units ? aliases[units] || aliases[units.toLowerCase()] : void 0;
}
function normalizeObjectUnits(inputObject) {
var normalizedProp, prop, normalizedInput = {};
for(prop in inputObject)hasOwnProp(inputObject, prop) && (normalizedProp = normalizeUnits(prop)) && (normalizedInput[normalizedProp] = inputObject[prop]);
return normalizedInput;
}
var priorities = {};
function isLeapYear(year) {
return year % 4 == 0 && year % 100 != 0 || year % 400 == 0;
}
function absFloor(number) {
return number < 0 ? Math.ceil(number) || 0 : Math.floor(number);
}
function toInt(argumentForCoercion) {
var coercedNumber = +argumentForCoercion, value = 0;
return 0 !== coercedNumber && isFinite(coercedNumber) && (value = absFloor(coercedNumber)), value;
}
function makeGetSet(unit, keepTime) {
return function(value) {
return null != value ? (set$1(this, unit, value), hooks.updateOffset(this, keepTime), this) : get(this, unit);
};
}
function get(mom, unit) {
return mom.isValid() ? mom._d["get" + (mom._isUTC ? "UTC" : "") + unit]() : NaN;
}
function set$1(mom, unit, value) {
mom.isValid() && !isNaN(value) && ("FullYear" === unit && isLeapYear(mom.year()) && 1 === mom.month() && 29 === mom.date() ? (value = toInt(value), mom._d["set" + (mom._isUTC ? "UTC" : "") + unit](value, mom.month(), daysInMonth(value, mom.month()))) : mom._d["set" + (mom._isUTC ? "UTC" : "") + unit](value));
}
var hookCallback, some, keys, regexes, match1 = /\d/, match2 = /\d\d/, match3 = /\d{3}/, match4 = /\d{4}/, match6 = /[+-]?\d{6}/, match1to2 = /\d\d?/, match3to4 = /\d\d\d\d?/, match5to6 = /\d\d\d\d\d\d?/, match1to3 = /\d{1,3}/, match1to4 = /\d{1,4}/, match1to6 = /[+-]?\d{1,6}/, matchUnsigned = /\d+/, matchSigned = /[+-]?\d+/, matchOffset = /Z|[+-]\d\d:?\d\d/gi, matchShortOffset = /Z|[+-]\d\d(?::?\d\d)?/gi, // any word (or two) characters or numbers including two/three word month in arabic.
// includes scottish gaelic two word and hyphenated months
matchWord = /[0-9]{0,256}['a-z\u00A0-\u05FF\u0700-\uD7FF\uF900-\uFDCF\uFDF0-\uFF07\uFF10-\uFFEF]{1,256}|[\u0600-\u06FF\/]{1,256}(\s*?[\u0600-\u06FF]{1,256}){1,2}/i;
function addRegexToken(token, regex, strictRegex) {
regexes[token] = isFunction(regex) ? regex : function(isStrict, localeData) {
return isStrict && strictRegex ? strictRegex : regex;
};
}
function regexEscape(s) {
return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, "\\$&");
}
regexes = {};
var tokens = {};
function addParseToken(token, callback) {
var i, func = callback;
for("string" == typeof token && (token = [
token
]), isNumber(callback) && (func = function(input, array) {
array[callback] = toInt(input);
}), i = 0; i < token.length; i++)tokens[token[i]] = func;
}
function addWeekParseToken(token, callback) {
addParseToken(token, function(input, array, config, token) {
config._w = config._w || {}, callback(input, config._w, config, token);
});
}
function daysInMonth(year, month) {
if (isNaN(year) || isNaN(month)) return NaN;
var modMonth = (month % 12 + 12) % 12;
return year += (month - modMonth) / 12, 1 === modMonth ? isLeapYear(year) ? 29 : 28 : 31 - modMonth % 7 % 2;
}
indexOf = Array.prototype.indexOf ? Array.prototype.indexOf : function(o) {
// I know
var i;
for(i = 0; i < this.length; ++i)if (this[i] === o) return i;
return -1;
}, // FORMATTING
addFormatToken("M", [
"MM",
2
], "Mo", function() {
return this.month() + 1;
}), addFormatToken("MMM", 0, 0, function(format) {
return this.localeData().monthsShort(this, format);
}), addFormatToken("MMMM", 0, 0, function(format) {
return this.localeData().months(this, format);
}), // ALIASES
addUnitAlias("month", "M"), priorities.month = 8, // PARSING
addRegexToken("M", match1to2), addRegexToken("MM", match1to2, match2), addRegexToken("MMM", function(isStrict, locale) {
return locale.monthsShortRegex(isStrict);
}), addRegexToken("MMMM", function(isStrict, locale) {
return locale.monthsRegex(isStrict);
}), addParseToken([
"M",
"MM"
], function(input, array) {
array[1] = toInt(input) - 1;
}), addParseToken([
"MMM",
"MMMM"
], function(input, array, config, token) {
var month = config._locale.monthsParse(input, token, config._strict);
// if we didn't find a month name, mark the date as invalid.
null != month ? array[1] = month : getParsingFlags(config).invalidMonth = input;
});
// LOCALES
var defaultLocaleMonthsShort = "Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec".split("_"), MONTHS_IN_FORMAT = /D[oD]?(\[[^\[\]]*\]|\s)+MMMM?/;
function handleStrictParse(monthName, format, strict) {
var i, ii, mom, llc = monthName.toLocaleLowerCase();
if (!this._monthsParse) for(i = 0, // this is not used
this._monthsParse = [], this._longMonthsParse = [], this._shortMonthsParse = []; i < 12; ++i)mom = createUTC([
2000,
i
]), this._shortMonthsParse[i] = this.monthsShort(mom, "").toLocaleLowerCase(), this._longMonthsParse[i] = this.months(mom, "").toLocaleLowerCase();
return strict ? "MMM" === format ? -1 !== (ii = indexOf.call(this._shortMonthsParse, llc)) ? ii : null : -1 !== (ii = indexOf.call(this._longMonthsParse, llc)) ? ii : null : "MMM" === format ? -1 !== (ii = indexOf.call(this._shortMonthsParse, llc)) ? ii : -1 !== (ii = indexOf.call(this._longMonthsParse, llc)) ? ii : null : -1 !== (ii = indexOf.call(this._longMonthsParse, llc)) ? ii : -1 !== (ii = indexOf.call(this._shortMonthsParse, llc)) ? ii : null;
}
// MOMENTS
function setMonth(mom, value) {
var dayOfMonth;
if (!mom.isValid()) // No op
return mom;
if ("string" == typeof value) {
if (/^\d+$/.test(value)) value = toInt(value);
else // TODO: Another silent failure?
if (!isNumber(value = mom.localeData().monthsParse(value))) return mom;
}
return dayOfMonth = Math.min(mom.date(), daysInMonth(mom.year(), value)), mom._d["set" + (mom._isUTC ? "UTC" : "") + "Month"](value, dayOfMonth), mom;
}
function getSetMonth(value) {
return null != value ? (setMonth(this, value), hooks.updateOffset(this, !0), this) : get(this, "Month");
}
function computeMonthsParse() {
function cmpLenRev(a, b) {
return b.length - a.length;
}
var i, mom, shortPieces = [], longPieces = [], mixedPieces = [];
for(i = 0; i < 12; i++)// make the regex if we don't have it already
mom = createUTC([
2000,
i
]), shortPieces.push(this.monthsShort(mom, "")), longPieces.push(this.months(mom, "")), mixedPieces.push(this.months(mom, "")), mixedPieces.push(this.monthsShort(mom, ""));
for(// Sorting makes sure if one month (or abbr) is a prefix of another it
// will match the longer piece.
shortPieces.sort(cmpLenRev), longPieces.sort(cmpLenRev), mixedPieces.sort(cmpLenRev), i = 0; i < 12; i++)shortPieces[i] = regexEscape(shortPieces[i]), longPieces[i] = regexEscape(longPieces[i]);
for(i = 0; i < 24; i++)mixedPieces[i] = regexEscape(mixedPieces[i]);
this._monthsRegex = RegExp("^(" + mixedPieces.join("|") + ")", "i"), this._monthsShortRegex = this._monthsRegex, this._monthsStrictRegex = RegExp("^(" + longPieces.join("|") + ")", "i"), this._monthsShortStrictRegex = RegExp("^(" + shortPieces.join("|") + ")", "i");
}
// HELPERS
function daysInYear(year) {
return isLeapYear(year) ? 366 : 365;
}
// FORMATTING
addFormatToken("Y", 0, 0, function() {
var y = this.year();
return y <= 9999 ? zeroFill(y, 4) : "+" + y;
}), addFormatToken(0, [
"YY",
2
], 0, function() {
return this.year() % 100;
}), addFormatToken(0, [
"YYYY",
4
], 0, "year"), addFormatToken(0, [
"YYYYY",
5
], 0, "year"), addFormatToken(0, [
"YYYYYY",
6,
!0
], 0, "year"), // ALIASES
addUnitAlias("year", "y"), priorities.year = 1, // PARSING
addRegexToken("Y", matchSigned), addRegexToken("YY", match1to2, match2), addRegexToken("YYYY", match1to4, match4), addRegexToken("YYYYY", match1to6, match6), addRegexToken("YYYYYY", match1to6, match6), addParseToken([
"YYYYY",
"YYYYYY"
], 0), addParseToken("YYYY", function(input, array) {
array[0] = 2 === input.length ? hooks.parseTwoDigitYear(input) : toInt(input);
}), addParseToken("YY", function(input, array) {
array[0] = hooks.parseTwoDigitYear(input);
}), addParseToken("Y", function(input, array) {
array[0] = parseInt(input, 10);
}), // HOOKS
hooks.parseTwoDigitYear = function(input) {
return toInt(input) + (toInt(input) > 68 ? 1900 : 2000);
};
// MOMENTS
var getSetYear = makeGetSet("FullYear", !0);
function createDate(y, m, d, h, M, s, ms) {
// can't just apply() to create a date:
// https://stackoverflow.com/q/181348
var date;
return y < 100 && y >= 0 ? isFinite(// preserve leap years using a full 400 year cycle, then reset
(date = new Date(y + 400, m, d, h, M, s, ms)).getFullYear()) && date.setFullYear(y) : date = new Date(y, m, d, h, M, s, ms), date;
}
function createUTCDate(y) {
var date, args;
return y < 100 && y >= 0 ? (args = Array.prototype.slice.call(arguments), // preserve leap years using a full 400 year cycle, then reset
args[0] = y + 400, isFinite((date = new Date(Date.UTC.apply(null, args))).getUTCFullYear()) && date.setUTCFullYear(y)) : date = new Date(Date.UTC.apply(null, arguments)), date;
}
// start-of-first-week - start-of-year
function firstWeekOffset(year, dow, doy) {
var fwd = 7 + dow - doy;
return -((7 + createUTCDate(year, 0, fwd).getUTCDay() - dow) % 7) + fwd - 1;
}
// https://en.wikipedia.org/wiki/ISO_week_date#Calculating_a_date_given_the_year.2C_week_number_and_weekday
function dayOfYearFromWeeks(year, week, weekday, dow, doy) {
var resYear, resDayOfYear, dayOfYear = 1 + 7 * (week - 1) + (7 + weekday - dow) % 7 + firstWeekOffset(year, dow, doy);
return dayOfYear <= 0 ? resDayOfYear = daysInYear(resYear = year - 1) + dayOfYear : dayOfYear > daysInYear(year) ? (resYear = year + 1, resDayOfYear = dayOfYear - daysInYear(year)) : (resYear = year, resDayOfYear = dayOfYear), {
year: resYear,
dayOfYear: resDayOfYear
};
}
function weekOfYear(mom, dow, doy) {
var resWeek, resYear, weekOffset = firstWeekOffset(mom.year(), dow, doy), week = Math.floor((mom.dayOfYear() - weekOffset - 1) / 7) + 1;
return week < 1 ? resWeek = week + weeksInYear(resYear = mom.year() - 1, dow, doy) : week > weeksInYear(mom.year(), dow, doy) ? (resWeek = week - weeksInYear(mom.year(), dow, doy), resYear = mom.year() + 1) : (resYear = mom.year(), resWeek = week), {
week: resWeek,
year: resYear
};
}
function weeksInYear(year, dow, doy) {
var weekOffset = firstWeekOffset(year, dow, doy), weekOffsetNext = firstWeekOffset(year + 1, dow, doy);
return (daysInYear(year) - weekOffset + weekOffsetNext) / 7;
}
// LOCALES
function shiftWeekdays(ws, n) {
return ws.slice(n, 7).concat(ws.slice(0, n));
}
// FORMATTING
addFormatToken("w", [
"ww",
2
], "wo", "week"), addFormatToken("W", [
"WW",
2
], "Wo", "isoWeek"), // ALIASES
addUnitAlias("week", "w"), addUnitAlias("isoWeek", "W"), priorities.week = 5, priorities.isoWeek = 5, // PARSING
addRegexToken("w", match1to2), addRegexToken("ww", match1to2, match2), addRegexToken("W", match1to2), addRegexToken("WW", match1to2, match2), addWeekParseToken([
"w",
"ww",
"W",
"WW"
], function(input, week, config, token) {
week[token.substr(0, 1)] = toInt(input);
}), // FORMATTING
addFormatToken("d", 0, "do", "day"), addFormatToken("dd", 0, 0, function(format) {
return this.localeData().weekdaysMin(this, format);
}), addFormatToken("ddd", 0, 0, function(format) {
return this.localeData().weekdaysShort(this, format);
}), addFormatToken("dddd", 0, 0, function(format) {
return this.localeData().weekdays(this, format);
}), addFormatToken("e", 0, 0, "weekday"), addFormatToken("E", 0, 0, "isoWeekday"), // ALIASES
addUnitAlias("day", "d"), addUnitAlias("weekday", "e"), addUnitAlias("isoWeekday", "E"), priorities.day = 11, priorities.weekday = 11, priorities.isoWeekday = 11, // PARSING
addRegexToken("d", match1to2), addRegexToken("e", match1to2), addRegexToken("E", match1to2), addRegexToken("dd", function(isStrict, locale) {
return locale.weekdaysMinRegex(isStrict);
}), addRegexToken("ddd", function(isStrict, locale) {
return locale.weekdaysShortRegex(isStrict);
}), addRegexToken("dddd", function(isStrict, locale) {
return locale.weekdaysRegex(isStrict);
}), addWeekParseToken([
"dd",
"ddd",
"dddd"
], function(input, week, config, token) {
var weekday = config._locale.weekdaysParse(input, token, config._strict);
// if we didn't get a weekday name, mark the date as invalid
null != weekday ? week.d = weekday : getParsingFlags(config).invalidWeekday = input;
}), addWeekParseToken([
"d",
"e",
"E"
], function(input, week, config, token) {
week[token] = toInt(input);
});
var defaultLocaleWeekdaysShort = "Sun_Mon_Tue_Wed_Thu_Fri_Sat".split("_");
function handleStrictParse$1(weekdayName, format, strict) {
var i, ii, mom, llc = weekdayName.toLocaleLowerCase();
if (!this._weekdaysParse) for(i = 0, this._weekdaysParse = [], this._shortWeekdaysParse = [], this._minWeekdaysParse = []; i < 7; ++i)mom = createUTC([
2000,
1
]).day(i), this._minWeekdaysParse[i] = this.weekdaysMin(mom, "").toLocaleLowerCase(), this._shortWeekdaysParse[i] = this.weekdaysShort(mom, "").toLocaleLowerCase(), this._weekdaysParse[i] = this.weekdays(mom, "").toLocaleLowerCase();
return strict ? "dddd" === format ? -1 !== (ii = indexOf.call(this._weekdaysParse, llc)) ? ii : null : "ddd" === format ? -1 !== (ii = indexOf.call(this._shortWeekdaysParse, llc)) ? ii : null : -1 !== (ii = indexOf.call(this._minWeekdaysParse, llc)) ? ii : null : "dddd" === format ? -1 !== (ii = indexOf.call(this._weekdaysParse, llc)) || -1 !== (ii = indexOf.call(this._shortWeekdaysParse, llc)) ? ii : -1 !== (ii = indexOf.call(this._minWeekdaysParse, llc)) ? ii : null : "ddd" === format ? -1 !== (ii = indexOf.call(this._shortWeekdaysParse, llc)) || -1 !== (ii = indexOf.call(this._weekdaysParse, llc)) ? ii : -1 !== (ii = indexOf.call(this._minWeekdaysParse, llc)) ? ii : null : -1 !== (ii = indexOf.call(this._minWeekdaysParse, llc)) || -1 !== (ii = indexOf.call(this._weekdaysParse, llc)) ? ii : -1 !== (ii = indexOf.call(this._shortWeekdaysParse, llc)) ? ii : null;
}
function computeWeekdaysParse() {
function cmpLenRev(a, b) {
return b.length - a.length;
}
var i, mom, minp, shortp, longp, minPieces = [], shortPieces = [], longPieces = [], mixedPieces = [];
for(i = 0; i < 7; i++)// make the regex if we don't have it already
mom = createUTC([
2000,
1
]).day(i), minp = regexEscape(this.weekdaysMin(mom, "")), shortp = regexEscape(this.weekdaysShort(mom, "")), longp = regexEscape(this.weekdays(mom, "")), minPieces.push(minp), shortPieces.push(shortp), longPieces.push(longp), mixedPieces.push(minp), mixedPieces.push(shortp), mixedPieces.push(longp);
// Sorting makes sure if one weekday (or abbr) is a prefix of another it
// will match the longer piece.
minPieces.sort(cmpLenRev), shortPieces.sort(cmpLenRev), longPieces.sort(cmpLenRev), mixedPieces.sort(cmpLenRev), this._weekdaysRegex = RegExp("^(" + mixedPieces.join("|") + ")", "i"), this._weekdaysShortRegex = this._weekdaysRegex, this._weekdaysMinRegex = this._weekdaysRegex, this._weekdaysStrictRegex = RegExp("^(" + longPieces.join("|") + ")", "i"), this._weekdaysShortStrictRegex = RegExp("^(" + shortPieces.join("|") + ")", "i"), this._weekdaysMinStrictRegex = RegExp("^(" + minPieces.join("|") + ")", "i");
}
// FORMATTING
function hFormat() {
return this.hours() % 12 || 12;
}
function meridiem(token, lowercase) {
addFormatToken(token, 0, 0, function() {
return this.localeData().meridiem(this.hours(), this.minutes(), lowercase);
});
}
// PARSING
function matchMeridiem(isStrict, locale) {
return locale._meridiemParse;
}
addFormatToken("H", [
"HH",
2
], 0, "hour"), addFormatToken("h", [
"hh",
2
], 0, hFormat), addFormatToken("k", [
"kk",
2
], 0, function() {
return this.hours() || 24;
}), addFormatToken("hmm", 0, 0, function() {
return "" + hFormat.apply(this) + zeroFill(this.minutes(), 2);
}), addFormatToken("hmmss", 0, 0, function() {
return "" + hFormat.apply(this) + zeroFill(this.minutes(), 2) + zeroFill(this.seconds(), 2);
}), addFormatToken("Hmm", 0, 0, function() {
return "" + this.hours() + zeroFill(this.minutes(), 2);
}), addFormatToken("Hmmss", 0, 0, function() {
return "" + this.hours() + zeroFill(this.minutes(), 2) + zeroFill(this.seconds(), 2);
}), meridiem("a", !0), meridiem("A", !1), // ALIASES
addUnitAlias("hour", "h"), priorities.hour = 13, addRegexToken("a", matchMeridiem), addRegexToken("A", matchMeridiem), addRegexToken("H", match1to2), addRegexToken("h", match1to2), addRegexToken("k", match1to2), addRegexToken("HH", match1to2, match2), addRegexToken("hh", match1to2, match2), addRegexToken("kk", match1to2, match2), addRegexToken("hmm", match3to4), addRegexToken("hmmss", match5to6), addRegexToken("Hmm", match3to4), addRegexToken("Hmmss", match5to6), addParseToken([
"H",
"HH"
], 3), addParseToken([
"k",
"kk"
], function(input, array, config) {
var kInput = toInt(input);
array[3] = 24 === kInput ? 0 : kInput;
}), addParseToken([
"a",
"A"
], function(input, array, config) {
config._isPm = config._locale.isPM(input), config._meridiem = input;
}), addParseToken([
"h",
"hh"
], function(input, array, config) {
array[3] = toInt(input), getParsingFlags(config).bigHour = !0;
}), addParseToken("hmm", function(input, array, config) {
var pos = input.length - 2;
array[3] = toInt(input.substr(0, pos)), array[4] = toInt(input.substr(pos)), getParsingFlags(config).bigHour = !0;
}), addParseToken("hmmss", function(input, array, config) {
var pos1 = input.length - 4, pos2 = input.length - 2;
array[3] = toInt(input.substr(0, pos1)), array[4] = toInt(input.substr(pos1, 2)), array[5] = toInt(input.substr(pos2)), getParsingFlags(config).bigHour = !0;
}), addParseToken("Hmm", function(input, array, config) {
var pos = input.length - 2;
array[3] = toInt(input.substr(0, pos)), array[4] = toInt(input.substr(pos));
}), addParseToken("Hmmss", function(input, array, config) {
var pos1 = input.length - 4, pos2 = input.length - 2;
array[3] = toInt(input.substr(0, pos1)), array[4] = toInt(input.substr(pos1, 2)), array[5] = toInt(input.substr(pos2));
});
var indexOf, globalLocale, // Setting the hour should keep the time, because the user explicitly
// specified which hour they want. So trying to maintain the same hour (in
// a new timezone) makes sense. Adding/subtracting hours does not follow
// this rule.
getSetHour = makeGetSet("Hours", !0), baseConfig = {
calendar: {
sameDay: "[Today at] LT",
nextDay: "[Tomorrow at] LT",
nextWeek: "dddd [at] LT",
lastDay: "[Yesterday at] LT",
lastWeek: "[Last] dddd [at] LT",
sameElse: "L"
},
longDateFormat: {
LTS: "h:mm:ss A",
LT: "h:mm A",
L: "MM/DD/YYYY",
LL: "MMMM D, YYYY",
LLL: "MMMM D, YYYY h:mm A",
LLLL: "dddd, MMMM D, YYYY h:mm A"
},
invalidDate: "Invalid date",
ordinal: "%d",
dayOfMonthOrdinalParse: /\d{1,2}/,
relativeTime: {
future: "in %s",
past: "%s ago",
s: "a few seconds",
ss: "%d seconds",
m: "a minute",
mm: "%d minutes",
h: "an hour",
hh: "%d hours",
d: "a day",
dd: "%d days",
w: "a week",
ww: "%d weeks",
M: "a month",
MM: "%d months",
y: "a year",
yy: "%d years"
},
months: "January_February_March_April_May_June_July_August_September_October_November_December".split("_"),
monthsShort: defaultLocaleMonthsShort,
week: {
dow: 0,
doy: 6
},
weekdays: "Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_"),
weekdaysMin: "Su_Mo_Tu_We_Th_Fr_Sa".split("_"),
weekdaysShort: defaultLocaleWeekdaysShort,
meridiemParse: /[ap]\.?m?\.?/i
}, locales = {}, localeFamilies = {};
function normalizeLocale(key) {
return key ? key.toLowerCase().replace("_", "-") : key;
}
function loadLocale(name) {
var oldLocale = null;
// TODO: Find a better way to register and load all the locales in Node
if (void 0 === locales[name] && "undefined" != typeof module && module && module.exports) try {
oldLocale = globalLocale._abbr, require("./locale/" + name), getSetGlobalLocale(oldLocale);
} catch (e) {
// mark as not found to avoid repeating expensive file require call causing high CPU
// when trying to find en-US, en_US, en-us for every format call
locales[name] = null; // null means not found
}
return locales[name];
}
// This function will load locale and then set the global locale. If
// no arguments are passed in, it will simply return the current global
// locale key.
function getSetGlobalLocale(key, values) {
var data;
return key && ((data = isUndefined(values) ? getLocale(key) : defineLocale(key, values)) ? // moment.duration._locale = moment._locale = data;
globalLocale = data : "undefined" != typeof console && console.warn && //warn user if arguments are passed but the locale could not be set
console.warn("Locale " + key + " not found. Did you forget to load it?")), globalLocale._abbr;
}
function defineLocale(name, config) {
if (null === config) return(// useful for testing
delete locales[name], null);
var locale, parentConfig = baseConfig;
if (config.abbr = name, null != locales[name]) deprecateSimple("defineLocaleOverride", "use moment.updateLocale(localeName, config) to change an existing locale. moment.defineLocale(localeName, config) should only be used for creating a new locale See http://momentjs.com/guides/#/warnings/define-locale/ for more info."), parentConfig = locales[name]._config;
else if (null != config.parentLocale) {
if (null != locales[config.parentLocale]) parentConfig = locales[config.parentLocale]._config;
else {
if (null == (locale = loadLocale(config.parentLocale))) return localeFamilies[config.parentLocale] || (localeFamilies[config.parentLocale] = []), localeFamilies[config.parentLocale].push({
name: name,
config: config
}), null;
parentConfig = locale._config;
}
}
return locales[name] = new Locale(mergeConfigs(parentConfig, config)), localeFamilies[name] && localeFamilies[name].forEach(function(x) {
defineLocale(x.name, x.config);
}), // backwards compat for now: also set the locale
// make sure we set the locale AFTER all child locales have been
// created, so we won't end up with the child locale set.
getSetGlobalLocale(name), locales[name];
}
// returns locale data
function getLocale(key) {
var locale;
if (key && key._locale && key._locale._abbr && (key = key._locale._abbr), !key) return globalLocale;
if (!isArray(key)) {
if (//short-circuit everything else
locale = loadLocale(key)) return locale;
key = [
key
];
}
return(// pick the locale from the array
// try ['en-au', 'en-gb'] as 'en-au', 'en-gb', 'en', as in move through the list trying each
// substring from most specific to least, but move to the next array item if it's a more specific variant than the current root
function(names) {
for(var j, next, locale, split, i = 0; i < names.length;){
for(j = (split = normalizeLocale(names[i]).split("-")).length, next = (next = normalizeLocale(names[i + 1])) ? next.split("-") : null; j > 0;){
if (locale = loadLocale(split.slice(0, j).join("-"))) return locale;
if (next && next.length >= j && function(arr1, arr2) {
var i, minl = Math.min(arr1.length, arr2.length);
for(i = 0; i < minl; i += 1)if (arr1[i] !== arr2[i]) return i;
return minl;
}(split, next) >= j - 1) break;
j--;
}
i++;
}
return globalLocale;
}(key));
}
function checkOverflow(m) {
var overflow, a = m._a;
return a && -2 === getParsingFlags(m).overflow && (overflow = a[1] < 0 || a[1] > 11 ? 1 : a[2] < 1 || a[2] > daysInMonth(a[0], a[1]) ? 2 : a[3] < 0 || a[3] > 24 || 24 === a[3] && (0 !== a[4] || 0 !== a[5] || 0 !== a[6]) ? 3 : a[4] < 0 || a[4] > 59 ? 4 : a[5] < 0 || a[5] > 59 ? 5 : a[6] < 0 || a[6] > 999 ? 6 : -1, getParsingFlags(m)._overflowDayOfYear && (overflow < 0 || overflow > 2) && (overflow = 2), getParsingFlags(m)._overflowWeeks && -1 === overflow && (overflow = 7), getParsingFlags(m)._overflowWeekday && -1 === overflow && (overflow = 8), getParsingFlags(m).overflow = overflow), m;
}
// iso 8601 regex
// 0000-00-00 0000-W00 or 0000-W00-0 + T + 00 or 00:00 or 00:00:00 or 00:00:00.000 + +00:00 or +0000 or +00)
var extendedIsoRegex = /^\s*((?:[+-]\d{6}|\d{4})-(?:\d\d-\d\d|W\d\d-\d|W\d\d|\d\d\d|\d\d))(?:(T| )(\d\d(?::\d\d(?::\d\d(?:[.,]\d+)?)?)?)([+-]\d\d(?::?\d\d)?|\s*Z)?)?$/, basicIsoRegex = /^\s*((?:[+-]\d{6}|\d{4})(?:\d\d\d\d|W\d\d\d|W\d\d|\d\d\d|\d\d|))(?:(T| )(\d\d(?:\d\d(?:\d\d(?:[.,]\d+)?)?)?)([+-]\d\d(?::?\d\d)?|\s*Z)?)?$/, tzRegex = /Z|[+-]\d\d(?::?\d\d)?/, isoDates = [
[
"YYYYYY-MM-DD",
/[+-]\d{6}-\d\d-\d\d/
],
[
"YYYY-MM-DD",
/\d{4}-\d\d-\d\d/
],
[
"GGGG-[W]WW-E",
/\d{4}-W\d\d-\d/
],
[
"GGGG-[W]WW",
/\d{4}-W\d\d/,
!1
],
[
"YYYY-DDD",
/\d{4}-\d{3}/
],
[
"YYYY-MM",
/\d{4}-\d\d/,
!1
],
[
"YYYYYYMMDD",
/[+-]\d{10}/
],
[
"YYYYMMDD",
/\d{8}/
],
[
"GGGG[W]WWE",
/\d{4}W\d{3}/
],
[
"GGGG[W]WW",
/\d{4}W\d{2}/,
!1
],
[
"YYYYDDD",
/\d{7}/
],
[
"YYYYMM",
/\d{6}/,
!1
],
[
"YYYY",
/\d{4}/,
!1
]
], // iso time formats and regexes
isoTimes = [
[
"HH:mm:ss.SSSS",
/\d\d:\d\d:\d\d\.\d+/
],
[
"HH:mm:ss,SSSS",
/\d\d:\d\d:\d\d,\d+/
],
[
"HH:mm:ss",
/\d\d:\d\d:\d\d/
],
[
"HH:mm",
/\d\d:\d\d/
],
[
"HHmmss.SSSS",
/\d\d\d\d\d\d\.\d+/
],
[
"HHmmss,SSSS",
/\d\d\d\d\d\d,\d+/
],
[
"HHmmss",
/\d\d\d\d\d\d/
],
[
"HHmm",
/\d\d\d\d/
],
[
"HH",
/\d\d/
]
], aspNetJsonRegex = /^\/?Date\((-?\d+)/i, // RFC 2822 regex: For details see https://tools.ietf.org/html/rfc2822#section-3.3
rfc2822 = /^(?:(Mon|Tue|Wed|Thu|Fri|Sat|Sun),?\s)?(\d{1,2})\s(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s(\d{2,4})\s(\d\d):(\d\d)(?::(\d\d))?\s(?:(UT|GMT|[ECMP][SD]T)|([Zz])|([+-]\d{4}))$/, obsOffsets = {
UT: 0,
GMT: 0,
EDT: -240,
EST: -300,
CDT: -300,
CST: -360,
MDT: -360,
MST: -420,
PDT: -420,
PST: -480
};
// date from iso format
function configFromISO(config) {
var i, l, allowTime, dateFormat, timeFormat, tzFormat, string = config._i, match = extendedIsoRegex.exec(string) || basicIsoRegex.exec(string);
if (match) {
for(i = 0, getParsingFlags(config).iso = !0, l = isoDates.length; i < l; i++)if (isoDates[i][1].exec(match[1])) {
dateFormat = isoDates[i][0], allowTime = !1 !== isoDates[i][2];
break;
}
if (null == dateFormat) {
config._isValid = !1;
return;
}
if (match[3]) {
for(i = 0, l = isoTimes.length; i < l; i++)if (isoTimes[i][1].exec(match[3])) {
// match[2] should be 'T' or space
timeFormat = (match[2] || " ") + isoTimes[i][0];
break;
}
if (null == timeFormat) {
config._isValid = !1;
return;
}
}
if (!allowTime && null != timeFormat) {
config._isValid = !1;
return;
}
if (match[4]) {
if (tzRegex.exec(match[4])) tzFormat = "Z";
else {
config._isValid = !1;
return;
}
}
config._f = dateFormat + (timeFormat || "") + (tzFormat || ""), configFromStringAndFormat(config);
} else config._isValid = !1;
}
// date and time from ref 2822 format
function configFromRFC2822(config) {
var year, yearStr, monthStr, dayStr, hourStr, minuteStr, secondStr, result, weekdayStr, match = rfc2822.exec(config._i.replace(/\([^)]*\)|[\n\t]/g, " ").replace(/(\s\s+)/g, " ").replace(/^\s\s*/, "").replace(/\s\s*$/, ""));
if (match) {
if (yearStr = match[4], monthStr = match[3], dayStr = match[2], hourStr = match[5], minuteStr = match[6], secondStr = match[7], result = [
(year = parseInt(yearStr, 10)) <= 49 ? 2000 + year : year <= 999 ? 1900 + year : year,
defaultLocaleMonthsShort.indexOf(monthStr),
parseInt(dayStr, 10),
parseInt(hourStr, 10),
parseInt(minuteStr, 10)
], secondStr && result.push(parseInt(secondStr, 10)), (weekdayStr = match[1]) && defaultLocaleWeekdaysShort.indexOf(weekdayStr) !== new Date(result[0], result[1], result[2]).getDay() && (getParsingFlags(config).weekdayMismatch = !0, config._isValid = !1, 1)) return;
config._a = result, config._tzm = function(obsOffset, militaryOffset, numOffset) {
if (obsOffset) return obsOffsets[obsOffset];
if (militaryOffset) // the only allowed military tz is Z
return 0;
var hm = parseInt(numOffset, 10), m = hm % 100;
return (hm - m) / 100 * 60 + m;
}(match[8], match[9], match[10]), config._d = createUTCDate.apply(null, config._a), config._d.setUTCMinutes(config._d.getUTCMinutes() - config._tzm), getParsingFlags(config).rfc2822 = !0;
} else config._isValid = !1;
}
// Pick the first defined of two or three arguments.
function defaults(a, b, c) {
return null != a ? a : null != b ? b : c;
}
// convert an array to a date.
// the array should mirror the parameters below
// note: all values past the year are optional and will default to the lowest possible value.
// [year, month, day , hour, minute, second, millisecond]
function configFromArray(config) {
var w, weekYear, week, weekday, dow, doy, temp, weekdayOverflow, curWeek, nowValue, i, date, currentDate, expectedWeekday, yearToUse, input = [];
if (!config._d) {
// Default to current date.
// * if no year, month, day of month are given, default to today
// * if day of month is given, default month and year
// * if month is given, default only year
// * if year is given, don't default anything
for(nowValue = new Date(hooks.now()), currentDate = config._useUTC ? [
nowValue.getUTCFullYear(),
nowValue.getUTCMonth(),
nowValue.getUTCDate()
] : [
nowValue.getFullYear(),
nowValue.getMonth(),
nowValue.getDate()
], config._w && null == config._a[2] && null == config._a[1] && (null != (w = config._w).GG || null != w.W || null != w.E ? (dow = 1, doy = 4, // TODO: We need to take the current isoWeekYear, but that depends on
// how we interpret now (local, utc, fixed offset). So create
// a now version of current config (take local/utc/offset flags, and
// create now).
weekYear = defaults(w.GG, config._a[0], weekOfYear(createLocal(), 1, 4).year), week = defaults(w.W, 1), ((weekday = defaults(w.E, 1)) < 1 || weekday > 7) && (weekdayOverflow = !0)) : (dow = config._locale._week.dow, doy = config._locale._week.doy, curWeek = weekOfYear(createLocal(), dow, doy), weekYear = defaults(w.gg, config._a[0], curWeek.year), // Default to current week.
week = defaults(w.w, curWeek.week), null != w.d ? (// weekday -- low day numbers are considered next week
(weekday = w.d) < 0 || weekday > 6) && (weekdayOverflow = !0) : null != w.e ? (// local weekday -- counting starts from beginning of week
weekday = w.e + dow, (w.e < 0 || w.e > 6) && (weekdayOverflow = !0)) : // default to beginning of week
weekday = dow), week < 1 || week > weeksInYear(weekYear, dow, doy) ? getParsingFlags(config)._overflowWeeks = !0 : null != weekdayOverflow ? getParsingFlags(config)._overflowWeekday = !0 : (temp = dayOfYearFromWeeks(weekYear, week, weekday, dow, doy), config._a[0] = temp.year, config._dayOfYear = temp.dayOfYear)), null != config._dayOfYear && (yearToUse = defaults(config._a[0], currentDate[0]), (config._dayOfYear > daysInYear(yearToUse) || 0 === config._dayOfYear) && (getParsingFlags(config)._overflowDayOfYear = !0), date = createUTCDate(yearToUse, 0, config._dayOfYear), config._a[1] = date.getUTCMonth(), config._a[2] = date.getUTCDate()), i = 0; i < 3 && null == config._a[i]; ++i)config._a[i] = input[i] = currentDate[i];
// Zero out whatever was not defaulted, including time
for(; i < 7; i++)config._a[i] = input[i] = null == config._a[i] ? +(2 === i) : config._a[i];
24 === config._a[3] && 0 === config._a[4] && 0 === config._a[5] && 0 === config._a[6] && (config._nextDay = !0, config._a[3] = 0), config._d = (config._useUTC ? createUTCDate : createDate).apply(null, input), expectedWeekday = config._useUTC ? config._d.getUTCDay() : config._d.getDay(), null != config._tzm && config._d.setUTCMinutes(config._d.getUTCMinutes() - config._tzm), config._nextDay && (config._a[3] = 24), config._w && void 0 !== config._w.d && config._w.d !== expectedWeekday && (getParsingFlags(config).weekdayMismatch = !0);
}
}
// date from string and format string
function configFromStringAndFormat(config) {
// TODO: Move this to another part of the creation flow to prevent circular deps
if (config._f === hooks.ISO_8601) {
configFromISO(config);
return;
}
if (config._f === hooks.RFC_2822) {
configFromRFC2822(config);
return;
}
config._a = [], getParsingFlags(config).empty = !0;
// This array is used to make a Date, either with `new Date` or `Date.UTC`
var locale, hour, meridiem, isPm, i, parsedInput, tokens1, token, skipped, era, string = "" + config._i, stringLength = string.length, totalParsedInputLength = 0;
for(i = 0, tokens1 = expandFormat(config._f, config._locale).match(formattingTokens) || []; i < tokens1.length; i++)// don't parse if it's not a known token
(token = tokens1[i], (parsedInput = (string.match(hasOwnProp(regexes, token) ? regexes[token](config._strict, config._locale) : new RegExp(regexEscape(token.replace("\\", "").replace(/\\(\[)|\\(\])|\[([^\]\[]*)\]|\\(.)/g, function(matched, p1, p2, p3, p4) {
return p1 || p2 || p3 || p4;
})))) || [])[0]) && ((skipped = string.substr(0, string.indexOf(parsedInput))).length > 0 && getParsingFlags(config).unusedInput.push(skipped), string = string.slice(string.indexOf(parsedInput) + parsedInput.length), totalParsedInputLength += parsedInput.length), formatTokenFunctions[token]) ? (parsedInput ? getParsingFlags(config).empty = !1 : getParsingFlags(config).unusedTokens.push(token), null != parsedInput && hasOwnProp(tokens, token) && tokens[token](parsedInput, config._a, config, token)) : config._strict && !parsedInput && getParsingFlags(config).unusedTokens.push(token);
// add remaining unparsed input length to the string
getParsingFlags(config).charsLeftOver = stringLength - totalParsedInputLength, string.length > 0 && getParsingFlags(config).unusedInput.push(string), config._a[3] <= 12 && !0 === getParsingFlags(config).bigHour && config._a[3] > 0 && (getParsingFlags(config).bigHour = void 0), getParsingFlags(config).parsedDateParts = config._a.slice(0), getParsingFlags(config).meridiem = config._meridiem, // handle meridiem
config._a[3] = (locale = config._locale, hour = config._a[3], null == (meridiem = config._meridiem) ? hour : null != locale.meridiemHour ? locale.meridiemHour(hour, meridiem) : (null != locale.isPM && (// Fallback
(isPm = locale.isPM(meridiem)) && hour < 12 && (hour += 12), isPm || 12 !== hour || (hour = 0)), hour)), null !== // handle era
(era = getParsingFlags(config).era) && (config._a[0] = config._locale.erasConvertYear(era, config._a[0])), configFromArray(config), checkOverflow(config);
}
function prepareConfig(config) {
var input, input1 = config._i, format = config._f;
return (config._locale = config._locale || getLocale(config._l), null === input1 || void 0 === format && "" === input1) ? createInvalid({
nullInput: !0
}) : ("string" == typeof input1 && (config._i = input1 = config._locale.preparse(input1)), isMoment(input1)) ? new Moment(checkOverflow(input1)) : (isDate(input1) ? config._d = input1 : isArray(format) ? // date from string and array of format strings
function(config) {
var tempConfig, bestMoment, scoreToBeat, i, currentScore, validFormatFound, bestFormatIsValid = !1;
if (0 === config._f.length) {
getParsingFlags(config).invalidFormat = !0, config._d = new Date(NaN);
return;
}
for(i = 0; i < config._f.length; i++)currentScore = 0, validFormatFound = !1, tempConfig = copyConfig({}, config), null != config._useUTC && (tempConfig._useUTC = config._useUTC), tempConfig._f = config._f[i], configFromStringAndFormat(tempConfig), isValid(tempConfig) && (validFormatFound = !0), // if there is any input that was not parsed add a penalty for that format
currentScore += getParsingFlags(tempConfig).charsLeftOver, //or tokens
currentScore += 10 * getParsingFlags(tempConfig).unusedTokens.length, getParsingFlags(tempConfig).score = currentScore, bestFormatIsValid ? currentScore < scoreToBeat && (scoreToBeat = currentScore, bestMoment = tempConfig) : (null == scoreToBeat || currentScore < scoreToBeat || validFormatFound) && (scoreToBeat = currentScore, bestMoment = tempConfig, validFormatFound && (bestFormatIsValid = !0));
extend(config, bestMoment || tempConfig);
}(config) : format ? configFromStringAndFormat(config) : isUndefined(input = config._i) ? config._d = new Date(hooks.now()) : isDate(input) ? config._d = new Date(input.valueOf()) : "string" == typeof input ? // date from 1) ASP.NET, 2) ISO, 3) RFC 2822 formats, or 4) optional fallback if parsing isn't strict
function(config) {
var matched = aspNetJsonRegex.exec(config._i);
if (null !== matched) {
config._d = new Date(+matched[1]);
return;
}
configFromISO(config), !1 === config._isValid && (delete config._isValid, configFromRFC2822(config), !1 === config._isValid && (delete config._isValid, config._strict ? config._isValid = !1 : // Final attempt, use Input Fallback
hooks.createFromInputFallback(config)));
}(config) : isArray(input) ? (config._a = map(input.slice(0), function(obj) {
return parseInt(obj, 10);
}), configFromArray(config)) : isObject(input) ? function(config) {
if (!config._d) {
var i = normalizeObjectUnits(config._i), dayOrDate = void 0 === i.day ? i.date : i.day;
config._a = map([
i.year,
i.month,
dayOrDate,
i.hour,
i.minute,
i.second,
i.millisecond
], function(obj) {
return obj && parseInt(obj, 10);
}), configFromArray(config);
}
}(config) : isNumber(input) ? // from milliseconds
config._d = new Date(input) : hooks.createFromInputFallback(config), isValid(config) || (config._d = null), config);
}
function createLocalOrUTC(input, format, locale, strict, isUTC) {
var res, c = {};
return (!0 === format || !1 === format) && (strict = format, format = void 0), (!0 === locale || !1 === locale) && (strict = locale, locale = void 0), (isObject(input) && isObjectEmpty(input) || isArray(input) && 0 === input.length) && (input = void 0), // object construction must be done this way.
// https://github.com/moment/moment/issues/1423
c._isAMomentObject = !0, c._useUTC = c._isUTC = isUTC, c._l = locale, c._i = input, c._f = format, c._strict = strict, (res = new Moment(checkOverflow(prepareConfig(c))))._nextDay && (// Adding is smart enough around DST
res.add(1, "d"), res._nextDay = void 0), res;
}
function createLocal(input, format, locale, strict) {
return createLocalOrUTC(input, format, locale, strict, !1);
}
hooks.createFromInputFallback = deprecate("value provided is not in a recognized RFC2822 or ISO format. moment construction falls back to js Date(), which is not reliable across all browsers and versions. Non RFC2822/ISO date formats are discouraged. Please refer to http://momentjs.com/guides/#/warnings/js-date/ for more info.", function(config) {
config._d = new Date(config._i + (config._useUTC ? " UTC" : ""));
}), // constant that refers to the ISO standard
hooks.ISO_8601 = function() {}, // constant that refers to the RFC 2822 form
hooks.RFC_2822 = function() {};
var prototypeMin = deprecate("moment().min is deprecated, use moment.max instead. http://momentjs.com/guides/#/warnings/min-max/", function() {
var other = createLocal.apply(null, arguments);
return this.isValid() && other.isValid() ? other < this ? this : other : createInvalid();
}), prototypeMax = deprecate("moment().max is deprecated, use moment.min instead. http://momentjs.com/guides/#/warnings/min-max/", function() {
var other = createLocal.apply(null, arguments);
return this.isValid() && other.isValid() ? other > this ? this : other : createInvalid();
});
// Pick a moment m from moments so that m[fn](other) is true for all
// other. This relies on the function fn to be transitive.
//
// moments should either be an array of moment objects or an array, whose
// first element is an array of moment objects.
function pickBy(fn, moments) {
var res, i;
if (1 === moments.length && isArray(moments[0]) && (moments = moments[0]), !moments.length) return createLocal();
for(i = 1, res = moments[0]; i < moments.length; ++i)(!moments[i].isValid() || moments[i][fn](res)) && (res = moments[i]);
return res;
}
var ordering = [
"year",
"quarter",
"month",
"week",
"day",
"hour",
"minute",
"second",
"millisecond"
];
function Duration(duration) {
var normalizedInput = normalizeObjectUnits(duration), years = normalizedInput.year || 0, quarters = normalizedInput.quarter || 0, months = normalizedInput.month || 0, weeks = normalizedInput.week || normalizedInput.isoWeek || 0, days = normalizedInput.day || 0, hours = normalizedInput.hour || 0, minutes = normalizedInput.minute || 0, seconds = normalizedInput.second || 0, milliseconds = normalizedInput.millisecond || 0;
this._isValid = function(m) {
var key, i, unitHasDecimal = !1;
for(key in m)if (hasOwnProp(m, key) && !(-1 !== indexOf.call(ordering, key) && (null == m[key] || !isNaN(m[key])))) return !1;
for(i = 0; i < ordering.length; ++i)if (m[ordering[i]]) {
if (unitHasDecimal) return !1; // only allow non-integers for smallest unit
parseFloat(m[ordering[i]]) !== toInt(m[ordering[i]]) && (unitHasDecimal = !0);
}
return !0;
}(normalizedInput), // representation for dateAddRemove
this._milliseconds = +milliseconds + 1e3 * seconds + // 1000
6e4 * minutes + // 1000 * 60
3600000 * hours, // Because of dateAddRemove treats 24 hours as different from a
// day when working around DST, we need to store them separately
this._days = +days + 7 * weeks, // It is impossible to translate months into days without knowing
// which months you are are talking about, so we have to store
// it separately.
this._months = +months + 3 * quarters + 12 * years, this._data = {}, this._locale = getLocale(), this._bubble();
}
function isDuration(obj) {
return obj instanceof Duration;
}
function absRound(number) {
return number < 0 ? -1 * Math.round(-1 * number) : Math.round(number);
}
// FORMATTING
function offset(token, separator) {
addFormatToken(token, 0, 0, function() {
var offset = this.utcOffset(), sign = "+";
return offset < 0 && (offset = -offset, sign = "-"), sign + zeroFill(~~(offset / 60), 2) + separator + zeroFill(~~offset % 60, 2);
});
}
offset("Z", ":"), offset("ZZ", ""), // PARSING
addRegexToken("Z", matchShortOffset), addRegexToken("ZZ", matchShortOffset), addParseToken([
"Z",
"ZZ"
], function(input, array, config) {
config._useUTC = !0, config._tzm = offsetFromString(matchShortOffset, input);
});
// HELPERS
// timezone chunker
// '+10:00' > ['10', '00']
// '-1530' > ['-15', '30']
var chunkOffset = /([\+\-]|\d\d)/gi;
function offsetFromString(matcher, string) {
var parts, minutes, matches = (string || "").match(matcher);
return null === matches ? null : 0 === (minutes = +(60 * (parts = ((matches[matches.length - 1] || []) + "").match(chunkOffset) || [
"-",
0,
0
])[1]) + toInt(parts[2])) ? 0 : "+" === parts[0] ? minutes : -minutes;
}
// Return a moment from input, that is local/utc/zone equivalent to model.
function cloneWithOffset(input, model) {
var res, diff;
return model._isUTC ? (res = model.clone(), diff = (isMoment(input) || isDate(input) ? input.valueOf() : createLocal(input).valueOf()) - res.valueOf(), // Use low-level api, because this fn is low-level api.
res._d.setTime(res._d.valueOf() + diff), hooks.updateOffset(res, !1), res) : createLocal(input).local();
}
function getDateOffset(m) {
// On Firefox.24 Date#getTimezoneOffset returns a floating point.
// https://github.com/moment/moment/pull/1871
return -Math.round(m._d.getTimezoneOffset());
}
function isUtc() {
return !!this.isValid() && this._isUTC && 0 === this._offset;
}
// HOOKS
// This function will be called whenever a moment is mutated.
// It is intended to keep the offset in sync with the timezone.
hooks.updateOffset = function() {};
// ASP.NET json date format regex
var aspNetRegex = /^(-|\+)?(?:(\d*)[. ])?(\d+):(\d+)(?::(\d+)(\.\d*)?)?$/, // from http://docs.closure-library.googlecode.com/git/closure_goog_date_date.js.source.html
// somewhat more in line with 4.4.3.2 2004 spec, but allows decimal anywhere
// and further modified to allow for strings containing both week and day
isoRegex = /^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/;
function createDuration(input, key) {
var base, other, res, sign, ret, diffRes, duration = input, // matching against regexp is expensive, do it on demand
match = null;
return isDuration(input) ? duration = {
ms: input._milliseconds,
d: input._days,
M: input._months
} : isNumber(input) || !isNaN(+input) ? (duration = {}, key ? duration[key] = +input : duration.milliseconds = +input) : (match = aspNetRegex.exec(input)) ? (sign = "-" === match[1] ? -1 : 1, duration = {
y: 0,
d: toInt(match[2]) * sign,
h: toInt(match[3]) * sign,
m: toInt(match[4]) * sign,
s: toInt(match[5]) * sign,
ms: toInt(absRound(1000 * match[6])) * sign
}) : (match = isoRegex.exec(input)) ? (sign = "-" === match[1] ? -1 : 1, duration = {
y: parseIso(match[2], sign),
M: parseIso(match[3], sign),
w: parseIso(match[4], sign),
d: parseIso(match[5], sign),
h: parseIso(match[6], sign),
m: parseIso(match[7], sign),
s: parseIso(match[8], sign)
}) : null == duration ? // checks for null or undefined
duration = {} : "object" == typeof duration && ("from" in duration || "to" in duration) && (base = createLocal(duration.from), other = createLocal(duration.to), diffRes = base.isValid() && other.isValid() ? (other = cloneWithOffset(other, base), base.isBefore(other) ? res = positiveMomentsDifference(base, other) : ((res = positiveMomentsDifference(other, base)).milliseconds = -res.milliseconds, res.months = -res.months), res) : {
milliseconds: 0,
months: 0
}, (duration = {}).ms = diffRes.milliseconds, duration.M = diffRes.months), ret = new Duration(duration), isDuration(input) && hasOwnProp(input, "_locale") && (ret._locale = input._locale), isDuration(input) && hasOwnProp(input, "_isValid") && (ret._isValid = input._isValid), ret;
}
function parseIso(inp, sign) {
// We'd normally use ~~inp for this, but unfortunately it also
// converts floats to ints.
// inp may be undefined, so careful calling replace on it.
var res = inp && parseFloat(inp.replace(",", "."));
// apply sign while we're at it
return (isNaN(res) ? 0 : res) * sign;
}
function positiveMomentsDifference(base, other) {
var res = {};
return res.months = other.month() - base.month() + (other.year() - base.year()) * 12, base.clone().add(res.months, "M").isAfter(other) && --res.months, res.milliseconds = +other - +base.clone().add(res.months, "M"), res;
}
// TODO: remove 'name' arg after deprecation is removed
function createAdder(direction, name) {
return function(val, period) {
var tmp;
return null === period || isNaN(+period) || (deprecateSimple(name, "moment()." + name + "(period, number) is deprecated. Please use moment()." + name + "(number, period). See http://momentjs.com/guides/#/warnings/add-inverted-param/ for more info."), tmp = val, val = period, period = tmp), addSubtract(this, createDuration(val, period), direction), this;
};
}
function addSubtract(mom, duration, isAdding, updateOffset) {
var milliseconds = duration._milliseconds, days = absRound(duration._days), months = absRound(duration._months);
mom.isValid() && (updateOffset = null == updateOffset || updateOffset, months && setMonth(mom, get(mom, "Month") + months * isAdding), days && set$1(mom, "Date", get(mom, "Date") + days * isAdding), milliseconds && mom._d.setTime(mom._d.valueOf() + milliseconds * isAdding), updateOffset && hooks.updateOffset(mom, days || months));
}
createDuration.fn = Duration.prototype, createDuration.invalid = function() {
return createDuration(NaN);
};
var add = createAdder(1, "add"), subtract = createAdder(-1, "subtract");
function isString(input) {
return "string" == typeof input || input instanceof String;
}
function monthDiff(a, b) {
if (a.date() < b.date()) // end-of-month calculations work correct when the start month has more
// days than the end month.
return -monthDiff(b, a);
// difference in months
var adjust, wholeMonthDiff = (b.year() - a.year()) * 12 + (b.month() - a.month()), // b is in (anchor - 1 month, anchor + 1 month)
anchor = a.clone().add(wholeMonthDiff, "months");
//check for negative zero, return zero if negative zero
return(// linear across the month
adjust = b - anchor < 0 ? (b - anchor) / (anchor - a.clone().add(wholeMonthDiff - 1, "months")) : (b - anchor) / (a.clone().add(wholeMonthDiff + 1, "months") - anchor), -(wholeMonthDiff + adjust) || 0);
}
// If passed a locale key, it will set the locale for this
// instance. Otherwise, it will return the locale configuration
// variables for this instance.
function locale(key) {
var newLocaleData;
return void 0 === key ? this._locale._abbr : (null != (newLocaleData = getLocale(key)) && (this._locale = newLocaleData), this);
}
hooks.defaultFormat = "YYYY-MM-DDTHH:mm:ssZ", hooks.defaultFormatUtc = "YYYY-MM-DDTHH:mm:ss[Z]";
var lang = deprecate("moment().lang() is deprecated. Instead, use moment().localeData() to get the language configuration. Use moment().locale() to change languages.", function(key) {
return void 0 === key ? this.localeData() : this.locale(key);
});
function localeData() {
return this._locale;
}
function localStartOfDate(y, m, d) {
return(// the date constructor remaps years 0-99 to 1900-1999
y < 100 && y >= 0 ? new Date(y + 400, m, d) - 12622780800000 : new Date(y, m, d).valueOf());
}
function utcStartOfDate(y, m, d) {
return(// Date.UTC remaps years 0-99 to 1900-1999
y < 100 && y >= 0 ? Date.UTC(y + 400, m, d) - 12622780800000 : Date.UTC(y, m, d));
}
function matchEraAbbr(isStrict, locale) {
return locale.erasAbbrRegex(isStrict);
}
function computeErasParse() {
var i, l, abbrPieces = [], namePieces = [], narrowPieces = [], mixedPieces = [], eras = this.eras();
for(i = 0, l = eras.length; i < l; ++i)namePieces.push(regexEscape(eras[i].name)), abbrPieces.push(regexEscape(eras[i].abbr)), narrowPieces.push(regexEscape(eras[i].narrow)), mixedPieces.push(regexEscape(eras[i].name)), mixedPieces.push(regexEscape(eras[i].abbr)), mixedPieces.push(regexEscape(eras[i].narrow));
this._erasRegex = RegExp("^(" + mixedPieces.join("|") + ")", "i"), this._erasNameRegex = RegExp("^(" + namePieces.join("|") + ")", "i"), this._erasAbbrRegex = RegExp("^(" + abbrPieces.join("|") + ")", "i"), this._erasNarrowRegex = RegExp("^(" + narrowPieces.join("|") + ")", "i");
}
function addWeekYearFormatToken(token, getter) {
addFormatToken(0, [
token,
token.length
], 0, getter);
}
function getSetWeekYearHelper(input, week, weekday, dow, doy) {
var weeksTarget;
return null == input ? weekOfYear(this, dow, doy).year : (week > (weeksTarget = weeksInYear(input, dow, doy)) && (week = weeksTarget), setWeekAll.call(this, input, week, weekday, dow, doy));
}
function setWeekAll(weekYear, week, weekday, dow, doy) {
var dayOfYearData = dayOfYearFromWeeks(weekYear, week, weekday, dow, doy), date = createUTCDate(dayOfYearData.year, 0, dayOfYearData.dayOfYear);
return this.year(date.getUTCFullYear()), this.month(date.getUTCMonth()), this.date(date.getUTCDate()), this;
}
addFormatToken("N", 0, 0, "eraAbbr"), addFormatToken("NN", 0, 0, "eraAbbr"), addFormatToken("NNN", 0, 0, "eraAbbr"), addFormatToken("NNNN", 0, 0, "eraName"), addFormatToken("NNNNN", 0, 0, "eraNarrow"), addFormatToken("y", [
"y",
1
], "yo", "eraYear"), addFormatToken("y", [
"yy",
2
], 0, "eraYear"), addFormatToken("y", [
"yyy",
3
], 0, "eraYear"), addFormatToken("y", [
"yyyy",
4
], 0, "eraYear"), addRegexToken("N", matchEraAbbr), addRegexToken("NN", matchEraAbbr), addRegexToken("NNN", matchEraAbbr), addRegexToken("NNNN", function(isStrict, locale) {
return locale.erasNameRegex(isStrict);
}), addRegexToken("NNNNN", function(isStrict, locale) {
return locale.erasNarrowRegex(isStrict);
}), addParseToken([
"N",
"NN",
"NNN",
"NNNN",
"NNNNN"
], function(input, array, config, token) {
var era = config._locale.erasParse(input, token, config._strict);
era ? getParsingFlags(config).era = era : getParsingFlags(config).invalidEra = input;
}), addRegexToken("y", matchUnsigned), addRegexToken("yy", matchUnsigned), addRegexToken("yyy", matchUnsigned), addRegexToken("yyyy", matchUnsigned), addRegexToken("yo", function(isStrict, locale) {
return locale._eraYearOrdinalRegex || matchUnsigned;
}), addParseToken([
"y",
"yy",
"yyy",
"yyyy"
], 0), addParseToken([
"yo"
], function(input, array, config, token) {
var match;
config._locale._eraYearOrdinalRegex && (match = input.match(config._locale._eraYearOrdinalRegex)), config._locale.eraYearOrdinalParse ? array[0] = config._locale.eraYearOrdinalParse(input, match) : array[0] = parseInt(input, 10);
}), // FORMATTING
addFormatToken(0, [
"gg",
2
], 0, function() {
return this.weekYear() % 100;
}), addFormatToken(0, [
"GG",
2
], 0, function() {
return this.isoWeekYear() % 100;
}), addWeekYearFormatToken("gggg", "weekYear"), addWeekYearFormatToken("ggggg", "weekYear"), addWeekYearFormatToken("GGGG", "isoWeekYear"), addWeekYearFormatToken("GGGGG", "isoWeekYear"), // ALIASES
addUnitAlias("weekYear", "gg"), addUnitAlias("isoWeekYear", "GG"), priorities.weekYear = 1, priorities.isoWeekYear = 1, // PARSING
addRegexToken("G", matchSigned), addRegexToken("g", matchSigned), addRegexToken("GG", match1to2, match2), addRegexToken("gg", match1to2, match2), addRegexToken("GGGG", match1to4, match4), addRegexToken("gggg", match1to4, match4), addRegexToken("GGGGG", match1to6, match6), addRegexToken("ggggg", match1to6, match6), addWeekParseToken([
"gggg",
"ggggg",
"GGGG",
"GGGGG"
], function(input, week, config, token) {
week[token.substr(0, 2)] = toInt(input);
}), addWeekParseToken([
"gg",
"GG"
], function(input, week, config, token) {
week[token] = hooks.parseTwoDigitYear(input);
}), // FORMATTING
addFormatToken("Q", 0, "Qo", "quarter"), // ALIASES
addUnitAlias("quarter", "Q"), priorities.quarter = 7, // PARSING
addRegexToken("Q", match1), addParseToken("Q", function(input, array) {
array[1] = (toInt(input) - 1) * 3;
}), // FORMATTING
addFormatToken("D", [
"DD",
2
], "Do", "date"), // ALIASES
addUnitAlias("date", "D"), priorities.date = 9, // PARSING
addRegexToken("D", match1to2), addRegexToken("DD", match1to2, match2), addRegexToken("Do", function(isStrict, locale) {
// TODO: Remove "ordinalParse" fallback in next major release.
return isStrict ? locale._dayOfMonthOrdinalParse || locale._ordinalParse : locale._dayOfMonthOrdinalParseLenient;
}), addParseToken([
"D",
"DD"
], 2), addParseToken("Do", function(input, array) {
array[2] = toInt(input.match(match1to2)[0]);
});
// MOMENTS
var getSetDayOfMonth = makeGetSet("Date", !0);
// FORMATTING
addFormatToken("DDD", [
"DDDD",
3
], "DDDo", "dayOfYear"), // ALIASES
addUnitAlias("dayOfYear", "DDD"), priorities.dayOfYear = 4, // PARSING
addRegexToken("DDD", match1to3), addRegexToken("DDDD", match3), addParseToken([
"DDD",
"DDDD"
], function(input, array, config) {
config._dayOfYear = toInt(input);
}), // FORMATTING
addFormatToken("m", [
"mm",
2
], 0, "minute"), // ALIASES
addUnitAlias("minute", "m"), priorities.minute = 14, // PARSING
addRegexToken("m", match1to2), addRegexToken("mm", match1to2, match2), addParseToken([
"m",
"mm"
], 4);
// MOMENTS
var getSetMinute = makeGetSet("Minutes", !1);
// FORMATTING
addFormatToken("s", [
"ss",
2
], 0, "second"), // ALIASES
addUnitAlias("second", "s"), priorities.second = 15, // PARSING
addRegexToken("s", match1to2), addRegexToken("ss", match1to2, match2), addParseToken([
"s",
"ss"
], 5);
// MOMENTS
var getSetSecond = makeGetSet("Seconds", !1);
for(// FORMATTING
addFormatToken("S", 0, 0, function() {
return ~~(this.millisecond() / 100);
}), addFormatToken(0, [
"SS",
2
], 0, function() {
return ~~(this.millisecond() / 10);
}), addFormatToken(0, [
"SSS",
3
], 0, "millisecond"), addFormatToken(0, [
"SSSS",
4
], 0, function() {
return 10 * this.millisecond();
}), addFormatToken(0, [
"SSSSS",
5
], 0, function() {
return 100 * this.millisecond();
}), addFormatToken(0, [
"SSSSSS",
6
], 0, function() {
return 1000 * this.millisecond();
}), addFormatToken(0, [
"SSSSSSS",
7
], 0, function() {
return 10000 * this.millisecond();
}), addFormatToken(0, [
"SSSSSSSS",
8
], 0, function() {
return 100000 * this.millisecond();
}), addFormatToken(0, [
"SSSSSSSSS",
9
], 0, function() {
return 1000000 * this.millisecond();
}), // ALIASES
addUnitAlias("millisecond", "ms"), priorities.millisecond = 16, // PARSING
addRegexToken("S", match1to3, match1), addRegexToken("SS", match1to3, match2), addRegexToken("SSS", match1to3, match3), token = "SSSS"; token.length <= 9; token += "S")addRegexToken(token, matchUnsigned);
function parseMs(input, array) {
array[6] = toInt(("0." + input) * 1000);
}
for(token = "S"; token.length <= 9; token += "S")addParseToken(token, parseMs);
getSetMillisecond = makeGetSet("Milliseconds", !1), // FORMATTING
addFormatToken("z", 0, 0, "zoneAbbr"), addFormatToken("zz", 0, 0, "zoneName");
var proto = Moment.prototype;
function preParsePostFormat(string) {
return string;
}
proto.add = add, proto.calendar = function(time, formats) {
// Support for single parameter, formats only overload to the calendar function
if (1 == arguments.length) {
if (arguments[0]) {
var input, arrayTest, dataTypeTest;
(input = arguments[0], isMoment(input) || isDate(input) || isString(input) || isNumber(input) || (arrayTest = isArray(input), dataTypeTest = !1, arrayTest && (dataTypeTest = 0 === input.filter(function(item) {
return !isNumber(item) && isString(input);
}).length), arrayTest && dataTypeTest) || function(input) {
var i, property, objectTest = isObject(input) && !isObjectEmpty(input), propertyTest = !1, properties = [
"years",
"year",
"y",
"months",
"month",
"M",
"days",
"day",
"d",
"dates",
"date",
"D",
"hours",
"hour",
"h",
"minutes",
"minute",
"m",
"seconds",
"second",
"s",
"milliseconds",
"millisecond",
"ms"
];
for(i = 0; i < properties.length; i += 1)property = properties[i], propertyTest = propertyTest || hasOwnProp(input, property);
return objectTest && propertyTest;
}(input) || null == input) ? (time = arguments[0], formats = void 0) : function(input) {
var i, property, objectTest = isObject(input) && !isObjectEmpty(input), propertyTest = !1, properties = [
"sameDay",
"nextDay",
"lastDay",
"nextWeek",
"lastWeek",
"sameElse"
];
for(i = 0; i < properties.length; i += 1)property = properties[i], propertyTest = propertyTest || hasOwnProp(input, property);
return objectTest && propertyTest;
}(arguments[0]) && (formats = arguments[0], time = void 0);
} else time = void 0, formats = void 0;
}
// We want to compare the start of today, vs this.
// Getting start-of-today depends on whether we're local/utc/offset or not.
var now = time || createLocal(), sod = cloneWithOffset(now, this).startOf("day"), format = hooks.calendarFormat(this, sod) || "sameElse", output = formats && (isFunction(formats[format]) ? formats[format].call(this, now) : formats[format]);
return this.format(output || this.localeData().calendar(format, this, createLocal(now)));
}, proto.clone = function() {
return new Moment(this);
}, proto.diff = function(input, units, asFloat) {
var that, zoneDelta, output;
if (!this.isValid() || !(that = cloneWithOffset(input, this)).isValid()) return NaN;
switch(zoneDelta = (that.utcOffset() - this.utcOffset()) * 6e4, units = normalizeUnits(units)){
case "year":
output = monthDiff(this, that) / 12;
break;
case "month":
output = monthDiff(this, that);
break;
case "quarter":
output = monthDiff(this, that) / 3;
break;
case "second":
output = (this - that) / 1e3;
break; // 1000
case "minute":
output = (this - that) / 6e4;
break; // 1000 * 60
case "hour":
output = (this - that) / 36e5;
break; // 1000 * 60 * 60
case "day":
output = (this - that - zoneDelta) / 864e5;
break; // 1000 * 60 * 60 * 24, negate dst
case "week":
output = (this - that - zoneDelta) / 6048e5;
break; // 1000 * 60 * 60 * 24 * 7, negate dst
default:
output = this - that;
}
return asFloat ? output : absFloor(output);
}, proto.endOf = function(units) {
var time, startOfDate;
if (void 0 === (units = normalizeUnits(units)) || "millisecond" === units || !this.isValid()) return this;
switch(startOfDate = this._isUTC ? utcStartOfDate : localStartOfDate, units){
case "year":
time = startOfDate(this.year() + 1, 0, 1) - 1;
break;
case "quarter":
time = startOfDate(this.year(), this.month() - this.month() % 3 + 3, 1) - 1;
break;
case "month":
time = startOfDate(this.year(), this.month() + 1, 1) - 1;
break;
case "week":
time = startOfDate(this.year(), this.month(), this.date() - this.weekday() + 7) - 1;
break;
case "isoWeek":
time = startOfDate(this.year(), this.month(), this.date() - (this.isoWeekday() - 1) + 7) - 1;
break;
case "day":
case "date":
time = startOfDate(this.year(), this.month(), this.date() + 1) - 1;
break;
case "hour":
time = this._d.valueOf(), time += 3600000 - ((time + (this._isUTC ? 0 : 60000 * this.utcOffset())) % 3600000 + 3600000) % 3600000 - 1;
break;
case "minute":
time = this._d.valueOf(), time += 60000 - (time % 60000 + 60000) % 60000 - 1;
break;
case "second":
time = this._d.valueOf(), time += 1000 - (time % 1000 + 1000) % 1000 - 1;
}
return this._d.setTime(time), hooks.updateOffset(this, !0), this;
}, proto.format = function(inputString) {
inputString || (inputString = this.isUtc() ? hooks.defaultFormatUtc : hooks.defaultFormat);
var output = formatMoment(this, inputString);
return this.localeData().postformat(output);
}, proto.from = function(time, withoutSuffix) {
return this.isValid() && (isMoment(time) && time.isValid() || createLocal(time).isValid()) ? createDuration({
to: this,
from: time
}).locale(this.locale()).humanize(!withoutSuffix) : this.localeData().invalidDate();
}, proto.fromNow = function(withoutSuffix) {
return this.from(createLocal(), withoutSuffix);
}, proto.to = function(time, withoutSuffix) {
return this.isValid() && (isMoment(time) && time.isValid() || createLocal(time).isValid()) ? createDuration({
from: this,
to: time
}).locale(this.locale()).humanize(!withoutSuffix) : this.localeData().invalidDate();
}, proto.toNow = function(withoutSuffix) {
return this.to(createLocal(), withoutSuffix);
}, proto.get = // MOMENTS
function(units) {
return isFunction(this[units = normalizeUnits(units)]) ? this[units]() : this;
}, proto.invalidAt = function() {
return getParsingFlags(this).overflow;
}, proto.isAfter = function(input, units) {
var localInput = isMoment(input) ? input : createLocal(input);
return !!(this.isValid() && localInput.isValid()) && ("millisecond" === (units = normalizeUnits(units) || "millisecond") ? this.valueOf() > localInput.valueOf() : localInput.valueOf() < this.clone().startOf(units).valueOf());
}, proto.isBefore = function(input, units) {
var localInput = isMoment(input) ? input : createLocal(input);
return !!(this.isValid() && localInput.isValid()) && ("millisecond" === (units = normalizeUnits(units) || "millisecond") ? this.valueOf() < localInput.valueOf() : this.clone().endOf(units).valueOf() < localInput.valueOf());
}, proto.isBetween = function(from, to, units, inclusivity) {
var localFrom = isMoment(from) ? from : createLocal(from), localTo = isMoment(to) ? to : createLocal(to);
return !!(this.isValid() && localFrom.isValid() && localTo.isValid()) && ("(" === (inclusivity = inclusivity || "()")[0] ? this.isAfter(localFrom, units) : !this.isBefore(localFrom, units)) && (")" === inclusivity[1] ? this.isBefore(localTo, units) : !this.isAfter(localTo, units));
}, proto.isSame = function(input, units) {
var inputMs, localInput = isMoment(input) ? input : createLocal(input);
return !!(this.isValid() && localInput.isValid()) && ("millisecond" === (units = normalizeUnits(units) || "millisecond") ? this.valueOf() === localInput.valueOf() : (inputMs = localInput.valueOf(), this.clone().startOf(units).valueOf() <= inputMs && inputMs <= this.clone().endOf(units).valueOf()));
}, proto.isSameOrAfter = function(input, units) {
return this.isSame(input, units) || this.isAfter(input, units);
}, proto.isSameOrBefore = function(input, units) {
return this.isSame(input, units) || this.isBefore(input, units);
}, proto.isValid = function() {
return isValid(this);
}, proto.lang = lang, proto.locale = locale, proto.localeData = localeData, proto.max = prototypeMax, proto.min = prototypeMin, proto.parsingFlags = function() {
return extend({}, getParsingFlags(this));
}, proto.set = function(units, value) {
if ("object" == typeof units) {
var i, prioritized = function(unitsObj) {
var u, units = [];
for(u in unitsObj)hasOwnProp(unitsObj, u) && units.push({
unit: u,
priority: priorities[u]
});
return units.sort(function(a, b) {
return a.priority - b.priority;
}), units;
}(units = normalizeObjectUnits(units));
for(i = 0; i < prioritized.length; i++)this[prioritized[i].unit](units[prioritized[i].unit]);
} else if (isFunction(this[units = normalizeUnits(units)])) return this[units](value);
return this;
}, proto.startOf = function(units) {
var time, startOfDate;
if (void 0 === (units = normalizeUnits(units)) || "millisecond" === units || !this.isValid()) return this;
switch(startOfDate = this._isUTC ? utcStartOfDate : localStartOfDate, units){
case "year":
time = startOfDate(this.year(), 0, 1);
break;
case "quarter":
time = startOfDate(this.year(), this.month() - this.month() % 3, 1);
break;
case "month":
time = startOfDate(this.year(), this.month(), 1);
break;
case "week":
time = startOfDate(this.year(), this.month(), this.date() - this.weekday());
break;
case "isoWeek":
time = startOfDate(this.year(), this.month(), this.date() - (this.isoWeekday() - 1));
break;
case "day":
case "date":
time = startOfDate(this.year(), this.month(), this.date());
break;
case "hour":
time = this._d.valueOf(), time -= ((time + (this._isUTC ? 0 : 60000 * this.utcOffset())) % 3600000 + 3600000) % 3600000;
break;
case "minute":
time = this._d.valueOf(), time -= (time % 60000 + 60000) % 60000;
break;
case "second":
time = this._d.valueOf(), time -= (time % 1000 + 1000) % 1000;
}
return this._d.setTime(time), hooks.updateOffset(this, !0), this;
}, proto.subtract = subtract, proto.toArray = function() {
return [
this.year(),
this.month(),
this.date(),
this.hour(),
this.minute(),
this.second(),
this.millisecond()
];
}, proto.toObject = function() {
return {
years: this.year(),
months: this.month(),
date: this.date(),
hours: this.hours(),
minutes: this.minutes(),
seconds: this.seconds(),
milliseconds: this.milliseconds()
};
}, proto.toDate = function() {
return new Date(this.valueOf());
}, proto.toISOString = function(keepOffset) {
if (!this.isValid()) return null;
var utc = !0 !== keepOffset, m = utc ? this.clone().utc() : this;
return 0 > m.year() || m.year() > 9999 ? formatMoment(m, utc ? "YYYYYY-MM-DD[T]HH:mm:ss.SSS[Z]" : "YYYYYY-MM-DD[T]HH:mm:ss.SSSZ") : isFunction(Date.prototype.toISOString) ? // native implementation is ~50x faster, use it when we can
utc ? this.toDate().toISOString() : new Date(this.valueOf() + 60000 * this.utcOffset()).toISOString().replace("Z", formatMoment(m, "Z")) : formatMoment(m, utc ? "YYYY-MM-DD[T]HH:mm:ss.SSS[Z]" : "YYYY-MM-DD[T]HH:mm:ss.SSSZ");
}, proto.inspect = /**
* Return a human readable representation of a moment that can
* also be evaluated to get a new moment which is the same
*
* @link https://nodejs.org/dist/latest/docs/api/util.html#util_custom_inspect_function_on_objects
*/ function() {
if (!this.isValid()) return "moment.invalid(/* " + this._i + " */)";
var prefix, year, suffix, func = "moment", zone = "";
return this.isLocal() || (func = 0 === this.utcOffset() ? "moment.utc" : "moment.parseZone", zone = "Z"), prefix = "[" + func + '("]', year = 0 <= this.year() && 9999 >= this.year() ? "YYYY" : "YYYYYY", suffix = zone + '[")]', this.format(prefix + year + "-MM-DD[T]HH:mm:ss.SSS" + suffix);
}, "undefined" != typeof Symbol && null != Symbol.for && (proto[Symbol.for("nodejs.util.inspect.custom")] = function() {
return "Moment<" + this.format() + ">";
}), proto.toJSON = function() {
// new Date(NaN).toJSON() === null
return this.isValid() ? this.toISOString() : null;
}, proto.toString = function() {
return this.clone().locale("en").format("ddd MMM DD YYYY HH:mm:ss [GMT]ZZ");
}, proto.unix = function() {
return Math.floor(this.valueOf() / 1000);
}, proto.valueOf = function() {
return this._d.valueOf() - 60000 * (this._offset || 0);
}, proto.creationData = function() {
return {
input: this._i,
format: this._f,
locale: this._locale,
isUTC: this._isUTC,
strict: this._strict
};
}, proto.eraName = function() {
var i, l, val, eras = this.localeData().eras();
for(i = 0, l = eras.length; i < l; ++i)if (// truncate time
val = this.clone().startOf("day").valueOf(), eras[i].since <= val && val <= eras[i].until || eras[i].until <= val && val <= eras[i].since) return eras[i].name;
return "";
}, proto.eraNarrow = function() {
var i, l, val, eras = this.localeData().eras();
for(i = 0, l = eras.length; i < l; ++i)if (// truncate time
val = this.clone().startOf("day").valueOf(), eras[i].since <= val && val <= eras[i].until || eras[i].until <= val && val <= eras[i].since) return eras[i].narrow;
return "";
}, proto.eraAbbr = function() {
var i, l, val, eras = this.localeData().eras();
for(i = 0, l = eras.length; i < l; ++i)if (// truncate time
val = this.clone().startOf("day").valueOf(), eras[i].since <= val && val <= eras[i].until || eras[i].until <= val && val <= eras[i].since) return eras[i].abbr;
return "";
}, proto.eraYear = function() {
var i, l, dir, val, eras = this.localeData().eras();
for(i = 0, l = eras.length; i < l; ++i)if (dir = eras[i].since <= eras[i].until ? 1 : -1, // truncate time
val = this.clone().startOf("day").valueOf(), eras[i].since <= val && val <= eras[i].until || eras[i].until <= val && val <= eras[i].since) return (this.year() - hooks(eras[i].since).year()) * dir + eras[i].offset;
return this.year();
}, proto.year = getSetYear, proto.isLeapYear = function() {
return isLeapYear(this.year());
}, proto.weekYear = // MOMENTS
function(input) {
return getSetWeekYearHelper.call(this, input, this.week(), this.weekday(), this.localeData()._week.dow, this.localeData()._week.doy);
}, proto.isoWeekYear = function(input) {
return getSetWeekYearHelper.call(this, input, this.isoWeek(), this.isoWeekday(), 1, 4);
}, proto.quarter = proto.quarters = // MOMENTS
function(input) {
return null == input ? Math.ceil((this.month() + 1) / 3) : this.month((input - 1) * 3 + this.month() % 3);
}, proto.month = getSetMonth, proto.daysInMonth = function() {
return daysInMonth(this.year(), this.month());
}, proto.week = proto.weeks = // MOMENTS
function(input) {
var week = this.localeData().week(this);
return null == input ? week : this.add((input - week) * 7, "d");
}, proto.isoWeek = proto.isoWeeks = function(input) {
var week = weekOfYear(this, 1, 4).week;
return null == input ? week : this.add((input - week) * 7, "d");
}, proto.weeksInYear = function() {
var weekInfo = this.localeData()._week;
return weeksInYear(this.year(), weekInfo.dow, weekInfo.doy);
}, proto.weeksInWeekYear = function() {
var weekInfo = this.localeData()._week;
return weeksInYear(this.weekYear(), weekInfo.dow, weekInfo.doy);
}, proto.isoWeeksInYear = function() {
return weeksInYear(this.year(), 1, 4);
}, proto.isoWeeksInISOWeekYear = function() {
return weeksInYear(this.isoWeekYear(), 1, 4);
}, proto.date = getSetDayOfMonth, proto.day = proto.days = // MOMENTS
function(input) {
if (!this.isValid()) return null != input ? this : NaN;
var input1, locale, day = this._isUTC ? this._d.getUTCDay() : this._d.getDay();
return null == input ? day : (input1 = input, locale = this.localeData(), input = "string" != typeof input1 ? input1 : isNaN(input1) ? "number" == typeof (input1 = locale.weekdaysParse(input1)) ? input1 : null : parseInt(input1, 10), this.add(input - day, "d"));
}, proto.weekday = function(input) {
if (!this.isValid()) return null != input ? this : NaN;
var weekday = (this.day() + 7 - this.localeData()._week.dow) % 7;
return null == input ? weekday : this.add(input - weekday, "d");
}, proto.isoWeekday = function(input) {
if (!this.isValid()) return null != input ? this : NaN;
// behaves the same as moment#day except
// as a getter, returns 7 instead of 0 (1-7 range instead of 0-6)
// as a setter, sunday should belong to the previous week.
if (null == input) return this.day() || 7;
var locale, weekday = (locale = this.localeData(), "string" == typeof input ? locale.weekdaysParse(input) % 7 || 7 : isNaN(input) ? null : input);
return this.day(this.day() % 7 ? weekday : weekday - 7);
}, proto.dayOfYear = // HELPERS
// MOMENTS
function(input) {
var dayOfYear = Math.round((this.clone().startOf("day") - this.clone().startOf("year")) / 864e5) + 1;
return null == input ? dayOfYear : this.add(input - dayOfYear, "d");
}, proto.hour = proto.hours = getSetHour, proto.minute = proto.minutes = getSetMinute, proto.second = proto.seconds = getSetSecond, proto.millisecond = proto.milliseconds = getSetMillisecond, proto.utcOffset = // MOMENTS
// keepLocalTime = true means only change the timezone, without
// affecting the local hour. So 5:31:26 +0300 --[utcOffset(2, true)]-->
// 5:31:26 +0200 It is possible that 5:31:26 doesn't exist with offset
// +0200, so we adjust the time as needed, to be valid.
//
// Keeping the time actually adds/subtracts (one hour)
// from the actual represented time. That is why we call updateOffset
// a second time. In case it wants us to change the offset again
// _changeInProgress == true case, then we have to adjust, because
// there is no such time in the given timezone.
function(input, keepLocalTime, keepMinutes) {
var localAdjust, offset = this._offset || 0;
if (!this.isValid()) return null != input ? this : NaN;
if (null == input) return this._isUTC ? offset : getDateOffset(this);
if ("string" == typeof input) {
if (null === (input = offsetFromString(matchShortOffset, input))) return this;
} else 16 > Math.abs(input) && !keepMinutes && (input *= 60);
return !this._isUTC && keepLocalTime && (localAdjust = getDateOffset(this)), this._offset = input, this._isUTC = !0, null != localAdjust && this.add(localAdjust, "m"), offset === input || (!keepLocalTime || this._changeInProgress ? addSubtract(this, createDuration(input - offset, "m"), 1, !1) : this._changeInProgress || (this._changeInProgress = !0, hooks.updateOffset(this, !0), this._changeInProgress = null)), this;
}, proto.utc = function(keepLocalTime) {
return this.utcOffset(0, keepLocalTime);
}, proto.local = function(keepLocalTime) {
return this._isUTC && (this.utcOffset(0, keepLocalTime), this._isUTC = !1, keepLocalTime && this.subtract(getDateOffset(this), "m")), this;
}, proto.parseZone = function() {
if (null != this._tzm) this.utcOffset(this._tzm, !1, !0);
else if ("string" == typeof this._i) {
var tZone = offsetFromString(matchOffset, this._i);
null != tZone ? this.utcOffset(tZone) : this.utcOffset(0, !0);
}
return this;
}, proto.hasAlignedHourOffset = function(input) {
return !!this.isValid() && (input = input ? createLocal(input).utcOffset() : 0, (this.utcOffset() - input) % 60 == 0);
}, proto.isDST = function() {
return this.utcOffset() > this.clone().month(0).utcOffset() || this.utcOffset() > this.clone().month(5).utcOffset();
}, proto.isLocal = function() {
return !!this.isValid() && !this._isUTC;
}, proto.isUtcOffset = function() {
return !!this.isValid() && this._isUTC;
}, proto.isUtc = isUtc, proto.isUTC = isUtc, proto.zoneAbbr = // MOMENTS
function() {
return this._isUTC ? "UTC" : "";
}, proto.zoneName = function() {
return this._isUTC ? "Coordinated Universal Time" : "";
}, proto.dates = deprecate("dates accessor is deprecated. Use date instead.", getSetDayOfMonth), proto.months = deprecate("months accessor is deprecated. Use month instead", getSetMonth), proto.years = deprecate("years accessor is deprecated. Use year instead", getSetYear), proto.zone = deprecate("moment().zone is deprecated, use moment().utcOffset instead. http://momentjs.com/guides/#/warnings/zone/", function(input, keepLocalTime) {
return null != input ? ("string" != typeof input && (input = -input), this.utcOffset(input, keepLocalTime), this) : -this.utcOffset();
}), proto.isDSTShifted = deprecate("isDSTShifted is deprecated. See http://momentjs.com/guides/#/warnings/dst-shifted/ for more information", function() {
if (!isUndefined(this._isDSTShifted)) return this._isDSTShifted;
var other, c = {};
return copyConfig(c, this), (c = prepareConfig(c))._a ? (other = c._isUTC ? createUTC(c._a) : createLocal(c._a), this._isDSTShifted = this.isValid() && // compare two arrays, return the number of differences
function(array1, array2, dontConvert) {
var i, len = Math.min(array1.length, array2.length), lengthDiff = Math.abs(array1.length - array2.length), diffs = 0;
for(i = 0; i < len; i++)toInt(array1[i]) !== toInt(array2[i]) && diffs++;
return diffs + lengthDiff;
}(c._a, other.toArray()) > 0) : this._isDSTShifted = !1, this._isDSTShifted;
});
var proto$1 = Locale.prototype;
function get$1(format, index, field, setter) {
var locale = getLocale(), utc = createUTC().set(setter, index);
return locale[field](utc, format);
}
function listMonthsImpl(format, index, field) {
if (isNumber(format) && (index = format, format = void 0), format = format || "", null != index) return get$1(format, index, field, "month");
var i, out = [];
for(i = 0; i < 12; i++)out[i] = get$1(format, i, field, "month");
return out;
}
// ()
// (5)
// (fmt, 5)
// (fmt)
// (true)
// (true, 5)
// (true, fmt, 5)
// (true, fmt)
function listWeekdaysImpl(localeSorted, format, index, field) {
"boolean" == typeof localeSorted || (index = format = localeSorted, localeSorted = !1), isNumber(format) && (index = format, format = void 0), format = format || "";
var i, locale = getLocale(), shift = localeSorted ? locale._week.dow : 0, out = [];
if (null != index) return get$1(format, (index + shift) % 7, field, "day");
for(i = 0; i < 7; i++)out[i] = get$1(format, (i + shift) % 7, field, "day");
return out;
}
proto$1.calendar = function(key, mom, now) {
var output = this._calendar[key] || this._calendar.sameElse;
return isFunction(output) ? output.call(mom, now) : output;
}, proto$1.longDateFormat = function(key) {
var format = this._longDateFormat[key], formatUpper = this._longDateFormat[key.toUpperCase()];
return format || !formatUpper ? format : (this._longDateFormat[key] = formatUpper.match(formattingTokens).map(function(tok) {
return "MMMM" === tok || "MM" === tok || "DD" === tok || "dddd" === tok ? tok.slice(1) : tok;
}).join(""), this._longDateFormat[key]);
}, proto$1.invalidDate = function() {
return this._invalidDate;
}, proto$1.ordinal = function(number) {
return this._ordinal.replace("%d", number);
}, proto$1.preparse = preParsePostFormat, proto$1.postformat = preParsePostFormat, proto$1.relativeTime = function(number, withoutSuffix, string, isFuture) {
var output = this._relativeTime[string];
return isFunction(output) ? output(number, withoutSuffix, string, isFuture) : output.replace(/%d/i, number);
}, proto$1.pastFuture = function(diff, output) {
var format = this._relativeTime[diff > 0 ? "future" : "past"];
return isFunction(format) ? format(output) : format.replace(/%s/i, output);
}, proto$1.set = function(config) {
var prop, i;
for(i in config)hasOwnProp(config, i) && (isFunction(prop = config[i]) ? this[i] = prop : this["_" + i] = prop);
this._config = config, // Lenient ordinal parsing accepts just a number in addition to
// number + (possibly) stuff coming from _dayOfMonthOrdinalParse.
// TODO: Remove "ordinalParse" fallback in next major release.
this._dayOfMonthOrdinalParseLenient = RegExp((this._dayOfMonthOrdinalParse.source || this._ordinalParse.source) + "|" + /\d{1,2}/.source);
}, proto$1.eras = function(m, format) {
var i, l, date, eras = this._eras || getLocale("en")._eras;
for(i = 0, l = eras.length; i < l; ++i)switch("string" == typeof eras[i].since && (// truncate time
date = hooks(eras[i].since).startOf("day"), eras[i].since = date.valueOf()), typeof eras[i].until){
case "undefined":
eras[i].until = Infinity;
break;
case "string":
// truncate time
date = hooks(eras[i].until).startOf("day").valueOf(), eras[i].until = date.valueOf();
}
return eras;
}, proto$1.erasParse = function(eraName, format, strict) {
var i, l, name, abbr, narrow, eras = this.eras();
for(i = 0, eraName = eraName.toUpperCase(), l = eras.length; i < l; ++i)if (name = eras[i].name.toUpperCase(), abbr = eras[i].abbr.toUpperCase(), narrow = eras[i].narrow.toUpperCase(), strict) switch(format){
case "N":
case "NN":
case "NNN":
if (abbr === eraName) return eras[i];
break;
case "NNNN":
if (name === eraName) return eras[i];
break;
case "NNNNN":
if (narrow === eraName) return eras[i];
}
else if ([
name,
abbr,
narrow
].indexOf(eraName) >= 0) return eras[i];
}, proto$1.erasConvertYear = function(era, year) {
var dir = era.since <= era.until ? 1 : -1;
return void 0 === year ? hooks(era.since).year() : hooks(era.since).year() + (year - era.offset) * dir;
}, proto$1.erasAbbrRegex = function(isStrict) {
return hasOwnProp(this, "_erasAbbrRegex") || computeErasParse.call(this), isStrict ? this._erasAbbrRegex : this._erasRegex;
}, proto$1.erasNameRegex = function(isStrict) {
return hasOwnProp(this, "_erasNameRegex") || computeErasParse.call(this), isStrict ? this._erasNameRegex : this._erasRegex;
}, proto$1.erasNarrowRegex = function(isStrict) {
return hasOwnProp(this, "_erasNarrowRegex") || computeErasParse.call(this), isStrict ? this._erasNarrowRegex : this._erasRegex;
}, proto$1.months = function(m, format) {
return m ? isArray(this._months) ? this._months[m.month()] : this._months[(this._months.isFormat || MONTHS_IN_FORMAT).test(format) ? "format" : "standalone"][m.month()] : isArray(this._months) ? this._months : this._months.standalone;
}, proto$1.monthsShort = function(m, format) {
return m ? isArray(this._monthsShort) ? this._monthsShort[m.month()] : this._monthsShort[MONTHS_IN_FORMAT.test(format) ? "format" : "standalone"][m.month()] : isArray(this._monthsShort) ? this._monthsShort : this._monthsShort.standalone;
}, proto$1.monthsParse = function(monthName, format, strict) {
var i, mom, regex;
if (this._monthsParseExact) return handleStrictParse.call(this, monthName, format, strict);
// TODO: add sorting
// Sorting makes sure if one month (or abbr) is a prefix of another
// see sorting in computeMonthsParse
for(this._monthsParse || (this._monthsParse = [], this._longMonthsParse = [], this._shortMonthsParse = []), i = 0; i < 12; i++)// test the regex
if (// make the regex if we don't have it already
mom = createUTC([
2000,
i
]), strict && !this._longMonthsParse[i] && (this._longMonthsParse[i] = RegExp("^" + this.months(mom, "").replace(".", "") + "$", "i"), this._shortMonthsParse[i] = RegExp("^" + this.monthsShort(mom, "").replace(".", "") + "$", "i")), strict || this._monthsParse[i] || (regex = "^" + this.months(mom, "") + "|^" + this.monthsShort(mom, ""), this._monthsParse[i] = RegExp(regex.replace(".", ""), "i")), strict && "MMMM" === format && this._longMonthsParse[i].test(monthName) || strict && "MMM" === format && this._shortMonthsParse[i].test(monthName) || !strict && this._monthsParse[i].test(monthName)) return i;
}, proto$1.monthsRegex = function(isStrict) {
return this._monthsParseExact ? (hasOwnProp(this, "_monthsRegex") || computeMonthsParse.call(this), isStrict) ? this._monthsStrictRegex : this._monthsRegex : (hasOwnProp(this, "_monthsRegex") || (this._monthsRegex = matchWord), this._monthsStrictRegex && isStrict ? this._monthsStrictRegex : this._monthsRegex);
}, proto$1.monthsShortRegex = function(isStrict) {
return this._monthsParseExact ? (hasOwnProp(this, "_monthsRegex") || computeMonthsParse.call(this), isStrict) ? this._monthsShortStrictRegex : this._monthsShortRegex : (hasOwnProp(this, "_monthsShortRegex") || (this._monthsShortRegex = matchWord), this._monthsShortStrictRegex && isStrict ? this._monthsShortStrictRegex : this._monthsShortRegex);
}, proto$1.week = // HELPERS
// LOCALES
function(mom) {
return weekOfYear(mom, this._week.dow, this._week.doy).week;
}, proto$1.firstDayOfYear = function() {
return this._week.doy;
}, proto$1.firstDayOfWeek = function() {
return this._week.dow;
}, proto$1.weekdays = function(m, format) {
var weekdays = isArray(this._weekdays) ? this._weekdays : this._weekdays[m && !0 !== m && this._weekdays.isFormat.test(format) ? "format" : "standalone"];
return !0 === m ? shiftWeekdays(weekdays, this._week.dow) : m ? weekdays[m.day()] : weekdays;
}, proto$1.weekdaysMin = function(m) {
return !0 === m ? shiftWeekdays(this._weekdaysMin, this._week.dow) : m ? this._weekdaysMin[m.day()] : this._weekdaysMin;
}, proto$1.weekdaysShort = function(m) {
return !0 === m ? shiftWeekdays(this._weekdaysShort, this._week.dow) : m ? this._weekdaysShort[m.day()] : this._weekdaysShort;
}, proto$1.weekdaysParse = function(weekdayName, format, strict) {
var i, mom, regex;
if (this._weekdaysParseExact) return handleStrictParse$1.call(this, weekdayName, format, strict);
for(this._weekdaysParse || (this._weekdaysParse = [], this._minWeekdaysParse = [], this._shortWeekdaysParse = [], this._fullWeekdaysParse = []), i = 0; i < 7; i++)// test the regex
if (// make the regex if we don't have it already
mom = createUTC([
2000,
1
]).day(i), strict && !this._fullWeekdaysParse[i] && (this._fullWeekdaysParse[i] = RegExp("^" + this.weekdays(mom, "").replace(".", "\\.?") + "$", "i"), this._shortWeekdaysParse[i] = RegExp("^" + this.weekdaysShort(mom, "").replace(".", "\\.?") + "$", "i"), this._minWeekdaysParse[i] = RegExp("^" + this.weekdaysMin(mom, "").replace(".", "\\.?") + "$", "i")), this._weekdaysParse[i] || (regex = "^" + this.weekdays(mom, "") + "|^" + this.weekdaysShort(mom, "") + "|^" + this.weekdaysMin(mom, ""), this._weekdaysParse[i] = RegExp(regex.replace(".", ""), "i")), strict && "dddd" === format && this._fullWeekdaysParse[i].test(weekdayName) || strict && "ddd" === format && this._shortWeekdaysParse[i].test(weekdayName) || strict && "dd" === format && this._minWeekdaysParse[i].test(weekdayName) || !strict && this._weekdaysParse[i].test(weekdayName)) return i;
}, proto$1.weekdaysRegex = function(isStrict) {
return this._weekdaysParseExact ? (hasOwnProp(this, "_weekdaysRegex") || computeWeekdaysParse.call(this), isStrict) ? this._weekdaysStrictRegex : this._weekdaysRegex : (hasOwnProp(this, "_weekdaysRegex") || (this._weekdaysRegex = matchWord), this._weekdaysStrictRegex && isStrict ? this._weekdaysStrictRegex : this._weekdaysRegex);
}, proto$1.weekdaysShortRegex = function(isStrict) {
return this._weekdaysParseExact ? (hasOwnProp(this, "_weekdaysRegex") || computeWeekdaysParse.call(this), isStrict) ? this._weekdaysShortStrictRegex : this._weekdaysShortRegex : (hasOwnProp(this, "_weekdaysShortRegex") || (this._weekdaysShortRegex = matchWord), this._weekdaysShortStrictRegex && isStrict ? this._weekdaysShortStrictRegex : this._weekdaysShortRegex);
}, proto$1.weekdaysMinRegex = function(isStrict) {
return this._weekdaysParseExact ? (hasOwnProp(this, "_weekdaysRegex") || computeWeekdaysParse.call(this), isStrict) ? this._weekdaysMinStrictRegex : this._weekdaysMinRegex : (hasOwnProp(this, "_weekdaysMinRegex") || (this._weekdaysMinRegex = matchWord), this._weekdaysMinStrictRegex && isStrict ? this._weekdaysMinStrictRegex : this._weekdaysMinRegex);
}, proto$1.isPM = // LOCALES
function(input) {
// IE8 Quirks Mode & IE7 Standards Mode do not allow accessing strings like arrays
// Using charAt should be more compatible.
return "p" === (input + "").toLowerCase().charAt(0);
}, proto$1.meridiem = function(hours, minutes, isLower) {
return hours > 11 ? isLower ? "pm" : "PM" : isLower ? "am" : "AM";
}, getSetGlobalLocale("en", {
eras: [
{
since: "0001-01-01",
until: Infinity,
offset: 1,
name: "Anno Domini",
narrow: "AD",
abbr: "AD"
},
{
since: "0000-12-31",
until: -1 / 0,
offset: 1,
name: "Before Christ",
narrow: "BC",
abbr: "BC"
}
],
dayOfMonthOrdinalParse: /\d{1,2}(th|st|nd|rd)/,
ordinal: function(number) {
var b = number % 10, output = 1 === toInt(number % 100 / 10) ? "th" : 1 === b ? "st" : 2 === b ? "nd" : 3 === b ? "rd" : "th";
return number + output;
}
}), // Side effect imports
hooks.lang = deprecate("moment.lang is deprecated. Use moment.locale instead.", getSetGlobalLocale), hooks.langData = deprecate("moment.langData is deprecated. Use moment.localeData instead.", getLocale);
var mathAbs = Math.abs;
function addSubtract$1(duration, input, value, direction) {
var other = createDuration(input, value);
return duration._milliseconds += direction * other._milliseconds, duration._days += direction * other._days, duration._months += direction * other._months, duration._bubble();
}
function absCeil(number) {
return number < 0 ? Math.floor(number) : Math.ceil(number);
}
function daysToMonths(days) {
// 400 years have 146097 days (taking into account leap year rules)
// 400 years have 12 months === 4800
return 4800 * days / 146097;
}
function monthsToDays(months) {
// the reverse of daysToMonths
return 146097 * months / 4800;
}
function makeAs(alias) {
return function() {
return this.as(alias);
};
}
var asMilliseconds = makeAs("ms"), asSeconds = makeAs("s"), asMinutes = makeAs("m"), asHours = makeAs("h"), asDays = makeAs("d"), asWeeks = makeAs("w"), asMonths = makeAs("M"), asQuarters = makeAs("Q"), asYears = makeAs("y");
function makeGetter(name) {
return function() {
return this.isValid() ? this._data[name] : NaN;
};
}
var milliseconds = makeGetter("milliseconds"), seconds = makeGetter("seconds"), minutes = makeGetter("minutes"), hours = makeGetter("hours"), days = makeGetter("days"), months = makeGetter("months"), years = makeGetter("years"), round = Math.round, thresholds = {
ss: 44,
s: 45,
m: 45,
h: 22,
d: 26,
w: null,
M: 11
};
// helper function for moment.fn.from, moment.fn.fromNow, and moment.duration.fn.humanize
function substituteTimeAgo(string, number, withoutSuffix, isFuture, locale) {
return locale.relativeTime(number || 1, !!withoutSuffix, string, isFuture);
}
var abs$1 = Math.abs;
function sign(x) {
return (x > 0) - (x < 0) || +x;
}
function toISOString$1() {
// for ISO strings we do not use the normal bubbling rules:
// * milliseconds bubble up until they become hours
// * days do not bubble at all
// * months bubble up until they become years
// This is because there is no context-free conversion between hours and days
// (think of clock changes)
// and also not between days and months (28-31 days per month)
if (!this.isValid()) return this.localeData().invalidDate();
var minutes, hours, years, s, totalSign, ymSign, daysSign, hmsSign, seconds = abs$1(this._milliseconds) / 1000, days = abs$1(this._days), months = abs$1(this._months), total = this.asSeconds();
return total ? (// 3600 seconds -> 60 minutes -> 1 hour
minutes = absFloor(seconds / 60), hours = absFloor(minutes / 60), seconds %= 60, minutes %= 60, // 12 months -> 1 year
years = absFloor(months / 12), months %= 12, // inspired by https://github.com/dordille/moment-isoduration/blob/master/moment.isoduration.js
s = seconds ? seconds.toFixed(3).replace(/\.?0+$/, "") : "", totalSign = total < 0 ? "-" : "", ymSign = sign(this._months) !== sign(total) ? "-" : "", daysSign = sign(this._days) !== sign(total) ? "-" : "", hmsSign = sign(this._milliseconds) !== sign(total) ? "-" : "", totalSign + "P" + (years ? ymSign + years + "Y" : "") + (months ? ymSign + months + "M" : "") + (days ? daysSign + days + "D" : "") + (hours || minutes || seconds ? "T" : "") + (hours ? hmsSign + hours + "H" : "") + (minutes ? hmsSign + minutes + "M" : "") + (seconds ? hmsSign + s + "S" : "")) : "P0D";
}
var proto$2 = Duration.prototype;
return proto$2.isValid = function() {
return this._isValid;
}, proto$2.abs = function() {
var data = this._data;
return this._milliseconds = mathAbs(this._milliseconds), this._days = mathAbs(this._days), this._months = mathAbs(this._months), data.milliseconds = mathAbs(data.milliseconds), data.seconds = mathAbs(data.seconds), data.minutes = mathAbs(data.minutes), data.hours = mathAbs(data.hours), data.months = mathAbs(data.months), data.years = mathAbs(data.years), this;
}, proto$2.add = // supports only 2.0-style add(1, 's') or add(duration)
function(input, value) {
return addSubtract$1(this, input, value, 1);
}, proto$2.subtract = // supports only 2.0-style subtract(1, 's') or subtract(duration)
function(input, value) {
return addSubtract$1(this, input, value, -1);
}, proto$2.as = function(units) {
if (!this.isValid()) return NaN;
var days, months, milliseconds = this._milliseconds;
if ("month" === (units = normalizeUnits(units)) || "quarter" === units || "year" === units) switch(days = this._days + milliseconds / 864e5, months = this._months + daysToMonths(days), units){
case "month":
return months;
case "quarter":
return months / 3;
case "year":
return months / 12;
}
else switch(// handle milliseconds separately because of floating point math errors (issue #1867)
days = this._days + Math.round(monthsToDays(this._months)), units){
case "week":
return days / 7 + milliseconds / 6048e5;
case "day":
return days + milliseconds / 864e5;
case "hour":
return 24 * days + milliseconds / 36e5;
case "minute":
return 1440 * days + milliseconds / 6e4;
case "second":
return 86400 * days + milliseconds / 1000;
// Math.floor prevents floating point math errors here
case "millisecond":
return Math.floor(864e5 * days) + milliseconds;
default:
throw Error("Unknown unit " + units);
}
}, proto$2.asMilliseconds = asMilliseconds, proto$2.asSeconds = asSeconds, proto$2.asMinutes = asMinutes, proto$2.asHours = asHours, proto$2.asDays = asDays, proto$2.asWeeks = asWeeks, proto$2.asMonths = asMonths, proto$2.asQuarters = asQuarters, proto$2.asYears = asYears, proto$2.valueOf = // TODO: Use this.as('ms')?
function() {
return this.isValid() ? this._milliseconds + 864e5 * this._days + this._months % 12 * 2592e6 + 31536e6 * toInt(this._months / 12) : NaN;
}, proto$2._bubble = function() {
var seconds, minutes, hours, years, monthsFromDays, milliseconds = this._milliseconds, days = this._days, months = this._months, data = this._data;
return milliseconds >= 0 && days >= 0 && months >= 0 || milliseconds <= 0 && days <= 0 && months <= 0 || (milliseconds += 864e5 * absCeil(monthsToDays(months) + days), days = 0, months = 0), // The following code bubbles up values, see the tests for
// examples of what that means.
data.milliseconds = milliseconds % 1000, data.seconds = (seconds = absFloor(milliseconds / 1000)) % 60, data.minutes = (minutes = absFloor(seconds / 60)) % 60, data.hours = (hours = absFloor(minutes / 60)) % 24, days += absFloor(hours / 24), months += // convert days to months
monthsFromDays = absFloor(daysToMonths(days)), days -= absCeil(monthsToDays(monthsFromDays)), // 12 months -> 1 year
years = absFloor(months / 12), months %= 12, data.days = days, data.months = months, data.years = years, this;
}, proto$2.clone = function() {
return createDuration(this);
}, proto$2.get = function(units) {
return units = normalizeUnits(units), this.isValid() ? this[units + "s"]() : NaN;
}, proto$2.milliseconds = milliseconds, proto$2.seconds = seconds, proto$2.minutes = minutes, proto$2.hours = hours, proto$2.days = days, proto$2.weeks = function() {
return absFloor(this.days() / 7);
}, proto$2.months = months, proto$2.years = years, proto$2.humanize = function(argWithSuffix, argThresholds) {
if (!this.isValid()) return this.localeData().invalidDate();
var withoutSuffix, thresholds1, duration, seconds, minutes, hours, days, months, weeks, years, a, locale, output, withSuffix = !1, th = thresholds;
return "object" == typeof argWithSuffix && (argThresholds = argWithSuffix, argWithSuffix = !1), "boolean" == typeof argWithSuffix && (withSuffix = argWithSuffix), "object" == typeof argThresholds && (th = Object.assign({}, thresholds, argThresholds), null != argThresholds.s && null == argThresholds.ss && (th.ss = argThresholds.s - 1)), locale = this.localeData(), withoutSuffix = !withSuffix, thresholds1 = th, duration = createDuration(this).abs(), seconds = round(duration.as("s")), minutes = round(duration.as("m")), hours = round(duration.as("h")), days = round(duration.as("d")), months = round(duration.as("M")), weeks = round(duration.as("w")), years = round(duration.as("y")), a = seconds <= thresholds1.ss && [
"s",
seconds
] || seconds < thresholds1.s && [
"ss",
seconds
] || minutes <= 1 && [
"m"
] || minutes < thresholds1.m && [
"mm",
minutes
] || hours <= 1 && [
"h"
] || hours < thresholds1.h && [
"hh",
hours
] || days <= 1 && [
"d"
] || days < thresholds1.d && [
"dd",
days
], null != thresholds1.w && (a = a || weeks <= 1 && [
"w"
] || weeks < thresholds1.w && [
"ww",
weeks
]), (a = a || months <= 1 && [
"M"
] || months < thresholds1.M && [
"MM",
months
] || years <= 1 && [
"y"
] || [
"yy",
years
])[2] = withoutSuffix, a[3] = +this > 0, a[4] = locale, output = substituteTimeAgo.apply(null, a), withSuffix && (output = locale.pastFuture(+this, output)), locale.postformat(output);
}, proto$2.toISOString = toISOString$1, proto$2.toString = toISOString$1, proto$2.toJSON = toISOString$1, proto$2.locale = locale, proto$2.localeData = localeData, proto$2.toIsoString = deprecate("toIsoString() is deprecated. Please use toISOString() instead (notice the capitals)", toISOString$1), proto$2.lang = lang, // FORMATTING
addFormatToken("X", 0, 0, "unix"), addFormatToken("x", 0, 0, "valueOf"), // PARSING
addRegexToken("x", matchSigned), addRegexToken("X", /[+-]?\d+(\.\d{1,3})?/), addParseToken("X", function(input, array, config) {
config._d = new Date(1000 * parseFloat(input));
}), addParseToken("x", function(input, array, config) {
config._d = new Date(toInt(input));
}), //! moment.js
hooks.version = "2.29.1", hookCallback = createLocal, hooks.fn = proto, hooks.min = // TODO: Use [].sort instead?
function() {
var args = [].slice.call(arguments, 0);
return pickBy("isBefore", args);
}, hooks.max = function() {
var args = [].slice.call(arguments, 0);
return pickBy("isAfter", args);
}, hooks.now = function() {
return Date.now ? Date.now() : +new Date();
}, hooks.utc = createUTC, hooks.unix = function(input) {
return createLocal(1000 * input);
}, hooks.months = function(format, index) {
return listMonthsImpl(format, index, "months");
}, hooks.isDate = isDate, hooks.locale = getSetGlobalLocale, hooks.invalid = createInvalid, hooks.duration = createDuration, hooks.isMoment = isMoment, hooks.weekdays = function(localeSorted, format, index) {
return listWeekdaysImpl(localeSorted, format, index, "weekdays");
}, hooks.parseZone = function() {
return createLocal.apply(null, arguments).parseZone();
}, hooks.localeData = getLocale, hooks.isDuration = isDuration, hooks.monthsShort = function(format, index) {
return listMonthsImpl(format, index, "monthsShort");
}, hooks.weekdaysMin = function(localeSorted, format, index) {
return listWeekdaysImpl(localeSorted, format, index, "weekdaysMin");
}, hooks.defineLocale = defineLocale, hooks.updateLocale = function(name, config) {
if (null != config) {
var locale, tmpLocale, parentConfig = baseConfig;
null != locales[name] && null != locales[name].parentLocale ? // Update existing child locale in-place to avoid memory-leaks
locales[name].set(mergeConfigs(locales[name]._config, config)) : (null != // MERGE
(tmpLocale = loadLocale(name)) && (parentConfig = tmpLocale._config), config = mergeConfigs(parentConfig, config), null == tmpLocale && // updateLocale is called for creating a new locale
// Set abbr so it will have a name (getters return
// undefined otherwise).
(config.abbr = name), (locale = new Locale(config)).parentLocale = locales[name], locales[name] = locale), // backwards compat for now: also set the locale
getSetGlobalLocale(name);
} else // pass null for config to unupdate, useful for tests
null != locales[name] && (null != locales[name].parentLocale ? (locales[name] = locales[name].parentLocale, name === getSetGlobalLocale() && getSetGlobalLocale(name)) : null != locales[name] && delete locales[name]);
return locales[name];
}, hooks.locales = function() {
return keys(locales);
}, hooks.weekdaysShort = function(localeSorted, format, index) {
return listWeekdaysImpl(localeSorted, format, index, "weekdaysShort");
}, hooks.normalizeUnits = normalizeUnits, hooks.relativeTimeRounding = // This function allows you to set the rounding function for relative time strings
function(roundingFunction) {
return void 0 === roundingFunction ? round : "function" == typeof roundingFunction && (round = roundingFunction, !0);
}, hooks.relativeTimeThreshold = // This function allows you to set a threshold for relative time strings
function(threshold, limit) {
return void 0 !== thresholds[threshold] && (void 0 === limit ? thresholds[threshold] : (thresholds[threshold] = limit, "s" === threshold && (thresholds.ss = limit - 1), !0));
}, hooks.calendarFormat = function(myMoment, now) {
var diff = myMoment.diff(now, "days", !0);
return diff < -6 ? "sameElse" : diff < -1 ? "lastWeek" : diff < 0 ? "lastDay" : diff < 1 ? "sameDay" : diff < 2 ? "nextDay" : diff < 7 ? "nextWeek" : "sameElse";
}, hooks.prototype = proto, // currently HTML5 input type only supports 24-hour formats
hooks.HTML5_FMT = {
DATETIME_LOCAL: "YYYY-MM-DDTHH:mm",
DATETIME_LOCAL_SECONDS: "YYYY-MM-DDTHH:mm:ss",
DATETIME_LOCAL_MS: "YYYY-MM-DDTHH:mm:ss.SSS",
DATE: "YYYY-MM-DD",
TIME: "HH:mm",
TIME_SECONDS: "HH:mm:ss",
TIME_MS: "HH:mm:ss.SSS",
WEEK: "GGGG-[W]WW",
MONTH: "YYYY-MM"
}, hooks;
});
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_minifier/tests/fixture/issues/murmur2/1/input.js | JavaScript | export default function murmur2(str) {
// 'm' and 'r' are mixing constants generated offline.
// They're not really 'magic', they just happen to work well.
// const m = 0x5bd1e995;
// const r = 24;
// Initialize the hash
var h = 0; // Mix 4 bytes at a time into the hash
var k,
i = 0,
len = str.length;
for (; len >= 4; ++i, len -= 4) {
k =
(str.charCodeAt(i) & 0xff) |
((str.charCodeAt(++i) & 0xff) << 8) |
((str.charCodeAt(++i) & 0xff) << 16) |
((str.charCodeAt(++i) & 0xff) << 24);
k =
/* Math.imul(k, m): */
(k & 0xffff) * 0x5bd1e995 + (((k >>> 16) * 0xe995) << 16);
k ^=
/* k >>> r: */
k >>> 24;
h =
/* Math.imul(k, m): */
((k & 0xffff) * 0x5bd1e995 + (((k >>> 16) * 0xe995) << 16)) ^
/* Math.imul(h, m): */
((h & 0xffff) * 0x5bd1e995 + (((h >>> 16) * 0xe995) << 16));
} // Handle the last few bytes of the input array
switch (len) {
case 3:
h ^= (str.charCodeAt(i + 2) & 0xff) << 16;
case 2:
h ^= (str.charCodeAt(i + 1) & 0xff) << 8;
case 1:
h ^= str.charCodeAt(i) & 0xff;
h =
/* Math.imul(h, m): */
(h & 0xffff) * 0x5bd1e995 + (((h >>> 16) * 0xe995) << 16);
} // Do a few final mixes of the hash to ensure the last few
// bytes are well-incorporated.
h ^= h >>> 13;
h =
/* Math.imul(h, m): */
(h & 0xffff) * 0x5bd1e995 + (((h >>> 16) * 0xe995) << 16);
return ((h ^ (h >>> 15)) >>> 0).toString(36);
}
function isProcessableValue(value) {
return value != null && typeof value !== "boolean";
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_minifier/tests/fixture/issues/murmur2/1/output.js | JavaScript | export default function murmur2(str) {
for(// 'm' and 'r' are mixing constants generated offline.
// They're not really 'magic', they just happen to work well.
// const m = 0x5bd1e995;
// const r = 24;
// Initialize the hash
var k, h = 0, i = 0, len = str.length; len >= 4; ++i, len -= 4)k = /* Math.imul(k, m): */ (0xffff & (k = 0xff & str.charCodeAt(i) | (0xff & str.charCodeAt(++i)) << 8 | (0xff & str.charCodeAt(++i)) << 16 | (0xff & str.charCodeAt(++i)) << 24)) * 0x5bd1e995 + ((k >>> 16) * 0xe995 << 16), k ^= /* k >>> r: */ k >>> 24, h = (0xffff & k) * 0x5bd1e995 + ((k >>> 16) * 0xe995 << 16) ^ /* Math.imul(h, m): */ (0xffff & h) * 0x5bd1e995 + ((h >>> 16) * 0xe995 << 16);
// Handle the last few bytes of the input array
switch(len){
case 3:
h ^= (0xff & str.charCodeAt(i + 2)) << 16;
case 2:
h ^= (0xff & str.charCodeAt(i + 1)) << 8;
case 1:
h ^= 0xff & str.charCodeAt(i), h = /* Math.imul(h, m): */ (0xffff & h) * 0x5bd1e995 + ((h >>> 16) * 0xe995 << 16);
} // Do a few final mixes of the hash to ensure the last few
return(// bytes are well-incorporated.
h ^= h >>> 13, (((h = /* Math.imul(h, m): */ (0xffff & h) * 0x5bd1e995 + ((h >>> 16) * 0xe995 << 16)) ^ h >>> 15) >>> 0).toString(36));
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_minifier/tests/fixture/issues/quagga2/1.4.2/1/input.js | JavaScript | (function webpackUniversalModuleDefinition(root, factory) {
if (typeof exports === "object" && typeof module === "object")
module.exports = factory();
else if (typeof define === "function" && define.amd) define([], factory);
else if (typeof exports === "object") exports["Quagga"] = factory();
else root["Quagga"] = factory();
})(window, function () {
return /******/ (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 = 89));
/******/
})(
/************************************************************************/
/******/ [
/* 0 */
/***/ function (module, exports) {
function _defineProperty(obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true,
});
} else {
obj[key] = value;
}
return obj;
}
module.exports = _defineProperty;
(module.exports["default"] = module.exports),
(module.exports.__esModule = true);
/***/
},
/* 1 */
/***/ function (module, exports) {
function _assertThisInitialized(self) {
if (self === void 0) {
throw new ReferenceError(
"this hasn't been initialised - super() hasn't been called"
);
}
return self;
}
module.exports = _assertThisInitialized;
(module.exports["default"] = module.exports),
(module.exports.__esModule = true);
/***/
},
/* 2 */
/***/ function (module, exports) {
function _getPrototypeOf(o) {
module.exports = _getPrototypeOf = Object.setPrototypeOf
? Object.getPrototypeOf
: function _getPrototypeOf(o) {
return o.__proto__ || Object.getPrototypeOf(o);
};
(module.exports["default"] = module.exports),
(module.exports.__esModule = true);
return _getPrototypeOf(o);
}
module.exports = _getPrototypeOf;
(module.exports["default"] = module.exports),
(module.exports.__esModule = true);
/***/
},
/* 3 */
/***/ function (module, exports) {
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError(
"Cannot call a class as a function"
);
}
}
module.exports = _classCallCheck;
(module.exports["default"] = module.exports),
(module.exports.__esModule = true);
/***/
},
/* 4 */
/***/ function (module, exports) {
function _defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor) descriptor.writable = true;
Object.defineProperty(
target,
descriptor.key,
descriptor
);
}
}
function _createClass(Constructor, protoProps, staticProps) {
if (protoProps)
_defineProperties(Constructor.prototype, protoProps);
if (staticProps)
_defineProperties(Constructor, staticProps);
return Constructor;
}
module.exports = _createClass;
(module.exports["default"] = module.exports),
(module.exports.__esModule = true);
/***/
},
/* 5 */
/***/ function (module, exports, __webpack_require__) {
var _typeof = __webpack_require__(19)["default"];
var assertThisInitialized = __webpack_require__(1);
function _possibleConstructorReturn(self, call) {
if (
call &&
(_typeof(call) === "object" ||
typeof call === "function")
) {
return call;
} else if (call !== void 0) {
throw new TypeError(
"Derived constructors may only return object or undefined"
);
}
return assertThisInitialized(self);
}
module.exports = _possibleConstructorReturn;
(module.exports["default"] = module.exports),
(module.exports.__esModule = true);
/***/
},
/* 6 */
/***/ function (module, exports, __webpack_require__) {
var setPrototypeOf = __webpack_require__(41);
function _inherits(subClass, superClass) {
if (
typeof superClass !== "function" &&
superClass !== null
) {
throw new TypeError(
"Super expression must either be null or a function"
);
}
subClass.prototype = Object.create(
superClass && superClass.prototype,
{
constructor: {
value: subClass,
writable: true,
configurable: true,
},
}
);
if (superClass) setPrototypeOf(subClass, superClass);
}
module.exports = _inherits;
(module.exports["default"] = module.exports),
(module.exports.__esModule = true);
/***/
},
/* 7 */
/***/ function (module, exports, __webpack_require__) {
module.exports = {
EPSILON: __webpack_require__(62),
create: __webpack_require__(63),
clone: __webpack_require__(156),
fromValues: __webpack_require__(157),
copy: __webpack_require__(158),
set: __webpack_require__(159),
equals: __webpack_require__(160),
exactEquals: __webpack_require__(161),
add: __webpack_require__(162),
subtract: __webpack_require__(64),
sub: __webpack_require__(163),
multiply: __webpack_require__(65),
mul: __webpack_require__(164),
divide: __webpack_require__(66),
div: __webpack_require__(165),
inverse: __webpack_require__(166),
min: __webpack_require__(167),
max: __webpack_require__(168),
rotate: __webpack_require__(169),
floor: __webpack_require__(170),
ceil: __webpack_require__(171),
round: __webpack_require__(172),
scale: __webpack_require__(173),
scaleAndAdd: __webpack_require__(174),
distance: __webpack_require__(67),
dist: __webpack_require__(175),
squaredDistance: __webpack_require__(68),
sqrDist: __webpack_require__(176),
length: __webpack_require__(69),
len: __webpack_require__(177),
squaredLength: __webpack_require__(70),
sqrLen: __webpack_require__(178),
negate: __webpack_require__(179),
normalize: __webpack_require__(180),
dot: __webpack_require__(181),
cross: __webpack_require__(182),
lerp: __webpack_require__(183),
random: __webpack_require__(184),
transformMat2: __webpack_require__(185),
transformMat2d: __webpack_require__(186),
transformMat3: __webpack_require__(187),
transformMat4: __webpack_require__(188),
forEach: __webpack_require__(189),
limit: __webpack_require__(190),
};
/***/
},
/* 8 */
/***/ function (module, __webpack_exports__, __webpack_require__) {
"use strict";
// EXPORTS
__webpack_require__.d(__webpack_exports__, "h", function () {
return /* binding */ imageRef;
});
__webpack_require__.d(__webpack_exports__, "i", function () {
return /* binding */ otsuThreshold;
});
__webpack_require__.d(__webpack_exports__, "b", function () {
return /* binding */ cv_utils_cluster;
});
__webpack_require__.d(__webpack_exports__, "j", function () {
return /* binding */ topGeneric;
});
__webpack_require__.d(__webpack_exports__, "e", function () {
return /* binding */ grayAndHalfSampleFromCanvasData;
});
__webpack_require__.d(__webpack_exports__, "c", function () {
return /* binding */ computeGray;
});
__webpack_require__.d(__webpack_exports__, "f", function () {
return /* binding */ halfSample;
});
__webpack_require__.d(__webpack_exports__, "g", function () {
return /* binding */ hsv2rgb;
});
__webpack_require__.d(__webpack_exports__, "a", function () {
return /* binding */ calculatePatchSize;
});
__webpack_require__.d(__webpack_exports__, "d", function () {
return /* binding */ computeImageArea;
});
// UNUSED EXPORTS: computeIntegralImage2, computeIntegralImage, thresholdImage, computeHistogram, sharpenLine, determineOtsuThreshold, computeBinaryImage, Tracer, DILATE, ERODE, dilate, erode, subtract, bitwiseOr, countNonZero, grayArrayFromImage, grayArrayFromContext, loadImageArray, _computeDivisors, _parseCSSDimensionValues, _dimensionsConverters
// EXTERNAL MODULE: ./node_modules/gl-vec2/index.js
var gl_vec2 = __webpack_require__(7);
// EXTERNAL MODULE: ./node_modules/gl-vec3/index.js
var gl_vec3 = __webpack_require__(84);
// CONCATENATED MODULE: ./src/common/cluster.js
// TODO: cluster.js and cv_utils.js are pretty tightly intertwined, making for a complex conversion
// into typescript. be warned. :-)
var vec2 = {
clone: gl_vec2["clone"],
dot: gl_vec2["dot"],
};
/**
* Creates a cluster for grouping similar orientations of datapoints
*/
/* harmony default export */ var cluster = {
create: function create(point, threshold) {
var points = [];
var center = {
rad: 0,
vec: vec2.clone([0, 0]),
};
var pointMap = {};
function _add(pointToAdd) {
pointMap[pointToAdd.id] = pointToAdd;
points.push(pointToAdd);
}
function updateCenter() {
var i;
var sum = 0;
for (i = 0; i < points.length; i++) {
sum += points[i].rad;
}
center.rad = sum / points.length;
center.vec = vec2.clone([
Math.cos(center.rad),
Math.sin(center.rad),
]);
}
function init() {
_add(point);
updateCenter();
}
init();
return {
add: function add(pointToAdd) {
if (!pointMap[pointToAdd.id]) {
_add(pointToAdd);
updateCenter();
}
},
fits: function fits(otherPoint) {
// check cosine similarity to center-angle
var similarity = Math.abs(
vec2.dot(otherPoint.point.vec, center.vec)
);
if (similarity > threshold) {
return true;
}
return false;
},
getPoints: function getPoints() {
return points;
},
getCenter: function getCenter() {
return center;
},
};
},
createPoint: function createPoint(newPoint, id, property) {
return {
rad: newPoint[property],
point: newPoint,
id: id,
};
},
};
// EXTERNAL MODULE: ./src/common/array_helper.ts
var array_helper = __webpack_require__(10);
// CONCATENATED MODULE: ./src/common/cv_utils.js
/* eslint-disable no-mixed-operators */
/* eslint-disable no-bitwise */
var cv_utils_vec2 = {
clone: gl_vec2["clone"],
};
var vec3 = {
clone: gl_vec3["clone"],
};
/**
* @param x x-coordinate
* @param y y-coordinate
* @return ImageReference {x,y} Coordinate
*/
function imageRef(x, y) {
var that = {
x: x,
y: y,
toVec2: function toVec2() {
return cv_utils_vec2.clone([this.x, this.y]);
},
toVec3: function toVec3() {
return vec3.clone([this.x, this.y, 1]);
},
round: function round() {
this.x =
this.x > 0.0
? Math.floor(this.x + 0.5)
: Math.floor(this.x - 0.5);
this.y =
this.y > 0.0
? Math.floor(this.y + 0.5)
: Math.floor(this.y - 0.5);
return this;
},
};
return that;
}
/**
* Computes an integral image of a given grayscale image.
* @param imageDataContainer {ImageDataContainer} the image to be integrated
*/
function computeIntegralImage2(imageWrapper, integralWrapper) {
var imageData = imageWrapper.data;
var width = imageWrapper.size.x;
var height = imageWrapper.size.y;
var integralImageData = integralWrapper.data;
var sum = 0;
var posA = 0;
var posB = 0;
var posC = 0;
var posD = 0;
var x;
var y; // sum up first column
posB = width;
sum = 0;
for (y = 1; y < height; y++) {
sum += imageData[posA];
integralImageData[posB] += sum;
posA += width;
posB += width;
}
posA = 0;
posB = 1;
sum = 0;
for (x = 1; x < width; x++) {
sum += imageData[posA];
integralImageData[posB] += sum;
posA++;
posB++;
}
for (y = 1; y < height; y++) {
posA = y * width + 1;
posB = (y - 1) * width + 1;
posC = y * width;
posD = (y - 1) * width;
for (x = 1; x < width; x++) {
integralImageData[posA] +=
imageData[posA] +
integralImageData[posB] +
integralImageData[posC] -
integralImageData[posD];
posA++;
posB++;
posC++;
posD++;
}
}
}
function computeIntegralImage(imageWrapper, integralWrapper) {
var imageData = imageWrapper.data;
var width = imageWrapper.size.x;
var height = imageWrapper.size.y;
var integralImageData = integralWrapper.data;
var sum = 0; // sum up first row
for (var i = 0; i < width; i++) {
sum += imageData[i];
integralImageData[i] = sum;
}
for (var v = 1; v < height; v++) {
sum = 0;
for (var u = 0; u < width; u++) {
sum += imageData[v * width + u];
integralImageData[v * width + u] =
sum + integralImageData[(v - 1) * width + u];
}
}
}
function thresholdImage(
imageWrapper,
threshold,
targetWrapper
) {
if (!targetWrapper) {
// eslint-disable-next-line no-param-reassign
targetWrapper = imageWrapper;
}
var imageData = imageWrapper.data;
var length = imageData.length;
var targetData = targetWrapper.data;
while (length--) {
targetData[length] =
imageData[length] < threshold ? 1 : 0;
}
}
function computeHistogram(imageWrapper, bitsPerPixel) {
if (!bitsPerPixel) {
// eslint-disable-next-line no-param-reassign
bitsPerPixel = 8;
}
var imageData = imageWrapper.data;
var length = imageData.length;
var bitShift = 8 - bitsPerPixel;
var bucketCnt = 1 << bitsPerPixel;
var hist = new Int32Array(bucketCnt);
while (length--) {
hist[imageData[length] >> bitShift]++;
}
return hist;
}
function sharpenLine(line) {
var i;
var length = line.length;
var left = line[0];
var center = line[1];
var right;
for (i = 1; i < length - 1; i++) {
right = line[i + 1]; // -1 4 -1 kernel
// eslint-disable-next-line no-param-reassign
line[i - 1] = (center * 2 - left - right) & 255;
left = center;
center = right;
}
return line;
}
function determineOtsuThreshold(imageWrapper) {
var bitsPerPixel =
arguments.length > 1 && arguments[1] !== undefined
? arguments[1]
: 8;
var hist;
var bitShift = 8 - bitsPerPixel;
function px(init, end) {
var sum = 0;
for (var i = init; i <= end; i++) {
sum += hist[i];
}
return sum;
}
function mx(init, end) {
var sum = 0;
for (var i = init; i <= end; i++) {
sum += i * hist[i];
}
return sum;
}
function determineThreshold() {
var vet = [0];
var p1;
var p2;
var p12;
var m1;
var m2;
var m12;
var max = (1 << bitsPerPixel) - 1;
hist = computeHistogram(imageWrapper, bitsPerPixel);
for (var k = 1; k < max; k++) {
p1 = px(0, k);
p2 = px(k + 1, max);
p12 = p1 * p2;
if (p12 === 0) {
p12 = 1;
}
m1 = mx(0, k) * p2;
m2 = mx(k + 1, max) * p1;
m12 = m1 - m2;
vet[k] = (m12 * m12) / p12;
}
return array_helper["a" /* default */].maxIndex(vet);
}
var threshold = determineThreshold();
return threshold << bitShift;
}
function otsuThreshold(imageWrapper, targetWrapper) {
var threshold = determineOtsuThreshold(imageWrapper);
thresholdImage(imageWrapper, threshold, targetWrapper);
return threshold;
} // local thresholding
function computeBinaryImage(
imageWrapper,
integralWrapper,
targetWrapper
) {
computeIntegralImage(imageWrapper, integralWrapper);
if (!targetWrapper) {
// eslint-disable-next-line no-param-reassign
targetWrapper = imageWrapper;
}
var imageData = imageWrapper.data;
var targetData = targetWrapper.data;
var width = imageWrapper.size.x;
var height = imageWrapper.size.y;
var integralImageData = integralWrapper.data;
var sum = 0;
var v;
var u;
var kernel = 3;
var A;
var B;
var C;
var D;
var avg;
var size = (kernel * 2 + 1) * (kernel * 2 + 1); // clear out top & bottom-border
for (v = 0; v <= kernel; v++) {
for (u = 0; u < width; u++) {
targetData[v * width + u] = 0;
targetData[(height - 1 - v) * width + u] = 0;
}
} // clear out left & right border
for (v = kernel; v < height - kernel; v++) {
for (u = 0; u <= kernel; u++) {
targetData[v * width + u] = 0;
targetData[v * width + (width - 1 - u)] = 0;
}
}
for (v = kernel + 1; v < height - kernel - 1; v++) {
for (u = kernel + 1; u < width - kernel; u++) {
A =
integralImageData[
(v - kernel - 1) * width + (u - kernel - 1)
];
B =
integralImageData[
(v - kernel - 1) * width + (u + kernel)
];
C =
integralImageData[
(v + kernel) * width + (u - kernel - 1)
];
D =
integralImageData[
(v + kernel) * width + (u + kernel)
];
sum = D - C - B + A;
avg = sum / size;
targetData[v * width + u] =
imageData[v * width + u] > avg + 5 ? 0 : 1;
}
}
}
function cv_utils_cluster(points, threshold, property) {
var i;
var k;
var thisCluster;
var point;
var clusters = [];
if (!property) {
// eslint-disable-next-line no-param-reassign
property = "rad";
}
function addToCluster(newPoint) {
var found = false;
for (k = 0; k < clusters.length; k++) {
thisCluster = clusters[k];
if (thisCluster.fits(newPoint)) {
thisCluster.add(newPoint);
found = true;
}
}
return found;
} // iterate over each cloud
for (i = 0; i < points.length; i++) {
point = cluster.createPoint(points[i], i, property);
if (!addToCluster(point)) {
clusters.push(cluster.create(point, threshold));
}
}
return clusters;
}
var Tracer = {
trace: function trace(points, vec) {
var iteration;
var maxIterations = 10;
var top = [];
var result = [];
var centerPos = 0;
var currentPos = 0;
function trace(idx, forward) {
var to;
var toIdx;
var predictedPos;
var thresholdX = 1;
var thresholdY = Math.abs(vec[1] / 10);
var found = false;
function match(pos, predicted) {
if (
pos.x > predicted.x - thresholdX &&
pos.x < predicted.x + thresholdX &&
pos.y > predicted.y - thresholdY &&
pos.y < predicted.y + thresholdY
) {
return true;
}
return false;
} // check if the next index is within the vec specifications
// if not, check as long as the threshold is met
var from = points[idx];
if (forward) {
predictedPos = {
x: from.x + vec[0],
y: from.y + vec[1],
};
} else {
predictedPos = {
x: from.x - vec[0],
y: from.y - vec[1],
};
}
toIdx = forward ? idx + 1 : idx - 1;
to = points[toIdx]; // eslint-disable-next-line no-cond-assign
while (
to &&
(found = match(to, predictedPos)) !== true &&
Math.abs(to.y - from.y) < vec[1]
) {
toIdx = forward ? toIdx + 1 : toIdx - 1;
to = points[toIdx];
}
return found ? toIdx : null;
}
for (
iteration = 0;
iteration < maxIterations;
iteration++
) {
// randomly select point to start with
centerPos = Math.floor(
Math.random() * points.length
); // trace forward
top = [];
currentPos = centerPos;
top.push(points[currentPos]); // eslint-disable-next-line no-cond-assign
while (
(currentPos = trace(currentPos, true)) !== null
) {
top.push(points[currentPos]);
}
if (centerPos > 0) {
currentPos = centerPos; // eslint-disable-next-line no-cond-assign
while (
(currentPos = trace(currentPos, false)) !==
null
) {
top.push(points[currentPos]);
}
}
if (top.length > result.length) {
result = top;
}
}
return result;
},
};
var DILATE = 1;
var ERODE = 2;
function dilate(inImageWrapper, outImageWrapper) {
var v;
var u;
var inImageData = inImageWrapper.data;
var outImageData = outImageWrapper.data;
var height = inImageWrapper.size.y;
var width = inImageWrapper.size.x;
var sum;
var yStart1;
var yStart2;
var xStart1;
var xStart2;
for (v = 1; v < height - 1; v++) {
for (u = 1; u < width - 1; u++) {
yStart1 = v - 1;
yStart2 = v + 1;
xStart1 = u - 1;
xStart2 = u + 1;
sum =
inImageData[yStart1 * width + xStart1] +
inImageData[yStart1 * width + xStart2] +
inImageData[v * width + u] +
inImageData[yStart2 * width + xStart1] +
inImageData[yStart2 * width + xStart2];
outImageData[v * width + u] = sum > 0 ? 1 : 0;
}
}
}
function erode(inImageWrapper, outImageWrapper) {
var v;
var u;
var inImageData = inImageWrapper.data;
var outImageData = outImageWrapper.data;
var height = inImageWrapper.size.y;
var width = inImageWrapper.size.x;
var sum;
var yStart1;
var yStart2;
var xStart1;
var xStart2;
for (v = 1; v < height - 1; v++) {
for (u = 1; u < width - 1; u++) {
yStart1 = v - 1;
yStart2 = v + 1;
xStart1 = u - 1;
xStart2 = u + 1;
sum =
inImageData[yStart1 * width + xStart1] +
inImageData[yStart1 * width + xStart2] +
inImageData[v * width + u] +
inImageData[yStart2 * width + xStart1] +
inImageData[yStart2 * width + xStart2];
outImageData[v * width + u] = sum === 5 ? 1 : 0;
}
}
}
function subtract(
aImageWrapper,
bImageWrapper,
resultImageWrapper
) {
if (!resultImageWrapper) {
// eslint-disable-next-line no-param-reassign
resultImageWrapper = aImageWrapper;
}
var length = aImageWrapper.data.length;
var aImageData = aImageWrapper.data;
var bImageData = bImageWrapper.data;
var cImageData = resultImageWrapper.data;
while (length--) {
cImageData[length] =
aImageData[length] - bImageData[length];
}
}
function bitwiseOr(
aImageWrapper,
bImageWrapper,
resultImageWrapper
) {
if (!resultImageWrapper) {
// eslint-disable-next-line no-param-reassign
resultImageWrapper = aImageWrapper;
}
var length = aImageWrapper.data.length;
var aImageData = aImageWrapper.data;
var bImageData = bImageWrapper.data;
var cImageData = resultImageWrapper.data;
while (length--) {
cImageData[length] =
aImageData[length] || bImageData[length];
}
}
function countNonZero(imageWrapper) {
var length = imageWrapper.data.length;
var data = imageWrapper.data;
var sum = 0;
while (length--) {
sum += data[length];
}
return sum;
}
function topGeneric(list, top, scoreFunc) {
var i;
var minIdx = 0;
var min = 0;
var queue = [];
var score;
var hit;
var pos;
for (i = 0; i < top; i++) {
queue[i] = {
score: 0,
item: null,
};
}
for (i = 0; i < list.length; i++) {
score = scoreFunc.apply(this, [list[i]]);
if (score > min) {
hit = queue[minIdx];
hit.score = score;
hit.item = list[i];
min = Number.MAX_VALUE;
for (pos = 0; pos < top; pos++) {
if (queue[pos].score < min) {
min = queue[pos].score;
minIdx = pos;
}
}
}
}
return queue;
}
function grayArrayFromImage(htmlImage, offsetX, ctx, array) {
ctx.drawImage(
htmlImage,
offsetX,
0,
htmlImage.width,
htmlImage.height
);
var ctxData = ctx.getImageData(
offsetX,
0,
htmlImage.width,
htmlImage.height
).data;
computeGray(ctxData, array);
}
function grayArrayFromContext(ctx, size, offset, array) {
var ctxData = ctx.getImageData(
offset.x,
offset.y,
size.x,
size.y
).data;
computeGray(ctxData, array);
}
function grayAndHalfSampleFromCanvasData(
canvasData,
size,
outArray
) {
var topRowIdx = 0;
var bottomRowIdx = size.x;
var endIdx = Math.floor(canvasData.length / 4);
var outWidth = size.x / 2;
var outImgIdx = 0;
var inWidth = size.x;
var i;
while (bottomRowIdx < endIdx) {
for (i = 0; i < outWidth; i++) {
// eslint-disable-next-line no-param-reassign
outArray[outImgIdx] =
(0.299 * canvasData[topRowIdx * 4 + 0] +
0.587 * canvasData[topRowIdx * 4 + 1] +
0.114 * canvasData[topRowIdx * 4 + 2] +
(0.299 *
canvasData[(topRowIdx + 1) * 4 + 0] +
0.587 *
canvasData[
(topRowIdx + 1) * 4 + 1
] +
0.114 *
canvasData[
(topRowIdx + 1) * 4 + 2
]) +
(0.299 * canvasData[bottomRowIdx * 4 + 0] +
0.587 *
canvasData[bottomRowIdx * 4 + 1] +
0.114 *
canvasData[bottomRowIdx * 4 + 2]) +
(0.299 *
canvasData[(bottomRowIdx + 1) * 4 + 0] +
0.587 *
canvasData[
(bottomRowIdx + 1) * 4 + 1
] +
0.114 *
canvasData[
(bottomRowIdx + 1) * 4 + 2
])) /
4;
outImgIdx++;
topRowIdx += 2;
bottomRowIdx += 2;
}
topRowIdx += inWidth;
bottomRowIdx += inWidth;
}
}
function computeGray(imageData, outArray, config) {
var l = (imageData.length / 4) | 0;
var singleChannel = config && config.singleChannel === true;
if (singleChannel) {
for (var i = 0; i < l; i++) {
// eslint-disable-next-line no-param-reassign
outArray[i] = imageData[i * 4 + 0];
}
} else {
for (var _i = 0; _i < l; _i++) {
// eslint-disable-next-line no-param-reassign
outArray[_i] =
0.299 * imageData[_i * 4 + 0] +
0.587 * imageData[_i * 4 + 1] +
0.114 * imageData[_i * 4 + 2];
}
}
}
function loadImageArray(src, callback) {
var canvas =
arguments.length > 2 && arguments[2] !== undefined
? arguments[2]
: document && document.createElement("canvas");
var img = new Image();
img.callback = callback;
img.onload = function () {
// eslint-disable-next-line no-param-reassign
canvas.width = this.width; // eslint-disable-next-line no-param-reassign
canvas.height = this.height;
var ctx = canvas.getContext("2d");
ctx.drawImage(this, 0, 0);
var array = new Uint8Array(this.width * this.height);
ctx.drawImage(this, 0, 0);
var _ctx$getImageData = ctx.getImageData(
0,
0,
this.width,
this.height
),
data = _ctx$getImageData.data;
computeGray(data, array);
this.callback(
array,
{
x: this.width,
y: this.height,
},
this
);
};
img.src = src;
}
/**
* @param inImg {ImageWrapper} input image to be sampled
* @param outImg {ImageWrapper} to be stored in
*/
function halfSample(inImgWrapper, outImgWrapper) {
var inImg = inImgWrapper.data;
var inWidth = inImgWrapper.size.x;
var outImg = outImgWrapper.data;
var topRowIdx = 0;
var bottomRowIdx = inWidth;
var endIdx = inImg.length;
var outWidth = inWidth / 2;
var outImgIdx = 0;
while (bottomRowIdx < endIdx) {
for (var i = 0; i < outWidth; i++) {
outImg[outImgIdx] = Math.floor(
(inImg[topRowIdx] +
inImg[topRowIdx + 1] +
inImg[bottomRowIdx] +
inImg[bottomRowIdx + 1]) /
4
);
outImgIdx++;
topRowIdx += 2;
bottomRowIdx += 2;
}
topRowIdx += inWidth;
bottomRowIdx += inWidth;
}
}
function hsv2rgb(hsv) {
var rgb =
arguments.length > 1 && arguments[1] !== undefined
? arguments[1]
: [0, 0, 0];
var h = hsv[0];
var s = hsv[1];
var v = hsv[2];
var c = v * s;
var x = c * (1 - Math.abs(((h / 60) % 2) - 1));
var m = v - c;
var r = 0;
var g = 0;
var b = 0;
if (h < 60) {
r = c;
g = x;
} else if (h < 120) {
r = x;
g = c;
} else if (h < 180) {
g = c;
b = x;
} else if (h < 240) {
g = x;
b = c;
} else if (h < 300) {
r = x;
b = c;
} else if (h < 360) {
r = c;
b = x;
} // eslint-disable-next-line no-param-reassign
rgb[0] = ((r + m) * 255) | 0; // eslint-disable-next-line no-param-reassign
rgb[1] = ((g + m) * 255) | 0; // eslint-disable-next-line no-param-reassign
rgb[2] = ((b + m) * 255) | 0;
return rgb;
}
function _computeDivisors(n) {
var largeDivisors = [];
var divisors = [];
for (var i = 1; i < Math.sqrt(n) + 1; i++) {
if (n % i === 0) {
divisors.push(i);
if (i !== n / i) {
largeDivisors.unshift(Math.floor(n / i));
}
}
}
return divisors.concat(largeDivisors);
}
function _computeIntersection(arr1, arr2) {
var i = 0;
var j = 0;
var result = [];
while (i < arr1.length && j < arr2.length) {
if (arr1[i] === arr2[j]) {
result.push(arr1[i]);
i++;
j++;
} else if (arr1[i] > arr2[j]) {
j++;
} else {
i++;
}
}
return result;
}
function calculatePatchSize(patchSize, imgSize) {
var divisorsX = _computeDivisors(imgSize.x);
var divisorsY = _computeDivisors(imgSize.y);
var wideSide = Math.max(imgSize.x, imgSize.y);
var common = _computeIntersection(divisorsX, divisorsY);
var nrOfPatchesList = [8, 10, 15, 20, 32, 60, 80];
var nrOfPatchesMap = {
"x-small": 5,
small: 4,
medium: 3,
large: 2,
"x-large": 1,
};
var nrOfPatchesIdx =
nrOfPatchesMap[patchSize] || nrOfPatchesMap.medium;
var nrOfPatches = nrOfPatchesList[nrOfPatchesIdx];
var desiredPatchSize = Math.floor(wideSide / nrOfPatches);
var optimalPatchSize;
function findPatchSizeForDivisors(divisors) {
var i = 0;
var found = divisors[Math.floor(divisors.length / 2)];
while (
i < divisors.length - 1 &&
divisors[i] < desiredPatchSize
) {
i++;
}
if (i > 0) {
if (
Math.abs(divisors[i] - desiredPatchSize) >
Math.abs(divisors[i - 1] - desiredPatchSize)
) {
found = divisors[i - 1];
} else {
found = divisors[i];
}
}
if (
desiredPatchSize / found <
nrOfPatchesList[nrOfPatchesIdx + 1] /
nrOfPatchesList[nrOfPatchesIdx] &&
desiredPatchSize / found >
nrOfPatchesList[nrOfPatchesIdx - 1] /
nrOfPatchesList[nrOfPatchesIdx]
) {
return {
x: found,
y: found,
};
}
return null;
}
optimalPatchSize = findPatchSizeForDivisors(common);
if (!optimalPatchSize) {
optimalPatchSize = findPatchSizeForDivisors(
_computeDivisors(wideSide)
);
if (!optimalPatchSize) {
optimalPatchSize = findPatchSizeForDivisors(
_computeDivisors(desiredPatchSize * nrOfPatches)
);
}
}
return optimalPatchSize;
}
function _parseCSSDimensionValues(value) {
var dimension = {
value: parseFloat(value),
unit:
value.indexOf("%") === value.length - 1 ? "%" : "%",
};
return dimension;
}
var _dimensionsConverters = {
top: function top(dimension, context) {
return dimension.unit === "%"
? Math.floor(
context.height * (dimension.value / 100)
)
: null;
},
right: function right(dimension, context) {
return dimension.unit === "%"
? Math.floor(
context.width -
context.width * (dimension.value / 100)
)
: null;
},
bottom: function bottom(dimension, context) {
return dimension.unit === "%"
? Math.floor(
context.height -
context.height * (dimension.value / 100)
)
: null;
},
left: function left(dimension, context) {
return dimension.unit === "%"
? Math.floor(
context.width * (dimension.value / 100)
)
: null;
},
};
function computeImageArea(inputWidth, inputHeight, area) {
var context = {
width: inputWidth,
height: inputHeight,
};
var parsedArea = Object.keys(area).reduce(function (
result,
key
) {
var value = area[key];
var parsed = _parseCSSDimensionValues(value);
var calculated = _dimensionsConverters[key](
parsed,
context
); // eslint-disable-next-line no-param-reassign
result[key] = calculated;
return result;
},
{});
return {
sx: parsedArea.left,
sy: parsedArea.top,
sw: parsedArea.right - parsedArea.left,
sh: parsedArea.bottom - parsedArea.top,
};
}
/***/
},
/* 9 */
/***/ function (module, __webpack_exports__, __webpack_require__) {
"use strict";
// TODO: XYPosition should be an XYObject, but that breaks XYDefinition, which breaks drawPath() below.
// XYDefinition tells us which component of a given array or object is the "X" and which is the "Y".
// Usually this is 0 for X and 1 for Y, but might be used as 'x' for x and 'y' for Y.
/* harmony default export */ __webpack_exports__["a"] = {
drawRect: function drawRect(pos, size, ctx, style) {
ctx.strokeStyle = style.color;
ctx.fillStyle = style.color;
ctx.lineWidth = style.lineWidth || 1;
ctx.beginPath();
ctx.strokeRect(pos.x, pos.y, size.x, size.y);
},
drawPath: function drawPath(path, def, ctx, style) {
ctx.strokeStyle = style.color;
ctx.fillStyle = style.color;
ctx.lineWidth = style.lineWidth;
ctx.beginPath();
ctx.moveTo(path[0][def.x], path[0][def.y]);
for (var j = 1; j < path.length; j++) {
ctx.lineTo(path[j][def.x], path[j][def.y]);
}
ctx.closePath();
ctx.stroke();
},
drawImage: function drawImage(imageData, size, ctx) {
var canvasData = ctx.getImageData(0, 0, size.x, size.y);
var data = canvasData.data;
var canvasDataPos = data.length;
var imageDataPos = imageData.length;
if (canvasDataPos / imageDataPos !== 4) {
return false;
}
while (imageDataPos--) {
var value = imageData[imageDataPos];
data[--canvasDataPos] = 255;
data[--canvasDataPos] = value;
data[--canvasDataPos] = value;
data[--canvasDataPos] = value;
}
ctx.putImageData(canvasData, 0, 0);
return true;
},
};
/***/
},
/* 10 */
/***/ function (module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony default export */ __webpack_exports__["a"] = {
init: function init(arr, val) {
// arr.fill(val);
var l = arr.length;
while (l--) {
arr[l] = val;
}
},
/**
* Shuffles the content of an array
*/
shuffle: function shuffle(arr) {
var i = arr.length - 1;
for (i; i >= 0; i--) {
var j = Math.floor(Math.random() * i);
var x = arr[i];
arr[i] = arr[j];
arr[j] = x;
}
return arr;
},
toPointList: function toPointList(arr) {
var rows = arr.reduce(function (p, n) {
var row = "[".concat(n.join(","), "]");
p.push(row);
return p;
}, []);
return "[".concat(rows.join(",\r\n"), "]");
},
/**
* returns the elements which's score is bigger than the threshold
*/
threshold: function threshold(arr, _threshold, scoreFunc) {
var queue = arr.reduce(function (prev, next) {
if (scoreFunc.apply(arr, [next]) >= _threshold) {
prev.push(next);
}
return prev;
}, []);
return queue;
},
maxIndex: function maxIndex(arr) {
var max = 0;
for (var i = 0; i < arr.length; i++) {
if (arr[i] > arr[max]) {
max = i;
}
}
return max;
},
max: function max(arr) {
var max = 0;
for (var i = 0; i < arr.length; i++) {
if (arr[i] > max) {
max = arr[i];
}
}
return max;
},
sum: function sum(arr) {
var length = arr.length;
var sum = 0;
while (length--) {
sum += arr[length];
}
return sum;
},
};
/***/
},
/* 11 */
/***/ function (module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony import */ var _babel_runtime_helpers_slicedToArray__WEBPACK_IMPORTED_MODULE_0__ =
__webpack_require__(83);
/* harmony import */ var _babel_runtime_helpers_slicedToArray__WEBPACK_IMPORTED_MODULE_0___default =
/*#__PURE__*/ __webpack_require__.n(
_babel_runtime_helpers_slicedToArray__WEBPACK_IMPORTED_MODULE_0__
);
/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_1__ =
__webpack_require__(3);
/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_1___default =
/*#__PURE__*/ __webpack_require__.n(
_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_1__
);
/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_2__ =
__webpack_require__(4);
/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_2___default =
/*#__PURE__*/ __webpack_require__.n(
_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_2__
);
/* harmony import */ var _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_3__ =
__webpack_require__(0);
/* harmony import */ var _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_3___default =
/*#__PURE__*/ __webpack_require__.n(
_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_3__
);
/* harmony import */ var gl_vec2__WEBPACK_IMPORTED_MODULE_4__ =
__webpack_require__(7);
/* harmony import */ var gl_vec2__WEBPACK_IMPORTED_MODULE_4___default =
/*#__PURE__*/ __webpack_require__.n(
gl_vec2__WEBPACK_IMPORTED_MODULE_4__
);
/* harmony import */ var _cv_utils__WEBPACK_IMPORTED_MODULE_5__ =
__webpack_require__(8);
/* harmony import */ var _array_helper__WEBPACK_IMPORTED_MODULE_6__ =
__webpack_require__(10);
var vec2 = {
clone: gl_vec2__WEBPACK_IMPORTED_MODULE_4__["clone"],
};
function assertNumberPositive(val) {
if (val < 0) {
throw new Error(
"expected positive number, received ".concat(val)
);
}
}
var ImageWrapper = /*#__PURE__*/ (function () {
// Represents a basic image combining the data and size. In addition, some methods for
// manipulation are contained within.
function ImageWrapper(size, data) {
var ArrayType =
arguments.length > 2 && arguments[2] !== undefined
? arguments[2]
: Uint8Array;
var initialize =
arguments.length > 3 ? arguments[3] : undefined;
_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_1___default()(
this,
ImageWrapper
);
_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_3___default()(
this,
"data",
void 0
);
_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_3___default()(
this,
"size",
void 0
);
_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_3___default()(
this,
"indexMapping",
void 0
);
if (!data) {
this.data = new ArrayType(size.x * size.y);
if (initialize) {
_array_helper__WEBPACK_IMPORTED_MODULE_6__[
/* default */ "a"
].init(this.data, 0);
}
} else {
this.data = data;
}
this.size = size;
} // tests if a position is within the image, extended out by a border on each side
_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_2___default()(
ImageWrapper,
[
{
key: "inImageWithBorder",
value: function inImageWithBorder(imgRef) {
var border =
arguments.length > 1 &&
arguments[1] !== undefined
? arguments[1]
: 0;
assertNumberPositive(border); // TODO: code_128 starts failing miserably when i only allow imgRef to contain positive numbers.
// TODO: this doesn't make much sense to me, why does it go negative? Tests are not affected by
// returning false, but the whole code_128 reader blows up when i throw on negative imgRef.
// assertNumberPositive(imgRef.x);
// assertNumberPositive(imgRef.y);
return (
imgRef.x >= 0 &&
imgRef.y >= 0 &&
imgRef.x < this.size.x + border * 2 &&
imgRef.y < this.size.y + border * 2
);
}, // Copy from THIS ImageWrapper to the new imageWrapper parameter, starting at from, stopping at
// end of new imageWrapper size.
},
{
key: "subImageAsCopy",
value: function subImageAsCopy(
imageWrapper,
from
) {
assertNumberPositive(from.x);
assertNumberPositive(from.y);
var _imageWrapper$size = imageWrapper.size,
sizeX = _imageWrapper$size.x,
sizeY = _imageWrapper$size.y;
for (var x = 0; x < sizeX; x++) {
for (var y = 0; y < sizeY; y++) {
// eslint-disable-next-line no-param-reassign
imageWrapper.data[y * sizeX + x] =
this.data[
(from.y + y) * this.size.x +
from.x +
x
];
}
}
return imageWrapper; // TODO: this function really probably should call into ImageWrapper somewhere to make
// sure that all of it's parameters are set properly, something like
// ImageWrapper.UpdateFrom()
// that might take a provided data and size, and make sure there's no invalid indexMapping
// hanging around, and such.
}, // Retrieve a grayscale value at the given pixel position of the image
},
{
key: "get",
value: function get(x, y) {
return this.data[y * this.size.x + x];
}, // Retrieve a grayscale value at the given pixel position of the image (safe, whatever that
// means)
},
{
key: "getSafe",
value: function getSafe(x, y) {
// cache indexMapping because if we're using it once, we'll probably need it a bunch more
// too
if (!this.indexMapping) {
this.indexMapping = {
x: [],
y: [],
};
for (var i = 0; i < this.size.x; i++) {
this.indexMapping.x[i] = i;
this.indexMapping.x[
i + this.size.x
] = i;
}
for (
var _i = 0;
_i < this.size.y;
_i++
) {
this.indexMapping.y[_i] = _i;
this.indexMapping.y[
_i + this.size.y
] = _i;
}
}
return this.data[
this.indexMapping.y[y + this.size.y] *
this.size.x +
this.indexMapping.x[x + this.size.x]
];
}, // Sets a given pixel position in the image to the given grayscale value
},
{
key: "set",
value: function set(x, y, value) {
this.data[y * this.size.x + x] = value;
delete this.indexMapping;
return this;
}, // Sets the border of the image (1 pixel) to zero
},
{
key: "zeroBorder",
value: function zeroBorder() {
var _this$size = this.size,
width = _this$size.x,
height = _this$size.y;
for (var i = 0; i < width; i++) {
// eslint-disable-next-line no-multi-assign
this.data[i] = this.data[
(height - 1) * width + i
] = 0;
}
for (var _i2 = 1; _i2 < height - 1; _i2++) {
// eslint-disable-next-line no-multi-assign
this.data[_i2 * width] = this.data[
_i2 * width + (width - 1)
] = 0;
}
delete this.indexMapping;
return this;
}, // TODO: this function is entirely too large for me to reason out right at this moment that i'm handling
// all the rest of it, so this is a verbatim copy of the javascript source, with only tweaks
// necessary to get it to run, no thought put into it yet.
},
{
key: "moments",
value: function moments(labelCount) {
var data = this.data;
var x;
var y;
var height = this.size.y;
var width = this.size.x;
var val;
var ysq;
var labelSum = [];
var i;
var label;
var mu11;
var mu02;
var mu20;
var x_;
var y_;
var tmp;
var result = [];
var PI = Math.PI;
var PI_4 = PI / 4;
if (labelCount <= 0) {
return result;
}
for (i = 0; i < labelCount; i++) {
labelSum[i] = {
m00: 0,
m01: 0,
m10: 0,
m11: 0,
m02: 0,
m20: 0,
theta: 0,
rad: 0,
};
}
for (y = 0; y < height; y++) {
ysq = y * y;
for (x = 0; x < width; x++) {
val = data[y * width + x];
if (val > 0) {
label = labelSum[val - 1];
label.m00 += 1;
label.m01 += y;
label.m10 += x;
label.m11 += x * y;
label.m02 += ysq;
label.m20 += x * x;
}
}
}
for (i = 0; i < labelCount; i++) {
label = labelSum[i]; // eslint-disable-next-line no-restricted-globals
if (
!isNaN(label.m00) &&
label.m00 !== 0
) {
x_ = label.m10 / label.m00;
y_ = label.m01 / label.m00;
mu11 =
label.m11 / label.m00 - x_ * y_;
mu02 =
label.m02 / label.m00 - y_ * y_;
mu20 =
label.m20 / label.m00 - x_ * x_;
tmp = (mu02 - mu20) / (2 * mu11);
tmp =
0.5 * Math.atan(tmp) +
(mu11 >= 0 ? PI_4 : -PI_4) +
PI; // eslint-disable-next-line no-mixed-operators
label.theta =
(((tmp * 180) / PI + 90) %
180) -
90;
if (label.theta < 0) {
label.theta += 180;
}
label.rad =
tmp > PI ? tmp - PI : tmp;
label.vec = vec2.clone([
Math.cos(tmp),
Math.sin(tmp),
]);
result.push(label);
}
}
return result;
}, // return a Uint8ClampedArray containing this grayscale image converted to RGBA form
},
{
key: "getAsRGBA",
value: function getAsRGBA() {
var scale =
arguments.length > 0 &&
arguments[0] !== undefined
? arguments[0]
: 1.0;
var ret = new Uint8ClampedArray(
4 * this.size.x * this.size.y
);
for (var y = 0; y < this.size.y; y++) {
for (var x = 0; x < this.size.x; x++) {
var pixel = y * this.size.x + x;
var current =
this.get(x, y) * scale;
ret[pixel * 4 + 0] = current;
ret[pixel * 4 + 1] = current;
ret[pixel * 4 + 2] = current;
ret[pixel * 4 + 3] = 255;
}
}
return ret;
}, // Display this ImageWrapper in a given Canvas element at the specified scale
},
{
key: "show",
value: function show(canvas) {
var scale =
arguments.length > 1 &&
arguments[1] !== undefined
? arguments[1]
: 1.0;
var ctx = canvas.getContext("2d");
if (!ctx) {
throw new Error(
"Unable to get canvas context"
);
}
var frame = ctx.getImageData(
0,
0,
canvas.width,
canvas.height
);
var data = this.getAsRGBA(scale); // eslint-disable-next-line no-param-reassign
canvas.width = this.size.x; // eslint-disable-next-line no-param-reassign
canvas.height = this.size.y;
var newFrame = new ImageData(
data,
frame.width,
frame.height
);
ctx.putImageData(newFrame, 0, 0);
}, // Displays a specified SubImage area in a given canvas. This differs drastically from
// creating a new SubImage and using it's show() method. Why? I don't have the answer to that
// yet. I suspect the HSV/RGB operations involved here are making it significantly different,
// but until I can visualize these functions side by side, I'm just going to copy the existing
// implementation.
},
{
key: "overlay",
value: function overlay(canvas, inScale, from) {
var adjustedScale =
inScale < 0 || inScale > 360
? 360
: inScale;
var hsv = [0, 1, 1];
var rgb = [0, 0, 0];
var whiteRgb = [255, 255, 255];
var blackRgb = [0, 0, 0];
var result = [];
var ctx = canvas.getContext("2d");
if (!ctx) {
throw new Error(
"Unable to get canvas context"
);
}
var frame = ctx.getImageData(
from.x,
from.y,
this.size.x,
this.size.y
);
var data = frame.data;
var length = this.data.length;
while (length--) {
hsv[0] =
this.data[length] * adjustedScale; // eslint-disable-next-line no-nested-ternary
result =
hsv[0] <= 0
? whiteRgb
: hsv[0] >= 360
? blackRgb
: Object(
_cv_utils__WEBPACK_IMPORTED_MODULE_5__[
/* hsv2rgb */ "g"
]
)(hsv, rgb);
var pos = length * 4;
var _result = result;
var _result2 =
_babel_runtime_helpers_slicedToArray__WEBPACK_IMPORTED_MODULE_0___default()(
_result,
3
);
data[pos] = _result2[0];
data[pos + 1] = _result2[1];
data[pos + 2] = _result2[2];
data[pos + 3] = 255;
}
ctx.putImageData(frame, from.x, from.y);
},
},
]
);
return ImageWrapper;
})();
/* harmony default export */ __webpack_exports__["a"] =
ImageWrapper;
/***/
},
/* 12 */
/***/ function (module, exports, __webpack_require__) {
module.exports = __webpack_require__(228);
/***/
},
/* 13 */
/***/ function (module, exports, __webpack_require__) {
var superPropBase = __webpack_require__(227);
function _get(target, property, receiver) {
if (typeof Reflect !== "undefined" && Reflect.get) {
module.exports = _get = Reflect.get;
(module.exports["default"] = module.exports),
(module.exports.__esModule = true);
} else {
module.exports = _get = function _get(
target,
property,
receiver
) {
var base = superPropBase(target, property);
if (!base) return;
var desc = Object.getOwnPropertyDescriptor(
base,
property
);
if (desc.get) {
return desc.get.call(receiver);
}
return desc.value;
};
(module.exports["default"] = module.exports),
(module.exports.__esModule = true);
}
return _get(target, property, receiver || target);
}
module.exports = _get;
(module.exports["default"] = module.exports),
(module.exports.__esModule = true);
/***/
},
/* 14 */
/***/ function (module, exports) {
/**
* 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")
);
}
module.exports = isObject;
/***/
},
/* 15 */
/***/ function (module, exports) {
/**
* 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;
module.exports = isArray;
/***/
},
/* 16 */
/***/ function (module, exports, __webpack_require__) {
var baseMerge = __webpack_require__(90),
createAssigner = __webpack_require__(145);
/**
* 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);
});
module.exports = merge;
/***/
},
/* 17 */
/***/ function (module, exports, __webpack_require__) {
var freeGlobal = __webpack_require__(45);
/** 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")();
module.exports = root;
/***/
},
/* 18 */
/***/ function (module, exports) {
/**
* 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";
}
module.exports = isObjectLike;
/***/
},
/* 19 */
/***/ function (module, exports) {
function _typeof(obj) {
"@babel/helpers - typeof";
if (
typeof Symbol === "function" &&
typeof Symbol.iterator === "symbol"
) {
module.exports = _typeof = function _typeof(obj) {
return typeof obj;
};
(module.exports["default"] = module.exports),
(module.exports.__esModule = true);
} else {
module.exports = _typeof = function _typeof(obj) {
return obj &&
typeof Symbol === "function" &&
obj.constructor === Symbol &&
obj !== Symbol.prototype
? "symbol"
: typeof obj;
};
(module.exports["default"] = module.exports),
(module.exports.__esModule = true);
}
return _typeof(obj);
}
module.exports = _typeof;
(module.exports["default"] = module.exports),
(module.exports.__esModule = true);
/***/
},
/* 20 */
/***/ function (module, exports) {
function asyncGeneratorStep(
gen,
resolve,
reject,
_next,
_throw,
key,
arg
) {
try {
var info = gen[key](arg);
var value = info.value;
} catch (error) {
reject(error);
return;
}
if (info.done) {
resolve(value);
} else {
Promise.resolve(value).then(_next, _throw);
}
}
function _asyncToGenerator(fn) {
return function () {
var self = this,
args = arguments;
return new Promise(function (resolve, reject) {
var gen = fn.apply(self, args);
function _next(value) {
asyncGeneratorStep(
gen,
resolve,
reject,
_next,
_throw,
"next",
value
);
}
function _throw(err) {
asyncGeneratorStep(
gen,
resolve,
reject,
_next,
_throw,
"throw",
err
);
}
_next(undefined);
});
};
}
module.exports = _asyncToGenerator;
(module.exports["default"] = module.exports),
(module.exports.__esModule = true);
/***/
},
/* 21 */
/***/ function (module, __webpack_exports__, __webpack_require__) {
"use strict";
/**
* http://www.codeproject.com/Tips/407172/Connected-Component-Labeling-and-Vectorization
*/
var Tracer = {
searchDirections: [
[0, 1],
[1, 1],
[1, 0],
[1, -1],
[0, -1],
[-1, -1],
[-1, 0],
[-1, 1],
],
create: function create(imageWrapper, labelWrapper) {
var imageData = imageWrapper.data;
var labelData = labelWrapper.data;
var searchDirections = this.searchDirections;
var width = imageWrapper.size.x;
var pos;
function _trace(current, color, label, edgelabel) {
var i;
var y;
var x;
for (i = 0; i < 7; i++) {
y =
current.cy +
searchDirections[current.dir][0];
x =
current.cx +
searchDirections[current.dir][1];
pos = y * width + x;
if (
imageData[pos] === color &&
(labelData[pos] === 0 ||
labelData[pos] === label)
) {
labelData[pos] = label;
current.cy = y;
current.cx = x;
return true;
}
if (labelData[pos] === 0) {
labelData[pos] = edgelabel;
}
current.dir = (current.dir + 1) % 8;
}
return false;
}
function vertex2D(x, y, dir) {
return {
dir: dir,
x: x,
y: y,
next: null,
prev: null,
};
}
function _contourTracing(
sy,
sx,
label,
color,
edgelabel
) {
var Fv = null;
var Cv;
var P;
var ldir;
var current = {
cx: sx,
cy: sy,
dir: 0,
};
if (_trace(current, color, label, edgelabel)) {
Fv = vertex2D(sx, sy, current.dir);
Cv = Fv;
ldir = current.dir;
P = vertex2D(current.cx, current.cy, 0);
P.prev = Cv;
Cv.next = P;
P.next = null;
Cv = P;
do {
current.dir = (current.dir + 6) % 8;
_trace(current, color, label, edgelabel);
if (ldir !== current.dir) {
Cv.dir = current.dir;
P = vertex2D(current.cx, current.cy, 0);
P.prev = Cv;
Cv.next = P;
P.next = null;
Cv = P;
} else {
Cv.dir = ldir;
Cv.x = current.cx;
Cv.y = current.cy;
}
ldir = current.dir;
} while (
current.cx !== sx ||
current.cy !== sy
);
Fv.prev = Cv.prev;
Cv.prev.next = Fv;
}
return Fv;
}
return {
trace: function trace(
current,
color,
label,
edgelabel
) {
return _trace(current, color, label, edgelabel);
},
contourTracing: function contourTracing(
sy,
sx,
label,
color,
edgelabel
) {
return _contourTracing(
sy,
sx,
label,
color,
edgelabel
);
},
};
},
};
/* harmony default export */ __webpack_exports__["a"] = Tracer;
/***/
},
/* 22 */
/***/ function (module, exports, __webpack_require__) {
var Symbol = __webpack_require__(27),
getRawTag = __webpack_require__(103),
objectToString = __webpack_require__(104);
/** `Object#toString` result references. */
var nullTag = "[object Null]",
undefinedTag = "[object Undefined]";
/** Built-in value references. */
var symToStringTag = Symbol ? Symbol.toStringTag : undefined;
/**
* 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);
}
module.exports = baseGetTag;
/***/
},
/* 23 */
/***/ function (module, __webpack_exports__, __webpack_require__) {
"use strict";
/* WEBPACK VAR INJECTION */ (function (global) {
/* harmony import */ var gl_vec2__WEBPACK_IMPORTED_MODULE_0__ =
__webpack_require__(7);
/* harmony import */ var gl_vec2__WEBPACK_IMPORTED_MODULE_0___default =
/*#__PURE__*/ __webpack_require__.n(
gl_vec2__WEBPACK_IMPORTED_MODULE_0__
);
/* harmony import */ var gl_mat2__WEBPACK_IMPORTED_MODULE_1__ =
__webpack_require__(34);
/* harmony import */ var gl_mat2__WEBPACK_IMPORTED_MODULE_1___default =
/*#__PURE__*/ __webpack_require__.n(
gl_mat2__WEBPACK_IMPORTED_MODULE_1__
);
/* harmony import */ var _common_image_wrapper__WEBPACK_IMPORTED_MODULE_2__ =
__webpack_require__(11);
/* harmony import */ var _common_cv_utils__WEBPACK_IMPORTED_MODULE_3__ =
__webpack_require__(8);
/* harmony import */ var _common_array_helper__WEBPACK_IMPORTED_MODULE_4__ =
__webpack_require__(10);
/* harmony import */ var _common_image_debug__WEBPACK_IMPORTED_MODULE_5__ =
__webpack_require__(9);
/* harmony import */ var _rasterizer__WEBPACK_IMPORTED_MODULE_6__ =
__webpack_require__(87);
/* harmony import */ var _tracer__WEBPACK_IMPORTED_MODULE_7__ =
__webpack_require__(21);
/* harmony import */ var _skeletonizer__WEBPACK_IMPORTED_MODULE_8__ =
__webpack_require__(88);
var _config;
var _currentImageWrapper;
var _skelImageWrapper;
var _subImageWrapper;
var _labelImageWrapper;
var _patchGrid;
var _patchLabelGrid;
var _imageToPatchGrid;
var _binaryImageWrapper;
var _patchSize;
var _canvasContainer = {
ctx: {
binary: null,
},
dom: {
binary: null,
},
};
var _numPatches = {
x: 0,
y: 0,
};
var _inputImageWrapper;
var _skeletonizer;
function initBuffers() {
if (_config.halfSample) {
_currentImageWrapper =
new _common_image_wrapper__WEBPACK_IMPORTED_MODULE_2__[
/* default */ "a"
]({
// eslint-disable-next-line no-bitwise
x: (_inputImageWrapper.size.x / 2) | 0,
// eslint-disable-next-line no-bitwise
y: (_inputImageWrapper.size.y / 2) | 0,
});
} else {
_currentImageWrapper = _inputImageWrapper;
}
_patchSize = Object(
_common_cv_utils__WEBPACK_IMPORTED_MODULE_3__[
/* calculatePatchSize */ "a"
]
)(_config.patchSize, _currentImageWrapper.size); // eslint-disable-next-line no-bitwise
_numPatches.x =
(_currentImageWrapper.size.x / _patchSize.x) | 0; // eslint-disable-next-line no-bitwise
_numPatches.y =
(_currentImageWrapper.size.y / _patchSize.y) | 0;
_binaryImageWrapper =
new _common_image_wrapper__WEBPACK_IMPORTED_MODULE_2__[
/* default */ "a"
](
_currentImageWrapper.size,
undefined,
Uint8Array,
false
);
_labelImageWrapper =
new _common_image_wrapper__WEBPACK_IMPORTED_MODULE_2__[
/* default */ "a"
](_patchSize, undefined, Array, true);
var skeletonImageData = new ArrayBuffer(64 * 1024);
_subImageWrapper =
new _common_image_wrapper__WEBPACK_IMPORTED_MODULE_2__[
/* default */ "a"
](
_patchSize,
new Uint8Array(
skeletonImageData,
0,
_patchSize.x * _patchSize.y
)
);
_skelImageWrapper =
new _common_image_wrapper__WEBPACK_IMPORTED_MODULE_2__[
/* default */ "a"
](
_patchSize,
new Uint8Array(
skeletonImageData,
_patchSize.x * _patchSize.y * 3,
_patchSize.x * _patchSize.y
),
undefined,
true
);
_skeletonizer = Object(
_skeletonizer__WEBPACK_IMPORTED_MODULE_8__[
/* default */ "a"
]
)(
typeof window !== "undefined"
? window
: typeof self !== "undefined"
? self
: global,
{
size: _patchSize.x,
},
skeletonImageData
);
_imageToPatchGrid =
new _common_image_wrapper__WEBPACK_IMPORTED_MODULE_2__[
/* default */ "a"
](
{
// eslint-disable-next-line no-bitwise
x:
(_currentImageWrapper.size.x /
_subImageWrapper.size.x) |
0,
// eslint-disable-next-line no-bitwise
y:
(_currentImageWrapper.size.y /
_subImageWrapper.size.y) |
0,
},
undefined,
Array,
true
);
_patchGrid =
new _common_image_wrapper__WEBPACK_IMPORTED_MODULE_2__[
/* default */ "a"
](
_imageToPatchGrid.size,
undefined,
undefined,
true
);
_patchLabelGrid =
new _common_image_wrapper__WEBPACK_IMPORTED_MODULE_2__[
/* default */ "a"
](
_imageToPatchGrid.size,
undefined,
Int32Array,
true
);
}
function initCanvas() {
if (
_config.useWorker ||
typeof document === "undefined"
) {
return;
}
_canvasContainer.dom.binary =
document.createElement("canvas");
_canvasContainer.dom.binary.className = "binaryBuffer";
if (true && _config.debug.showCanvas === true) {
document
.querySelector("#debug")
.appendChild(_canvasContainer.dom.binary);
}
_canvasContainer.ctx.binary =
_canvasContainer.dom.binary.getContext("2d");
_canvasContainer.dom.binary.width =
_binaryImageWrapper.size.x;
_canvasContainer.dom.binary.height =
_binaryImageWrapper.size.y;
}
/**
* Creates a bounding box which encloses all the given patches
* @returns {Array} The minimal bounding box
*/
function boxFromPatches(patches) {
var overAvg;
var i;
var j;
var patch;
var transMat;
var minx = _binaryImageWrapper.size.x;
var miny = _binaryImageWrapper.size.y;
var maxx = -_binaryImageWrapper.size.x;
var maxy = -_binaryImageWrapper.size.y;
var box;
var scale; // draw all patches which are to be taken into consideration
overAvg = 0;
for (i = 0; i < patches.length; i++) {
patch = patches[i];
overAvg += patch.rad;
if (true && _config.debug.showPatches) {
_common_image_debug__WEBPACK_IMPORTED_MODULE_5__[
/* default */ "a"
].drawRect(
patch.pos,
_subImageWrapper.size,
_canvasContainer.ctx.binary,
{
color: "red",
}
);
}
}
overAvg /= patches.length;
overAvg = (((overAvg * 180) / Math.PI + 90) % 180) - 90;
if (overAvg < 0) {
overAvg += 180;
}
overAvg = ((180 - overAvg) * Math.PI) / 180;
transMat = gl_mat2__WEBPACK_IMPORTED_MODULE_1__["copy"](
gl_mat2__WEBPACK_IMPORTED_MODULE_1__["create"](),
[
Math.cos(overAvg),
Math.sin(overAvg),
-Math.sin(overAvg),
Math.cos(overAvg),
]
); // iterate over patches and rotate by angle
for (i = 0; i < patches.length; i++) {
patch = patches[i];
for (j = 0; j < 4; j++) {
gl_vec2__WEBPACK_IMPORTED_MODULE_0__[
"transformMat2"
](patch.box[j], patch.box[j], transMat);
}
if (
true &&
_config.debug.boxFromPatches.showTransformed
) {
_common_image_debug__WEBPACK_IMPORTED_MODULE_5__[
/* default */ "a"
].drawPath(
patch.box,
{
x: 0,
y: 1,
},
_canvasContainer.ctx.binary,
{
color: "#99ff00",
lineWidth: 2,
}
);
}
} // find bounding box
for (i = 0; i < patches.length; i++) {
patch = patches[i];
for (j = 0; j < 4; j++) {
if (patch.box[j][0] < minx) {
minx = patch.box[j][0];
}
if (patch.box[j][0] > maxx) {
maxx = patch.box[j][0];
}
if (patch.box[j][1] < miny) {
miny = patch.box[j][1];
}
if (patch.box[j][1] > maxy) {
maxy = patch.box[j][1];
}
}
}
box = [
[minx, miny],
[maxx, miny],
[maxx, maxy],
[minx, maxy],
];
if (
true &&
_config.debug.boxFromPatches.showTransformedBox
) {
_common_image_debug__WEBPACK_IMPORTED_MODULE_5__[
/* default */ "a"
].drawPath(
box,
{
x: 0,
y: 1,
},
_canvasContainer.ctx.binary,
{
color: "#ff0000",
lineWidth: 2,
}
);
}
scale = _config.halfSample ? 2 : 1; // reverse rotation;
transMat = gl_mat2__WEBPACK_IMPORTED_MODULE_1__[
"invert"
](transMat, transMat);
for (j = 0; j < 4; j++) {
gl_vec2__WEBPACK_IMPORTED_MODULE_0__[
"transformMat2"
](box[j], box[j], transMat);
}
if (true && _config.debug.boxFromPatches.showBB) {
_common_image_debug__WEBPACK_IMPORTED_MODULE_5__[
/* default */ "a"
].drawPath(
box,
{
x: 0,
y: 1,
},
_canvasContainer.ctx.binary,
{
color: "#ff0000",
lineWidth: 2,
}
);
}
for (j = 0; j < 4; j++) {
gl_vec2__WEBPACK_IMPORTED_MODULE_0__["scale"](
box[j],
box[j],
scale
);
}
return box;
}
/**
* Creates a binary image of the current image
*/
function binarizeImage() {
Object(
_common_cv_utils__WEBPACK_IMPORTED_MODULE_3__[
/* otsuThreshold */ "i"
]
)(_currentImageWrapper, _binaryImageWrapper);
_binaryImageWrapper.zeroBorder();
if (true && _config.debug.showCanvas) {
_binaryImageWrapper.show(
_canvasContainer.dom.binary,
255
);
}
}
/**
* Iterate over the entire image
* extract patches
*/
function findPatches() {
var i;
var j;
var x;
var y;
var moments;
var patchesFound = [];
var rasterizer;
var rasterResult;
var patch;
for (i = 0; i < _numPatches.x; i++) {
for (j = 0; j < _numPatches.y; j++) {
x = _subImageWrapper.size.x * i;
y = _subImageWrapper.size.y * j; // seperate parts
skeletonize(x, y); // Rasterize, find individual bars
_skelImageWrapper.zeroBorder();
_common_array_helper__WEBPACK_IMPORTED_MODULE_4__[
/* default */ "a"
].init(_labelImageWrapper.data, 0);
rasterizer =
_rasterizer__WEBPACK_IMPORTED_MODULE_6__[
/* default */ "a"
].create(
_skelImageWrapper,
_labelImageWrapper
);
rasterResult = rasterizer.rasterize(0);
if (true && _config.debug.showLabels) {
_labelImageWrapper.overlay(
_canvasContainer.dom.binary,
Math.floor(360 / rasterResult.count),
{
x: x,
y: y,
}
);
} // calculate moments from the skeletonized patch
moments = _labelImageWrapper.moments(
rasterResult.count
); // extract eligible patches
patchesFound = patchesFound.concat(
describePatch(moments, [i, j], x, y)
);
}
}
if (true && _config.debug.showFoundPatches) {
for (i = 0; i < patchesFound.length; i++) {
patch = patchesFound[i];
_common_image_debug__WEBPACK_IMPORTED_MODULE_5__[
/* default */ "a"
].drawRect(
patch.pos,
_subImageWrapper.size,
_canvasContainer.ctx.binary,
{
color: "#99ff00",
lineWidth: 2,
}
);
}
}
return patchesFound;
}
/**
* Finds those connected areas which contain at least 6 patches
* and returns them ordered DESC by the number of contained patches
* @param {Number} maxLabel
*/
function findBiggestConnectedAreas(maxLabel) {
var i;
var sum;
var labelHist = [];
var topLabels = [];
for (i = 0; i < maxLabel; i++) {
labelHist.push(0);
}
sum = _patchLabelGrid.data.length;
while (sum--) {
if (_patchLabelGrid.data[sum] > 0) {
labelHist[_patchLabelGrid.data[sum] - 1]++;
}
}
labelHist = labelHist.map(function (val, idx) {
return {
val: val,
label: idx + 1,
};
});
labelHist.sort(function (a, b) {
return b.val - a.val;
}); // extract top areas with at least 6 patches present
topLabels = labelHist.filter(function (el) {
return el.val >= 5;
});
return topLabels;
}
/**
*
*/
function findBoxes(topLabels, maxLabel) {
var i;
var j;
var sum;
var patches = [];
var patch;
var box;
var boxes = [];
var hsv = [0, 1, 1];
var rgb = [0, 0, 0];
for (i = 0; i < topLabels.length; i++) {
sum = _patchLabelGrid.data.length;
patches.length = 0;
while (sum--) {
if (
_patchLabelGrid.data[sum] ===
topLabels[i].label
) {
patch = _imageToPatchGrid.data[sum];
patches.push(patch);
}
}
box = boxFromPatches(patches);
if (box) {
boxes.push(box); // draw patch-labels if requested
if (
true &&
_config.debug.showRemainingPatchLabels
) {
for (j = 0; j < patches.length; j++) {
patch = patches[j];
hsv[0] =
(topLabels[i].label /
(maxLabel + 1)) *
360;
Object(
_common_cv_utils__WEBPACK_IMPORTED_MODULE_3__[
/* hsv2rgb */ "g"
]
)(hsv, rgb);
_common_image_debug__WEBPACK_IMPORTED_MODULE_5__[
/* default */ "a"
].drawRect(
patch.pos,
_subImageWrapper.size,
_canvasContainer.ctx.binary,
{
color: "rgb(".concat(
rgb.join(","),
")"
),
lineWidth: 2,
}
);
}
}
}
}
return boxes;
}
/**
* Find similar moments (via cluster)
* @param {Object} moments
*/
function similarMoments(moments) {
var clusters = Object(
_common_cv_utils__WEBPACK_IMPORTED_MODULE_3__[
/* cluster */ "b"
]
)(moments, 0.9);
var topCluster = Object(
_common_cv_utils__WEBPACK_IMPORTED_MODULE_3__[
/* topGeneric */ "j"
]
)(clusters, 1, function (e) {
return e.getPoints().length;
});
var points = [];
var result = [];
if (topCluster.length === 1) {
points = topCluster[0].item.getPoints();
for (var i = 0; i < points.length; i++) {
result.push(points[i].point);
}
}
return result;
}
function skeletonize(x, y) {
_binaryImageWrapper.subImageAsCopy(
_subImageWrapper,
Object(
_common_cv_utils__WEBPACK_IMPORTED_MODULE_3__[
/* imageRef */ "h"
]
)(x, y)
);
_skeletonizer.skeletonize(); // Show skeleton if requested
if (true && _config.debug.showSkeleton) {
_skelImageWrapper.overlay(
_canvasContainer.dom.binary,
360,
Object(
_common_cv_utils__WEBPACK_IMPORTED_MODULE_3__[
/* imageRef */ "h"
]
)(x, y)
);
}
}
/**
* Extracts and describes those patches which seem to contain a barcode pattern
* @param {Array} moments
* @param {Object} patchPos,
* @param {Number} x
* @param {Number} y
* @returns {Array} list of patches
*/
function describePatch(moments, patchPos, x, y) {
var k;
var avg;
var eligibleMoments = [];
var matchingMoments;
var patch;
var patchesFound = [];
var minComponentWeight = Math.ceil(_patchSize.x / 3);
if (moments.length >= 2) {
// only collect moments which's area covers at least minComponentWeight pixels.
for (k = 0; k < moments.length; k++) {
if (moments[k].m00 > minComponentWeight) {
eligibleMoments.push(moments[k]);
}
} // if at least 2 moments are found which have at least minComponentWeights covered
if (eligibleMoments.length >= 2) {
matchingMoments =
similarMoments(eligibleMoments);
avg = 0; // determine the similarity of the moments
for (k = 0; k < matchingMoments.length; k++) {
avg += matchingMoments[k].rad;
} // Only two of the moments are allowed not to fit into the equation
// add the patch to the set
if (
matchingMoments.length > 1 &&
matchingMoments.length >=
(eligibleMoments.length / 4) * 3 &&
matchingMoments.length > moments.length / 4
) {
avg /= matchingMoments.length;
patch = {
index:
patchPos[1] * _numPatches.x +
patchPos[0],
pos: {
x: x,
y: y,
},
box: [
gl_vec2__WEBPACK_IMPORTED_MODULE_0__[
"clone"
]([x, y]),
gl_vec2__WEBPACK_IMPORTED_MODULE_0__[
"clone"
]([x + _subImageWrapper.size.x, y]),
gl_vec2__WEBPACK_IMPORTED_MODULE_0__[
"clone"
]([
x + _subImageWrapper.size.x,
y + _subImageWrapper.size.y,
]),
gl_vec2__WEBPACK_IMPORTED_MODULE_0__[
"clone"
]([x, y + _subImageWrapper.size.y]),
],
moments: matchingMoments,
rad: avg,
vec: gl_vec2__WEBPACK_IMPORTED_MODULE_0__[
"clone"
]([Math.cos(avg), Math.sin(avg)]),
};
patchesFound.push(patch);
}
}
}
return patchesFound;
}
/**
* finds patches which are connected and share the same orientation
* @param {Object} patchesFound
*/
function rasterizeAngularSimilarity(patchesFound) {
var label = 0;
var threshold = 0.95;
var currIdx = 0;
var j;
var patch;
var hsv = [0, 1, 1];
var rgb = [0, 0, 0];
function notYetProcessed() {
var i;
for (i = 0; i < _patchLabelGrid.data.length; i++) {
if (
_patchLabelGrid.data[i] === 0 &&
_patchGrid.data[i] === 1
) {
return i;
}
}
return _patchLabelGrid.length;
}
function trace(currentIdx) {
var x;
var y;
var currentPatch;
var idx;
var dir;
var current = {
x: currentIdx % _patchLabelGrid.size.x,
y: (currentIdx / _patchLabelGrid.size.x) | 0,
};
var similarity;
if (currentIdx < _patchLabelGrid.data.length) {
currentPatch =
_imageToPatchGrid.data[currentIdx]; // assign label
_patchLabelGrid.data[currentIdx] = label;
for (
dir = 0;
dir <
_tracer__WEBPACK_IMPORTED_MODULE_7__[
/* default */ "a"
].searchDirections.length;
dir++
) {
y =
current.y +
_tracer__WEBPACK_IMPORTED_MODULE_7__[
/* default */ "a"
].searchDirections[dir][0];
x =
current.x +
_tracer__WEBPACK_IMPORTED_MODULE_7__[
/* default */ "a"
].searchDirections[dir][1];
idx = y * _patchLabelGrid.size.x + x; // continue if patch empty
if (_patchGrid.data[idx] === 0) {
_patchLabelGrid.data[idx] =
Number.MAX_VALUE; // eslint-disable-next-line no-continue
continue;
}
if (_patchLabelGrid.data[idx] === 0) {
similarity = Math.abs(
gl_vec2__WEBPACK_IMPORTED_MODULE_0__[
"dot"
](
_imageToPatchGrid.data[idx].vec,
currentPatch.vec
)
);
if (similarity > threshold) {
trace(idx);
}
}
}
}
} // prepare for finding the right patches
_common_array_helper__WEBPACK_IMPORTED_MODULE_4__[
/* default */ "a"
].init(_patchGrid.data, 0);
_common_array_helper__WEBPACK_IMPORTED_MODULE_4__[
/* default */ "a"
].init(_patchLabelGrid.data, 0);
_common_array_helper__WEBPACK_IMPORTED_MODULE_4__[
/* default */ "a"
].init(_imageToPatchGrid.data, null);
for (j = 0; j < patchesFound.length; j++) {
patch = patchesFound[j];
_imageToPatchGrid.data[patch.index] = patch;
_patchGrid.data[patch.index] = 1;
} // rasterize the patches found to determine area
_patchGrid.zeroBorder(); // eslint-disable-next-line no-cond-assign
while (
(currIdx = notYetProcessed()) <
_patchLabelGrid.data.length
) {
label++;
trace(currIdx);
} // draw patch-labels if requested
if (true && _config.debug.showPatchLabels) {
for (j = 0; j < _patchLabelGrid.data.length; j++) {
if (
_patchLabelGrid.data[j] > 0 &&
_patchLabelGrid.data[j] <= label
) {
patch = _imageToPatchGrid.data[j];
hsv[0] =
(_patchLabelGrid.data[j] /
(label + 1)) *
360;
Object(
_common_cv_utils__WEBPACK_IMPORTED_MODULE_3__[
/* hsv2rgb */ "g"
]
)(hsv, rgb);
_common_image_debug__WEBPACK_IMPORTED_MODULE_5__[
/* default */ "a"
].drawRect(
patch.pos,
_subImageWrapper.size,
_canvasContainer.ctx.binary,
{
color: "rgb(".concat(
rgb.join(","),
")"
),
lineWidth: 2,
}
);
}
}
}
return label;
}
/* harmony default export */ __webpack_exports__["a"] = {
init: function init(inputImageWrapper, config) {
_config = config;
_inputImageWrapper = inputImageWrapper;
initBuffers();
initCanvas();
},
locate: function locate() {
if (_config.halfSample) {
Object(
_common_cv_utils__WEBPACK_IMPORTED_MODULE_3__[
/* halfSample */ "f"
]
)(_inputImageWrapper, _currentImageWrapper);
}
binarizeImage();
var patchesFound = findPatches(); // return unless 5% or more patches are found
if (
patchesFound.length <
_numPatches.x * _numPatches.y * 0.05
) {
return null;
} // rasterrize area by comparing angular similarity;
var maxLabel =
rasterizeAngularSimilarity(patchesFound);
if (maxLabel < 1) {
return null;
} // search for area with the most patches (biggest connected area)
var topLabels = findBiggestConnectedAreas(maxLabel);
if (topLabels.length === 0) {
return null;
}
var boxes = findBoxes(topLabels, maxLabel);
return boxes;
},
checkImageConstraints: function checkImageConstraints(
inputStream,
config
) {
var patchSize;
var width = inputStream.getWidth();
var height = inputStream.getHeight();
var thisHalfSample = config.halfSample ? 0.5 : 1;
var area; // calculate width and height based on area
if (inputStream.getConfig().area) {
area = Object(
_common_cv_utils__WEBPACK_IMPORTED_MODULE_3__[
/* computeImageArea */ "d"
]
)(width, height, inputStream.getConfig().area);
inputStream.setTopRight({
x: area.sx,
y: area.sy,
});
inputStream.setCanvasSize({
x: width,
y: height,
});
width = area.sw;
height = area.sh;
}
var size = {
x: Math.floor(width * thisHalfSample),
y: Math.floor(height * thisHalfSample),
};
patchSize = Object(
_common_cv_utils__WEBPACK_IMPORTED_MODULE_3__[
/* calculatePatchSize */ "a"
]
)(config.patchSize, size);
if (true) {
console.log(
"Patch-Size: ".concat(
JSON.stringify(patchSize)
)
);
}
inputStream.setWidth(
Math.floor(
Math.floor(size.x / patchSize.x) *
(1 / thisHalfSample) *
patchSize.x
)
);
inputStream.setHeight(
Math.floor(
Math.floor(size.y / patchSize.y) *
(1 / thisHalfSample) *
patchSize.y
)
);
if (
inputStream.getWidth() % patchSize.x === 0 &&
inputStream.getHeight() % patchSize.y === 0
) {
return true;
}
throw new Error(
"Image dimensions do not comply with the current settings: Width ("
.concat(width, " )and height (")
.concat(height, ") must a multiple of ")
.concat(patchSize.x)
);
},
};
/* WEBPACK VAR INJECTION */
}.call(this, __webpack_require__(46)));
/***/
},
/* 24 */
/***/ function (module, exports, __webpack_require__) {
var listCacheClear = __webpack_require__(92),
listCacheDelete = __webpack_require__(93),
listCacheGet = __webpack_require__(94),
listCacheHas = __webpack_require__(95),
listCacheSet = __webpack_require__(96);
/**
* 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]);
}
} // Add methods to `ListCache`.
ListCache.prototype.clear = listCacheClear;
ListCache.prototype["delete"] = listCacheDelete;
ListCache.prototype.get = listCacheGet;
ListCache.prototype.has = listCacheHas;
ListCache.prototype.set = listCacheSet;
module.exports = ListCache;
/***/
},
/* 25 */
/***/ function (module, exports, __webpack_require__) {
var eq = __webpack_require__(26);
/**
* 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;
}
module.exports = assocIndexOf;
/***/
},
/* 26 */
/***/ function (module, exports) {
/**
* 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)
);
}
module.exports = eq;
/***/
},
/* 27 */
/***/ function (module, exports, __webpack_require__) {
var root = __webpack_require__(17);
/** Built-in value references. */
var Symbol = root.Symbol;
module.exports = Symbol;
/***/
},
/* 28 */
/***/ function (module, exports, __webpack_require__) {
var getNative = __webpack_require__(35);
/* Built-in method references that are verified to be native. */
var nativeCreate = getNative(Object, "create");
module.exports = nativeCreate;
/***/
},
/* 29 */
/***/ function (module, exports, __webpack_require__) {
var isKeyable = __webpack_require__(117);
/**
* 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;
}
module.exports = getMapData;
/***/
},
/* 30 */
/***/ function (module, exports, __webpack_require__) {
var baseIsArguments = __webpack_require__(132),
isObjectLike = __webpack_require__(18);
/** Used for built-in method references. */
var objectProto = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/** Built-in value references. */
var propertyIsEnumerable = objectProto.propertyIsEnumerable;
/**
* 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")
);
};
module.exports = isArguments;
/***/
},
/* 31 */
/***/ function (module, exports) {
/** Used as references for various `Number` constants. */
var MAX_SAFE_INTEGER = 9007199254740991;
/** Used to detect unsigned integer values. */
var reIsUint = /^(?:0|[1-9]\d*)$/;
/**
* 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
);
}
module.exports = isIndex;
/***/
},
/* 32 */
/***/ function (module, exports, __webpack_require__) {
var isArray = __webpack_require__(15),
isKey = __webpack_require__(232),
stringToPath = __webpack_require__(233),
toString = __webpack_require__(236);
/**
* 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));
}
module.exports = castPath;
/***/
},
/* 33 */
/***/ function (module, exports, __webpack_require__) {
var arrayWithoutHoles = __webpack_require__(224);
var iterableToArray = __webpack_require__(225);
var unsupportedIterableToArray = __webpack_require__(60);
var nonIterableSpread = __webpack_require__(226);
function _toConsumableArray(arr) {
return (
arrayWithoutHoles(arr) ||
iterableToArray(arr) ||
unsupportedIterableToArray(arr) ||
nonIterableSpread()
);
}
module.exports = _toConsumableArray;
(module.exports["default"] = module.exports),
(module.exports.__esModule = true);
/***/
},
/* 34 */
/***/ function (module, exports, __webpack_require__) {
module.exports = {
determinant: __webpack_require__(251),
transpose: __webpack_require__(252),
multiply: __webpack_require__(253),
identity: __webpack_require__(254),
adjoint: __webpack_require__(255),
rotate: __webpack_require__(256),
invert: __webpack_require__(257),
create: __webpack_require__(258),
scale: __webpack_require__(259),
copy: __webpack_require__(260),
frob: __webpack_require__(261),
ldu: __webpack_require__(262),
};
/***/
},
/* 35 */
/***/ function (module, exports, __webpack_require__) {
var baseIsNative = __webpack_require__(102),
getValue = __webpack_require__(108);
/**
* 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;
}
module.exports = getNative;
/***/
},
/* 36 */
/***/ function (module, exports, __webpack_require__) {
var baseGetTag = __webpack_require__(22),
isObject = __webpack_require__(14);
/** `Object#toString` result references. */
var asyncTag = "[object AsyncFunction]",
funcTag = "[object Function]",
genTag = "[object GeneratorFunction]",
proxyTag = "[object Proxy]";
/**
* 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
);
}
module.exports = isFunction;
/***/
},
/* 37 */
/***/ function (module, exports, __webpack_require__) {
var defineProperty = __webpack_require__(49);
/**
* 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;
}
}
module.exports = baseAssignValue;
/***/
},
/* 38 */
/***/ function (module, exports) {
module.exports = function (module) {
if (!module.webpackPolyfill) {
module.deprecate = function () {};
module.paths = []; // module.parent = undefined by default
if (!module.children) module.children = [];
Object.defineProperty(module, "loaded", {
enumerable: true,
get: function () {
return module.l;
},
});
Object.defineProperty(module, "id", {
enumerable: true,
get: function () {
return module.i;
},
});
module.webpackPolyfill = 1;
}
return module;
};
/***/
},
/* 39 */
/***/ function (module, exports, __webpack_require__) {
var isFunction = __webpack_require__(36),
isLength = __webpack_require__(40);
/**
* 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)
);
}
module.exports = isArrayLike;
/***/
},
/* 40 */
/***/ function (module, exports) {
/** Used as references for various `Number` constants. */
var MAX_SAFE_INTEGER = 9007199254740991;
/**
* 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
);
}
module.exports = isLength;
/***/
},
/* 41 */
/***/ function (module, exports) {
function _setPrototypeOf(o, p) {
module.exports = _setPrototypeOf =
Object.setPrototypeOf ||
function _setPrototypeOf(o, p) {
o.__proto__ = p;
return o;
};
(module.exports["default"] = module.exports),
(module.exports.__esModule = true);
return _setPrototypeOf(o, p);
}
module.exports = _setPrototypeOf;
(module.exports["default"] = module.exports),
(module.exports.__esModule = true);
/***/
},
/* 42 */
/***/ function (module, exports, __webpack_require__) {
var baseGetTag = __webpack_require__(22),
isObjectLike = __webpack_require__(18);
/** `Object#toString` result references. */
var symbolTag = "[object Symbol]";
/**
* 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)
);
}
module.exports = isSymbol;
/***/
},
/* 43 */
/***/ function (module, exports, __webpack_require__) {
var isSymbol = __webpack_require__(42);
/** Used as references for various `Number` constants. */
var INFINITY = 1 / 0;
/**
* 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;
}
module.exports = toKey;
/***/
},
/* 44 */
/***/ function (module, exports, __webpack_require__) {
var getNative = __webpack_require__(35),
root = __webpack_require__(17);
/* Built-in method references that are verified to be native. */
var Map = getNative(root, "Map");
module.exports = Map;
/***/
},
/* 45 */
/***/ function (module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */ (function (global) {
/** Detect free variable `global` from Node.js. */
var freeGlobal =
typeof global == "object" &&
global &&
global.Object === Object &&
global;
module.exports = freeGlobal;
/* WEBPACK VAR INJECTION */
}.call(this, __webpack_require__(46)));
/***/
},
/* 46 */
/***/ function (module, exports) {
var g; // This works in non-strict mode
g = (function () {
return this;
})();
try {
// This works if eval is allowed (see CSP)
g = g || new Function("return this")();
} catch (e) {
// This works if the window reference is available
if (typeof window === "object") g = window;
} // g can still be undefined, but nothing to do about it...
// We return undefined, instead of nothing here, so it's
// easier to handle this case. if(!global) { ...}
module.exports = g;
/***/
},
/* 47 */
/***/ function (module, exports, __webpack_require__) {
var mapCacheClear = __webpack_require__(109),
mapCacheDelete = __webpack_require__(116),
mapCacheGet = __webpack_require__(118),
mapCacheHas = __webpack_require__(119),
mapCacheSet = __webpack_require__(120);
/**
* 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]);
}
} // Add methods to `MapCache`.
MapCache.prototype.clear = mapCacheClear;
MapCache.prototype["delete"] = mapCacheDelete;
MapCache.prototype.get = mapCacheGet;
MapCache.prototype.has = mapCacheHas;
MapCache.prototype.set = mapCacheSet;
module.exports = MapCache;
/***/
},
/* 48 */
/***/ function (module, exports, __webpack_require__) {
var baseAssignValue = __webpack_require__(37),
eq = __webpack_require__(26);
/**
* 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);
}
}
module.exports = assignMergeValue;
/***/
},
/* 49 */
/***/ function (module, exports, __webpack_require__) {
var getNative = __webpack_require__(35);
var defineProperty = (function () {
try {
var func = getNative(Object, "defineProperty");
func({}, "", {});
return func;
} catch (e) {}
})();
module.exports = defineProperty;
/***/
},
/* 50 */
/***/ function (module, exports, __webpack_require__) {
var overArg = __webpack_require__(131);
/** Built-in value references. */
var getPrototype = overArg(Object.getPrototypeOf, Object);
module.exports = getPrototype;
/***/
},
/* 51 */
/***/ function (module, exports) {
/** Used for built-in method references. */
var objectProto = Object.prototype;
/**
* 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;
}
module.exports = isPrototype;
/***/
},
/* 52 */
/***/ function (module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */ (function (module) {
var root = __webpack_require__(17),
stubFalse = __webpack_require__(134);
/** 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;
/** Built-in value references. */
var Buffer = moduleExports ? root.Buffer : undefined;
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined;
/**
* 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;
module.exports = isBuffer;
/* WEBPACK VAR INJECTION */
}.call(this, __webpack_require__(38)(module)));
/***/
},
/* 53 */
/***/ function (module, exports, __webpack_require__) {
var baseIsTypedArray = __webpack_require__(136),
baseUnary = __webpack_require__(137),
nodeUtil = __webpack_require__(138);
/* Node.js helper references. */
var nodeIsTypedArray = nodeUtil && nodeUtil.isTypedArray;
/**
* 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;
module.exports = isTypedArray;
/***/
},
/* 54 */
/***/ function (module, exports) {
/**
* 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];
}
module.exports = safeGet;
/***/
},
/* 55 */
/***/ function (module, exports, __webpack_require__) {
var baseAssignValue = __webpack_require__(37),
eq = __webpack_require__(26);
/** Used for built-in method references. */
var objectProto = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/**
* 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);
}
}
module.exports = assignValue;
/***/
},
/* 56 */
/***/ function (module, exports, __webpack_require__) {
var arrayLikeKeys = __webpack_require__(141),
baseKeysIn = __webpack_require__(143),
isArrayLike = __webpack_require__(39);
/**
* 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);
}
module.exports = keysIn;
/***/
},
/* 57 */
/***/ function (module, exports) {
/**
* This method returns the first argument it receives.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Util
* @param {*} value Any value.
* @returns {*} Returns `value`.
* @example
*
* var object = { 'a': 1 };
*
* console.log(_.identity(object) === object);
* // => true
*/
function identity(value) {
return value;
}
module.exports = identity;
/***/
},
/* 58 */
/***/ function (module, exports, __webpack_require__) {
var apply = __webpack_require__(147);
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeMax = Math.max;
/**
* 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);
};
}
module.exports = overRest;
/***/
},
/* 59 */
/***/ function (module, exports, __webpack_require__) {
var baseSetToString = __webpack_require__(148),
shortOut = __webpack_require__(150);
/**
* 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);
module.exports = setToString;
/***/
},
/* 60 */
/***/ function (module, exports, __webpack_require__) {
var arrayLikeToArray = __webpack_require__(61);
function _unsupportedIterableToArray(o, minLen) {
if (!o) return;
if (typeof o === "string")
return arrayLikeToArray(o, minLen);
var n = Object.prototype.toString.call(o).slice(8, -1);
if (n === "Object" && o.constructor) n = o.constructor.name;
if (n === "Map" || n === "Set") return Array.from(o);
if (
n === "Arguments" ||
/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)
)
return arrayLikeToArray(o, minLen);
}
module.exports = _unsupportedIterableToArray;
(module.exports["default"] = module.exports),
(module.exports.__esModule = true);
/***/
},
/* 61 */
/***/ function (module, exports) {
function _arrayLikeToArray(arr, len) {
if (len == null || len > arr.length) len = arr.length;
for (var i = 0, arr2 = new Array(len); i < len; i++) {
arr2[i] = arr[i];
}
return arr2;
}
module.exports = _arrayLikeToArray;
(module.exports["default"] = module.exports),
(module.exports.__esModule = true);
/***/
},
/* 62 */
/***/ function (module, exports) {
module.exports = 0.000001;
/***/
},
/* 63 */
/***/ function (module, exports) {
module.exports = create;
/**
* Creates a new, empty vec2
*
* @returns {vec2} a new 2D vector
*/
function create() {
var out = new Float32Array(2);
out[0] = 0;
out[1] = 0;
return out;
}
/***/
},
/* 64 */
/***/ function (module, exports) {
module.exports = subtract;
/**
* Subtracts vector b from vector a
*
* @param {vec2} out the receiving vector
* @param {vec2} a the first operand
* @param {vec2} b the second operand
* @returns {vec2} out
*/
function subtract(out, a, b) {
out[0] = a[0] - b[0];
out[1] = a[1] - b[1];
return out;
}
/***/
},
/* 65 */
/***/ function (module, exports) {
module.exports = multiply;
/**
* Multiplies two vec2's
*
* @param {vec2} out the receiving vector
* @param {vec2} a the first operand
* @param {vec2} b the second operand
* @returns {vec2} out
*/
function multiply(out, a, b) {
out[0] = a[0] * b[0];
out[1] = a[1] * b[1];
return out;
}
/***/
},
/* 66 */
/***/ function (module, exports) {
module.exports = divide;
/**
* Divides two vec2's
*
* @param {vec2} out the receiving vector
* @param {vec2} a the first operand
* @param {vec2} b the second operand
* @returns {vec2} out
*/
function divide(out, a, b) {
out[0] = a[0] / b[0];
out[1] = a[1] / b[1];
return out;
}
/***/
},
/* 67 */
/***/ function (module, exports) {
module.exports = distance;
/**
* Calculates the euclidian distance between two vec2's
*
* @param {vec2} a the first operand
* @param {vec2} b the second operand
* @returns {Number} distance between a and b
*/
function distance(a, b) {
var x = b[0] - a[0],
y = b[1] - a[1];
return Math.sqrt(x * x + y * y);
}
/***/
},
/* 68 */
/***/ function (module, exports) {
module.exports = squaredDistance;
/**
* Calculates the squared euclidian distance between two vec2's
*
* @param {vec2} a the first operand
* @param {vec2} b the second operand
* @returns {Number} squared distance between a and b
*/
function squaredDistance(a, b) {
var x = b[0] - a[0],
y = b[1] - a[1];
return x * x + y * y;
}
/***/
},
/* 69 */
/***/ function (module, exports) {
module.exports = length;
/**
* Calculates the length of a vec2
*
* @param {vec2} a vector to calculate length of
* @returns {Number} length of a
*/
function length(a) {
var x = a[0],
y = a[1];
return Math.sqrt(x * x + y * y);
}
/***/
},
/* 70 */
/***/ function (module, exports) {
module.exports = squaredLength;
/**
* Calculates the squared length of a vec2
*
* @param {vec2} a vector to calculate squared length of
* @returns {Number} squared length of a
*/
function squaredLength(a) {
var x = a[0],
y = a[1];
return x * x + y * y;
}
/***/
},
/* 71 */
/***/ function (module, exports) {
module.exports = 0.000001;
/***/
},
/* 72 */
/***/ function (module, exports) {
module.exports = create;
/**
* Creates a new, empty vec3
*
* @returns {vec3} a new 3D vector
*/
function create() {
var out = new Float32Array(3);
out[0] = 0;
out[1] = 0;
out[2] = 0;
return out;
}
/***/
},
/* 73 */
/***/ function (module, exports) {
module.exports = fromValues;
/**
* Creates a new vec3 initialized with the given values
*
* @param {Number} x X component
* @param {Number} y Y component
* @param {Number} z Z component
* @returns {vec3} a new 3D vector
*/
function fromValues(x, y, z) {
var out = new Float32Array(3);
out[0] = x;
out[1] = y;
out[2] = z;
return out;
}
/***/
},
/* 74 */
/***/ function (module, exports) {
module.exports = normalize;
/**
* Normalize a vec3
*
* @param {vec3} out the receiving vector
* @param {vec3} a vector to normalize
* @returns {vec3} out
*/
function normalize(out, a) {
var x = a[0],
y = a[1],
z = a[2];
var len = x * x + y * y + z * z;
if (len > 0) {
//TODO: evaluate use of glm_invsqrt here?
len = 1 / Math.sqrt(len);
out[0] = a[0] * len;
out[1] = a[1] * len;
out[2] = a[2] * len;
}
return out;
}
/***/
},
/* 75 */
/***/ function (module, exports) {
module.exports = dot;
/**
* Calculates the dot product of two vec3's
*
* @param {vec3} a the first operand
* @param {vec3} b the second operand
* @returns {Number} dot product of a and b
*/
function dot(a, b) {
return a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
}
/***/
},
/* 76 */
/***/ function (module, exports) {
module.exports = subtract;
/**
* Subtracts vector b from vector a
*
* @param {vec3} out the receiving vector
* @param {vec3} a the first operand
* @param {vec3} b the second operand
* @returns {vec3} out
*/
function subtract(out, a, b) {
out[0] = a[0] - b[0];
out[1] = a[1] - b[1];
out[2] = a[2] - b[2];
return out;
}
/***/
},
/* 77 */
/***/ function (module, exports) {
module.exports = multiply;
/**
* Multiplies two vec3's
*
* @param {vec3} out the receiving vector
* @param {vec3} a the first operand
* @param {vec3} b the second operand
* @returns {vec3} out
*/
function multiply(out, a, b) {
out[0] = a[0] * b[0];
out[1] = a[1] * b[1];
out[2] = a[2] * b[2];
return out;
}
/***/
},
/* 78 */
/***/ function (module, exports) {
module.exports = divide;
/**
* Divides two vec3's
*
* @param {vec3} out the receiving vector
* @param {vec3} a the first operand
* @param {vec3} b the second operand
* @returns {vec3} out
*/
function divide(out, a, b) {
out[0] = a[0] / b[0];
out[1] = a[1] / b[1];
out[2] = a[2] / b[2];
return out;
}
/***/
},
/* 79 */
/***/ function (module, exports) {
module.exports = distance;
/**
* Calculates the euclidian distance between two vec3's
*
* @param {vec3} a the first operand
* @param {vec3} b the second operand
* @returns {Number} distance between a and b
*/
function distance(a, b) {
var x = b[0] - a[0],
y = b[1] - a[1],
z = b[2] - a[2];
return Math.sqrt(x * x + y * y + z * z);
}
/***/
},
/* 80 */
/***/ function (module, exports) {
module.exports = squaredDistance;
/**
* Calculates the squared euclidian distance between two vec3's
*
* @param {vec3} a the first operand
* @param {vec3} b the second operand
* @returns {Number} squared distance between a and b
*/
function squaredDistance(a, b) {
var x = b[0] - a[0],
y = b[1] - a[1],
z = b[2] - a[2];
return x * x + y * y + z * z;
}
/***/
},
/* 81 */
/***/ function (module, exports) {
module.exports = length;
/**
* Calculates the length of a vec3
*
* @param {vec3} a vector to calculate length of
* @returns {Number} length of a
*/
function length(a) {
var x = a[0],
y = a[1],
z = a[2];
return Math.sqrt(x * x + y * y + z * z);
}
/***/
},
/* 82 */
/***/ function (module, exports) {
module.exports = squaredLength;
/**
* Calculates the squared length of a vec3
*
* @param {vec3} a vector to calculate squared length of
* @returns {Number} squared length of a
*/
function squaredLength(a) {
var x = a[0],
y = a[1],
z = a[2];
return x * x + y * y + z * z;
}
/***/
},
/* 83 */
/***/ function (module, exports, __webpack_require__) {
var arrayWithHoles = __webpack_require__(153);
var iterableToArrayLimit = __webpack_require__(154);
var unsupportedIterableToArray = __webpack_require__(60);
var nonIterableRest = __webpack_require__(155);
function _slicedToArray(arr, i) {
return (
arrayWithHoles(arr) ||
iterableToArrayLimit(arr, i) ||
unsupportedIterableToArray(arr, i) ||
nonIterableRest()
);
}
module.exports = _slicedToArray;
(module.exports["default"] = module.exports),
(module.exports.__esModule = true);
/***/
},
/* 84 */
/***/ function (module, exports, __webpack_require__) {
module.exports = {
EPSILON: __webpack_require__(71),
create: __webpack_require__(72),
clone: __webpack_require__(191),
angle: __webpack_require__(192),
fromValues: __webpack_require__(73),
copy: __webpack_require__(193),
set: __webpack_require__(194),
equals: __webpack_require__(195),
exactEquals: __webpack_require__(196),
add: __webpack_require__(197),
subtract: __webpack_require__(76),
sub: __webpack_require__(198),
multiply: __webpack_require__(77),
mul: __webpack_require__(199),
divide: __webpack_require__(78),
div: __webpack_require__(200),
min: __webpack_require__(201),
max: __webpack_require__(202),
floor: __webpack_require__(203),
ceil: __webpack_require__(204),
round: __webpack_require__(205),
scale: __webpack_require__(206),
scaleAndAdd: __webpack_require__(207),
distance: __webpack_require__(79),
dist: __webpack_require__(208),
squaredDistance: __webpack_require__(80),
sqrDist: __webpack_require__(209),
length: __webpack_require__(81),
len: __webpack_require__(210),
squaredLength: __webpack_require__(82),
sqrLen: __webpack_require__(211),
negate: __webpack_require__(212),
inverse: __webpack_require__(213),
normalize: __webpack_require__(74),
dot: __webpack_require__(75),
cross: __webpack_require__(214),
lerp: __webpack_require__(215),
random: __webpack_require__(216),
transformMat4: __webpack_require__(217),
transformMat3: __webpack_require__(218),
transformQuat: __webpack_require__(219),
rotateX: __webpack_require__(220),
rotateY: __webpack_require__(221),
rotateZ: __webpack_require__(222),
forEach: __webpack_require__(223),
};
/***/
},
/* 85 */
/***/ function (module, exports, __webpack_require__) {
var basePick = __webpack_require__(229),
flatRest = __webpack_require__(243);
/**
* 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);
});
module.exports = pick;
/***/
},
/* 86 */
/***/ function (module, exports, __webpack_require__) {
var getPrototypeOf = __webpack_require__(2);
var setPrototypeOf = __webpack_require__(41);
var isNativeFunction = __webpack_require__(248);
var construct = __webpack_require__(249);
function _wrapNativeSuper(Class) {
var _cache =
typeof Map === "function" ? new Map() : undefined;
module.exports = _wrapNativeSuper =
function _wrapNativeSuper(Class) {
if (Class === null || !isNativeFunction(Class))
return Class;
if (typeof Class !== "function") {
throw new TypeError(
"Super expression must either be null or a function"
);
}
if (typeof _cache !== "undefined") {
if (_cache.has(Class)) return _cache.get(Class);
_cache.set(Class, Wrapper);
}
function Wrapper() {
return construct(
Class,
arguments,
getPrototypeOf(this).constructor
);
}
Wrapper.prototype = Object.create(Class.prototype, {
constructor: {
value: Wrapper,
enumerable: false,
writable: true,
configurable: true,
},
});
return setPrototypeOf(Wrapper, Class);
};
(module.exports["default"] = module.exports),
(module.exports.__esModule = true);
return _wrapNativeSuper(Class);
}
module.exports = _wrapNativeSuper;
(module.exports["default"] = module.exports),
(module.exports.__esModule = true);
/***/
},
/* 87 */
/***/ function (module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony import */ var _tracer__WEBPACK_IMPORTED_MODULE_0__ =
__webpack_require__(21);
/**
* http://www.codeproject.com/Tips/407172/Connected-Component-Labeling-and-Vectorization
*/
var Rasterizer = {
createContour2D: function createContour2D() {
return {
dir: null,
index: null,
firstVertex: null,
insideContours: null,
nextpeer: null,
prevpeer: null,
};
},
CONTOUR_DIR: {
CW_DIR: 0,
CCW_DIR: 1,
UNKNOWN_DIR: 2,
},
DIR: {
OUTSIDE_EDGE: -32767,
INSIDE_EDGE: -32766,
},
create: function create(imageWrapper, labelWrapper) {
var imageData = imageWrapper.data;
var labelData = labelWrapper.data;
var width = imageWrapper.size.x;
var height = imageWrapper.size.y;
var tracer = _tracer__WEBPACK_IMPORTED_MODULE_0__[
/* default */ "a"
].create(imageWrapper, labelWrapper);
return {
rasterize: function rasterize(depthlabel) {
var color;
var bc;
var lc;
var labelindex;
var cx;
var cy;
var colorMap = [];
var vertex;
var p;
var cc;
var sc;
var pos;
var connectedCount = 0;
var i;
for (i = 0; i < 400; i++) {
colorMap[i] = 0;
}
colorMap[0] = imageData[0];
cc = null;
for (cy = 1; cy < height - 1; cy++) {
labelindex = 0;
bc = colorMap[0];
for (cx = 1; cx < width - 1; cx++) {
pos = cy * width + cx;
if (labelData[pos] === 0) {
color = imageData[pos];
if (color !== bc) {
if (labelindex === 0) {
lc = connectedCount + 1;
colorMap[lc] = color;
bc = color;
vertex =
tracer.contourTracing(
cy,
cx,
lc,
color,
Rasterizer.DIR
.OUTSIDE_EDGE
);
if (vertex !== null) {
connectedCount++;
labelindex = lc;
p =
Rasterizer.createContour2D();
p.dir =
Rasterizer.CONTOUR_DIR.CW_DIR;
p.index = labelindex;
p.firstVertex = vertex;
p.nextpeer = cc;
p.insideContours = null;
if (cc !== null) {
cc.prevpeer = p;
}
cc = p;
}
} else {
vertex =
tracer.contourTracing(
cy,
cx,
Rasterizer.DIR
.INSIDE_EDGE,
color,
labelindex
);
if (vertex !== null) {
p =
Rasterizer.createContour2D();
p.firstVertex = vertex;
p.insideContours = null;
if (depthlabel === 0) {
p.dir =
Rasterizer.CONTOUR_DIR.CCW_DIR;
} else {
p.dir =
Rasterizer.CONTOUR_DIR.CW_DIR;
}
p.index = depthlabel;
sc = cc;
while (
sc !== null &&
sc.index !==
labelindex
) {
sc = sc.nextpeer;
}
if (sc !== null) {
p.nextpeer =
sc.insideContours;
if (
sc.insideContours !==
null
) {
sc.insideContours.prevpeer =
p;
}
sc.insideContours =
p;
}
}
}
} else {
labelData[pos] = labelindex;
}
} else if (
labelData[pos] ===
Rasterizer.DIR.OUTSIDE_EDGE ||
labelData[pos] ===
Rasterizer.DIR.INSIDE_EDGE
) {
labelindex = 0;
if (
labelData[pos] ===
Rasterizer.DIR.INSIDE_EDGE
) {
bc = imageData[pos];
} else {
bc = colorMap[0];
}
} else {
labelindex = labelData[pos];
bc = colorMap[labelindex];
}
}
}
sc = cc;
while (sc !== null) {
sc.index = depthlabel;
sc = sc.nextpeer;
}
return {
cc: cc,
count: connectedCount,
};
},
debug: {
drawContour: function drawContour(
canvas,
firstContour
) {
var ctx = canvas.getContext("2d");
var pq = firstContour;
var iq;
var q;
var p;
ctx.strokeStyle = "red";
ctx.fillStyle = "red";
ctx.lineWidth = 1;
if (pq !== null) {
iq = pq.insideContours;
} else {
iq = null;
}
while (pq !== null) {
if (iq !== null) {
q = iq;
iq = iq.nextpeer;
} else {
q = pq;
pq = pq.nextpeer;
if (pq !== null) {
iq = pq.insideContours;
} else {
iq = null;
}
}
switch (q.dir) {
case Rasterizer.CONTOUR_DIR.CW_DIR:
ctx.strokeStyle = "red";
break;
case Rasterizer.CONTOUR_DIR.CCW_DIR:
ctx.strokeStyle = "blue";
break;
case Rasterizer.CONTOUR_DIR
.UNKNOWN_DIR:
ctx.strokeStyle = "green";
break;
}
p = q.firstVertex;
ctx.beginPath();
ctx.moveTo(p.x, p.y);
do {
p = p.next;
ctx.lineTo(p.x, p.y);
} while (p !== q.firstVertex);
ctx.stroke();
}
},
},
};
},
};
/* harmony default export */ __webpack_exports__["a"] =
Rasterizer;
/***/
},
/* 88 */
/***/ function (module, __webpack_exports__, __webpack_require__) {
"use strict";
/* eslint-disable no-param-reassign */
/* eslint-disable no-bitwise */
/* eslint-disable eqeqeq */
/* @preserve ASM BEGIN */
function Skeletonizer(stdlib, foreign, buffer) {
"use asm";
var images = new stdlib.Uint8Array(buffer);
var size = foreign.size | 0;
var imul = stdlib.Math.imul;
function erode(inImagePtr, outImagePtr) {
inImagePtr |= 0;
outImagePtr |= 0;
var v = 0;
var u = 0;
var sum = 0;
var yStart1 = 0;
var yStart2 = 0;
var xStart1 = 0;
var xStart2 = 0;
var offset = 0;
for (
v = 1;
(v | 0) < ((size - 1) | 0);
v = (v + 1) | 0
) {
offset = (offset + size) | 0;
for (
u = 1;
(u | 0) < ((size - 1) | 0);
u = (u + 1) | 0
) {
yStart1 = (offset - size) | 0;
yStart2 = (offset + size) | 0;
xStart1 = (u - 1) | 0;
xStart2 = (u + 1) | 0;
sum =
((images[
(inImagePtr + yStart1 + xStart1) | 0
] |
0) +
(images[
(inImagePtr + yStart1 + xStart2) | 0
] |
0) +
(images[(inImagePtr + offset + u) | 0] |
0) +
(images[
(inImagePtr + yStart2 + xStart1) | 0
] |
0) +
(images[
(inImagePtr + yStart2 + xStart2) | 0
] |
0)) |
0;
if ((sum | 0) == (5 | 0)) {
images[(outImagePtr + offset + u) | 0] = 1;
} else {
images[(outImagePtr + offset + u) | 0] = 0;
}
}
}
}
function subtract(aImagePtr, bImagePtr, outImagePtr) {
aImagePtr |= 0;
bImagePtr |= 0;
outImagePtr |= 0;
var length = 0;
length = imul(size, size) | 0;
while ((length | 0) > 0) {
length = (length - 1) | 0;
images[(outImagePtr + length) | 0] =
((images[(aImagePtr + length) | 0] | 0) -
(images[(bImagePtr + length) | 0] | 0)) |
0;
}
}
function bitwiseOr(aImagePtr, bImagePtr, outImagePtr) {
aImagePtr |= 0;
bImagePtr |= 0;
outImagePtr |= 0;
var length = 0;
length = imul(size, size) | 0;
while ((length | 0) > 0) {
length = (length - 1) | 0;
images[(outImagePtr + length) | 0] =
images[(aImagePtr + length) | 0] |
0 |
(images[(bImagePtr + length) | 0] | 0) |
0;
}
}
function countNonZero(imagePtr) {
imagePtr |= 0;
var sum = 0;
var length = 0;
length = imul(size, size) | 0;
while ((length | 0) > 0) {
length = (length - 1) | 0;
sum =
((sum | 0) +
(images[(imagePtr + length) | 0] | 0)) |
0;
}
return sum | 0;
}
function init(imagePtr, value) {
imagePtr |= 0;
value |= 0;
var length = 0;
length = imul(size, size) | 0;
while ((length | 0) > 0) {
length = (length - 1) | 0;
images[(imagePtr + length) | 0] = value;
}
}
function dilate(inImagePtr, outImagePtr) {
inImagePtr |= 0;
outImagePtr |= 0;
var v = 0;
var u = 0;
var sum = 0;
var yStart1 = 0;
var yStart2 = 0;
var xStart1 = 0;
var xStart2 = 0;
var offset = 0;
for (
v = 1;
(v | 0) < ((size - 1) | 0);
v = (v + 1) | 0
) {
offset = (offset + size) | 0;
for (
u = 1;
(u | 0) < ((size - 1) | 0);
u = (u + 1) | 0
) {
yStart1 = (offset - size) | 0;
yStart2 = (offset + size) | 0;
xStart1 = (u - 1) | 0;
xStart2 = (u + 1) | 0;
sum =
((images[
(inImagePtr + yStart1 + xStart1) | 0
] |
0) +
(images[
(inImagePtr + yStart1 + xStart2) | 0
] |
0) +
(images[(inImagePtr + offset + u) | 0] |
0) +
(images[
(inImagePtr + yStart2 + xStart1) | 0
] |
0) +
(images[
(inImagePtr + yStart2 + xStart2) | 0
] |
0)) |
0;
if ((sum | 0) > (0 | 0)) {
images[(outImagePtr + offset + u) | 0] = 1;
} else {
images[(outImagePtr + offset + u) | 0] = 0;
}
}
}
}
function memcpy(srcImagePtr, dstImagePtr) {
srcImagePtr |= 0;
dstImagePtr |= 0;
var length = 0;
length = imul(size, size) | 0;
while ((length | 0) > 0) {
length = (length - 1) | 0;
images[(dstImagePtr + length) | 0] =
images[(srcImagePtr + length) | 0] | 0;
}
}
function zeroBorder(imagePtr) {
imagePtr |= 0;
var x = 0;
var y = 0;
for (
x = 0;
(x | 0) < ((size - 1) | 0);
x = (x + 1) | 0
) {
images[(imagePtr + x) | 0] = 0;
images[(imagePtr + y) | 0] = 0;
y = (y + size - 1) | 0;
images[(imagePtr + y) | 0] = 0;
y = (y + 1) | 0;
}
for (x = 0; (x | 0) < (size | 0); x = (x + 1) | 0) {
images[(imagePtr + y) | 0] = 0;
y = (y + 1) | 0;
}
}
function skeletonize() {
var subImagePtr = 0;
var erodedImagePtr = 0;
var tempImagePtr = 0;
var skelImagePtr = 0;
var sum = 0;
var done = 0;
erodedImagePtr = imul(size, size) | 0;
tempImagePtr = (erodedImagePtr + erodedImagePtr) | 0;
skelImagePtr = (tempImagePtr + erodedImagePtr) | 0; // init skel-image
init(skelImagePtr, 0);
zeroBorder(subImagePtr);
do {
erode(subImagePtr, erodedImagePtr);
dilate(erodedImagePtr, tempImagePtr);
subtract(subImagePtr, tempImagePtr, tempImagePtr);
bitwiseOr(skelImagePtr, tempImagePtr, skelImagePtr);
memcpy(erodedImagePtr, subImagePtr);
sum = countNonZero(subImagePtr) | 0;
done = ((sum | 0) == 0) | 0;
} while (!done);
}
return {
skeletonize: skeletonize,
};
}
/* @preserve ASM END */
/* harmony default export */ __webpack_exports__["a"] =
Skeletonizer;
/* eslint-enable eqeqeq */
/***/
},
/* 89 */
/***/ function (module, exports, __webpack_require__) {
module.exports = __webpack_require__(263);
/***/
},
/* 90 */
/***/ function (module, exports, __webpack_require__) {
var Stack = __webpack_require__(91),
assignMergeValue = __webpack_require__(48),
baseFor = __webpack_require__(121),
baseMergeDeep = __webpack_require__(123),
isObject = __webpack_require__(14),
keysIn = __webpack_require__(56),
safeGet = __webpack_require__(54);
/**
* 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
);
}
module.exports = baseMerge;
/***/
},
/* 91 */
/***/ function (module, exports, __webpack_require__) {
var ListCache = __webpack_require__(24),
stackClear = __webpack_require__(97),
stackDelete = __webpack_require__(98),
stackGet = __webpack_require__(99),
stackHas = __webpack_require__(100),
stackSet = __webpack_require__(101);
/**
* 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;
} // Add methods to `Stack`.
Stack.prototype.clear = stackClear;
Stack.prototype["delete"] = stackDelete;
Stack.prototype.get = stackGet;
Stack.prototype.has = stackHas;
Stack.prototype.set = stackSet;
module.exports = Stack;
/***/
},
/* 92 */
/***/ function (module, exports) {
/**
* Removes all key-value entries from the list cache.
*
* @private
* @name clear
* @memberOf ListCache
*/
function listCacheClear() {
this.__data__ = [];
this.size = 0;
}
module.exports = listCacheClear;
/***/
},
/* 93 */
/***/ function (module, exports, __webpack_require__) {
var assocIndexOf = __webpack_require__(25);
/** Used for built-in method references. */
var arrayProto = Array.prototype;
/** Built-in value references. */
var splice = arrayProto.splice;
/**
* 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;
}
module.exports = listCacheDelete;
/***/
},
/* 94 */
/***/ function (module, exports, __webpack_require__) {
var assocIndexOf = __webpack_require__(25);
/**
* 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];
}
module.exports = listCacheGet;
/***/
},
/* 95 */
/***/ function (module, exports, __webpack_require__) {
var assocIndexOf = __webpack_require__(25);
/**
* 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;
}
module.exports = listCacheHas;
/***/
},
/* 96 */
/***/ function (module, exports, __webpack_require__) {
var assocIndexOf = __webpack_require__(25);
/**
* 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;
}
module.exports = listCacheSet;
/***/
},
/* 97 */
/***/ function (module, exports, __webpack_require__) {
var ListCache = __webpack_require__(24);
/**
* Removes all key-value entries from the stack.
*
* @private
* @name clear
* @memberOf Stack
*/
function stackClear() {
this.__data__ = new ListCache();
this.size = 0;
}
module.exports = stackClear;
/***/
},
/* 98 */
/***/ function (module, exports) {
/**
* 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;
}
module.exports = stackDelete;
/***/
},
/* 99 */
/***/ function (module, exports) {
/**
* 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);
}
module.exports = stackGet;
/***/
},
/* 100 */
/***/ function (module, exports) {
/**
* 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);
}
module.exports = stackHas;
/***/
},
/* 101 */
/***/ function (module, exports, __webpack_require__) {
var ListCache = __webpack_require__(24),
Map = __webpack_require__(44),
MapCache = __webpack_require__(47);
/** Used as the size to enable large array optimizations. */
var LARGE_ARRAY_SIZE = 200;
/**
* 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;
}
module.exports = stackSet;
/***/
},
/* 102 */
/***/ function (module, exports, __webpack_require__) {
var isFunction = __webpack_require__(36),
isMasked = __webpack_require__(105),
isObject = __webpack_require__(14),
toSource = __webpack_require__(107);
/**
* Used to match `RegExp`
* [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns).
*/
var reRegExpChar = /[\\^$.*+?()[\]{}|]/g;
/** Used to detect host constructors (Safari). */
var reIsHostCtor = /^\[object .+?Constructor\]$/;
/** Used for built-in method references. */
var funcProto = Function.prototype,
objectProto = Object.prototype;
/** 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 detect if a method is native. */
var reIsNative = RegExp(
"^" +
funcToString
.call(hasOwnProperty)
.replace(reRegExpChar, "\\$&")
.replace(
/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,
"$1.*?"
) +
"$"
);
/**
* 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));
}
module.exports = baseIsNative;
/***/
},
/* 103 */
/***/ function (module, exports, __webpack_require__) {
var Symbol = __webpack_require__(27);
/** Used for built-in method references. */
var objectProto = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/**
* Used to resolve the
* [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
* of values.
*/
var nativeObjectToString = objectProto.toString;
/** Built-in value references. */
var symToStringTag = Symbol ? Symbol.toStringTag : 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;
}
module.exports = getRawTag;
/***/
},
/* 104 */
/***/ function (module, exports) {
/** Used for built-in method references. */
var objectProto = Object.prototype;
/**
* Used to resolve the
* [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
* of values.
*/
var nativeObjectToString = objectProto.toString;
/**
* 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);
}
module.exports = objectToString;
/***/
},
/* 105 */
/***/ function (module, exports, __webpack_require__) {
var coreJsData = __webpack_require__(106);
/** 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 : "";
})();
/**
* 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;
}
module.exports = isMasked;
/***/
},
/* 106 */
/***/ function (module, exports, __webpack_require__) {
var root = __webpack_require__(17);
/** Used to detect overreaching core-js shims. */
var coreJsData = root["__core-js_shared__"];
module.exports = coreJsData;
/***/
},
/* 107 */
/***/ function (module, exports) {
/** Used for built-in method references. */
var funcProto = Function.prototype;
/** Used to resolve the decompiled source of functions. */
var funcToString = funcProto.toString;
/**
* 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 "";
}
module.exports = toSource;
/***/
},
/* 108 */
/***/ function (module, exports) {
/**
* 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];
}
module.exports = getValue;
/***/
},
/* 109 */
/***/ function (module, exports, __webpack_require__) {
var Hash = __webpack_require__(110),
ListCache = __webpack_require__(24),
Map = __webpack_require__(44);
/**
* 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(),
};
}
module.exports = mapCacheClear;
/***/
},
/* 110 */
/***/ function (module, exports, __webpack_require__) {
var hashClear = __webpack_require__(111),
hashDelete = __webpack_require__(112),
hashGet = __webpack_require__(113),
hashHas = __webpack_require__(114),
hashSet = __webpack_require__(115);
/**
* 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]);
}
} // Add methods to `Hash`.
Hash.prototype.clear = hashClear;
Hash.prototype["delete"] = hashDelete;
Hash.prototype.get = hashGet;
Hash.prototype.has = hashHas;
Hash.prototype.set = hashSet;
module.exports = Hash;
/***/
},
/* 111 */
/***/ function (module, exports, __webpack_require__) {
var nativeCreate = __webpack_require__(28);
/**
* Removes all key-value entries from the hash.
*
* @private
* @name clear
* @memberOf Hash
*/
function hashClear() {
this.__data__ = nativeCreate ? nativeCreate(null) : {};
this.size = 0;
}
module.exports = hashClear;
/***/
},
/* 112 */
/***/ function (module, exports) {
/**
* 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;
}
module.exports = hashDelete;
/***/
},
/* 113 */
/***/ function (module, exports, __webpack_require__) {
var nativeCreate = __webpack_require__(28);
/** Used to stand-in for `undefined` hash values. */
var HASH_UNDEFINED = "__lodash_hash_undefined__";
/** Used for built-in method references. */
var objectProto = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/**
* 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;
}
module.exports = hashGet;
/***/
},
/* 114 */
/***/ function (module, exports, __webpack_require__) {
var nativeCreate = __webpack_require__(28);
/** Used for built-in method references. */
var objectProto = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/**
* 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);
}
module.exports = hashHas;
/***/
},
/* 115 */
/***/ function (module, exports, __webpack_require__) {
var nativeCreate = __webpack_require__(28);
/** Used to stand-in for `undefined` hash values. */
var HASH_UNDEFINED = "__lodash_hash_undefined__";
/**
* 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;
}
module.exports = hashSet;
/***/
},
/* 116 */
/***/ function (module, exports, __webpack_require__) {
var getMapData = __webpack_require__(29);
/**
* 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;
}
module.exports = mapCacheDelete;
/***/
},
/* 117 */
/***/ function (module, exports) {
/**
* 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;
}
module.exports = isKeyable;
/***/
},
/* 118 */
/***/ function (module, exports, __webpack_require__) {
var getMapData = __webpack_require__(29);
/**
* 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);
}
module.exports = mapCacheGet;
/***/
},
/* 119 */
/***/ function (module, exports, __webpack_require__) {
var getMapData = __webpack_require__(29);
/**
* 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);
}
module.exports = mapCacheHas;
/***/
},
/* 120 */
/***/ function (module, exports, __webpack_require__) {
var getMapData = __webpack_require__(29);
/**
* 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;
}
module.exports = mapCacheSet;
/***/
},
/* 121 */
/***/ function (module, exports, __webpack_require__) {
var createBaseFor = __webpack_require__(122);
/**
* 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();
module.exports = baseFor;
/***/
},
/* 122 */
/***/ function (module, exports) {
/**
* 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;
};
}
module.exports = createBaseFor;
/***/
},
/* 123 */
/***/ function (module, exports, __webpack_require__) {
var assignMergeValue = __webpack_require__(48),
cloneBuffer = __webpack_require__(124),
cloneTypedArray = __webpack_require__(125),
copyArray = __webpack_require__(128),
initCloneObject = __webpack_require__(129),
isArguments = __webpack_require__(30),
isArray = __webpack_require__(15),
isArrayLikeObject = __webpack_require__(133),
isBuffer = __webpack_require__(52),
isFunction = __webpack_require__(36),
isObject = __webpack_require__(14),
isPlainObject = __webpack_require__(135),
isTypedArray = __webpack_require__(53),
safeGet = __webpack_require__(54),
toPlainObject = __webpack_require__(139);
/**
* 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);
}
module.exports = baseMergeDeep;
/***/
},
/* 124 */
/***/ function (module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */ (function (module) {
var root = __webpack_require__(17);
/** 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;
/** Built-in value references. */
var Buffer = moduleExports ? root.Buffer : undefined,
allocUnsafe = Buffer ? Buffer.allocUnsafe : undefined;
/**
* 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;
}
module.exports = cloneBuffer;
/* WEBPACK VAR INJECTION */
}.call(this, __webpack_require__(38)(module)));
/***/
},
/* 125 */
/***/ function (module, exports, __webpack_require__) {
var cloneArrayBuffer = __webpack_require__(126);
/**
* 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
);
}
module.exports = cloneTypedArray;
/***/
},
/* 126 */
/***/ function (module, exports, __webpack_require__) {
var Uint8Array = __webpack_require__(127);
/**
* 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;
}
module.exports = cloneArrayBuffer;
/***/
},
/* 127 */
/***/ function (module, exports, __webpack_require__) {
var root = __webpack_require__(17);
/** Built-in value references. */
var Uint8Array = root.Uint8Array;
module.exports = Uint8Array;
/***/
},
/* 128 */
/***/ function (module, exports) {
/**
* 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;
}
module.exports = copyArray;
/***/
},
/* 129 */
/***/ function (module, exports, __webpack_require__) {
var baseCreate = __webpack_require__(130),
getPrototype = __webpack_require__(50),
isPrototype = __webpack_require__(51);
/**
* 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))
: {};
}
module.exports = initCloneObject;
/***/
},
/* 130 */
/***/ function (module, exports, __webpack_require__) {
var isObject = __webpack_require__(14);
/** Built-in value references. */
var objectCreate = Object.create;
/**
* 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;
};
})();
module.exports = baseCreate;
/***/
},
/* 131 */
/***/ function (module, exports) {
/**
* 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));
};
}
module.exports = overArg;
/***/
},
/* 132 */
/***/ function (module, exports, __webpack_require__) {
var baseGetTag = __webpack_require__(22),
isObjectLike = __webpack_require__(18);
/** `Object#toString` result references. */
var argsTag = "[object Arguments]";
/**
* 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;
}
module.exports = baseIsArguments;
/***/
},
/* 133 */
/***/ function (module, exports, __webpack_require__) {
var isArrayLike = __webpack_require__(39),
isObjectLike = __webpack_require__(18);
/**
* 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);
}
module.exports = isArrayLikeObject;
/***/
},
/* 134 */
/***/ function (module, exports) {
/**
* This method returns `false`.
*
* @static
* @memberOf _
* @since 4.13.0
* @category Util
* @returns {boolean} Returns `false`.
* @example
*
* _.times(2, _.stubFalse);
* // => [false, false]
*/
function stubFalse() {
return false;
}
module.exports = stubFalse;
/***/
},
/* 135 */
/***/ function (module, exports, __webpack_require__) {
var baseGetTag = __webpack_require__(22),
getPrototype = __webpack_require__(50),
isObjectLike = __webpack_require__(18);
/** `Object#toString` result references. */
var objectTag = "[object Object]";
/** Used for built-in method references. */
var funcProto = Function.prototype,
objectProto = Object.prototype;
/** 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 infer the `Object` constructor. */
var objectCtorString = funcToString.call(Object);
/**
* 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
);
}
module.exports = isPlainObject;
/***/
},
/* 136 */
/***/ function (module, exports, __webpack_require__) {
var baseGetTag = __webpack_require__(22),
isLength = __webpack_require__(40),
isObjectLike = __webpack_require__(18);
/** `Object#toString` result references. */
var argsTag = "[object Arguments]",
arrayTag = "[object Array]",
boolTag = "[object Boolean]",
dateTag = "[object Date]",
errorTag = "[object Error]",
funcTag = "[object Function]",
mapTag = "[object Map]",
numberTag = "[object Number]",
objectTag = "[object Object]",
regexpTag = "[object RegExp]",
setTag = "[object Set]",
stringTag = "[object String]",
weakMapTag = "[object WeakMap]";
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 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;
/**
* 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)]
);
}
module.exports = baseIsTypedArray;
/***/
},
/* 137 */
/***/ function (module, exports) {
/**
* 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);
};
}
module.exports = baseUnary;
/***/
},
/* 138 */
/***/ function (module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */ (function (module) {
var freeGlobal = __webpack_require__(45);
/** 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) {}
})();
module.exports = nodeUtil;
/* WEBPACK VAR INJECTION */
}.call(this, __webpack_require__(38)(module)));
/***/
},
/* 139 */
/***/ function (module, exports, __webpack_require__) {
var copyObject = __webpack_require__(140),
keysIn = __webpack_require__(56);
/**
* 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));
}
module.exports = toPlainObject;
/***/
},
/* 140 */
/***/ function (module, exports, __webpack_require__) {
var assignValue = __webpack_require__(55),
baseAssignValue = __webpack_require__(37);
/**
* 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;
}
module.exports = copyObject;
/***/
},
/* 141 */
/***/ function (module, exports, __webpack_require__) {
var baseTimes = __webpack_require__(142),
isArguments = __webpack_require__(30),
isArray = __webpack_require__(15),
isBuffer = __webpack_require__(52),
isIndex = __webpack_require__(31),
isTypedArray = __webpack_require__(53);
/** Used for built-in method references. */
var objectProto = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/**
* 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" ||
(isBuff &&
(key == "offset" || key == "parent")) ||
(isType &&
(key == "buffer" ||
key == "byteLength" ||
key == "byteOffset")) || // Skip index properties.
isIndex(key, length))
)
) {
result.push(key);
}
}
return result;
}
module.exports = arrayLikeKeys;
/***/
},
/* 142 */
/***/ function (module, exports) {
/**
* 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;
}
module.exports = baseTimes;
/***/
},
/* 143 */
/***/ function (module, exports, __webpack_require__) {
var isObject = __webpack_require__(14),
isPrototype = __webpack_require__(51),
nativeKeysIn = __webpack_require__(144);
/** Used for built-in method references. */
var objectProto = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/**
* 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;
}
module.exports = baseKeysIn;
/***/
},
/* 144 */
/***/ function (module, exports) {
/**
* 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;
}
module.exports = nativeKeysIn;
/***/
},
/* 145 */
/***/ function (module, exports, __webpack_require__) {
var baseRest = __webpack_require__(146),
isIterateeCall = __webpack_require__(151);
/**
* 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;
});
}
module.exports = createAssigner;
/***/
},
/* 146 */
/***/ function (module, exports, __webpack_require__) {
var identity = __webpack_require__(57),
overRest = __webpack_require__(58),
setToString = __webpack_require__(59);
/**
* 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 + ""
);
}
module.exports = baseRest;
/***/
},
/* 147 */
/***/ function (module, exports) {
/**
* 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);
}
module.exports = apply;
/***/
},
/* 148 */
/***/ function (module, exports, __webpack_require__) {
var constant = __webpack_require__(149),
defineProperty = __webpack_require__(49),
identity = __webpack_require__(57);
/**
* 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,
});
};
module.exports = baseSetToString;
/***/
},
/* 149 */
/***/ function (module, exports) {
/**
* Creates a function that returns `value`.
*
* @static
* @memberOf _
* @since 2.4.0
* @category Util
* @param {*} value The value to return from the new function.
* @returns {Function} Returns the new constant function.
* @example
*
* var objects = _.times(2, _.constant({ 'a': 1 }));
*
* console.log(objects);
* // => [{ 'a': 1 }, { 'a': 1 }]
*
* console.log(objects[0] === objects[1]);
* // => true
*/
function constant(value) {
return function () {
return value;
};
}
module.exports = constant;
/***/
},
/* 150 */
/***/ function (module, exports) {
/** Used to detect hot functions by number of calls within a span of milliseconds. */
var HOT_COUNT = 800,
HOT_SPAN = 16;
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeNow = Date.now;
/**
* 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);
};
}
module.exports = shortOut;
/***/
},
/* 151 */
/***/ function (module, exports, __webpack_require__) {
var eq = __webpack_require__(26),
isArrayLike = __webpack_require__(39),
isIndex = __webpack_require__(31),
isObject = __webpack_require__(14);
/**
* 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;
}
module.exports = isIterateeCall;
/***/
},
/* 152 */
/***/ function (module, exports) {
/*
* typedefs.js
* Normalizes browser-specific prefixes and provide some basic polyfills
*/
if (typeof window !== "undefined") {
if (!window.requestAnimationFrame) {
window.requestAnimationFrame = (function () {
return (
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
function (
/* function FrameRequestCallback */
callback
) {
window.setTimeout(callback, 1000 / 60);
}
);
})();
}
}
if (typeof Math.imul !== "function") {
/* eslint-disable no-bitwise */
Math.imul = function (a, b) {
var ah = (a >>> 16) & 0xffff;
var al = a & 0xffff;
var bh = (b >>> 16) & 0xffff;
var bl = b & 0xffff; // the shift by 0 fixes the sign on the high part
// the final |0 converts the unsigned value into a signed value
return (
(al * bl + (((ah * bl + al * bh) << 16) >>> 0)) | 0
);
};
/* eslint-enable no-bitwise */
}
if (typeof Object.assign !== "function") {
Object.assign = function (target) {
// .length of function is 2
"use strict";
if (target === null) {
// TypeError if undefined or null
throw new TypeError(
"Cannot convert undefined or null to object"
);
}
var to = Object(target);
for (var index = 1; index < arguments.length; index++) {
// eslint-disable-next-line prefer-rest-params
var nextSource = arguments[index];
if (nextSource !== null) {
// Skip over if undefined or null
// eslint-disable-next-line no-restricted-syntax
for (var nextKey in nextSource) {
// Avoid bugs when hasOwnProperty is shadowed
if (
Object.prototype.hasOwnProperty.call(
nextSource,
nextKey
)
) {
to[nextKey] = nextSource[nextKey];
}
}
}
}
return to;
};
}
/***/
},
/* 153 */
/***/ function (module, exports) {
function _arrayWithHoles(arr) {
if (Array.isArray(arr)) return arr;
}
module.exports = _arrayWithHoles;
(module.exports["default"] = module.exports),
(module.exports.__esModule = true);
/***/
},
/* 154 */
/***/ function (module, exports) {
function _iterableToArrayLimit(arr, i) {
var _i =
arr == null
? null
: (typeof Symbol !== "undefined" &&
arr[Symbol.iterator]) ||
arr["@@iterator"];
if (_i == null) return;
var _arr = [];
var _n = true;
var _d = false;
var _s, _e;
try {
for (
_i = _i.call(arr);
!(_n = (_s = _i.next()).done);
_n = true
) {
_arr.push(_s.value);
if (i && _arr.length === i) break;
}
} catch (err) {
_d = true;
_e = err;
} finally {
try {
if (!_n && _i["return"] != null) _i["return"]();
} finally {
if (_d) throw _e;
}
}
return _arr;
}
module.exports = _iterableToArrayLimit;
(module.exports["default"] = module.exports),
(module.exports.__esModule = true);
/***/
},
/* 155 */
/***/ function (module, exports) {
function _nonIterableRest() {
throw new TypeError(
"Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."
);
}
module.exports = _nonIterableRest;
(module.exports["default"] = module.exports),
(module.exports.__esModule = true);
/***/
},
/* 156 */
/***/ function (module, exports) {
module.exports = clone;
/**
* Creates a new vec2 initialized with values from an existing vector
*
* @param {vec2} a vector to clone
* @returns {vec2} a new 2D vector
*/
function clone(a) {
var out = new Float32Array(2);
out[0] = a[0];
out[1] = a[1];
return out;
}
/***/
},
/* 157 */
/***/ function (module, exports) {
module.exports = fromValues;
/**
* Creates a new vec2 initialized with the given values
*
* @param {Number} x X component
* @param {Number} y Y component
* @returns {vec2} a new 2D vector
*/
function fromValues(x, y) {
var out = new Float32Array(2);
out[0] = x;
out[1] = y;
return out;
}
/***/
},
/* 158 */
/***/ function (module, exports) {
module.exports = copy;
/**
* Copy the values from one vec2 to another
*
* @param {vec2} out the receiving vector
* @param {vec2} a the source vector
* @returns {vec2} out
*/
function copy(out, a) {
out[0] = a[0];
out[1] = a[1];
return out;
}
/***/
},
/* 159 */
/***/ function (module, exports) {
module.exports = set;
/**
* Set the components of a vec2 to the given values
*
* @param {vec2} out the receiving vector
* @param {Number} x X component
* @param {Number} y Y component
* @returns {vec2} out
*/
function set(out, x, y) {
out[0] = x;
out[1] = y;
return out;
}
/***/
},
/* 160 */
/***/ function (module, exports, __webpack_require__) {
module.exports = equals;
var EPSILON = __webpack_require__(62);
/**
* Returns whether or not the vectors have approximately the same elements in the same position.
*
* @param {vec2} a The first vector.
* @param {vec2} b The second vector.
* @returns {Boolean} True if the vectors are equal, false otherwise.
*/
function equals(a, b) {
var a0 = a[0];
var a1 = a[1];
var b0 = b[0];
var b1 = b[1];
return (
Math.abs(a0 - b0) <=
EPSILON *
Math.max(1.0, Math.abs(a0), Math.abs(b0)) &&
Math.abs(a1 - b1) <=
EPSILON * Math.max(1.0, Math.abs(a1), Math.abs(b1))
);
}
/***/
},
/* 161 */
/***/ function (module, exports) {
module.exports = exactEquals;
/**
* Returns whether or not the vectors exactly have the same elements in the same position (when compared with ===)
*
* @param {vec2} a The first vector.
* @param {vec2} b The second vector.
* @returns {Boolean} True if the vectors are equal, false otherwise.
*/
function exactEquals(a, b) {
return a[0] === b[0] && a[1] === b[1];
}
/***/
},
/* 162 */
/***/ function (module, exports) {
module.exports = add;
/**
* Adds two vec2's
*
* @param {vec2} out the receiving vector
* @param {vec2} a the first operand
* @param {vec2} b the second operand
* @returns {vec2} out
*/
function add(out, a, b) {
out[0] = a[0] + b[0];
out[1] = a[1] + b[1];
return out;
}
/***/
},
/* 163 */
/***/ function (module, exports, __webpack_require__) {
module.exports = __webpack_require__(64);
/***/
},
/* 164 */
/***/ function (module, exports, __webpack_require__) {
module.exports = __webpack_require__(65);
/***/
},
/* 165 */
/***/ function (module, exports, __webpack_require__) {
module.exports = __webpack_require__(66);
/***/
},
/* 166 */
/***/ function (module, exports) {
module.exports = inverse;
/**
* Returns the inverse of the components of a vec2
*
* @param {vec2} out the receiving vector
* @param {vec2} a vector to invert
* @returns {vec2} out
*/
function inverse(out, a) {
out[0] = 1.0 / a[0];
out[1] = 1.0 / a[1];
return out;
}
/***/
},
/* 167 */
/***/ function (module, exports) {
module.exports = min;
/**
* Returns the minimum of two vec2's
*
* @param {vec2} out the receiving vector
* @param {vec2} a the first operand
* @param {vec2} b the second operand
* @returns {vec2} out
*/
function min(out, a, b) {
out[0] = Math.min(a[0], b[0]);
out[1] = Math.min(a[1], b[1]);
return out;
}
/***/
},
/* 168 */
/***/ function (module, exports) {
module.exports = max;
/**
* Returns the maximum of two vec2's
*
* @param {vec2} out the receiving vector
* @param {vec2} a the first operand
* @param {vec2} b the second operand
* @returns {vec2} out
*/
function max(out, a, b) {
out[0] = Math.max(a[0], b[0]);
out[1] = Math.max(a[1], b[1]);
return out;
}
/***/
},
/* 169 */
/***/ function (module, exports) {
module.exports = rotate;
/**
* Rotates a vec2 by an angle
*
* @param {vec2} out the receiving vector
* @param {vec2} a the vector to rotate
* @param {Number} angle the angle of rotation (in radians)
* @returns {vec2} out
*/
function rotate(out, a, angle) {
var c = Math.cos(angle),
s = Math.sin(angle);
var x = a[0],
y = a[1];
out[0] = x * c - y * s;
out[1] = x * s + y * c;
return out;
}
/***/
},
/* 170 */
/***/ function (module, exports) {
module.exports = floor;
/**
* Math.floor the components of a vec2
*
* @param {vec2} out the receiving vector
* @param {vec2} a vector to floor
* @returns {vec2} out
*/
function floor(out, a) {
out[0] = Math.floor(a[0]);
out[1] = Math.floor(a[1]);
return out;
}
/***/
},
/* 171 */
/***/ function (module, exports) {
module.exports = ceil;
/**
* Math.ceil the components of a vec2
*
* @param {vec2} out the receiving vector
* @param {vec2} a vector to ceil
* @returns {vec2} out
*/
function ceil(out, a) {
out[0] = Math.ceil(a[0]);
out[1] = Math.ceil(a[1]);
return out;
}
/***/
},
/* 172 */
/***/ function (module, exports) {
module.exports = round;
/**
* Math.round the components of a vec2
*
* @param {vec2} out the receiving vector
* @param {vec2} a vector to round
* @returns {vec2} out
*/
function round(out, a) {
out[0] = Math.round(a[0]);
out[1] = Math.round(a[1]);
return out;
}
/***/
},
/* 173 */
/***/ function (module, exports) {
module.exports = scale;
/**
* Scales a vec2 by a scalar number
*
* @param {vec2} out the receiving vector
* @param {vec2} a the vector to scale
* @param {Number} b amount to scale the vector by
* @returns {vec2} out
*/
function scale(out, a, b) {
out[0] = a[0] * b;
out[1] = a[1] * b;
return out;
}
/***/
},
/* 174 */
/***/ function (module, exports) {
module.exports = scaleAndAdd;
/**
* Adds two vec2's after scaling the second operand by a scalar value
*
* @param {vec2} out the receiving vector
* @param {vec2} a the first operand
* @param {vec2} b the second operand
* @param {Number} scale the amount to scale b by before adding
* @returns {vec2} out
*/
function scaleAndAdd(out, a, b, scale) {
out[0] = a[0] + b[0] * scale;
out[1] = a[1] + b[1] * scale;
return out;
}
/***/
},
/* 175 */
/***/ function (module, exports, __webpack_require__) {
module.exports = __webpack_require__(67);
/***/
},
/* 176 */
/***/ function (module, exports, __webpack_require__) {
module.exports = __webpack_require__(68);
/***/
},
/* 177 */
/***/ function (module, exports, __webpack_require__) {
module.exports = __webpack_require__(69);
/***/
},
/* 178 */
/***/ function (module, exports, __webpack_require__) {
module.exports = __webpack_require__(70);
/***/
},
/* 179 */
/***/ function (module, exports) {
module.exports = negate;
/**
* Negates the components of a vec2
*
* @param {vec2} out the receiving vector
* @param {vec2} a vector to negate
* @returns {vec2} out
*/
function negate(out, a) {
out[0] = -a[0];
out[1] = -a[1];
return out;
}
/***/
},
/* 180 */
/***/ function (module, exports) {
module.exports = normalize;
/**
* Normalize a vec2
*
* @param {vec2} out the receiving vector
* @param {vec2} a vector to normalize
* @returns {vec2} out
*/
function normalize(out, a) {
var x = a[0],
y = a[1];
var len = x * x + y * y;
if (len > 0) {
//TODO: evaluate use of glm_invsqrt here?
len = 1 / Math.sqrt(len);
out[0] = a[0] * len;
out[1] = a[1] * len;
}
return out;
}
/***/
},
/* 181 */
/***/ function (module, exports) {
module.exports = dot;
/**
* Calculates the dot product of two vec2's
*
* @param {vec2} a the first operand
* @param {vec2} b the second operand
* @returns {Number} dot product of a and b
*/
function dot(a, b) {
return a[0] * b[0] + a[1] * b[1];
}
/***/
},
/* 182 */
/***/ function (module, exports) {
module.exports = cross;
/**
* Computes the cross product of two vec2's
* Note that the cross product must by definition produce a 3D vector
*
* @param {vec3} out the receiving vector
* @param {vec2} a the first operand
* @param {vec2} b the second operand
* @returns {vec3} out
*/
function cross(out, a, b) {
var z = a[0] * b[1] - a[1] * b[0];
out[0] = out[1] = 0;
out[2] = z;
return out;
}
/***/
},
/* 183 */
/***/ function (module, exports) {
module.exports = lerp;
/**
* Performs a linear interpolation between two vec2's
*
* @param {vec2} out the receiving vector
* @param {vec2} a the first operand
* @param {vec2} b the second operand
* @param {Number} t interpolation amount between the two inputs
* @returns {vec2} out
*/
function lerp(out, a, b, t) {
var ax = a[0],
ay = a[1];
out[0] = ax + t * (b[0] - ax);
out[1] = ay + t * (b[1] - ay);
return out;
}
/***/
},
/* 184 */
/***/ function (module, exports) {
module.exports = random;
/**
* Generates a random vector with the given scale
*
* @param {vec2} out the receiving vector
* @param {Number} [scale] Length of the resulting vector. If ommitted, a unit vector will be returned
* @returns {vec2} out
*/
function random(out, scale) {
scale = scale || 1.0;
var r = Math.random() * 2.0 * Math.PI;
out[0] = Math.cos(r) * scale;
out[1] = Math.sin(r) * scale;
return out;
}
/***/
},
/* 185 */
/***/ function (module, exports) {
module.exports = transformMat2;
/**
* Transforms the vec2 with a mat2
*
* @param {vec2} out the receiving vector
* @param {vec2} a the vector to transform
* @param {mat2} m matrix to transform with
* @returns {vec2} out
*/
function transformMat2(out, a, m) {
var x = a[0],
y = a[1];
out[0] = m[0] * x + m[2] * y;
out[1] = m[1] * x + m[3] * y;
return out;
}
/***/
},
/* 186 */
/***/ function (module, exports) {
module.exports = transformMat2d;
/**
* Transforms the vec2 with a mat2d
*
* @param {vec2} out the receiving vector
* @param {vec2} a the vector to transform
* @param {mat2d} m matrix to transform with
* @returns {vec2} out
*/
function transformMat2d(out, a, m) {
var x = a[0],
y = a[1];
out[0] = m[0] * x + m[2] * y + m[4];
out[1] = m[1] * x + m[3] * y + m[5];
return out;
}
/***/
},
/* 187 */
/***/ function (module, exports) {
module.exports = transformMat3;
/**
* Transforms the vec2 with a mat3
* 3rd vector component is implicitly '1'
*
* @param {vec2} out the receiving vector
* @param {vec2} a the vector to transform
* @param {mat3} m matrix to transform with
* @returns {vec2} out
*/
function transformMat3(out, a, m) {
var x = a[0],
y = a[1];
out[0] = m[0] * x + m[3] * y + m[6];
out[1] = m[1] * x + m[4] * y + m[7];
return out;
}
/***/
},
/* 188 */
/***/ function (module, exports) {
module.exports = transformMat4;
/**
* Transforms the vec2 with a mat4
* 3rd vector component is implicitly '0'
* 4th vector component is implicitly '1'
*
* @param {vec2} out the receiving vector
* @param {vec2} a the vector to transform
* @param {mat4} m matrix to transform with
* @returns {vec2} out
*/
function transformMat4(out, a, m) {
var x = a[0],
y = a[1];
out[0] = m[0] * x + m[4] * y + m[12];
out[1] = m[1] * x + m[5] * y + m[13];
return out;
}
/***/
},
/* 189 */
/***/ function (module, exports, __webpack_require__) {
module.exports = forEach;
var vec = __webpack_require__(63)();
/**
* Perform some operation over an array of vec2s.
*
* @param {Array} a the array of vectors to iterate over
* @param {Number} stride Number of elements between the start of each vec2. If 0 assumes tightly packed
* @param {Number} offset Number of elements to skip at the beginning of the array
* @param {Number} count Number of vec2s to iterate over. If 0 iterates over entire array
* @param {Function} fn Function to call for each vector in the array
* @param {Object} [arg] additional argument to pass to fn
* @returns {Array} a
* @function
*/
function forEach(a, stride, offset, count, fn, arg) {
var i, l;
if (!stride) {
stride = 2;
}
if (!offset) {
offset = 0;
}
if (count) {
l = Math.min(count * stride + offset, a.length);
} else {
l = a.length;
}
for (i = offset; i < l; i += stride) {
vec[0] = a[i];
vec[1] = a[i + 1];
fn(vec, vec, arg);
a[i] = vec[0];
a[i + 1] = vec[1];
}
return a;
}
/***/
},
/* 190 */
/***/ function (module, exports) {
module.exports = limit;
/**
* Limit the magnitude of this vector to the value used for the `max`
* parameter.
*
* @param {vec2} the vector to limit
* @param {Number} max the maximum magnitude for the vector
* @returns {vec2} out
*/
function limit(out, a, max) {
var mSq = a[0] * a[0] + a[1] * a[1];
if (mSq > max * max) {
var n = Math.sqrt(mSq);
out[0] = (a[0] / n) * max;
out[1] = (a[1] / n) * max;
} else {
out[0] = a[0];
out[1] = a[1];
}
return out;
}
/***/
},
/* 191 */
/***/ function (module, exports) {
module.exports = clone;
/**
* Creates a new vec3 initialized with values from an existing vector
*
* @param {vec3} a vector to clone
* @returns {vec3} a new 3D vector
*/
function clone(a) {
var out = new Float32Array(3);
out[0] = a[0];
out[1] = a[1];
out[2] = a[2];
return out;
}
/***/
},
/* 192 */
/***/ function (module, exports, __webpack_require__) {
module.exports = angle;
var fromValues = __webpack_require__(73);
var normalize = __webpack_require__(74);
var dot = __webpack_require__(75);
/**
* Get the angle between two 3D vectors
* @param {vec3} a The first operand
* @param {vec3} b The second operand
* @returns {Number} The angle in radians
*/
function angle(a, b) {
var tempA = fromValues(a[0], a[1], a[2]);
var tempB = fromValues(b[0], b[1], b[2]);
normalize(tempA, tempA);
normalize(tempB, tempB);
var cosine = dot(tempA, tempB);
if (cosine > 1.0) {
return 0;
} else {
return Math.acos(cosine);
}
}
/***/
},
/* 193 */
/***/ function (module, exports) {
module.exports = copy;
/**
* Copy the values from one vec3 to another
*
* @param {vec3} out the receiving vector
* @param {vec3} a the source vector
* @returns {vec3} out
*/
function copy(out, a) {
out[0] = a[0];
out[1] = a[1];
out[2] = a[2];
return out;
}
/***/
},
/* 194 */
/***/ function (module, exports) {
module.exports = set;
/**
* Set the components of a vec3 to the given values
*
* @param {vec3} out the receiving vector
* @param {Number} x X component
* @param {Number} y Y component
* @param {Number} z Z component
* @returns {vec3} out
*/
function set(out, x, y, z) {
out[0] = x;
out[1] = y;
out[2] = z;
return out;
}
/***/
},
/* 195 */
/***/ function (module, exports, __webpack_require__) {
module.exports = equals;
var EPSILON = __webpack_require__(71);
/**
* Returns whether or not the vectors have approximately the same elements in the same position.
*
* @param {vec3} a The first vector.
* @param {vec3} b The second vector.
* @returns {Boolean} True if the vectors are equal, false otherwise.
*/
function equals(a, b) {
var a0 = a[0];
var a1 = a[1];
var a2 = a[2];
var b0 = b[0];
var b1 = b[1];
var b2 = b[2];
return (
Math.abs(a0 - b0) <=
EPSILON *
Math.max(1.0, Math.abs(a0), Math.abs(b0)) &&
Math.abs(a1 - b1) <=
EPSILON *
Math.max(1.0, Math.abs(a1), Math.abs(b1)) &&
Math.abs(a2 - b2) <=
EPSILON * Math.max(1.0, Math.abs(a2), Math.abs(b2))
);
}
/***/
},
/* 196 */
/***/ function (module, exports) {
module.exports = exactEquals;
/**
* Returns whether or not the vectors exactly have the same elements in the same position (when compared with ===)
*
* @param {vec3} a The first vector.
* @param {vec3} b The second vector.
* @returns {Boolean} True if the vectors are equal, false otherwise.
*/
function exactEquals(a, b) {
return a[0] === b[0] && a[1] === b[1] && a[2] === b[2];
}
/***/
},
/* 197 */
/***/ function (module, exports) {
module.exports = add;
/**
* Adds two vec3's
*
* @param {vec3} out the receiving vector
* @param {vec3} a the first operand
* @param {vec3} b the second operand
* @returns {vec3} out
*/
function add(out, a, b) {
out[0] = a[0] + b[0];
out[1] = a[1] + b[1];
out[2] = a[2] + b[2];
return out;
}
/***/
},
/* 198 */
/***/ function (module, exports, __webpack_require__) {
module.exports = __webpack_require__(76);
/***/
},
/* 199 */
/***/ function (module, exports, __webpack_require__) {
module.exports = __webpack_require__(77);
/***/
},
/* 200 */
/***/ function (module, exports, __webpack_require__) {
module.exports = __webpack_require__(78);
/***/
},
/* 201 */
/***/ function (module, exports) {
module.exports = min;
/**
* Returns the minimum of two vec3's
*
* @param {vec3} out the receiving vector
* @param {vec3} a the first operand
* @param {vec3} b the second operand
* @returns {vec3} out
*/
function min(out, a, b) {
out[0] = Math.min(a[0], b[0]);
out[1] = Math.min(a[1], b[1]);
out[2] = Math.min(a[2], b[2]);
return out;
}
/***/
},
/* 202 */
/***/ function (module, exports) {
module.exports = max;
/**
* Returns the maximum of two vec3's
*
* @param {vec3} out the receiving vector
* @param {vec3} a the first operand
* @param {vec3} b the second operand
* @returns {vec3} out
*/
function max(out, a, b) {
out[0] = Math.max(a[0], b[0]);
out[1] = Math.max(a[1], b[1]);
out[2] = Math.max(a[2], b[2]);
return out;
}
/***/
},
/* 203 */
/***/ function (module, exports) {
module.exports = floor;
/**
* Math.floor the components of a vec3
*
* @param {vec3} out the receiving vector
* @param {vec3} a vector to floor
* @returns {vec3} out
*/
function floor(out, a) {
out[0] = Math.floor(a[0]);
out[1] = Math.floor(a[1]);
out[2] = Math.floor(a[2]);
return out;
}
/***/
},
/* 204 */
/***/ function (module, exports) {
module.exports = ceil;
/**
* Math.ceil the components of a vec3
*
* @param {vec3} out the receiving vector
* @param {vec3} a vector to ceil
* @returns {vec3} out
*/
function ceil(out, a) {
out[0] = Math.ceil(a[0]);
out[1] = Math.ceil(a[1]);
out[2] = Math.ceil(a[2]);
return out;
}
/***/
},
/* 205 */
/***/ function (module, exports) {
module.exports = round;
/**
* Math.round the components of a vec3
*
* @param {vec3} out the receiving vector
* @param {vec3} a vector to round
* @returns {vec3} out
*/
function round(out, a) {
out[0] = Math.round(a[0]);
out[1] = Math.round(a[1]);
out[2] = Math.round(a[2]);
return out;
}
/***/
},
/* 206 */
/***/ function (module, exports) {
module.exports = scale;
/**
* Scales a vec3 by a scalar number
*
* @param {vec3} out the receiving vector
* @param {vec3} a the vector to scale
* @param {Number} b amount to scale the vector by
* @returns {vec3} out
*/
function scale(out, a, b) {
out[0] = a[0] * b;
out[1] = a[1] * b;
out[2] = a[2] * b;
return out;
}
/***/
},
/* 207 */
/***/ function (module, exports) {
module.exports = scaleAndAdd;
/**
* Adds two vec3's after scaling the second operand by a scalar value
*
* @param {vec3} out the receiving vector
* @param {vec3} a the first operand
* @param {vec3} b the second operand
* @param {Number} scale the amount to scale b by before adding
* @returns {vec3} out
*/
function scaleAndAdd(out, a, b, scale) {
out[0] = a[0] + b[0] * scale;
out[1] = a[1] + b[1] * scale;
out[2] = a[2] + b[2] * scale;
return out;
}
/***/
},
/* 208 */
/***/ function (module, exports, __webpack_require__) {
module.exports = __webpack_require__(79);
/***/
},
/* 209 */
/***/ function (module, exports, __webpack_require__) {
module.exports = __webpack_require__(80);
/***/
},
/* 210 */
/***/ function (module, exports, __webpack_require__) {
module.exports = __webpack_require__(81);
/***/
},
/* 211 */
/***/ function (module, exports, __webpack_require__) {
module.exports = __webpack_require__(82);
/***/
},
/* 212 */
/***/ function (module, exports) {
module.exports = negate;
/**
* Negates the components of a vec3
*
* @param {vec3} out the receiving vector
* @param {vec3} a vector to negate
* @returns {vec3} out
*/
function negate(out, a) {
out[0] = -a[0];
out[1] = -a[1];
out[2] = -a[2];
return out;
}
/***/
},
/* 213 */
/***/ function (module, exports) {
module.exports = inverse;
/**
* Returns the inverse of the components of a vec3
*
* @param {vec3} out the receiving vector
* @param {vec3} a vector to invert
* @returns {vec3} out
*/
function inverse(out, a) {
out[0] = 1.0 / a[0];
out[1] = 1.0 / a[1];
out[2] = 1.0 / a[2];
return out;
}
/***/
},
/* 214 */
/***/ function (module, exports) {
module.exports = cross;
/**
* Computes the cross product of two vec3's
*
* @param {vec3} out the receiving vector
* @param {vec3} a the first operand
* @param {vec3} b the second operand
* @returns {vec3} out
*/
function cross(out, a, b) {
var ax = a[0],
ay = a[1],
az = a[2],
bx = b[0],
by = b[1],
bz = b[2];
out[0] = ay * bz - az * by;
out[1] = az * bx - ax * bz;
out[2] = ax * by - ay * bx;
return out;
}
/***/
},
/* 215 */
/***/ function (module, exports) {
module.exports = lerp;
/**
* Performs a linear interpolation between two vec3's
*
* @param {vec3} out the receiving vector
* @param {vec3} a the first operand
* @param {vec3} b the second operand
* @param {Number} t interpolation amount between the two inputs
* @returns {vec3} out
*/
function lerp(out, a, b, t) {
var ax = a[0],
ay = a[1],
az = a[2];
out[0] = ax + t * (b[0] - ax);
out[1] = ay + t * (b[1] - ay);
out[2] = az + t * (b[2] - az);
return out;
}
/***/
},
/* 216 */
/***/ function (module, exports) {
module.exports = random;
/**
* Generates a random vector with the given scale
*
* @param {vec3} out the receiving vector
* @param {Number} [scale] Length of the resulting vector. If ommitted, a unit vector will be returned
* @returns {vec3} out
*/
function random(out, scale) {
scale = scale || 1.0;
var r = Math.random() * 2.0 * Math.PI;
var z = Math.random() * 2.0 - 1.0;
var zScale = Math.sqrt(1.0 - z * z) * scale;
out[0] = Math.cos(r) * zScale;
out[1] = Math.sin(r) * zScale;
out[2] = z * scale;
return out;
}
/***/
},
/* 217 */
/***/ function (module, exports) {
module.exports = transformMat4;
/**
* Transforms the vec3 with a mat4.
* 4th vector component is implicitly '1'
*
* @param {vec3} out the receiving vector
* @param {vec3} a the vector to transform
* @param {mat4} m matrix to transform with
* @returns {vec3} out
*/
function transformMat4(out, a, m) {
var x = a[0],
y = a[1],
z = a[2],
w = m[3] * x + m[7] * y + m[11] * z + m[15];
w = w || 1.0;
out[0] = (m[0] * x + m[4] * y + m[8] * z + m[12]) / w;
out[1] = (m[1] * x + m[5] * y + m[9] * z + m[13]) / w;
out[2] = (m[2] * x + m[6] * y + m[10] * z + m[14]) / w;
return out;
}
/***/
},
/* 218 */
/***/ function (module, exports) {
module.exports = transformMat3;
/**
* Transforms the vec3 with a mat3.
*
* @param {vec3} out the receiving vector
* @param {vec3} a the vector to transform
* @param {mat4} m the 3x3 matrix to transform with
* @returns {vec3} out
*/
function transformMat3(out, a, m) {
var x = a[0],
y = a[1],
z = a[2];
out[0] = x * m[0] + y * m[3] + z * m[6];
out[1] = x * m[1] + y * m[4] + z * m[7];
out[2] = x * m[2] + y * m[5] + z * m[8];
return out;
}
/***/
},
/* 219 */
/***/ function (module, exports) {
module.exports = transformQuat;
/**
* Transforms the vec3 with a quat
*
* @param {vec3} out the receiving vector
* @param {vec3} a the vector to transform
* @param {quat} q quaternion to transform with
* @returns {vec3} out
*/
function transformQuat(out, a, q) {
// benchmarks: http://jsperf.com/quaternion-transform-vec3-implementations
var x = a[0],
y = a[1],
z = a[2],
qx = q[0],
qy = q[1],
qz = q[2],
qw = q[3],
// calculate quat * vec
ix = qw * x + qy * z - qz * y,
iy = qw * y + qz * x - qx * z,
iz = qw * z + qx * y - qy * x,
iw = -qx * x - qy * y - qz * z; // calculate result * inverse quat
out[0] = ix * qw + iw * -qx + iy * -qz - iz * -qy;
out[1] = iy * qw + iw * -qy + iz * -qx - ix * -qz;
out[2] = iz * qw + iw * -qz + ix * -qy - iy * -qx;
return out;
}
/***/
},
/* 220 */
/***/ function (module, exports) {
module.exports = rotateX;
/**
* Rotate a 3D vector around the x-axis
* @param {vec3} out The receiving vec3
* @param {vec3} a The vec3 point to rotate
* @param {vec3} b The origin of the rotation
* @param {Number} c The angle of rotation
* @returns {vec3} out
*/
function rotateX(out, a, b, c) {
var by = b[1];
var bz = b[2]; // Translate point to the origin
var py = a[1] - by;
var pz = a[2] - bz;
var sc = Math.sin(c);
var cc = Math.cos(c); // perform rotation and translate to correct position
out[0] = a[0];
out[1] = by + py * cc - pz * sc;
out[2] = bz + py * sc + pz * cc;
return out;
}
/***/
},
/* 221 */
/***/ function (module, exports) {
module.exports = rotateY;
/**
* Rotate a 3D vector around the y-axis
* @param {vec3} out The receiving vec3
* @param {vec3} a The vec3 point to rotate
* @param {vec3} b The origin of the rotation
* @param {Number} c The angle of rotation
* @returns {vec3} out
*/
function rotateY(out, a, b, c) {
var bx = b[0];
var bz = b[2]; // translate point to the origin
var px = a[0] - bx;
var pz = a[2] - bz;
var sc = Math.sin(c);
var cc = Math.cos(c); // perform rotation and translate to correct position
out[0] = bx + pz * sc + px * cc;
out[1] = a[1];
out[2] = bz + pz * cc - px * sc;
return out;
}
/***/
},
/* 222 */
/***/ function (module, exports) {
module.exports = rotateZ;
/**
* Rotate a 3D vector around the z-axis
* @param {vec3} out The receiving vec3
* @param {vec3} a The vec3 point to rotate
* @param {vec3} b The origin of the rotation
* @param {Number} c The angle of rotation
* @returns {vec3} out
*/
function rotateZ(out, a, b, c) {
var bx = b[0];
var by = b[1]; //Translate point to the origin
var px = a[0] - bx;
var py = a[1] - by;
var sc = Math.sin(c);
var cc = Math.cos(c); // perform rotation and translate to correct position
out[0] = bx + px * cc - py * sc;
out[1] = by + px * sc + py * cc;
out[2] = a[2];
return out;
}
/***/
},
/* 223 */
/***/ function (module, exports, __webpack_require__) {
module.exports = forEach;
var vec = __webpack_require__(72)();
/**
* Perform some operation over an array of vec3s.
*
* @param {Array} a the array of vectors to iterate over
* @param {Number} stride Number of elements between the start of each vec3. If 0 assumes tightly packed
* @param {Number} offset Number of elements to skip at the beginning of the array
* @param {Number} count Number of vec3s to iterate over. If 0 iterates over entire array
* @param {Function} fn Function to call for each vector in the array
* @param {Object} [arg] additional argument to pass to fn
* @returns {Array} a
* @function
*/
function forEach(a, stride, offset, count, fn, arg) {
var i, l;
if (!stride) {
stride = 3;
}
if (!offset) {
offset = 0;
}
if (count) {
l = Math.min(count * stride + offset, a.length);
} else {
l = a.length;
}
for (i = offset; i < l; i += stride) {
vec[0] = a[i];
vec[1] = a[i + 1];
vec[2] = a[i + 2];
fn(vec, vec, arg);
a[i] = vec[0];
a[i + 1] = vec[1];
a[i + 2] = vec[2];
}
return a;
}
/***/
},
/* 224 */
/***/ function (module, exports, __webpack_require__) {
var arrayLikeToArray = __webpack_require__(61);
function _arrayWithoutHoles(arr) {
if (Array.isArray(arr)) return arrayLikeToArray(arr);
}
module.exports = _arrayWithoutHoles;
(module.exports["default"] = module.exports),
(module.exports.__esModule = true);
/***/
},
/* 225 */
/***/ function (module, exports) {
function _iterableToArray(iter) {
if (
(typeof Symbol !== "undefined" &&
iter[Symbol.iterator] != null) ||
iter["@@iterator"] != null
)
return Array.from(iter);
}
module.exports = _iterableToArray;
(module.exports["default"] = module.exports),
(module.exports.__esModule = true);
/***/
},
/* 226 */
/***/ function (module, exports) {
function _nonIterableSpread() {
throw new TypeError(
"Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."
);
}
module.exports = _nonIterableSpread;
(module.exports["default"] = module.exports),
(module.exports.__esModule = true);
/***/
},
/* 227 */
/***/ function (module, exports, __webpack_require__) {
var getPrototypeOf = __webpack_require__(2);
function _superPropBase(object, property) {
while (
!Object.prototype.hasOwnProperty.call(object, property)
) {
object = getPrototypeOf(object);
if (object === null) break;
}
return object;
}
module.exports = _superPropBase;
(module.exports["default"] = module.exports),
(module.exports.__esModule = true);
/***/
},
/* 228 */
/***/ function (module, exports, __webpack_require__) {
/**
* Copyright (c) 2014-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
var runtime = (function (exports) {
"use strict";
var Op = Object.prototype;
var hasOwn = Op.hasOwnProperty;
var undefined; // More compressible than void 0.
var $Symbol = typeof Symbol === "function" ? Symbol : {};
var iteratorSymbol = $Symbol.iterator || "@@iterator";
var asyncIteratorSymbol =
$Symbol.asyncIterator || "@@asyncIterator";
var toStringTagSymbol =
$Symbol.toStringTag || "@@toStringTag";
function wrap(innerFn, outerFn, self, tryLocsList) {
// If outerFn provided and outerFn.prototype is a Generator, then outerFn.prototype instanceof Generator.
var protoGenerator =
outerFn && outerFn.prototype instanceof Generator
? outerFn
: Generator;
var generator = Object.create(protoGenerator.prototype);
var context = new Context(tryLocsList || []); // The ._invoke method unifies the implementations of the .next,
// .throw, and .return methods.
generator._invoke = makeInvokeMethod(
innerFn,
self,
context
);
return generator;
}
exports.wrap = wrap; // Try/catch helper to minimize deoptimizations. Returns a completion
// record like context.tryEntries[i].completion. This interface could
// have been (and was previously) designed to take a closure to be
// invoked without arguments, but in all the cases we care about we
// already have an existing method we want to call, so there's no need
// to create a new function object. We can even get away with assuming
// the method takes exactly one argument, since that happens to be true
// in every case, so we don't have to touch the arguments object. The
// only additional allocation required is the completion record, which
// has a stable shape and so hopefully should be cheap to allocate.
function tryCatch(fn, obj, arg) {
try {
return {
type: "normal",
arg: fn.call(obj, arg),
};
} catch (err) {
return {
type: "throw",
arg: err,
};
}
}
var GenStateSuspendedStart = "suspendedStart";
var GenStateSuspendedYield = "suspendedYield";
var GenStateExecuting = "executing";
var GenStateCompleted = "completed"; // Returning this object from the innerFn has the same effect as
// breaking out of the dispatch switch statement.
var ContinueSentinel = {}; // Dummy constructor functions that we use as the .constructor and
// .constructor.prototype properties for functions that return Generator
// objects. For full spec compliance, you may wish to configure your
// minifier not to mangle the names of these two functions.
function Generator() {}
function GeneratorFunction() {}
function GeneratorFunctionPrototype() {} // This is a polyfill for %IteratorPrototype% for environments that
// don't natively support it.
var IteratorPrototype = {};
IteratorPrototype[iteratorSymbol] = function () {
return this;
};
var getProto = Object.getPrototypeOf;
var NativeIteratorPrototype =
getProto && getProto(getProto(values([])));
if (
NativeIteratorPrototype &&
NativeIteratorPrototype !== Op &&
hasOwn.call(NativeIteratorPrototype, iteratorSymbol)
) {
// This environment has a native %IteratorPrototype%; use it instead
// of the polyfill.
IteratorPrototype = NativeIteratorPrototype;
}
var Gp =
(GeneratorFunctionPrototype.prototype =
Generator.prototype =
Object.create(IteratorPrototype));
GeneratorFunction.prototype = Gp.constructor =
GeneratorFunctionPrototype;
GeneratorFunctionPrototype.constructor = GeneratorFunction;
GeneratorFunctionPrototype[toStringTagSymbol] =
GeneratorFunction.displayName = "GeneratorFunction"; // Helper for defining the .next, .throw, and .return methods of the
// Iterator interface in terms of a single ._invoke method.
function defineIteratorMethods(prototype) {
["next", "throw", "return"].forEach(function (method) {
prototype[method] = function (arg) {
return this._invoke(method, arg);
};
});
}
exports.isGeneratorFunction = function (genFun) {
var ctor =
typeof genFun === "function" && genFun.constructor;
return ctor
? ctor === GeneratorFunction || // For the native GeneratorFunction constructor, the best we can
// do is to check its .name property.
(ctor.displayName || ctor.name) ===
"GeneratorFunction"
: false;
};
exports.mark = function (genFun) {
if (Object.setPrototypeOf) {
Object.setPrototypeOf(
genFun,
GeneratorFunctionPrototype
);
} else {
genFun.__proto__ = GeneratorFunctionPrototype;
if (!(toStringTagSymbol in genFun)) {
genFun[toStringTagSymbol] = "GeneratorFunction";
}
}
genFun.prototype = Object.create(Gp);
return genFun;
}; // Within the body of any async function, `await x` is transformed to
// `yield regeneratorRuntime.awrap(x)`, so that the runtime can test
// `hasOwn.call(value, "__await")` to determine if the yielded value is
// meant to be awaited.
exports.awrap = function (arg) {
return {
__await: arg,
};
};
function AsyncIterator(generator, PromiseImpl) {
function invoke(method, arg, resolve, reject) {
var record = tryCatch(
generator[method],
generator,
arg
);
if (record.type === "throw") {
reject(record.arg);
} else {
var result = record.arg;
var value = result.value;
if (
value &&
typeof value === "object" &&
hasOwn.call(value, "__await")
) {
return PromiseImpl.resolve(
value.__await
).then(
function (value) {
invoke(
"next",
value,
resolve,
reject
);
},
function (err) {
invoke(
"throw",
err,
resolve,
reject
);
}
);
}
return PromiseImpl.resolve(value).then(
function (unwrapped) {
// When a yielded Promise is resolved, its final value becomes
// the .value of the Promise<{value,done}> result for the
// current iteration.
result.value = unwrapped;
resolve(result);
},
function (error) {
// If a rejected Promise was yielded, throw the rejection back
// into the async generator function so it can be handled there.
return invoke(
"throw",
error,
resolve,
reject
);
}
);
}
}
var previousPromise;
function enqueue(method, arg) {
function callInvokeWithMethodAndArg() {
return new PromiseImpl(function (
resolve,
reject
) {
invoke(method, arg, resolve, reject);
});
}
return (previousPromise = // If enqueue has been called before, then we want to wait until
// all previous Promises have been resolved before calling invoke,
// so that results are always delivered in the correct order. If
// enqueue has not been called before, then it is important to
// call invoke immediately, without waiting on a callback to fire,
// so that the async generator function has the opportunity to do
// any necessary setup in a predictable way. This predictability
// is why the Promise constructor synchronously invokes its
// executor callback, and why async functions synchronously
// execute code before the first await. Since we implement simple
// async functions in terms of async generators, it is especially
// important to get this right, even though it requires care.
previousPromise
? previousPromise.then(
callInvokeWithMethodAndArg, // Avoid propagating failures to Promises returned by later
// invocations of the iterator.
callInvokeWithMethodAndArg
)
: callInvokeWithMethodAndArg());
} // Define the unified helper method that is used to implement .next,
// .throw, and .return (see defineIteratorMethods).
this._invoke = enqueue;
}
defineIteratorMethods(AsyncIterator.prototype);
AsyncIterator.prototype[asyncIteratorSymbol] = function () {
return this;
};
exports.AsyncIterator = AsyncIterator; // Note that simple async functions are implemented on top of
// AsyncIterator objects; they just return a Promise for the value of
// the final result produced by the iterator.
exports.async = function (
innerFn,
outerFn,
self,
tryLocsList,
PromiseImpl
) {
if (PromiseImpl === void 0) PromiseImpl = Promise;
var iter = new AsyncIterator(
wrap(innerFn, outerFn, self, tryLocsList),
PromiseImpl
);
return exports.isGeneratorFunction(outerFn)
? iter // If outerFn is a generator, return the full iterator.
: iter.next().then(function (result) {
return result.done
? result.value
: iter.next();
});
};
function makeInvokeMethod(innerFn, self, context) {
var state = GenStateSuspendedStart;
return function invoke(method, arg) {
if (state === GenStateExecuting) {
throw new Error("Generator is already running");
}
if (state === GenStateCompleted) {
if (method === "throw") {
throw arg;
} // Be forgiving, per 25.3.3.3.3 of the spec:
// https://people.mozilla.org/~jorendorff/es6-draft.html#sec-generatorresume
return doneResult();
}
context.method = method;
context.arg = arg;
while (true) {
var delegate = context.delegate;
if (delegate) {
var delegateResult = maybeInvokeDelegate(
delegate,
context
);
if (delegateResult) {
if (delegateResult === ContinueSentinel)
continue;
return delegateResult;
}
}
if (context.method === "next") {
// Setting context._sent for legacy support of Babel's
// function.sent implementation.
context.sent = context._sent = context.arg;
} else if (context.method === "throw") {
if (state === GenStateSuspendedStart) {
state = GenStateCompleted;
throw context.arg;
}
context.dispatchException(context.arg);
} else if (context.method === "return") {
context.abrupt("return", context.arg);
}
state = GenStateExecuting;
var record = tryCatch(innerFn, self, context);
if (record.type === "normal") {
// If an exception is thrown from innerFn, we leave state ===
// GenStateExecuting and loop back for another invocation.
state = context.done
? GenStateCompleted
: GenStateSuspendedYield;
if (record.arg === ContinueSentinel) {
continue;
}
return {
value: record.arg,
done: context.done,
};
} else if (record.type === "throw") {
state = GenStateCompleted; // Dispatch the exception by looping back around to the
// context.dispatchException(context.arg) call above.
context.method = "throw";
context.arg = record.arg;
}
}
};
} // Call delegate.iterator[context.method](context.arg) and handle the
// result, either by returning a { value, done } result from the
// delegate iterator, or by modifying context.method and context.arg,
// setting context.delegate to null, and returning the ContinueSentinel.
function maybeInvokeDelegate(delegate, context) {
var method = delegate.iterator[context.method];
if (method === undefined) {
// A .throw or .return when the delegate iterator has no .throw
// method always terminates the yield* loop.
context.delegate = null;
if (context.method === "throw") {
// Note: ["return"] must be used for ES3 parsing compatibility.
if (delegate.iterator["return"]) {
// If the delegate iterator has a return method, give it a
// chance to clean up.
context.method = "return";
context.arg = undefined;
maybeInvokeDelegate(delegate, context);
if (context.method === "throw") {
// If maybeInvokeDelegate(context) changed context.method from
// "return" to "throw", let that override the TypeError below.
return ContinueSentinel;
}
}
context.method = "throw";
context.arg = new TypeError(
"The iterator does not provide a 'throw' method"
);
}
return ContinueSentinel;
}
var record = tryCatch(
method,
delegate.iterator,
context.arg
);
if (record.type === "throw") {
context.method = "throw";
context.arg = record.arg;
context.delegate = null;
return ContinueSentinel;
}
var info = record.arg;
if (!info) {
context.method = "throw";
context.arg = new TypeError(
"iterator result is not an object"
);
context.delegate = null;
return ContinueSentinel;
}
if (info.done) {
// Assign the result of the finished delegate to the temporary
// variable specified by delegate.resultName (see delegateYield).
context[delegate.resultName] = info.value; // Resume execution at the desired location (see delegateYield).
context.next = delegate.nextLoc; // If context.method was "throw" but the delegate handled the
// exception, let the outer generator proceed normally. If
// context.method was "next", forget context.arg since it has been
// "consumed" by the delegate iterator. If context.method was
// "return", allow the original .return call to continue in the
// outer generator.
if (context.method !== "return") {
context.method = "next";
context.arg = undefined;
}
} else {
// Re-yield the result returned by the delegate method.
return info;
} // The delegate iterator is finished, so forget it and continue with
// the outer generator.
context.delegate = null;
return ContinueSentinel;
} // Define Generator.prototype.{next,throw,return} in terms of the
// unified ._invoke helper method.
defineIteratorMethods(Gp);
Gp[toStringTagSymbol] = "Generator"; // A Generator should always return itself as the iterator object when the
// @@iterator function is called on it. Some browsers' implementations of the
// iterator prototype chain incorrectly implement this, causing the Generator
// object to not be returned from this call. This ensures that doesn't happen.
// See https://github.com/facebook/regenerator/issues/274 for more details.
Gp[iteratorSymbol] = function () {
return this;
};
Gp.toString = function () {
return "[object Generator]";
};
function pushTryEntry(locs) {
var entry = {
tryLoc: locs[0],
};
if (1 in locs) {
entry.catchLoc = locs[1];
}
if (2 in locs) {
entry.finallyLoc = locs[2];
entry.afterLoc = locs[3];
}
this.tryEntries.push(entry);
}
function resetTryEntry(entry) {
var record = entry.completion || {};
record.type = "normal";
delete record.arg;
entry.completion = record;
}
function Context(tryLocsList) {
// The root entry object (effectively a try statement without a catch
// or a finally block) gives us a place to store values thrown from
// locations where there is no enclosing try statement.
this.tryEntries = [
{
tryLoc: "root",
},
];
tryLocsList.forEach(pushTryEntry, this);
this.reset(true);
}
exports.keys = function (object) {
var keys = [];
for (var key in object) {
keys.push(key);
}
keys.reverse(); // Rather than returning an object with a next method, we keep
// things simple and return the next function itself.
return function next() {
while (keys.length) {
var key = keys.pop();
if (key in object) {
next.value = key;
next.done = false;
return next;
}
} // To avoid creating an additional object, we just hang the .value
// and .done properties off the next function object itself. This
// also ensures that the minifier will not anonymize the function.
next.done = true;
return next;
};
};
function values(iterable) {
if (iterable) {
var iteratorMethod = iterable[iteratorSymbol];
if (iteratorMethod) {
return iteratorMethod.call(iterable);
}
if (typeof iterable.next === "function") {
return iterable;
}
if (!isNaN(iterable.length)) {
var i = -1,
next = function next() {
while (++i < iterable.length) {
if (hasOwn.call(iterable, i)) {
next.value = iterable[i];
next.done = false;
return next;
}
}
next.value = undefined;
next.done = true;
return next;
};
return (next.next = next);
}
} // Return an iterator with no values.
return {
next: doneResult,
};
}
exports.values = values;
function doneResult() {
return {
value: undefined,
done: true,
};
}
Context.prototype = {
constructor: Context,
reset: function (skipTempReset) {
this.prev = 0;
this.next = 0; // Resetting context._sent for legacy support of Babel's
// function.sent implementation.
this.sent = this._sent = undefined;
this.done = false;
this.delegate = null;
this.method = "next";
this.arg = undefined;
this.tryEntries.forEach(resetTryEntry);
if (!skipTempReset) {
for (var name in this) {
// Not sure about the optimal order of these conditions:
if (
name.charAt(0) === "t" &&
hasOwn.call(this, name) &&
!isNaN(+name.slice(1))
) {
this[name] = undefined;
}
}
}
},
stop: function () {
this.done = true;
var rootEntry = this.tryEntries[0];
var rootRecord = rootEntry.completion;
if (rootRecord.type === "throw") {
throw rootRecord.arg;
}
return this.rval;
},
dispatchException: function (exception) {
if (this.done) {
throw exception;
}
var context = this;
function handle(loc, caught) {
record.type = "throw";
record.arg = exception;
context.next = loc;
if (caught) {
// If the dispatched exception was caught by a catch block,
// then let that catch block handle the exception normally.
context.method = "next";
context.arg = undefined;
}
return !!caught;
}
for (
var i = this.tryEntries.length - 1;
i >= 0;
--i
) {
var entry = this.tryEntries[i];
var record = entry.completion;
if (entry.tryLoc === "root") {
// Exception thrown outside of any try block that could handle
// it, so set the completion value of the entire function to
// throw the exception.
return handle("end");
}
if (entry.tryLoc <= this.prev) {
var hasCatch = hasOwn.call(
entry,
"catchLoc"
);
var hasFinally = hasOwn.call(
entry,
"finallyLoc"
);
if (hasCatch && hasFinally) {
if (this.prev < entry.catchLoc) {
return handle(entry.catchLoc, true);
} else if (
this.prev < entry.finallyLoc
) {
return handle(entry.finallyLoc);
}
} else if (hasCatch) {
if (this.prev < entry.catchLoc) {
return handle(entry.catchLoc, true);
}
} else if (hasFinally) {
if (this.prev < entry.finallyLoc) {
return handle(entry.finallyLoc);
}
} else {
throw new Error(
"try statement without catch or finally"
);
}
}
}
},
abrupt: function (type, arg) {
for (
var i = this.tryEntries.length - 1;
i >= 0;
--i
) {
var entry = this.tryEntries[i];
if (
entry.tryLoc <= this.prev &&
hasOwn.call(entry, "finallyLoc") &&
this.prev < entry.finallyLoc
) {
var finallyEntry = entry;
break;
}
}
if (
finallyEntry &&
(type === "break" || type === "continue") &&
finallyEntry.tryLoc <= arg &&
arg <= finallyEntry.finallyLoc
) {
// Ignore the finally entry if control is not jumping to a
// location outside the try/catch block.
finallyEntry = null;
}
var record = finallyEntry
? finallyEntry.completion
: {};
record.type = type;
record.arg = arg;
if (finallyEntry) {
this.method = "next";
this.next = finallyEntry.finallyLoc;
return ContinueSentinel;
}
return this.complete(record);
},
complete: function (record, afterLoc) {
if (record.type === "throw") {
throw record.arg;
}
if (
record.type === "break" ||
record.type === "continue"
) {
this.next = record.arg;
} else if (record.type === "return") {
this.rval = this.arg = record.arg;
this.method = "return";
this.next = "end";
} else if (record.type === "normal" && afterLoc) {
this.next = afterLoc;
}
return ContinueSentinel;
},
finish: function (finallyLoc) {
for (
var i = this.tryEntries.length - 1;
i >= 0;
--i
) {
var entry = this.tryEntries[i];
if (entry.finallyLoc === finallyLoc) {
this.complete(
entry.completion,
entry.afterLoc
);
resetTryEntry(entry);
return ContinueSentinel;
}
}
},
catch: function (tryLoc) {
for (
var i = this.tryEntries.length - 1;
i >= 0;
--i
) {
var entry = this.tryEntries[i];
if (entry.tryLoc === tryLoc) {
var record = entry.completion;
if (record.type === "throw") {
var thrown = record.arg;
resetTryEntry(entry);
}
return thrown;
}
} // The context.catch method must only be called with a location
// argument that corresponds to a known catch block.
throw new Error("illegal catch attempt");
},
delegateYield: function (
iterable,
resultName,
nextLoc
) {
this.delegate = {
iterator: values(iterable),
resultName: resultName,
nextLoc: nextLoc,
};
if (this.method === "next") {
// Deliberately forget the last sent value so that we don't
// accidentally pass it on to the delegate.
this.arg = undefined;
}
return ContinueSentinel;
},
}; // Regardless of whether this script is executing as a CommonJS module
// or not, return the runtime object so that we can declare the variable
// regeneratorRuntime in the outer scope, which allows this module to be
// injected easily by `bin/regenerator --include-runtime script.js`.
return exports;
})(
// If this script is executing as a CommonJS module, use module.exports
// as the regeneratorRuntime namespace. Otherwise create a new empty
// object. Either way, the resulting object will be used to initialize
// the regeneratorRuntime variable at the top of this file.
true ? module.exports : undefined
);
try {
regeneratorRuntime = runtime;
} catch (accidentalStrictMode) {
// This module should not be running in strict mode, so the above
// assignment should always work unless something is misconfigured. Just
// in case runtime.js accidentally runs in strict mode, we can escape
// strict mode using a global Function call. This could conceivably fail
// if a Content Security Policy forbids using Function, but in that case
// the proper solution is to fix the accidental strict mode problem. If
// you've misconfigured your bundler to force strict mode and applied a
// CSP to forbid Function, and you're not willing to fix either of those
// problems, please detail your unique predicament in a GitHub issue.
Function("r", "regeneratorRuntime = r")(runtime);
}
/***/
},
/* 229 */
/***/ function (module, exports, __webpack_require__) {
var basePickBy = __webpack_require__(230),
hasIn = __webpack_require__(240);
/**
* 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);
});
}
module.exports = basePick;
/***/
},
/* 230 */
/***/ function (module, exports, __webpack_require__) {
var baseGet = __webpack_require__(231),
baseSet = __webpack_require__(239),
castPath = __webpack_require__(32);
/**
* 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;
}
module.exports = basePickBy;
/***/
},
/* 231 */
/***/ function (module, exports, __webpack_require__) {
var castPath = __webpack_require__(32),
toKey = __webpack_require__(43);
/**
* 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;
}
module.exports = baseGet;
/***/
},
/* 232 */
/***/ function (module, exports, __webpack_require__) {
var isArray = __webpack_require__(15),
isSymbol = __webpack_require__(42);
/** Used to match property names within property paths. */
var reIsDeepProp =
/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,
reIsPlainProp = /^\w*$/;
/**
* 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))
);
}
module.exports = isKey;
/***/
},
/* 233 */
/***/ function (module, exports, __webpack_require__) {
var memoizeCapped = __webpack_require__(234);
/** Used to match property names within property paths. */
var rePropName =
/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g;
/** Used to match backslashes in property paths. */
var reEscapeChar = /\\(\\)?/g;
/**
* 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;
});
module.exports = stringToPath;
/***/
},
/* 234 */
/***/ function (module, exports, __webpack_require__) {
var memoize = __webpack_require__(235);
/** Used as the maximum memoize cache size. */
var MAX_MEMOIZE_SIZE = 500;
/**
* 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;
}
module.exports = memoizeCapped;
/***/
},
/* 235 */
/***/ function (module, exports, __webpack_require__) {
var MapCache = __webpack_require__(47);
/** Error message constants. */
var FUNC_ERROR_TEXT = "Expected a function";
/**
* 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;
module.exports = memoize;
/***/
},
/* 236 */
/***/ function (module, exports, __webpack_require__) {
var baseToString = __webpack_require__(237);
/**
* 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);
}
module.exports = toString;
/***/
},
/* 237 */
/***/ function (module, exports, __webpack_require__) {
var Symbol = __webpack_require__(27),
arrayMap = __webpack_require__(238),
isArray = __webpack_require__(15),
isSymbol = __webpack_require__(42);
/** Used as references for various `Number` constants. */
var INFINITY = 1 / 0;
/** Used to convert symbols to primitives and strings. */
var symbolProto = Symbol ? Symbol.prototype : undefined,
symbolToString = symbolProto
? symbolProto.toString
: undefined;
/**
* 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;
}
module.exports = baseToString;
/***/
},
/* 238 */
/***/ function (module, exports) {
/**
* 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;
}
module.exports = arrayMap;
/***/
},
/* 239 */
/***/ function (module, exports, __webpack_require__) {
var assignValue = __webpack_require__(55),
castPath = __webpack_require__(32),
isIndex = __webpack_require__(31),
isObject = __webpack_require__(14),
toKey = __webpack_require__(43);
/**
* 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;
}
module.exports = baseSet;
/***/
},
/* 240 */
/***/ function (module, exports, __webpack_require__) {
var baseHasIn = __webpack_require__(241),
hasPath = __webpack_require__(242);
/**
* 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);
}
module.exports = hasIn;
/***/
},
/* 241 */
/***/ function (module, exports) {
/**
* 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);
}
module.exports = baseHasIn;
/***/
},
/* 242 */
/***/ function (module, exports, __webpack_require__) {
var castPath = __webpack_require__(32),
isArguments = __webpack_require__(30),
isArray = __webpack_require__(15),
isIndex = __webpack_require__(31),
isLength = __webpack_require__(40),
toKey = __webpack_require__(43);
/**
* 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))
);
}
module.exports = hasPath;
/***/
},
/* 243 */
/***/ function (module, exports, __webpack_require__) {
var flatten = __webpack_require__(244),
overRest = __webpack_require__(58),
setToString = __webpack_require__(59);
/**
* 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 + ""
);
}
module.exports = flatRest;
/***/
},
/* 244 */
/***/ function (module, exports, __webpack_require__) {
var baseFlatten = __webpack_require__(245);
/**
* 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) : [];
}
module.exports = flatten;
/***/
},
/* 245 */
/***/ function (module, exports, __webpack_require__) {
var arrayPush = __webpack_require__(246),
isFlattenable = __webpack_require__(247);
/**
* 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;
}
module.exports = baseFlatten;
/***/
},
/* 246 */
/***/ function (module, exports) {
/**
* 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;
}
module.exports = arrayPush;
/***/
},
/* 247 */
/***/ function (module, exports, __webpack_require__) {
var Symbol = __webpack_require__(27),
isArguments = __webpack_require__(30),
isArray = __webpack_require__(15);
/** Built-in value references. */
var spreadableSymbol = Symbol
? Symbol.isConcatSpreadable
: undefined;
/**
* 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])
);
}
module.exports = isFlattenable;
/***/
},
/* 248 */
/***/ function (module, exports) {
function _isNativeFunction(fn) {
return (
Function.toString.call(fn).indexOf("[native code]") !==
-1
);
}
module.exports = _isNativeFunction;
(module.exports["default"] = module.exports),
(module.exports.__esModule = true);
/***/
},
/* 249 */
/***/ function (module, exports, __webpack_require__) {
var setPrototypeOf = __webpack_require__(41);
var isNativeReflectConstruct = __webpack_require__(250);
function _construct(Parent, args, Class) {
if (isNativeReflectConstruct()) {
module.exports = _construct = Reflect.construct;
(module.exports["default"] = module.exports),
(module.exports.__esModule = true);
} else {
module.exports = _construct = function _construct(
Parent,
args,
Class
) {
var a = [null];
a.push.apply(a, args);
var Constructor = Function.bind.apply(Parent, a);
var instance = new Constructor();
if (Class)
setPrototypeOf(instance, Class.prototype);
return instance;
};
(module.exports["default"] = module.exports),
(module.exports.__esModule = true);
}
return _construct.apply(null, arguments);
}
module.exports = _construct;
(module.exports["default"] = module.exports),
(module.exports.__esModule = true);
/***/
},
/* 250 */
/***/ function (module, exports) {
function _isNativeReflectConstruct() {
if (typeof Reflect === "undefined" || !Reflect.construct)
return false;
if (Reflect.construct.sham) return false;
if (typeof Proxy === "function") return true;
try {
Boolean.prototype.valueOf.call(
Reflect.construct(Boolean, [], function () {})
);
return true;
} catch (e) {
return false;
}
}
module.exports = _isNativeReflectConstruct;
(module.exports["default"] = module.exports),
(module.exports.__esModule = true);
/***/
},
/* 251 */
/***/ function (module, exports) {
module.exports = determinant;
/**
* Calculates the determinant of a mat2
*
* @alias mat2.determinant
* @param {mat2} a the source matrix
* @returns {Number} determinant of a
*/
function determinant(a) {
return a[0] * a[3] - a[2] * a[1];
}
/***/
},
/* 252 */
/***/ function (module, exports) {
module.exports = transpose;
/**
* Transpose the values of a mat2
*
* @alias mat2.transpose
* @param {mat2} out the receiving matrix
* @param {mat2} a the source matrix
* @returns {mat2} out
*/
function transpose(out, a) {
// If we are transposing ourselves we can skip a few steps but have to cache some values
if (out === a) {
var a1 = a[1];
out[1] = a[2];
out[2] = a1;
} else {
out[0] = a[0];
out[1] = a[2];
out[2] = a[1];
out[3] = a[3];
}
return out;
}
/***/
},
/* 253 */
/***/ function (module, exports) {
module.exports = multiply;
/**
* Multiplies two mat2's
*
* @alias mat2.multiply
* @param {mat2} out the receiving matrix
* @param {mat2} a the first operand
* @param {mat2} b the second operand
* @returns {mat2} out
*/
function multiply(out, a, b) {
var a0 = a[0],
a1 = a[1],
a2 = a[2],
a3 = a[3];
var b0 = b[0],
b1 = b[1],
b2 = b[2],
b3 = b[3];
out[0] = a0 * b0 + a2 * b1;
out[1] = a1 * b0 + a3 * b1;
out[2] = a0 * b2 + a2 * b3;
out[3] = a1 * b2 + a3 * b3;
return out;
}
/***/
},
/* 254 */
/***/ function (module, exports) {
module.exports = identity;
/**
* Set a mat2 to the identity matrix
*
* @alias mat2.identity
* @param {mat2} out the receiving matrix
* @returns {mat2} out
*/
function identity(out) {
out[0] = 1;
out[1] = 0;
out[2] = 0;
out[3] = 1;
return out;
}
/***/
},
/* 255 */
/***/ function (module, exports) {
module.exports = adjoint;
/**
* Calculates the adjugate of a mat2
*
* @alias mat2.adjoint
* @param {mat2} out the receiving matrix
* @param {mat2} a the source matrix
* @returns {mat2} out
*/
function adjoint(out, a) {
// Caching this value is nessecary if out == a
var a0 = a[0];
out[0] = a[3];
out[1] = -a[1];
out[2] = -a[2];
out[3] = a0;
return out;
}
/***/
},
/* 256 */
/***/ function (module, exports) {
module.exports = rotate;
/**
* Rotates a mat2 by the given angle
*
* @alias mat2.rotate
* @param {mat2} out the receiving matrix
* @param {mat2} a the matrix to rotate
* @param {Number} rad the angle to rotate the matrix by
* @returns {mat2} out
*/
function rotate(out, a, rad) {
var a0 = a[0],
a1 = a[1],
a2 = a[2],
a3 = a[3];
var s = Math.sin(rad);
var c = Math.cos(rad);
out[0] = a0 * c + a2 * s;
out[1] = a1 * c + a3 * s;
out[2] = a0 * -s + a2 * c;
out[3] = a1 * -s + a3 * c;
return out;
}
/***/
},
/* 257 */
/***/ function (module, exports) {
module.exports = invert;
/**
* Inverts a mat2
*
* @alias mat2.invert
* @param {mat2} out the receiving matrix
* @param {mat2} a the source matrix
* @returns {mat2} out
*/
function invert(out, a) {
var a0 = a[0];
var a1 = a[1];
var a2 = a[2];
var a3 = a[3];
var det = a0 * a3 - a2 * a1;
if (!det) return null;
det = 1.0 / det;
out[0] = a3 * det;
out[1] = -a1 * det;
out[2] = -a2 * det;
out[3] = a0 * det;
return out;
}
/***/
},
/* 258 */
/***/ function (module, exports) {
module.exports = create;
/**
* Creates a new identity mat2
*
* @alias mat2.create
* @returns {mat2} a new 2x2 matrix
*/
function create() {
var out = new Float32Array(4);
out[0] = 1;
out[1] = 0;
out[2] = 0;
out[3] = 1;
return out;
}
/***/
},
/* 259 */
/***/ function (module, exports) {
module.exports = scale;
/**
* Scales the mat2 by the dimensions in the given vec2
*
* @alias mat2.scale
* @param {mat2} out the receiving matrix
* @param {mat2} a the matrix to rotate
* @param {vec2} v the vec2 to scale the matrix by
* @returns {mat2} out
**/
function scale(out, a, v) {
var a0 = a[0],
a1 = a[1],
a2 = a[2],
a3 = a[3];
var v0 = v[0],
v1 = v[1];
out[0] = a0 * v0;
out[1] = a1 * v0;
out[2] = a2 * v1;
out[3] = a3 * v1;
return out;
}
/***/
},
/* 260 */
/***/ function (module, exports) {
module.exports = copy;
/**
* Copy the values from one mat2 to another
*
* @alias mat2.copy
* @param {mat2} out the receiving matrix
* @param {mat2} a the source matrix
* @returns {mat2} out
*/
function copy(out, a) {
out[0] = a[0];
out[1] = a[1];
out[2] = a[2];
out[3] = a[3];
return out;
}
/***/
},
/* 261 */
/***/ function (module, exports) {
module.exports = frob;
/**
* Returns Frobenius norm of a mat2
*
* @alias mat2.frob
* @param {mat2} a the matrix to calculate Frobenius norm of
* @returns {Number} Frobenius norm
*/
function frob(a) {
return Math.sqrt(
Math.pow(a[0], 2) +
Math.pow(a[1], 2) +
Math.pow(a[2], 2) +
Math.pow(a[3], 2)
);
}
/***/
},
/* 262 */
/***/ function (module, exports) {
module.exports = ldu;
/**
* Returns L, D and U matrices (Lower triangular, Diagonal and Upper triangular) by factorizing the input matrix
*
* @alias mat2.ldu
* @param {mat2} L the lower triangular matrix
* @param {mat2} D the diagonal matrix
* @param {mat2} U the upper triangular matrix
* @param {mat2} a the input matrix to factorize
*/
function ldu(L, D, U, a) {
L[2] = a[2] / a[0];
U[0] = a[0];
U[1] = a[1];
U[3] = a[3] - L[2] * U[1];
return [L, D, U];
}
/***/
},
/* 263 */
/***/ function (module, __webpack_exports__, __webpack_require__) {
"use strict";
// ESM COMPAT FLAG
__webpack_require__.r(__webpack_exports__);
// EXPORTS
__webpack_require__.d(
__webpack_exports__,
"BarcodeDecoder",
function () {
return /* reexport */ barcode_decoder;
}
);
__webpack_require__.d(
__webpack_exports__,
"Readers",
function () {
return /* reexport */ reader_namespaceObject;
}
);
__webpack_require__.d(
__webpack_exports__,
"CameraAccess",
function () {
return /* reexport */ camera_access;
}
);
__webpack_require__.d(
__webpack_exports__,
"ImageDebug",
function () {
return /* reexport */ image_debug["a" /* default */];
}
);
__webpack_require__.d(
__webpack_exports__,
"ImageWrapper",
function () {
return /* reexport */ image_wrapper["a" /* default */];
}
);
__webpack_require__.d(
__webpack_exports__,
"ResultCollector",
function () {
return /* reexport */ result_collector;
}
);
// NAMESPACE OBJECT: ./src/reader/index.ts
var reader_namespaceObject = {};
__webpack_require__.r(reader_namespaceObject);
__webpack_require__.d(
reader_namespaceObject,
"BarcodeReader",
function () {
return barcode_reader;
}
);
__webpack_require__.d(
reader_namespaceObject,
"TwoOfFiveReader",
function () {
return _2of5_reader;
}
);
__webpack_require__.d(
reader_namespaceObject,
"NewCodabarReader",
function () {
return codabar_reader;
}
);
__webpack_require__.d(
reader_namespaceObject,
"Code128Reader",
function () {
return code_128_reader;
}
);
__webpack_require__.d(
reader_namespaceObject,
"Code32Reader",
function () {
return code_32_reader;
}
);
__webpack_require__.d(
reader_namespaceObject,
"Code39Reader",
function () {
return code_39_reader;
}
);
__webpack_require__.d(
reader_namespaceObject,
"Code39VINReader",
function () {
return code_39_vin_reader;
}
);
__webpack_require__.d(
reader_namespaceObject,
"Code93Reader",
function () {
return code_93_reader;
}
);
__webpack_require__.d(
reader_namespaceObject,
"EAN2Reader",
function () {
return ean_2_reader;
}
);
__webpack_require__.d(
reader_namespaceObject,
"EAN5Reader",
function () {
return ean_5_reader;
}
);
__webpack_require__.d(
reader_namespaceObject,
"EAN8Reader",
function () {
return ean_8_reader;
}
);
__webpack_require__.d(
reader_namespaceObject,
"EANReader",
function () {
return ean_reader;
}
);
__webpack_require__.d(
reader_namespaceObject,
"I2of5Reader",
function () {
return i2of5_reader;
}
);
__webpack_require__.d(
reader_namespaceObject,
"UPCEReader",
function () {
return upc_e_reader;
}
);
__webpack_require__.d(
reader_namespaceObject,
"UPCReader",
function () {
return upc_reader;
}
);
// EXTERNAL MODULE: ./node_modules/@babel/runtime/helpers/typeof.js
var helpers_typeof = __webpack_require__(19);
var typeof_default =
/*#__PURE__*/ __webpack_require__.n(helpers_typeof);
// EXTERNAL MODULE: ./node_modules/lodash/merge.js
var merge = __webpack_require__(16);
var merge_default = /*#__PURE__*/ __webpack_require__.n(merge);
// EXTERNAL MODULE: ./src/common/typedefs.js
var typedefs = __webpack_require__(152);
// EXTERNAL MODULE: ./src/common/image_wrapper.ts
var image_wrapper = __webpack_require__(11);
// CONCATENATED MODULE: ./src/decoder/bresenham.js
var Bresenham = {};
var Slope = {
DIR: {
UP: 1,
DOWN: -1,
},
};
/**
* Scans a line of the given image from point p1 to p2 and returns a result object containing
* gray-scale values (0-255) of the underlying pixels in addition to the min
* and max values.
* @param {Object} imageWrapper
* @param {Object} p1 The start point {x,y}
* @param {Object} p2 The end point {x,y}
* @returns {line, min, max}
*/
Bresenham.getBarcodeLine = function (imageWrapper, p1, p2) {
/* eslint-disable no-bitwise */
var x0 = p1.x | 0;
var y0 = p1.y | 0;
var x1 = p2.x | 0;
var y1 = p2.y | 0;
/* eslint-disable no-bitwise */
var steep = Math.abs(y1 - y0) > Math.abs(x1 - x0);
var error;
var y;
var tmp;
var x;
var line = [];
var imageData = imageWrapper.data;
var width = imageWrapper.size.x;
var val;
var min = 255;
var max = 0;
function read(a, b) {
val = imageData[b * width + a];
min = val < min ? val : min;
max = val > max ? val : max;
line.push(val);
}
if (steep) {
tmp = x0;
x0 = y0;
y0 = tmp;
tmp = x1;
x1 = y1;
y1 = tmp;
}
if (x0 > x1) {
tmp = x0;
x0 = x1;
x1 = tmp;
tmp = y0;
y0 = y1;
y1 = tmp;
}
var deltaX = x1 - x0;
var deltaY = Math.abs(y1 - y0);
error = (deltaX / 2) | 0;
y = y0;
var yStep = y0 < y1 ? 1 : -1;
for (x = x0; x < x1; x++) {
if (steep) {
read(y, x);
} else {
read(x, y);
}
error -= deltaY;
if (error < 0) {
y += yStep;
error += deltaX;
}
}
return {
line: line,
min: min,
max: max,
};
};
/**
* Converts the result from getBarcodeLine into a binary representation
* also considering the frequency and slope of the signal for more robust results
* @param {Object} result {line, min, max}
*/
Bresenham.toBinaryLine = function (result) {
var min = result.min;
var max = result.max;
var line = result.line;
var slope;
var slope2;
var center = min + (max - min) / 2;
var extrema = [];
var currentDir;
var dir;
var threshold = (max - min) / 12;
var rThreshold = -threshold;
var i;
var j; // 1. find extrema
currentDir =
line[0] > center ? Slope.DIR.UP : Slope.DIR.DOWN;
extrema.push({
pos: 0,
val: line[0],
});
for (i = 0; i < line.length - 2; i++) {
slope = line[i + 1] - line[i];
slope2 = line[i + 2] - line[i + 1];
if (
slope + slope2 < rThreshold &&
line[i + 1] < center * 1.5
) {
dir = Slope.DIR.DOWN;
} else if (
slope + slope2 > threshold &&
line[i + 1] > center * 0.5
) {
dir = Slope.DIR.UP;
} else {
dir = currentDir;
}
if (currentDir !== dir) {
extrema.push({
pos: i,
val: line[i],
});
currentDir = dir;
}
}
extrema.push({
pos: line.length,
val: line[line.length - 1],
});
for (j = extrema[0].pos; j < extrema[1].pos; j++) {
line[j] = line[j] > center ? 0 : 1;
} // iterate over extrema and convert to binary based on avg between minmax
for (i = 1; i < extrema.length - 1; i++) {
if (extrema[i + 1].val > extrema[i].val) {
threshold =
(extrema[i].val +
((extrema[i + 1].val - extrema[i].val) /
3) *
2) |
0;
} else {
threshold =
(extrema[i + 1].val +
(extrema[i].val - extrema[i + 1].val) / 3) |
0;
}
for (j = extrema[i].pos; j < extrema[i + 1].pos; j++) {
line[j] = line[j] > threshold ? 0 : 1;
}
}
return {
line: line,
threshold: threshold,
};
};
/**
* Used for development only
*/
Bresenham.debug = {
printFrequency: function printFrequency(line, canvas) {
var i;
var ctx = canvas.getContext("2d"); // eslint-disable-next-line no-param-reassign
canvas.width = line.length; // eslint-disable-next-line no-param-reassign
canvas.height = 256;
ctx.beginPath();
ctx.strokeStyle = "blue";
for (i = 0; i < line.length; i++) {
ctx.moveTo(i, 255);
ctx.lineTo(i, 255 - line[i]);
}
ctx.stroke();
ctx.closePath();
},
printPattern: function printPattern(line, canvas) {
var ctx = canvas.getContext("2d");
var i; // eslint-disable-next-line no-param-reassign
canvas.width = line.length;
ctx.fillColor = "black";
for (i = 0; i < line.length; i++) {
if (line[i] === 1) {
ctx.fillRect(i, 0, 1, 100);
}
}
},
};
/* harmony default export */ var bresenham = Bresenham;
// EXTERNAL MODULE: ./src/common/image_debug.ts
var image_debug = __webpack_require__(9);
// EXTERNAL MODULE: ./node_modules/@babel/runtime/helpers/classCallCheck.js
var classCallCheck = __webpack_require__(3);
var classCallCheck_default =
/*#__PURE__*/ __webpack_require__.n(classCallCheck);
// EXTERNAL MODULE: ./node_modules/@babel/runtime/helpers/createClass.js
var createClass = __webpack_require__(4);
var createClass_default =
/*#__PURE__*/ __webpack_require__.n(createClass);
// EXTERNAL MODULE: ./node_modules/@babel/runtime/helpers/assertThisInitialized.js
var assertThisInitialized = __webpack_require__(1);
var assertThisInitialized_default =
/*#__PURE__*/ __webpack_require__.n(assertThisInitialized);
// EXTERNAL MODULE: ./node_modules/@babel/runtime/helpers/inherits.js
var inherits = __webpack_require__(6);
var inherits_default =
/*#__PURE__*/ __webpack_require__.n(inherits);
// EXTERNAL MODULE: ./node_modules/@babel/runtime/helpers/possibleConstructorReturn.js
var possibleConstructorReturn = __webpack_require__(5);
var possibleConstructorReturn_default =
/*#__PURE__*/ __webpack_require__.n(
possibleConstructorReturn
);
// EXTERNAL MODULE: ./node_modules/@babel/runtime/helpers/getPrototypeOf.js
var getPrototypeOf = __webpack_require__(2);
var getPrototypeOf_default =
/*#__PURE__*/ __webpack_require__.n(getPrototypeOf);
// EXTERNAL MODULE: ./node_modules/@babel/runtime/helpers/defineProperty.js
var defineProperty = __webpack_require__(0);
var defineProperty_default =
/*#__PURE__*/ __webpack_require__.n(defineProperty);
// EXTERNAL MODULE: ./src/common/array_helper.ts
var array_helper = __webpack_require__(10);
// CONCATENATED MODULE: ./src/reader/barcode_reader.ts
var BarcodeDirection;
(function (BarcodeDirection) {
BarcodeDirection[(BarcodeDirection["Forward"] = 1)] =
"Forward";
BarcodeDirection[(BarcodeDirection["Reverse"] = -1)] =
"Reverse";
})(BarcodeDirection || (BarcodeDirection = {}));
var barcode_reader_BarcodeReader = /*#__PURE__*/ (function () {
function BarcodeReader(config, supplements) {
classCallCheck_default()(this, BarcodeReader);
defineProperty_default()(this, "_row", []);
defineProperty_default()(this, "config", {});
defineProperty_default()(this, "supplements", []);
defineProperty_default()(this, "SINGLE_CODE_ERROR", 0);
defineProperty_default()(this, "FORMAT", "unknown");
defineProperty_default()(this, "CONFIG_KEYS", {});
this._row = [];
this.config = config || {};
if (supplements) {
this.supplements = supplements;
}
return this;
}
createClass_default()(
BarcodeReader,
[
{
key: "_nextUnset",
value: function _nextUnset(line) {
var start =
arguments.length > 1 &&
arguments[1] !== undefined
? arguments[1]
: 0;
for (var i = start; i < line.length; i++) {
if (!line[i]) return i;
}
return line.length;
},
},
{
key: "_matchPattern",
value: function _matchPattern(
counter,
code,
maxSingleError
) {
var error = 0;
var singleError = 0;
var sum = 0;
var modulo = 0;
var barWidth = 0;
var count = 0;
var scaled = 0;
maxSingleError =
maxSingleError ||
this.SINGLE_CODE_ERROR ||
1;
for (var i = 0; i < counter.length; i++) {
sum += counter[i];
modulo += code[i];
}
if (sum < modulo) {
return Number.MAX_VALUE;
}
barWidth = sum / modulo;
maxSingleError *= barWidth;
for (
var _i = 0;
_i < counter.length;
_i++
) {
count = counter[_i];
scaled = code[_i] * barWidth;
singleError =
Math.abs(count - scaled) / scaled;
if (singleError > maxSingleError) {
return Number.MAX_VALUE;
}
error += singleError;
}
return error / modulo;
},
},
{
key: "_nextSet",
value: function _nextSet(line) {
var offset =
arguments.length > 1 &&
arguments[1] !== undefined
? arguments[1]
: 0;
for (var i = offset; i < line.length; i++) {
if (line[i]) return i;
}
return line.length;
},
},
{
key: "_correctBars",
value: function _correctBars(
counter,
correction,
indices
) {
var length = indices.length;
var tmp = 0;
while (length--) {
tmp =
counter[indices[length]] *
(1 - (1 - correction) / 2);
if (tmp > 1) {
counter[indices[length]] = tmp;
}
}
},
},
{
key: "decodePattern",
value: function decodePattern(pattern) {
// console.warn('* decodePattern', pattern);
this._row = pattern; // console.warn('* decodePattern calling decode', typeof this, this.constructor, this.FORMAT, JSON.stringify(this));
var result = this.decode(); // console.warn('* first result=', result);
if (result === null) {
this._row.reverse();
result = this.decode(); // console.warn('* reversed result=', result);
if (result) {
result.direction =
BarcodeDirection.Reverse;
result.start =
this._row.length - result.start;
result.end =
this._row.length - result.end;
}
} else {
result.direction =
BarcodeDirection.Forward;
}
if (result) {
result.format = this.FORMAT;
} // console.warn('* returning', result);
return result;
},
},
{
key: "_matchRange",
value: function _matchRange(start, end, value) {
var i;
start = start < 0 ? 0 : start;
for (i = start; i < end; i++) {
if (this._row[i] !== value) {
return false;
}
}
return true;
},
},
{
key: "_fillCounters",
value: function _fillCounters() {
var offset =
arguments.length > 0 &&
arguments[0] !== undefined
? arguments[0]
: this._nextUnset(this._row);
var end =
arguments.length > 1 &&
arguments[1] !== undefined
? arguments[1]
: this._row.length;
var isWhite =
arguments.length > 2 &&
arguments[2] !== undefined
? arguments[2]
: true;
var counters = [];
var counterPos = 0;
counters[counterPos] = 0;
for (var i = offset; i < end; i++) {
if (this._row[i] ^ (isWhite ? 1 : 0)) {
counters[counterPos]++;
} else {
counterPos++;
counters[counterPos] = 1;
isWhite = !isWhite;
}
}
return counters;
},
},
{
key: "_toCounters",
value: function _toCounters(start, counters) {
var numCounters = counters.length;
var end = this._row.length;
var isWhite = !this._row[start];
var counterPos = 0;
array_helper["a" /* default */].init(
counters,
0
);
for (var i = start; i < end; i++) {
if (this._row[i] ^ (isWhite ? 1 : 0)) {
counters[counterPos]++;
} else {
counterPos++;
if (counterPos === numCounters) {
break;
} else {
counters[counterPos] = 1;
isWhite = !isWhite;
}
}
}
return counters;
},
},
],
[
{
key: "Exception",
get: function get() {
return {
StartNotFoundException:
"Start-Info was not found!",
CodeNotFoundException:
"Code could not be found!",
PatternNotFoundException:
"Pattern could not be found!",
};
},
},
]
);
return BarcodeReader;
})();
/* harmony default export */ var barcode_reader =
barcode_reader_BarcodeReader;
// CONCATENATED MODULE: ./src/reader/code_128_reader.ts
function _createSuper(Derived) {
var hasNativeReflectConstruct = _isNativeReflectConstruct();
return function _createSuperInternal() {
var Super = getPrototypeOf_default()(Derived),
result;
if (hasNativeReflectConstruct) {
var NewTarget =
getPrototypeOf_default()(this).constructor;
result = Reflect.construct(
Super,
arguments,
NewTarget
);
} else {
result = Super.apply(this, arguments);
}
return possibleConstructorReturn_default()(
this,
result
);
};
}
function _isNativeReflectConstruct() {
if (typeof Reflect === "undefined" || !Reflect.construct)
return false;
if (Reflect.construct.sham) return false;
if (typeof Proxy === "function") return true;
try {
Boolean.prototype.valueOf.call(
Reflect.construct(Boolean, [], function () {})
);
return true;
} catch (e) {
return false;
}
}
var code_128_reader_Code128Reader = /*#__PURE__*/ (function (
_BarcodeReader
) {
inherits_default()(Code128Reader, _BarcodeReader);
var _super = _createSuper(Code128Reader);
function Code128Reader() {
var _this;
classCallCheck_default()(this, Code128Reader);
for (
var _len = arguments.length,
args = new Array(_len),
_key = 0;
_key < _len;
_key++
) {
args[_key] = arguments[_key];
}
_this = _super.call.apply(_super, [this].concat(args));
defineProperty_default()(
assertThisInitialized_default()(_this),
"CODE_SHIFT",
98
);
defineProperty_default()(
assertThisInitialized_default()(_this),
"CODE_C",
99
);
defineProperty_default()(
assertThisInitialized_default()(_this),
"CODE_B",
100
);
defineProperty_default()(
assertThisInitialized_default()(_this),
"CODE_A",
101
);
defineProperty_default()(
assertThisInitialized_default()(_this),
"START_CODE_A",
103
);
defineProperty_default()(
assertThisInitialized_default()(_this),
"START_CODE_B",
104
);
defineProperty_default()(
assertThisInitialized_default()(_this),
"START_CODE_C",
105
);
defineProperty_default()(
assertThisInitialized_default()(_this),
"STOP_CODE",
106
);
defineProperty_default()(
assertThisInitialized_default()(_this),
"CODE_PATTERN",
[
[2, 1, 2, 2, 2, 2],
[2, 2, 2, 1, 2, 2],
[2, 2, 2, 2, 2, 1],
[1, 2, 1, 2, 2, 3],
[1, 2, 1, 3, 2, 2],
[1, 3, 1, 2, 2, 2],
[1, 2, 2, 2, 1, 3],
[1, 2, 2, 3, 1, 2],
[1, 3, 2, 2, 1, 2],
[2, 2, 1, 2, 1, 3],
[2, 2, 1, 3, 1, 2],
[2, 3, 1, 2, 1, 2],
[1, 1, 2, 2, 3, 2],
[1, 2, 2, 1, 3, 2],
[1, 2, 2, 2, 3, 1],
[1, 1, 3, 2, 2, 2],
[1, 2, 3, 1, 2, 2],
[1, 2, 3, 2, 2, 1],
[2, 2, 3, 2, 1, 1],
[2, 2, 1, 1, 3, 2],
[2, 2, 1, 2, 3, 1],
[2, 1, 3, 2, 1, 2],
[2, 2, 3, 1, 1, 2],
[3, 1, 2, 1, 3, 1],
[3, 1, 1, 2, 2, 2],
[3, 2, 1, 1, 2, 2],
[3, 2, 1, 2, 2, 1],
[3, 1, 2, 2, 1, 2],
[3, 2, 2, 1, 1, 2],
[3, 2, 2, 2, 1, 1],
[2, 1, 2, 1, 2, 3],
[2, 1, 2, 3, 2, 1],
[2, 3, 2, 1, 2, 1],
[1, 1, 1, 3, 2, 3],
[1, 3, 1, 1, 2, 3],
[1, 3, 1, 3, 2, 1],
[1, 1, 2, 3, 1, 3],
[1, 3, 2, 1, 1, 3],
[1, 3, 2, 3, 1, 1],
[2, 1, 1, 3, 1, 3],
[2, 3, 1, 1, 1, 3],
[2, 3, 1, 3, 1, 1],
[1, 1, 2, 1, 3, 3],
[1, 1, 2, 3, 3, 1],
[1, 3, 2, 1, 3, 1],
[1, 1, 3, 1, 2, 3],
[1, 1, 3, 3, 2, 1],
[1, 3, 3, 1, 2, 1],
[3, 1, 3, 1, 2, 1],
[2, 1, 1, 3, 3, 1],
[2, 3, 1, 1, 3, 1],
[2, 1, 3, 1, 1, 3],
[2, 1, 3, 3, 1, 1],
[2, 1, 3, 1, 3, 1],
[3, 1, 1, 1, 2, 3],
[3, 1, 1, 3, 2, 1],
[3, 3, 1, 1, 2, 1],
[3, 1, 2, 1, 1, 3],
[3, 1, 2, 3, 1, 1],
[3, 3, 2, 1, 1, 1],
[3, 1, 4, 1, 1, 1],
[2, 2, 1, 4, 1, 1],
[4, 3, 1, 1, 1, 1],
[1, 1, 1, 2, 2, 4],
[1, 1, 1, 4, 2, 2],
[1, 2, 1, 1, 2, 4],
[1, 2, 1, 4, 2, 1],
[1, 4, 1, 1, 2, 2],
[1, 4, 1, 2, 2, 1],
[1, 1, 2, 2, 1, 4],
[1, 1, 2, 4, 1, 2],
[1, 2, 2, 1, 1, 4],
[1, 2, 2, 4, 1, 1],
[1, 4, 2, 1, 1, 2],
[1, 4, 2, 2, 1, 1],
[2, 4, 1, 2, 1, 1],
[2, 2, 1, 1, 1, 4],
[4, 1, 3, 1, 1, 1],
[2, 4, 1, 1, 1, 2],
[1, 3, 4, 1, 1, 1],
[1, 1, 1, 2, 4, 2],
[1, 2, 1, 1, 4, 2],
[1, 2, 1, 2, 4, 1],
[1, 1, 4, 2, 1, 2],
[1, 2, 4, 1, 1, 2],
[1, 2, 4, 2, 1, 1],
[4, 1, 1, 2, 1, 2],
[4, 2, 1, 1, 1, 2],
[4, 2, 1, 2, 1, 1],
[2, 1, 2, 1, 4, 1],
[2, 1, 4, 1, 2, 1],
[4, 1, 2, 1, 2, 1],
[1, 1, 1, 1, 4, 3],
[1, 1, 1, 3, 4, 1],
[1, 3, 1, 1, 4, 1],
[1, 1, 4, 1, 1, 3],
[1, 1, 4, 3, 1, 1],
[4, 1, 1, 1, 1, 3],
[4, 1, 1, 3, 1, 1],
[1, 1, 3, 1, 4, 1],
[1, 1, 4, 1, 3, 1],
[3, 1, 1, 1, 4, 1],
[4, 1, 1, 1, 3, 1],
[2, 1, 1, 4, 1, 2],
[2, 1, 1, 2, 1, 4],
[2, 1, 1, 2, 3, 2],
[2, 3, 3, 1, 1, 1, 2],
]
);
defineProperty_default()(
assertThisInitialized_default()(_this),
"SINGLE_CODE_ERROR",
0.64
);
defineProperty_default()(
assertThisInitialized_default()(_this),
"AVG_CODE_ERROR",
0.3
);
defineProperty_default()(
assertThisInitialized_default()(_this),
"FORMAT",
"code_128"
);
defineProperty_default()(
assertThisInitialized_default()(_this),
"MODULE_INDICES",
{
bar: [0, 2, 4],
space: [1, 3, 5],
}
);
return _this;
}
createClass_default()(Code128Reader, [
{
key: "_decodeCode",
value: function _decodeCode(start, correction) {
var bestMatch = {
error: Number.MAX_VALUE,
code: -1,
start: start,
end: start,
correction: {
bar: 1,
space: 1,
},
};
var counter = [0, 0, 0, 0, 0, 0];
var offset = start;
var isWhite = !this._row[offset];
var counterPos = 0;
for (
var i = offset;
i < this._row.length;
i++
) {
if (this._row[i] ^ (isWhite ? 1 : 0)) {
counter[counterPos]++;
} else {
if (counterPos === counter.length - 1) {
if (correction) {
this._correct(
counter,
correction
);
}
for (
var code = 0;
code < this.CODE_PATTERN.length;
code++
) {
var error = this._matchPattern(
counter,
this.CODE_PATTERN[code]
);
if (error < bestMatch.error) {
bestMatch.code = code;
bestMatch.error = error;
}
}
bestMatch.end = i;
if (
bestMatch.code === -1 ||
bestMatch.error >
this.AVG_CODE_ERROR
) {
return null;
}
if (
this.CODE_PATTERN[
bestMatch.code
]
) {
bestMatch.correction.bar =
this.calculateCorrection(
this.CODE_PATTERN[
bestMatch.code
],
counter,
this.MODULE_INDICES.bar
);
bestMatch.correction.space =
this.calculateCorrection(
this.CODE_PATTERN[
bestMatch.code
],
counter,
this.MODULE_INDICES
.space
);
}
return bestMatch;
} else {
counterPos++;
}
counter[counterPos] = 1;
isWhite = !isWhite;
}
}
return null;
},
},
{
key: "_correct",
value: function _correct(counter, correction) {
this._correctBars(
counter,
correction.bar,
this.MODULE_INDICES.bar
);
this._correctBars(
counter,
correction.space,
this.MODULE_INDICES.space
);
},
},
{
key: "_findStart",
// TODO: _findStart and decodeCode share similar code, can we re-use some?
value: function _findStart() {
var counter = [0, 0, 0, 0, 0, 0];
var offset = this._nextSet(this._row);
var bestMatch = {
error: Number.MAX_VALUE,
code: -1,
start: 0,
end: 0,
correction: {
bar: 1,
space: 1,
},
};
var isWhite = false;
var counterPos = 0;
for (
var i = offset;
i < this._row.length;
i++
) {
if (this._row[i] ^ (isWhite ? 1 : 0)) {
counter[counterPos]++;
} else {
if (counterPos === counter.length - 1) {
var sum = counter.reduce(function (
prev,
next
) {
return prev + next;
},
0);
for (
var code = this.START_CODE_A;
code <= this.START_CODE_C;
code++
) {
var error = this._matchPattern(
counter,
this.CODE_PATTERN[code]
);
if (error < bestMatch.error) {
bestMatch.code = code;
bestMatch.error = error;
}
}
if (
bestMatch.error <
this.AVG_CODE_ERROR
) {
bestMatch.start = i - sum;
bestMatch.end = i;
bestMatch.correction.bar =
this.calculateCorrection(
this.CODE_PATTERN[
bestMatch.code
],
counter,
this.MODULE_INDICES.bar
);
bestMatch.correction.space =
this.calculateCorrection(
this.CODE_PATTERN[
bestMatch.code
],
counter,
this.MODULE_INDICES
.space
);
return bestMatch;
}
for (var j = 0; j < 4; j++) {
counter[j] = counter[j + 2];
}
counter[4] = 0;
counter[5] = 0;
counterPos--;
} else {
counterPos++;
}
counter[counterPos] = 1;
isWhite = !isWhite;
}
}
return null;
},
},
{
key: "decode",
value: function decode(row, start) {
var _this2 = this;
var startInfo = this._findStart();
if (startInfo === null) {
return null;
} // var self = this,
// done = false,
// result = [],
// multiplier = 0,
// checksum = 0,
// codeset,
// rawResult = [],
// decodedCodes = [],
// shiftNext = false,
// unshift,
// removeLastCharacter = true;
var code = {
code: startInfo.code,
start: startInfo.start,
end: startInfo.end,
correction: {
bar: startInfo.correction.bar,
space: startInfo.correction.space,
},
};
var decodedCodes = [];
decodedCodes.push(code);
var checksum = code.code;
var codeset = (function (c) {
switch (c) {
case _this2.START_CODE_A:
return _this2.CODE_A;
case _this2.START_CODE_B:
return _this2.CODE_B;
case _this2.START_CODE_C:
return _this2.CODE_C;
default:
return null;
}
})(code.code);
var done = false;
var shiftNext = false;
var unshift = shiftNext;
var removeLastCharacter = true;
var multiplier = 0;
var rawResult = [];
var result = []; // TODO: i think this should be string only, but it creates problems if it is
while (!done) {
unshift = shiftNext;
shiftNext = false;
code = this._decodeCode(
code.end,
code.correction
);
if (code !== null) {
if (code.code !== this.STOP_CODE) {
removeLastCharacter = true;
}
if (code.code !== this.STOP_CODE) {
rawResult.push(code.code);
multiplier++;
checksum += multiplier * code.code;
}
decodedCodes.push(code);
switch (codeset) {
case this.CODE_A:
if (code.code < 64) {
result.push(
String.fromCharCode(
32 + code.code
)
);
} else if (code.code < 96) {
result.push(
String.fromCharCode(
code.code - 64
)
);
} else {
if (
code.code !==
this.STOP_CODE
) {
removeLastCharacter = false;
}
switch (code.code) {
case this.CODE_SHIFT:
shiftNext = true;
codeset =
this.CODE_B;
break;
case this.CODE_B:
codeset =
this.CODE_B;
break;
case this.CODE_C:
codeset =
this.CODE_C;
break;
case this.STOP_CODE:
done = true;
break;
}
}
break;
case this.CODE_B:
if (code.code < 96) {
result.push(
String.fromCharCode(
32 + code.code
)
);
} else {
if (
code.code !==
this.STOP_CODE
) {
removeLastCharacter = false;
}
switch (code.code) {
case this.CODE_SHIFT:
shiftNext = true;
codeset =
this.CODE_A;
break;
case this.CODE_A:
codeset =
this.CODE_A;
break;
case this.CODE_C:
codeset =
this.CODE_C;
break;
case this.STOP_CODE:
done = true;
break;
}
}
break;
case this.CODE_C:
if (code.code < 100) {
result.push(
code.code < 10
? "0" + code.code
: code.code
);
} else {
if (
code.code !==
this.STOP_CODE
) {
removeLastCharacter = false;
}
switch (code.code) {
case this.CODE_A:
codeset =
this.CODE_A;
break;
case this.CODE_B:
codeset =
this.CODE_B;
break;
case this.STOP_CODE:
done = true;
break;
}
}
break;
}
} else {
done = true;
}
if (unshift) {
codeset =
codeset === this.CODE_A
? this.CODE_B
: this.CODE_A;
}
}
if (code === null) {
return null;
}
code.end = this._nextUnset(this._row, code.end);
if (!this._verifyTrailingWhitespace(code)) {
return null;
}
checksum -=
multiplier *
rawResult[rawResult.length - 1];
if (
checksum % 103 !==
rawResult[rawResult.length - 1]
) {
return null;
}
if (!result.length) {
return null;
} // remove last code from result (checksum)
if (removeLastCharacter) {
result.splice(result.length - 1, 1);
}
return {
code: result.join(""),
start: startInfo.start,
end: code.end,
codeset: codeset,
startInfo: startInfo,
decodedCodes: decodedCodes,
endInfo: code,
format: this.FORMAT,
};
},
},
{
key: "_verifyTrailingWhitespace",
value: function _verifyTrailingWhitespace(endInfo) {
var self = this,
trailingWhitespaceEnd;
trailingWhitespaceEnd =
endInfo.end +
(endInfo.end - endInfo.start) / 2;
if (trailingWhitespaceEnd < self._row.length) {
if (
self._matchRange(
endInfo.end,
trailingWhitespaceEnd,
0
)
) {
return endInfo;
}
}
return null;
},
},
{
key: "calculateCorrection",
value: function calculateCorrection(
expected,
normalized,
indices
) {
var length = indices.length,
sumNormalized = 0,
sumExpected = 0;
while (length--) {
sumExpected += expected[indices[length]];
sumNormalized +=
normalized[indices[length]];
}
return sumExpected / sumNormalized;
},
},
]);
return Code128Reader;
})(barcode_reader);
/* harmony default export */ var code_128_reader =
code_128_reader_Code128Reader;
// CONCATENATED MODULE: ./src/reader/ean_reader.ts
function ownKeys(object, enumerableOnly) {
var keys = Object.keys(object);
if (Object.getOwnPropertySymbols) {
var symbols = Object.getOwnPropertySymbols(object);
if (enumerableOnly) {
symbols = symbols.filter(function (sym) {
return Object.getOwnPropertyDescriptor(
object,
sym
).enumerable;
});
}
keys.push.apply(keys, symbols);
}
return keys;
}
function _objectSpread(target) {
for (var i = 1; i < arguments.length; i++) {
var source = arguments[i] != null ? arguments[i] : {};
if (i % 2) {
ownKeys(Object(source), true).forEach(function (
key
) {
defineProperty_default()(
target,
key,
source[key]
);
});
} else if (Object.getOwnPropertyDescriptors) {
Object.defineProperties(
target,
Object.getOwnPropertyDescriptors(source)
);
} else {
ownKeys(Object(source)).forEach(function (key) {
Object.defineProperty(
target,
key,
Object.getOwnPropertyDescriptor(source, key)
);
});
}
}
return target;
}
function ean_reader_createSuper(Derived) {
var hasNativeReflectConstruct =
ean_reader_isNativeReflectConstruct();
return function _createSuperInternal() {
var Super = getPrototypeOf_default()(Derived),
result;
if (hasNativeReflectConstruct) {
var NewTarget =
getPrototypeOf_default()(this).constructor;
result = Reflect.construct(
Super,
arguments,
NewTarget
);
} else {
result = Super.apply(this, arguments);
}
return possibleConstructorReturn_default()(
this,
result
);
};
}
function ean_reader_isNativeReflectConstruct() {
if (typeof Reflect === "undefined" || !Reflect.construct)
return false;
if (Reflect.construct.sham) return false;
if (typeof Proxy === "function") return true;
try {
Boolean.prototype.valueOf.call(
Reflect.construct(Boolean, [], function () {})
);
return true;
} catch (e) {
return false;
}
}
// const CODE_L_START = 0;
var CODE_G_START = 10;
var START_PATTERN = [1, 1, 1];
var MIDDLE_PATTERN = [1, 1, 1, 1, 1];
var EXTENSION_START_PATTERN = [1, 1, 2];
var CODE_PATTERN = [
[3, 2, 1, 1],
[2, 2, 2, 1],
[2, 1, 2, 2],
[1, 4, 1, 1],
[1, 1, 3, 2],
[1, 2, 3, 1],
[1, 1, 1, 4],
[1, 3, 1, 2],
[1, 2, 1, 3],
[3, 1, 1, 2],
[1, 1, 2, 3],
[1, 2, 2, 2],
[2, 2, 1, 2],
[1, 1, 4, 1],
[2, 3, 1, 1],
[1, 3, 2, 1],
[4, 1, 1, 1],
[2, 1, 3, 1],
[3, 1, 2, 1],
[2, 1, 1, 3],
];
var CODE_FREQUENCY = [0, 11, 13, 14, 19, 25, 28, 21, 22, 26]; // const SINGLE_CODE_ERROR = 0.70;
var AVG_CODE_ERROR = 0.48;
var ean_reader_EANReader = /*#__PURE__*/ (function (
_BarcodeReader
) {
inherits_default()(EANReader, _BarcodeReader);
var _super = ean_reader_createSuper(EANReader);
// TODO: does this need to be in the class?
function EANReader(config, supplements) {
var _this;
classCallCheck_default()(this, EANReader);
_this = _super.call(
this,
merge_default()(
{
supplements: [],
},
config
),
supplements
);
defineProperty_default()(
assertThisInitialized_default()(_this),
"FORMAT",
"ean_13"
);
defineProperty_default()(
assertThisInitialized_default()(_this),
"SINGLE_CODE_ERROR",
0.7
);
defineProperty_default()(
assertThisInitialized_default()(_this),
"STOP_PATTERN",
[1, 1, 1]
);
return _this;
}
createClass_default()(EANReader, [
{
key: "_findPattern",
value: function _findPattern(
pattern,
offset,
isWhite,
tryHarder
) {
var counter = new Array(pattern.length).fill(0);
var bestMatch = {
error: Number.MAX_VALUE,
start: 0,
end: 0,
};
var epsilon = AVG_CODE_ERROR; // console.warn('* findPattern', pattern, offset, isWhite, tryHarder, epsilon);
var counterPos = 0;
if (!offset) {
offset = this._nextSet(this._row);
}
var found = false;
for (
var i = offset;
i < this._row.length;
i++
) {
// console.warn(`* loop i=${offset} len=${this._row.length} isWhite=${isWhite} counterPos=${counterPos}`);
if (this._row[i] ^ (isWhite ? 1 : 0)) {
counter[counterPos] += 1;
} else {
if (counterPos === counter.length - 1) {
var error = this._matchPattern(
counter,
pattern
); // console.warn('* matchPattern', error, counter, pattern);
if (
error < epsilon &&
bestMatch.error &&
error < bestMatch.error
) {
found = true;
bestMatch.error = error;
bestMatch.start =
i -
counter.reduce(function (
sum,
value
) {
return sum + value;
},
0);
bestMatch.end = i; // console.warn('* return bestMatch', JSON.stringify(bestMatch));
return bestMatch;
}
if (tryHarder) {
for (
var j = 0;
j < counter.length - 2;
j++
) {
counter[j] = counter[j + 2];
}
counter[counter.length - 2] = 0;
counter[counter.length - 1] = 0;
counterPos--;
}
} else {
counterPos++;
}
counter[counterPos] = 1;
isWhite = !isWhite;
}
}
if (found) {
// console.warn('* return bestMatch', JSON.stringify(bestMatch));
} else {
// console.warn('* return null');
}
return found ? bestMatch : null;
}, // TODO: findPattern and decodeCode appear to share quite similar code, can it be reduced?
},
{
key: "_decodeCode",
value: function _decodeCode(start, coderange) {
// console.warn('* decodeCode', start, coderange);
var counter = [0, 0, 0, 0];
var offset = start;
var bestMatch = {
error: Number.MAX_VALUE,
code: -1,
start: start,
end: start,
};
var epsilon = AVG_CODE_ERROR;
var isWhite = !this._row[offset];
var counterPos = 0;
if (!coderange) {
// console.warn('* decodeCode before length');
coderange = CODE_PATTERN.length; // console.warn('* decodeCode after length');
}
var found = false;
for (
var i = offset;
i < this._row.length;
i++
) {
if (this._row[i] ^ (isWhite ? 1 : 0)) {
counter[counterPos]++;
} else {
if (counterPos === counter.length - 1) {
for (
var code = 0;
code < coderange;
code++
) {
var error = this._matchPattern(
counter,
CODE_PATTERN[code]
);
bestMatch.end = i;
if (error < bestMatch.error) {
bestMatch.code = code;
bestMatch.error = error;
}
}
if (bestMatch.error > epsilon) {
// console.warn('* return null');
return null;
} // console.warn('* return bestMatch', JSON.stringify(bestMatch));
return bestMatch;
} else {
counterPos++;
}
counter[counterPos] = 1;
isWhite = !isWhite;
}
}
return found ? bestMatch : null;
},
},
{
key: "_findStart",
value: function _findStart() {
// console.warn('* findStart');
var offset = this._nextSet(this._row);
var startInfo = null;
while (!startInfo) {
startInfo = this._findPattern(
START_PATTERN,
offset,
false,
true
); // console.warn('* startInfo=', JSON.stringify(startInfo));
if (!startInfo) {
return null;
}
var leadingWhitespaceStart =
startInfo.start -
(startInfo.end - startInfo.start);
if (leadingWhitespaceStart >= 0) {
if (
this._matchRange(
leadingWhitespaceStart,
startInfo.start,
0
)
) {
// console.warn('* returning startInfo');
return startInfo;
}
}
offset = startInfo.end;
startInfo = null;
} // console.warn('* returning null');
return null;
},
},
{
key: "_calculateFirstDigit",
value: function _calculateFirstDigit(
codeFrequency
) {
// console.warn('* calculateFirstDigit', codeFrequency);
for (
var i = 0;
i < CODE_FREQUENCY.length;
i++
) {
if (codeFrequency === CODE_FREQUENCY[i]) {
// console.warn('* returning', i);
return i;
}
} // console.warn('* return null');
return null;
},
},
{
key: "_decodePayload",
value: function _decodePayload(
inCode,
result,
decodedCodes
) {
// console.warn('* decodePayload', inCode, result, decodedCodes);
var outCode = _objectSpread({}, inCode);
var codeFrequency = 0x0;
for (var i = 0; i < 6; i++) {
outCode = this._decodeCode(outCode.end); // console.warn('* decodeCode=', outCode);
if (!outCode) {
// console.warn('* return null');
return null;
}
if (outCode.code >= CODE_G_START) {
outCode.code -= CODE_G_START;
codeFrequency |= 1 << (5 - i);
} else {
codeFrequency |= 0 << (5 - i);
}
result.push(outCode.code);
decodedCodes.push(outCode);
}
var firstDigit =
this._calculateFirstDigit(codeFrequency); // console.warn('* firstDigit=', firstDigit);
if (firstDigit === null) {
// console.warn('* return null');
return null;
}
result.unshift(firstDigit);
var middlePattern = this._findPattern(
MIDDLE_PATTERN,
outCode.end,
true,
false
); // console.warn('* findPattern=', JSON.stringify(middlePattern));
if (
middlePattern === null ||
!middlePattern.end
) {
// console.warn('* return null');
return null;
}
decodedCodes.push(middlePattern);
for (var _i = 0; _i < 6; _i++) {
middlePattern = this._decodeCode(
middlePattern.end,
CODE_G_START
); // console.warn('* decodeCode=', JSON.stringify(middlePattern));
if (!middlePattern) {
// console.warn('* return null');
return null;
}
decodedCodes.push(middlePattern);
result.push(middlePattern.code);
} // console.warn('* end code=', JSON.stringify(middlePattern));
// console.warn('* end result=', JSON.stringify(result));
// console.warn('* end decodedCodes=', decodedCodes);
return middlePattern;
},
},
{
key: "_verifyTrailingWhitespace",
value: function _verifyTrailingWhitespace(endInfo) {
// console.warn('* verifyTrailingWhitespace', JSON.stringify(endInfo));
var trailingWhitespaceEnd =
endInfo.end + (endInfo.end - endInfo.start);
if (trailingWhitespaceEnd < this._row.length) {
if (
this._matchRange(
endInfo.end,
trailingWhitespaceEnd,
0
)
) {
// console.warn('* returning', JSON.stringify(endInfo));
return endInfo;
}
} // console.warn('* return null');
return null;
},
},
{
key: "_findEnd",
value: function _findEnd(offset, isWhite) {
// console.warn('* findEnd', offset, isWhite);
var endInfo = this._findPattern(
this.STOP_PATTERN,
offset,
isWhite,
false
);
return endInfo !== null
? this._verifyTrailingWhitespace(endInfo)
: null;
},
},
{
key: "_checksum",
value: function _checksum(result) {
// console.warn('* _checksum', result);
var sum = 0;
for (
var i = result.length - 2;
i >= 0;
i -= 2
) {
sum += result[i];
}
sum *= 3;
for (
var _i2 = result.length - 1;
_i2 >= 0;
_i2 -= 2
) {
sum += result[_i2];
} // console.warn('* end checksum', sum % 10 === 0);
return sum % 10 === 0;
},
},
{
key: "_decodeExtensions",
value: function _decodeExtensions(offset) {
var start = this._nextSet(this._row, offset);
var startInfo = this._findPattern(
EXTENSION_START_PATTERN,
start,
false,
false
);
if (startInfo === null) {
return null;
} // console.warn('* decodeExtensions', this.supplements);
// console.warn('* there are ', this.supplements.length, ' supplements');
for (
var i = 0;
i < this.supplements.length;
i++
) {
// console.warn('* extensions loop', i, this.supplements[i], this.supplements[i]._decode);
try {
var result = this.supplements[i].decode(
this._row,
startInfo.end
); // console.warn('* decode result=', result);
if (result !== null) {
return {
code: result.code,
start: start,
startInfo: startInfo,
end: result.end,
decodedCodes:
result.decodedCodes,
format: this.supplements[i]
.FORMAT,
};
}
} catch (err) {
console.error(
"* decodeExtensions error in ",
this.supplements[i],
": ",
err
);
}
} // console.warn('* end decodeExtensions');
return null;
},
},
{
key: "decode",
value: function decode(row, start) {
// console.warn('* decode', row);
// console.warn('* decode', start);
var result = new Array();
var decodedCodes = new Array();
var resultInfo = {};
var startInfo = this._findStart();
if (!startInfo) {
return null;
}
var code = {
start: startInfo.start,
end: startInfo.end,
};
decodedCodes.push(code);
code = this._decodePayload(
code,
result,
decodedCodes
);
if (!code) {
return null;
}
code = this._findEnd(code.end, false);
if (!code) {
return null;
}
decodedCodes.push(code); // Checksum
if (!this._checksum(result)) {
return null;
} // console.warn('* this.supplements=', this.supplements);
if (this.supplements.length > 0) {
var supplement = this._decodeExtensions(
code.end
); // console.warn('* decodeExtensions returns', supplement);
if (!supplement) {
return null;
}
if (!supplement.decodedCodes) {
return null;
}
var lastCode =
supplement.decodedCodes[
supplement.decodedCodes.length - 1
];
var endInfo = {
start:
lastCode.start +
(((lastCode.end - lastCode.start) /
2) |
0),
end: lastCode.end,
};
if (
!this._verifyTrailingWhitespace(endInfo)
) {
return null;
}
resultInfo = {
supplement: supplement,
code: result.join("") + supplement.code,
};
}
return _objectSpread(
_objectSpread(
{
code: result.join(""),
start: startInfo.start,
end: code.end,
startInfo: startInfo,
decodedCodes: decodedCodes,
},
resultInfo
),
{},
{
format: this.FORMAT,
}
);
},
},
]);
return EANReader;
})(barcode_reader);
/* harmony default export */ var ean_reader =
ean_reader_EANReader;
// EXTERNAL MODULE: ./node_modules/@babel/runtime/helpers/toConsumableArray.js
var toConsumableArray = __webpack_require__(33);
var toConsumableArray_default =
/*#__PURE__*/ __webpack_require__.n(toConsumableArray);
// CONCATENATED MODULE: ./src/reader/code_39_reader.ts
function code_39_reader_createSuper(Derived) {
var hasNativeReflectConstruct =
code_39_reader_isNativeReflectConstruct();
return function _createSuperInternal() {
var Super = getPrototypeOf_default()(Derived),
result;
if (hasNativeReflectConstruct) {
var NewTarget =
getPrototypeOf_default()(this).constructor;
result = Reflect.construct(
Super,
arguments,
NewTarget
);
} else {
result = Super.apply(this, arguments);
}
return possibleConstructorReturn_default()(
this,
result
);
};
}
function code_39_reader_isNativeReflectConstruct() {
if (typeof Reflect === "undefined" || !Reflect.construct)
return false;
if (Reflect.construct.sham) return false;
if (typeof Proxy === "function") return true;
try {
Boolean.prototype.valueOf.call(
Reflect.construct(Boolean, [], function () {})
);
return true;
} catch (e) {
return false;
}
}
var ALPHABETH_STRING =
"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ-. *$/+%";
var ALPHABET = new Uint16Array(
toConsumableArray_default()(ALPHABETH_STRING).map(function (
_char
) {
return _char.charCodeAt(0);
})
);
var CHARACTER_ENCODINGS = new Uint16Array([
0x034, 0x121, 0x061, 0x160, 0x031, 0x130, 0x070, 0x025,
0x124, 0x064, 0x109, 0x049, 0x148, 0x019, 0x118, 0x058,
0x00d, 0x10c, 0x04c, 0x01c, 0x103, 0x043, 0x142, 0x013,
0x112, 0x052, 0x007, 0x106, 0x046, 0x016, 0x181, 0x0c1,
0x1c0, 0x091, 0x190, 0x0d0, 0x085, 0x184, 0x0c4, 0x094,
0x0a8, 0x0a2, 0x08a, 0x02a,
]);
var ASTERISK = 0x094;
var code_39_reader_Code39Reader = /*#__PURE__*/ (function (
_BarcodeReader
) {
inherits_default()(Code39Reader, _BarcodeReader);
var _super = code_39_reader_createSuper(Code39Reader);
function Code39Reader() {
var _this;
classCallCheck_default()(this, Code39Reader);
for (
var _len = arguments.length,
args = new Array(_len),
_key = 0;
_key < _len;
_key++
) {
args[_key] = arguments[_key];
}
_this = _super.call.apply(_super, [this].concat(args));
defineProperty_default()(
assertThisInitialized_default()(_this),
"FORMAT",
"code_39"
);
return _this;
}
createClass_default()(Code39Reader, [
{
key: "_findStart",
value: function _findStart() {
var offset = this._nextSet(this._row);
var patternStart = offset;
var counter = new Uint16Array([
0, 0, 0, 0, 0, 0, 0, 0, 0,
]);
var counterPos = 0;
var isWhite = false;
for (
var i = offset;
i < this._row.length;
i++
) {
if (this._row[i] ^ (isWhite ? 1 : 0)) {
counter[counterPos]++;
} else {
if (counterPos === counter.length - 1) {
// find start pattern
if (
this._toPattern(counter) ===
ASTERISK
) {
var whiteSpaceMustStart =
Math.floor(
Math.max(
0,
patternStart -
(i -
patternStart) /
4
)
);
if (
this._matchRange(
whiteSpaceMustStart,
patternStart,
0
)
) {
return {
start: patternStart,
end: i,
};
}
}
patternStart +=
counter[0] + counter[1];
for (var j = 0; j < 7; j++) {
counter[j] = counter[j + 2];
}
counter[7] = 0;
counter[8] = 0;
counterPos--;
} else {
counterPos++;
}
counter[counterPos] = 1;
isWhite = !isWhite;
}
}
return null;
},
},
{
key: "_toPattern",
value: function _toPattern(counters) {
var numCounters = counters.length;
var maxNarrowWidth = 0;
var numWideBars = numCounters;
var wideBarWidth = 0;
while (numWideBars > 3) {
maxNarrowWidth = this._findNextWidth(
counters,
maxNarrowWidth
);
numWideBars = 0;
var pattern = 0;
for (var i = 0; i < numCounters; i++) {
if (counters[i] > maxNarrowWidth) {
pattern |=
1 << (numCounters - 1 - i);
numWideBars++;
wideBarWidth += counters[i];
}
}
if (numWideBars === 3) {
for (
var _i = 0;
_i < numCounters && numWideBars > 0;
_i++
) {
if (counters[_i] > maxNarrowWidth) {
numWideBars--;
if (
counters[_i] * 2 >=
wideBarWidth
) {
return -1;
}
}
}
return pattern;
}
}
return -1;
},
},
{
key: "_findNextWidth",
value: function _findNextWidth(counters, current) {
var minWidth = Number.MAX_VALUE;
for (var i = 0; i < counters.length; i++) {
if (
counters[i] < minWidth &&
counters[i] > current
) {
minWidth = counters[i];
}
}
return minWidth;
},
},
{
key: "_patternToChar",
value: function _patternToChar(pattern) {
for (
var i = 0;
i < CHARACTER_ENCODINGS.length;
i++
) {
if (CHARACTER_ENCODINGS[i] === pattern) {
return String.fromCharCode(ALPHABET[i]);
}
}
return null;
},
},
{
key: "_verifyTrailingWhitespace",
value: function _verifyTrailingWhitespace(
lastStart,
nextStart,
counters
) {
var patternSize =
array_helper["a" /* default */].sum(
counters
);
var trailingWhitespaceEnd =
nextStart - lastStart - patternSize;
if (trailingWhitespaceEnd * 3 >= patternSize) {
return true;
}
return false;
},
},
{
key: "decode",
value: function decode(row, start) {
var counters = new Uint16Array([
0, 0, 0, 0, 0, 0, 0, 0, 0,
]);
var result = [];
start = this._findStart();
if (!start) {
return null;
}
var nextStart = this._nextSet(
this._row,
start.end
);
var decodedChar;
var lastStart;
do {
counters = this._toCounters(
nextStart,
counters
);
var pattern = this._toPattern(counters);
if (pattern < 0) {
return null;
}
decodedChar = this._patternToChar(pattern);
if (decodedChar === null) {
return null;
}
result.push(decodedChar);
lastStart = nextStart;
nextStart +=
array_helper["a" /* default */].sum(
counters
);
nextStart = this._nextSet(
this._row,
nextStart
);
} while (decodedChar !== "*");
result.pop();
if (!result.length) {
return null;
}
if (
!this._verifyTrailingWhitespace(
lastStart,
nextStart,
counters
)
) {
return null;
}
return {
code: result.join(""),
start: start.start,
end: nextStart,
startInfo: start,
decodedCodes: result,
format: this.FORMAT,
};
},
},
]);
return Code39Reader;
})(barcode_reader);
/* harmony default export */ var code_39_reader =
code_39_reader_Code39Reader;
// EXTERNAL MODULE: ./node_modules/@babel/runtime/helpers/get.js
var get = __webpack_require__(13);
var get_default = /*#__PURE__*/ __webpack_require__.n(get);
// CONCATENATED MODULE: ./src/reader/code_39_vin_reader.ts
function code_39_vin_reader_createSuper(Derived) {
var hasNativeReflectConstruct =
code_39_vin_reader_isNativeReflectConstruct();
return function _createSuperInternal() {
var Super = getPrototypeOf_default()(Derived),
result;
if (hasNativeReflectConstruct) {
var NewTarget =
getPrototypeOf_default()(this).constructor;
result = Reflect.construct(
Super,
arguments,
NewTarget
);
} else {
result = Super.apply(this, arguments);
}
return possibleConstructorReturn_default()(
this,
result
);
};
}
function code_39_vin_reader_isNativeReflectConstruct() {
if (typeof Reflect === "undefined" || !Reflect.construct)
return false;
if (Reflect.construct.sham) return false;
if (typeof Proxy === "function") return true;
try {
Boolean.prototype.valueOf.call(
Reflect.construct(Boolean, [], function () {})
);
return true;
} catch (e) {
return false;
}
}
var patterns = {
IOQ: /[IOQ]/g,
AZ09: /[A-Z0-9]{17}/,
};
var code_39_vin_reader_Code39VINReader =
/*#__PURE__*/ (function (_Code39Reader) {
inherits_default()(Code39VINReader, _Code39Reader);
var _super =
code_39_vin_reader_createSuper(Code39VINReader);
function Code39VINReader() {
var _this;
classCallCheck_default()(this, Code39VINReader);
for (
var _len = arguments.length,
args = new Array(_len),
_key = 0;
_key < _len;
_key++
) {
args[_key] = arguments[_key];
}
_this = _super.call.apply(
_super,
[this].concat(args)
);
defineProperty_default()(
assertThisInitialized_default()(_this),
"FORMAT",
"code_39_vin"
);
return _this;
}
createClass_default()(Code39VINReader, [
{
key: "_checkChecksum",
// TODO (this was todo in original repo, no text was there. sorry.)
value: function _checkChecksum(code) {
return !!code;
}, // Cribbed from:
// https://github.com/zxing/zxing/blob/master/core/src/main/java/com/google/zxing/client/result/VINResultParser.java
},
{
key: "decode",
value: function decode(row, start) {
var result = get_default()(
getPrototypeOf_default()(
Code39VINReader.prototype
),
"decode",
this
).call(this, row, start);
if (!result) {
return null;
}
var code = result.code;
if (!code) {
return null;
}
code = code.replace(patterns.IOQ, "");
if (!code.match(patterns.AZ09)) {
if (true) {
console.log(
"Failed AZ09 pattern code:",
code
);
}
return null;
}
if (!this._checkChecksum(code)) {
return null;
}
result.code = code;
return result;
},
},
]);
return Code39VINReader;
})(code_39_reader);
/* harmony default export */ var code_39_vin_reader =
code_39_vin_reader_Code39VINReader;
// CONCATENATED MODULE: ./src/reader/codabar_reader.ts
function codabar_reader_createSuper(Derived) {
var hasNativeReflectConstruct =
codabar_reader_isNativeReflectConstruct();
return function _createSuperInternal() {
var Super = getPrototypeOf_default()(Derived),
result;
if (hasNativeReflectConstruct) {
var NewTarget =
getPrototypeOf_default()(this).constructor;
result = Reflect.construct(
Super,
arguments,
NewTarget
);
} else {
result = Super.apply(this, arguments);
}
return possibleConstructorReturn_default()(
this,
result
);
};
}
function codabar_reader_isNativeReflectConstruct() {
if (typeof Reflect === "undefined" || !Reflect.construct)
return false;
if (Reflect.construct.sham) return false;
if (typeof Proxy === "function") return true;
try {
Boolean.prototype.valueOf.call(
Reflect.construct(Boolean, [], function () {})
);
return true;
} catch (e) {
return false;
}
}
// const ALPHABETH_STRING = '0123456789-$:/.+ABCD';
var codabar_reader_ALPHABET = [
48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 45, 36, 58, 47, 46,
43, 65, 66, 67, 68,
];
var codabar_reader_CHARACTER_ENCODINGS = [
0x003, 0x006, 0x009, 0x060, 0x012, 0x042, 0x021, 0x024,
0x030, 0x048, 0x00c, 0x018, 0x045, 0x051, 0x054, 0x015,
0x01a, 0x029, 0x00b, 0x00e,
];
var START_END = [0x01a, 0x029, 0x00b, 0x00e];
var MIN_ENCODED_CHARS = 4;
var MAX_ACCEPTABLE = 2.0;
var PADDING = 1.5;
var codabar_reader_NewCodabarReader = /*#__PURE__*/ (function (
_BarcodeReader
) {
inherits_default()(NewCodabarReader, _BarcodeReader);
var _super = codabar_reader_createSuper(NewCodabarReader);
function NewCodabarReader() {
var _this;
classCallCheck_default()(this, NewCodabarReader);
for (
var _len = arguments.length,
args = new Array(_len),
_key = 0;
_key < _len;
_key++
) {
args[_key] = arguments[_key];
}
_this = _super.call.apply(_super, [this].concat(args));
defineProperty_default()(
assertThisInitialized_default()(_this),
"_counters",
[]
);
defineProperty_default()(
assertThisInitialized_default()(_this),
"FORMAT",
"codabar"
);
return _this;
}
createClass_default()(NewCodabarReader, [
{
key: "_computeAlternatingThreshold",
value: function _computeAlternatingThreshold(
offset,
end
) {
var min = Number.MAX_VALUE;
var max = 0;
var counter = 0;
for (var i = offset; i < end; i += 2) {
counter = this._counters[i];
if (counter > max) {
max = counter;
}
if (counter < min) {
min = counter;
}
}
return ((min + max) / 2.0) | 0;
},
},
{
key: "_toPattern",
value: function _toPattern(offset) {
var numCounters = 7;
var end = offset + numCounters;
if (end > this._counters.length) {
return -1;
}
var barThreshold =
this._computeAlternatingThreshold(
offset,
end
);
var spaceThreshold =
this._computeAlternatingThreshold(
offset + 1,
end
);
var bitmask = 1 << (numCounters - 1);
var threshold = 0;
var pattern = 0;
for (var i = 0; i < numCounters; i++) {
threshold =
(i & 1) === 0
? barThreshold
: spaceThreshold;
if (
this._counters[offset + i] > threshold
) {
pattern |= bitmask;
}
bitmask >>= 1;
}
return pattern;
},
},
{
key: "_isStartEnd",
value: function _isStartEnd(pattern) {
for (var i = 0; i < START_END.length; i++) {
if (START_END[i] === pattern) {
return true;
}
}
return false;
},
},
{
key: "_sumCounters",
value: function _sumCounters(start, end) {
var sum = 0;
for (var i = start; i < end; i++) {
sum += this._counters[i];
}
return sum;
},
},
{
key: "_findStart",
value: function _findStart() {
var start = this._nextUnset(this._row);
var end = start;
for (
var i = 1;
i < this._counters.length;
i++
) {
var pattern = this._toPattern(i);
if (
pattern !== -1 &&
this._isStartEnd(pattern)
) {
// TODO: Look for whitespace ahead
start += this._sumCounters(0, i);
end =
start + this._sumCounters(i, i + 8);
return {
start: start,
end: end,
startCounter: i,
endCounter: i + 8,
};
}
}
return null;
},
},
{
key: "_patternToChar",
value: function _patternToChar(pattern) {
for (
var i = 0;
i <
codabar_reader_CHARACTER_ENCODINGS.length;
i++
) {
if (
codabar_reader_CHARACTER_ENCODINGS[
i
] === pattern
) {
return String.fromCharCode(
codabar_reader_ALPHABET[i]
);
}
}
return null;
},
},
{
key: "_calculatePatternLength",
value: function _calculatePatternLength(offset) {
var sum = 0;
for (var i = offset; i < offset + 7; i++) {
sum += this._counters[i];
}
return sum;
},
},
{
key: "_verifyWhitespace",
value: function _verifyWhitespace(
startCounter,
endCounter
) {
if (
startCounter - 1 <= 0 ||
this._counters[startCounter - 1] >=
this._calculatePatternLength(
startCounter
) /
2.0
) {
if (
endCounter + 8 >=
this._counters.length ||
this._counters[endCounter + 7] >=
this._calculatePatternLength(
endCounter
) /
2.0
) {
return true;
}
}
return false;
},
},
{
key: "_charToPattern",
value: function _charToPattern(_char) {
var charCode = _char.charCodeAt(0);
for (
var i = 0;
i < codabar_reader_ALPHABET.length;
i++
) {
if (
codabar_reader_ALPHABET[i] === charCode
) {
return codabar_reader_CHARACTER_ENCODINGS[
i
];
}
}
return 0x0;
},
},
{
key: "_thresholdResultPattern",
value: function _thresholdResultPattern(
result,
startCounter
) {
var categorization = {
space: {
narrow: {
size: 0,
counts: 0,
min: 0,
max: Number.MAX_VALUE,
},
wide: {
size: 0,
counts: 0,
min: 0,
max: Number.MAX_VALUE,
},
},
bar: {
narrow: {
size: 0,
counts: 0,
min: 0,
max: Number.MAX_VALUE,
},
wide: {
size: 0,
counts: 0,
min: 0,
max: Number.MAX_VALUE,
},
},
};
var pos = startCounter;
var pattern;
for (var i = 0; i < result.length; i++) {
pattern = this._charToPattern(result[i]);
for (var j = 6; j >= 0; j--) {
var kind =
(j & 1) === 2
? categorization.bar
: categorization.space;
var cat =
(pattern & 1) === 1
? kind.wide
: kind.narrow;
cat.size += this._counters[pos + j];
cat.counts++;
pattern >>= 1;
}
pos += 8;
}
["space", "bar"].forEach(function (key) {
var newkind = categorization[key];
newkind.wide.min = Math.floor(
(newkind.narrow.size /
newkind.narrow.counts +
newkind.wide.size /
newkind.wide.counts) /
2
);
newkind.narrow.max = Math.ceil(
newkind.wide.min
);
newkind.wide.max = Math.ceil(
(newkind.wide.size * MAX_ACCEPTABLE +
PADDING) /
newkind.wide.counts
);
});
return categorization;
},
},
{
key: "_validateResult",
value: function _validateResult(
result,
startCounter
) {
var thresholds = this._thresholdResultPattern(
result,
startCounter
);
var pos = startCounter;
var pattern;
for (var i = 0; i < result.length; i++) {
pattern = this._charToPattern(result[i]);
for (var j = 6; j >= 0; j--) {
var kind =
(j & 1) === 0
? thresholds.bar
: thresholds.space;
var cat =
(pattern & 1) === 1
? kind.wide
: kind.narrow;
var size = this._counters[pos + j];
if (size < cat.min || size > cat.max) {
return false;
}
pattern >>= 1;
}
pos += 8;
}
return true;
},
},
{
key: "decode",
value: function decode(row, start) {
this._counters = this._fillCounters();
start = this._findStart();
if (!start) {
return null;
}
var nextStart = start.startCounter;
var result = [];
var pattern;
do {
pattern = this._toPattern(nextStart);
if (pattern < 0) {
return null;
}
var decodedChar =
this._patternToChar(pattern);
if (decodedChar === null) {
return null;
}
result.push(decodedChar);
nextStart += 8;
if (
result.length > 1 &&
this._isStartEnd(pattern)
) {
break;
}
} while (nextStart < this._counters.length); // verify end
if (
result.length - 2 < MIN_ENCODED_CHARS ||
!this._isStartEnd(pattern)
) {
return null;
} // verify end white space
if (
!this._verifyWhitespace(
start.startCounter,
nextStart - 8
)
) {
return null;
}
if (
!this._validateResult(
result,
start.startCounter
)
) {
return null;
}
nextStart =
nextStart > this._counters.length
? this._counters.length
: nextStart;
var end =
start.start +
this._sumCounters(
start.startCounter,
nextStart - 8
);
return {
code: result.join(""),
start: start.start,
end: end,
startInfo: start,
decodedCodes: result,
format: this.FORMAT, // TODO: i think it should not be required to return format from this, as barcode_reader force sets the format anyway
};
},
},
]);
return NewCodabarReader;
})(barcode_reader);
/* harmony default export */ var codabar_reader =
codabar_reader_NewCodabarReader;
// CONCATENATED MODULE: ./src/reader/upc_reader.ts
function upc_reader_createSuper(Derived) {
var hasNativeReflectConstruct =
upc_reader_isNativeReflectConstruct();
return function _createSuperInternal() {
var Super = getPrototypeOf_default()(Derived),
result;
if (hasNativeReflectConstruct) {
var NewTarget =
getPrototypeOf_default()(this).constructor;
result = Reflect.construct(
Super,
arguments,
NewTarget
);
} else {
result = Super.apply(this, arguments);
}
return possibleConstructorReturn_default()(
this,
result
);
};
}
function upc_reader_isNativeReflectConstruct() {
if (typeof Reflect === "undefined" || !Reflect.construct)
return false;
if (Reflect.construct.sham) return false;
if (typeof Proxy === "function") return true;
try {
Boolean.prototype.valueOf.call(
Reflect.construct(Boolean, [], function () {})
);
return true;
} catch (e) {
return false;
}
}
var upc_reader_UPCReader = /*#__PURE__*/ (function (
_EANReader
) {
inherits_default()(UPCReader, _EANReader);
var _super = upc_reader_createSuper(UPCReader);
function UPCReader() {
var _this;
classCallCheck_default()(this, UPCReader);
for (
var _len = arguments.length,
args = new Array(_len),
_key = 0;
_key < _len;
_key++
) {
args[_key] = arguments[_key];
}
_this = _super.call.apply(_super, [this].concat(args));
defineProperty_default()(
assertThisInitialized_default()(_this),
"FORMAT",
"upc_a"
);
return _this;
}
createClass_default()(UPCReader, [
{
key: "decode",
value: function decode(row, start) {
var result =
ean_reader.prototype.decode.call(this);
if (
result &&
result.code &&
result.code.length === 13 &&
result.code.charAt(0) === "0"
) {
result.code = result.code.substring(1);
return result;
}
return null;
},
},
]);
return UPCReader;
})(ean_reader);
/* harmony default export */ var upc_reader =
upc_reader_UPCReader;
// CONCATENATED MODULE: ./src/reader/ean_8_reader.ts
function ean_8_reader_createSuper(Derived) {
var hasNativeReflectConstruct =
ean_8_reader_isNativeReflectConstruct();
return function _createSuperInternal() {
var Super = getPrototypeOf_default()(Derived),
result;
if (hasNativeReflectConstruct) {
var NewTarget =
getPrototypeOf_default()(this).constructor;
result = Reflect.construct(
Super,
arguments,
NewTarget
);
} else {
result = Super.apply(this, arguments);
}
return possibleConstructorReturn_default()(
this,
result
);
};
}
function ean_8_reader_isNativeReflectConstruct() {
if (typeof Reflect === "undefined" || !Reflect.construct)
return false;
if (Reflect.construct.sham) return false;
if (typeof Proxy === "function") return true;
try {
Boolean.prototype.valueOf.call(
Reflect.construct(Boolean, [], function () {})
);
return true;
} catch (e) {
return false;
}
}
var ean_8_reader_EAN8Reader = /*#__PURE__*/ (function (
_EANReader
) {
inherits_default()(EAN8Reader, _EANReader);
var _super = ean_8_reader_createSuper(EAN8Reader);
function EAN8Reader() {
var _this;
classCallCheck_default()(this, EAN8Reader);
for (
var _len = arguments.length,
args = new Array(_len),
_key = 0;
_key < _len;
_key++
) {
args[_key] = arguments[_key];
}
_this = _super.call.apply(_super, [this].concat(args));
defineProperty_default()(
assertThisInitialized_default()(_this),
"FORMAT",
"ean_8"
);
return _this;
}
createClass_default()(EAN8Reader, [
{
key: "_decodePayload",
value: function _decodePayload(
inCode,
result,
decodedCodes
) {
var code = inCode;
for (var i = 0; i < 4; i++) {
code = this._decodeCode(
code.end,
CODE_G_START
);
if (!code) {
return null;
}
result.push(code.code);
decodedCodes.push(code);
}
code = this._findPattern(
MIDDLE_PATTERN,
code.end,
true,
false
);
if (code === null) {
return null;
}
decodedCodes.push(code);
for (var _i = 0; _i < 4; _i++) {
code = this._decodeCode(
code.end,
CODE_G_START
);
if (!code) {
return null;
}
decodedCodes.push(code);
result.push(code.code);
}
return code;
},
},
]);
return EAN8Reader;
})(ean_reader);
/* harmony default export */ var ean_8_reader =
ean_8_reader_EAN8Reader;
// CONCATENATED MODULE: ./src/reader/ean_2_reader.ts
function ean_2_reader_createSuper(Derived) {
var hasNativeReflectConstruct =
ean_2_reader_isNativeReflectConstruct();
return function _createSuperInternal() {
var Super = getPrototypeOf_default()(Derived),
result;
if (hasNativeReflectConstruct) {
var NewTarget =
getPrototypeOf_default()(this).constructor;
result = Reflect.construct(
Super,
arguments,
NewTarget
);
} else {
result = Super.apply(this, arguments);
}
return possibleConstructorReturn_default()(
this,
result
);
};
}
function ean_2_reader_isNativeReflectConstruct() {
if (typeof Reflect === "undefined" || !Reflect.construct)
return false;
if (Reflect.construct.sham) return false;
if (typeof Proxy === "function") return true;
try {
Boolean.prototype.valueOf.call(
Reflect.construct(Boolean, [], function () {})
);
return true;
} catch (e) {
return false;
}
}
var ean_2_reader_EAN2Reader = /*#__PURE__*/ (function (
_EANReader
) {
inherits_default()(EAN2Reader, _EANReader);
var _super = ean_2_reader_createSuper(EAN2Reader);
function EAN2Reader() {
var _this;
classCallCheck_default()(this, EAN2Reader);
for (
var _len = arguments.length,
args = new Array(_len),
_key = 0;
_key < _len;
_key++
) {
args[_key] = arguments[_key];
}
_this = _super.call.apply(_super, [this].concat(args));
defineProperty_default()(
assertThisInitialized_default()(_this),
"FORMAT",
"ean_2"
);
return _this;
}
createClass_default()(EAN2Reader, [
{
key: "decode",
value: function decode(row, start) {
if (row) {
this._row = row;
}
var codeFrequency = 0;
var offset = start;
var end = this._row.length;
var result = [];
var decodedCodes = [];
var code = null;
if (offset === undefined) {
return null;
}
for (var i = 0; i < 2 && offset < end; i++) {
code = this._decodeCode(offset);
if (!code) {
return null;
}
decodedCodes.push(code);
result.push(code.code % 10);
if (code.code >= CODE_G_START) {
codeFrequency |= 1 << (1 - i);
}
if (i !== 1) {
offset = this._nextSet(
this._row,
code.end
);
offset = this._nextUnset(
this._row,
offset
);
}
}
if (
result.length !== 2 ||
parseInt(result.join("")) % 4 !==
codeFrequency
) {
return null;
}
var startInfo = this._findStart();
return {
code: result.join(""),
decodedCodes: decodedCodes,
end: code.end,
format: this.FORMAT,
startInfo: startInfo,
start: startInfo.start,
};
},
},
]);
return EAN2Reader;
})(ean_reader);
/* harmony default export */ var ean_2_reader =
ean_2_reader_EAN2Reader;
// CONCATENATED MODULE: ./src/reader/ean_5_reader.ts
function ean_5_reader_createSuper(Derived) {
var hasNativeReflectConstruct =
ean_5_reader_isNativeReflectConstruct();
return function _createSuperInternal() {
var Super = getPrototypeOf_default()(Derived),
result;
if (hasNativeReflectConstruct) {
var NewTarget =
getPrototypeOf_default()(this).constructor;
result = Reflect.construct(
Super,
arguments,
NewTarget
);
} else {
result = Super.apply(this, arguments);
}
return possibleConstructorReturn_default()(
this,
result
);
};
}
function ean_5_reader_isNativeReflectConstruct() {
if (typeof Reflect === "undefined" || !Reflect.construct)
return false;
if (Reflect.construct.sham) return false;
if (typeof Proxy === "function") return true;
try {
Boolean.prototype.valueOf.call(
Reflect.construct(Boolean, [], function () {})
);
return true;
} catch (e) {
return false;
}
}
var CHECK_DIGIT_ENCODINGS = [
24, 20, 18, 17, 12, 6, 3, 10, 9, 5,
];
function determineCheckDigit(codeFrequency) {
for (var i = 0; i < 10; i++) {
if (codeFrequency === CHECK_DIGIT_ENCODINGS[i]) {
return i;
}
}
return null;
}
function extensionChecksum(result) {
var length = result.length;
var sum = 0;
for (var i = length - 2; i >= 0; i -= 2) {
sum += result[i];
}
sum *= 3;
for (var _i = length - 1; _i >= 0; _i -= 2) {
sum += result[_i];
}
sum *= 3;
return sum % 10;
}
var ean_5_reader_EAN5Reader = /*#__PURE__*/ (function (
_EANReader
) {
inherits_default()(EAN5Reader, _EANReader);
var _super = ean_5_reader_createSuper(EAN5Reader);
function EAN5Reader() {
var _this;
classCallCheck_default()(this, EAN5Reader);
for (
var _len = arguments.length,
args = new Array(_len),
_key = 0;
_key < _len;
_key++
) {
args[_key] = arguments[_key];
}
_this = _super.call.apply(_super, [this].concat(args));
defineProperty_default()(
assertThisInitialized_default()(_this),
"FORMAT",
"ean_5"
);
return _this;
}
createClass_default()(EAN5Reader, [
{
key: "decode",
value: function decode(row, start) {
if (start === undefined) {
return null;
}
if (row) {
this._row = row;
}
var codeFrequency = 0;
var offset = start;
var end = this._row.length;
var code = null;
var result = [];
var decodedCodes = [];
for (var i = 0; i < 5 && offset < end; i++) {
code = this._decodeCode(offset);
if (!code) {
return null;
}
decodedCodes.push(code);
result.push(code.code % 10);
if (code.code >= CODE_G_START) {
codeFrequency |= 1 << (4 - i);
}
if (i !== 4) {
offset = this._nextSet(
this._row,
code.end
);
offset = this._nextUnset(
this._row,
offset
);
}
}
if (result.length !== 5) {
return null;
}
if (
extensionChecksum(result) !==
determineCheckDigit(codeFrequency)
) {
return null;
}
var startInfo = this._findStart();
return {
code: result.join(""),
decodedCodes: decodedCodes,
end: code.end,
format: this.FORMAT,
startInfo: startInfo,
start: startInfo.start,
};
},
},
]);
return EAN5Reader;
})(ean_reader);
/* harmony default export */ var ean_5_reader =
ean_5_reader_EAN5Reader;
// CONCATENATED MODULE: ./src/reader/upc_e_reader.ts
function upc_e_reader_ownKeys(object, enumerableOnly) {
var keys = Object.keys(object);
if (Object.getOwnPropertySymbols) {
var symbols = Object.getOwnPropertySymbols(object);
if (enumerableOnly) {
symbols = symbols.filter(function (sym) {
return Object.getOwnPropertyDescriptor(
object,
sym
).enumerable;
});
}
keys.push.apply(keys, symbols);
}
return keys;
}
function upc_e_reader_objectSpread(target) {
for (var i = 1; i < arguments.length; i++) {
var source = arguments[i] != null ? arguments[i] : {};
if (i % 2) {
upc_e_reader_ownKeys(Object(source), true).forEach(
function (key) {
defineProperty_default()(
target,
key,
source[key]
);
}
);
} else if (Object.getOwnPropertyDescriptors) {
Object.defineProperties(
target,
Object.getOwnPropertyDescriptors(source)
);
} else {
upc_e_reader_ownKeys(Object(source)).forEach(
function (key) {
Object.defineProperty(
target,
key,
Object.getOwnPropertyDescriptor(
source,
key
)
);
}
);
}
}
return target;
}
function upc_e_reader_createSuper(Derived) {
var hasNativeReflectConstruct =
upc_e_reader_isNativeReflectConstruct();
return function _createSuperInternal() {
var Super = getPrototypeOf_default()(Derived),
result;
if (hasNativeReflectConstruct) {
var NewTarget =
getPrototypeOf_default()(this).constructor;
result = Reflect.construct(
Super,
arguments,
NewTarget
);
} else {
result = Super.apply(this, arguments);
}
return possibleConstructorReturn_default()(
this,
result
);
};
}
function upc_e_reader_isNativeReflectConstruct() {
if (typeof Reflect === "undefined" || !Reflect.construct)
return false;
if (Reflect.construct.sham) return false;
if (typeof Proxy === "function") return true;
try {
Boolean.prototype.valueOf.call(
Reflect.construct(Boolean, [], function () {})
);
return true;
} catch (e) {
return false;
}
}
var upc_e_reader_UPCEReader = /*#__PURE__*/ (function (
_EANReader
) {
inherits_default()(UPCEReader, _EANReader);
var _super = upc_e_reader_createSuper(UPCEReader);
function UPCEReader() {
var _this;
classCallCheck_default()(this, UPCEReader);
for (
var _len = arguments.length,
args = new Array(_len),
_key = 0;
_key < _len;
_key++
) {
args[_key] = arguments[_key];
}
_this = _super.call.apply(_super, [this].concat(args));
defineProperty_default()(
assertThisInitialized_default()(_this),
"CODE_FREQUENCY",
[
[56, 52, 50, 49, 44, 38, 35, 42, 41, 37],
[7, 11, 13, 14, 19, 25, 28, 21, 22, 26],
]
);
defineProperty_default()(
assertThisInitialized_default()(_this),
"STOP_PATTERN",
[
(1 / 6) * 7,
(1 / 6) * 7,
(1 / 6) * 7,
(1 / 6) * 7,
(1 / 6) * 7,
(1 / 6) * 7,
]
);
defineProperty_default()(
assertThisInitialized_default()(_this),
"FORMAT",
"upc_e"
);
return _this;
}
createClass_default()(UPCEReader, [
{
key: "_decodePayload",
value: function _decodePayload(
inCode,
result,
decodedCodes
) {
var outCode = upc_e_reader_objectSpread(
{},
inCode
);
var codeFrequency = 0x0;
for (var i = 0; i < 6; i++) {
outCode = this._decodeCode(outCode.end);
if (!outCode) {
return null;
}
if (outCode.code >= CODE_G_START) {
outCode.code =
outCode.code - CODE_G_START;
codeFrequency |= 1 << (5 - i);
}
result.push(outCode.code);
decodedCodes.push(outCode);
}
if (
!this._determineParity(
codeFrequency,
result
)
) {
return null;
}
return outCode;
},
},
{
key: "_determineParity",
value: function _determineParity(
codeFrequency,
result
) {
for (
var nrSystem = 0;
nrSystem < this.CODE_FREQUENCY.length;
nrSystem++
) {
for (
var i = 0;
i <
this.CODE_FREQUENCY[nrSystem].length;
i++
) {
if (
codeFrequency ===
this.CODE_FREQUENCY[nrSystem][i]
) {
result.unshift(nrSystem);
result.push(i);
return true;
}
}
}
return false;
},
},
{
key: "_convertToUPCA",
value: function _convertToUPCA(result) {
var upca = [result[0]];
var lastDigit = result[result.length - 2];
if (lastDigit <= 2) {
upca = upca
.concat(result.slice(1, 3))
.concat([lastDigit, 0, 0, 0, 0])
.concat(result.slice(3, 6));
} else if (lastDigit === 3) {
upca = upca
.concat(result.slice(1, 4))
.concat([0, 0, 0, 0, 0])
.concat(result.slice(4, 6));
} else if (lastDigit === 4) {
upca = upca
.concat(result.slice(1, 5))
.concat([0, 0, 0, 0, 0, result[5]]);
} else {
upca = upca
.concat(result.slice(1, 6))
.concat([0, 0, 0, 0, lastDigit]);
}
upca.push(result[result.length - 1]);
return upca;
},
},
{
key: "_checksum",
value: function _checksum(result) {
return get_default()(
getPrototypeOf_default()(
UPCEReader.prototype
),
"_checksum",
this
).call(this, this._convertToUPCA(result));
},
},
{
key: "_findEnd",
value: function _findEnd(offset, isWhite) {
return get_default()(
getPrototypeOf_default()(
UPCEReader.prototype
),
"_findEnd",
this
).call(this, offset, true);
},
},
{
key: "_verifyTrailingWhitespace",
value: function _verifyTrailingWhitespace(endInfo) {
var trailingWhitespaceEnd =
endInfo.end +
(endInfo.end - endInfo.start) / 2;
if (trailingWhitespaceEnd < this._row.length) {
if (
this._matchRange(
endInfo.end,
trailingWhitespaceEnd,
0
)
) {
return endInfo;
}
}
return null;
},
},
]);
return UPCEReader;
})(ean_reader);
/* harmony default export */ var upc_e_reader =
upc_e_reader_UPCEReader;
// CONCATENATED MODULE: ./src/reader/i2of5_reader.ts
function i2of5_reader_createSuper(Derived) {
var hasNativeReflectConstruct =
i2of5_reader_isNativeReflectConstruct();
return function _createSuperInternal() {
var Super = getPrototypeOf_default()(Derived),
result;
if (hasNativeReflectConstruct) {
var NewTarget =
getPrototypeOf_default()(this).constructor;
result = Reflect.construct(
Super,
arguments,
NewTarget
);
} else {
result = Super.apply(this, arguments);
}
return possibleConstructorReturn_default()(
this,
result
);
};
}
function i2of5_reader_isNativeReflectConstruct() {
if (typeof Reflect === "undefined" || !Reflect.construct)
return false;
if (Reflect.construct.sham) return false;
if (typeof Proxy === "function") return true;
try {
Boolean.prototype.valueOf.call(
Reflect.construct(Boolean, [], function () {})
);
return true;
} catch (e) {
return false;
}
}
// TODO: i2of5_reader and 2of5_reader share very similar code, make use of that
var N = 1;
var W = 3;
var i2of5_reader_I2of5Reader = /*#__PURE__*/ (function (
_BarcodeReader
) {
inherits_default()(I2of5Reader, _BarcodeReader);
var _super = i2of5_reader_createSuper(I2of5Reader);
function I2of5Reader(opts) {
var _this;
classCallCheck_default()(this, I2of5Reader);
_this = _super.call(
this,
merge_default()(
{
normalizeBarSpaceWidth: false,
},
opts
)
);
defineProperty_default()(
assertThisInitialized_default()(_this),
"barSpaceRatio",
[1, 1]
);
defineProperty_default()(
assertThisInitialized_default()(_this),
"SINGLE_CODE_ERROR",
0.78
);
defineProperty_default()(
assertThisInitialized_default()(_this),
"AVG_CODE_ERROR",
0.38
);
defineProperty_default()(
assertThisInitialized_default()(_this),
"START_PATTERN",
[N, N, N, N]
);
defineProperty_default()(
assertThisInitialized_default()(_this),
"STOP_PATTERN",
[N, N, W]
);
defineProperty_default()(
assertThisInitialized_default()(_this),
"CODE_PATTERN",
[
[N, N, W, W, N],
[W, N, N, N, W],
[N, W, N, N, W],
[W, W, N, N, N],
[N, N, W, N, W],
[W, N, W, N, N],
[N, W, W, N, N],
[N, N, N, W, W],
[W, N, N, W, N],
[N, W, N, W, N],
]
);
defineProperty_default()(
assertThisInitialized_default()(_this),
"MAX_CORRECTION_FACTOR",
5
);
defineProperty_default()(
assertThisInitialized_default()(_this),
"FORMAT",
"i2of5"
);
if (opts.normalizeBarSpaceWidth) {
_this.SINGLE_CODE_ERROR = 0.38;
_this.AVG_CODE_ERROR = 0.09;
}
_this.config = opts;
return possibleConstructorReturn_default()(
_this,
assertThisInitialized_default()(_this)
);
}
createClass_default()(I2of5Reader, [
{
key: "_matchPattern",
value: function _matchPattern(counter, code) {
if (this.config.normalizeBarSpaceWidth) {
var counterSum = [0, 0];
var codeSum = [0, 0];
var correction = [0, 0];
var correctionRatio =
this.MAX_CORRECTION_FACTOR;
var correctionRatioInverse =
1 / correctionRatio;
for (var i = 0; i < counter.length; i++) {
counterSum[i % 2] += counter[i];
codeSum[i % 2] += code[i];
}
correction[0] = codeSum[0] / counterSum[0];
correction[1] = codeSum[1] / counterSum[1];
correction[0] = Math.max(
Math.min(
correction[0],
correctionRatio
),
correctionRatioInverse
);
correction[1] = Math.max(
Math.min(
correction[1],
correctionRatio
),
correctionRatioInverse
);
this.barSpaceRatio = correction;
for (
var _i = 0;
_i < counter.length;
_i++
) {
counter[_i] *=
this.barSpaceRatio[_i % 2];
}
}
return get_default()(
getPrototypeOf_default()(
I2of5Reader.prototype
),
"_matchPattern",
this
).call(this, counter, code);
},
},
{
key: "_findPattern",
value: function _findPattern(pattern, offset) {
var isWhite =
arguments.length > 2 &&
arguments[2] !== undefined
? arguments[2]
: false;
var tryHarder =
arguments.length > 3 &&
arguments[3] !== undefined
? arguments[3]
: false;
var counter = new Array(pattern.length).fill(0);
var counterPos = 0;
var bestMatch = {
error: Number.MAX_VALUE,
start: 0,
end: 0,
};
var epsilon = this.AVG_CODE_ERROR;
isWhite = isWhite || false;
tryHarder = tryHarder || false;
if (!offset) {
offset = this._nextSet(this._row);
}
for (
var i = offset;
i < this._row.length;
i++
) {
if (this._row[i] ^ (isWhite ? 1 : 0)) {
counter[counterPos]++;
} else {
if (counterPos === counter.length - 1) {
var sum = counter.reduce(function (
prev,
next
) {
return prev + next;
},
0);
var error = this._matchPattern(
counter,
pattern
);
if (error < epsilon) {
bestMatch.error = error;
bestMatch.start = i - sum;
bestMatch.end = i;
return bestMatch;
}
if (tryHarder) {
for (
var j = 0;
j < counter.length - 2;
j++
) {
counter[j] = counter[j + 2];
}
counter[counter.length - 2] = 0;
counter[counter.length - 1] = 0;
counterPos--;
} else {
return null;
}
} else {
counterPos++;
}
counter[counterPos] = 1;
isWhite = !isWhite;
}
}
return null;
},
},
{
key: "_findStart",
value: function _findStart() {
var leadingWhitespaceStart = 0;
var offset = this._nextSet(this._row);
var startInfo = null;
var narrowBarWidth = 1;
while (!startInfo) {
startInfo = this._findPattern(
this.START_PATTERN,
offset,
false,
true
);
if (!startInfo) {
return null;
}
narrowBarWidth = Math.floor(
(startInfo.end - startInfo.start) / 4
);
leadingWhitespaceStart =
startInfo.start - narrowBarWidth * 10;
if (leadingWhitespaceStart >= 0) {
if (
this._matchRange(
leadingWhitespaceStart,
startInfo.start,
0
)
) {
return startInfo;
}
}
offset = startInfo.end;
startInfo = null;
}
return null;
},
},
{
key: "_verifyTrailingWhitespace",
value: function _verifyTrailingWhitespace(endInfo) {
var trailingWhitespaceEnd =
endInfo.end +
(endInfo.end - endInfo.start) / 2;
if (trailingWhitespaceEnd < this._row.length) {
if (
this._matchRange(
endInfo.end,
trailingWhitespaceEnd,
0
)
) {
return endInfo;
}
}
return null;
},
},
{
key: "_findEnd",
value: function _findEnd() {
this._row.reverse();
var endInfo = this._findPattern(
this.STOP_PATTERN
);
this._row.reverse();
if (endInfo === null) {
return null;
} // reverse numbers
var tmp = endInfo.start;
endInfo.start = this._row.length - endInfo.end;
endInfo.end = this._row.length - tmp;
return endInfo !== null
? this._verifyTrailingWhitespace(endInfo)
: null;
},
},
{
key: "_decodePair",
value: function _decodePair(counterPair) {
var codes = [];
for (var i = 0; i < counterPair.length; i++) {
var code = this._decodeCode(counterPair[i]);
if (!code) {
return null;
}
codes.push(code);
}
return codes;
},
},
{
key: "_decodeCode",
value: function _decodeCode(counter) {
var epsilon = this.AVG_CODE_ERROR;
var bestMatch = {
error: Number.MAX_VALUE,
code: -1,
start: 0,
end: 0,
};
for (
var code = 0;
code < this.CODE_PATTERN.length;
code++
) {
var error = this._matchPattern(
counter,
this.CODE_PATTERN[code]
);
if (error < bestMatch.error) {
bestMatch.code = code;
bestMatch.error = error;
}
}
if (bestMatch.error < epsilon) {
return bestMatch;
}
return null;
},
},
{
key: "_decodePayload",
value: function _decodePayload(
counters,
result,
decodedCodes
) {
var pos = 0;
var counterLength = counters.length;
var counterPair = [
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
];
var codes = null;
while (pos < counterLength) {
for (var i = 0; i < 5; i++) {
counterPair[0][i] =
counters[pos] *
this.barSpaceRatio[0];
counterPair[1][i] =
counters[pos + 1] *
this.barSpaceRatio[1];
pos += 2;
}
codes = this._decodePair(counterPair);
if (!codes) {
return null;
}
for (
var _i2 = 0;
_i2 < codes.length;
_i2++
) {
result.push(codes[_i2].code + "");
decodedCodes.push(codes[_i2]);
}
}
return codes;
},
},
{
key: "_verifyCounterLength",
value: function _verifyCounterLength(counters) {
return counters.length % 10 === 0;
},
},
{
key: "decode",
value: function decode(row, start) {
var result = new Array();
var decodedCodes = new Array();
var startInfo = this._findStart();
if (!startInfo) {
return null;
}
decodedCodes.push(startInfo);
var endInfo = this._findEnd();
if (!endInfo) {
return null;
}
var counters = this._fillCounters(
startInfo.end,
endInfo.start,
false
);
if (!this._verifyCounterLength(counters)) {
return null;
}
var code = this._decodePayload(
counters,
result,
decodedCodes
);
if (!code) {
return null;
}
if (
result.length % 2 !== 0 ||
result.length < 6
) {
return null;
}
decodedCodes.push(endInfo);
return {
code: result.join(""),
start: startInfo.start,
end: endInfo.end,
startInfo: startInfo,
decodedCodes: decodedCodes,
format: this.FORMAT,
};
},
},
]);
return I2of5Reader;
})(barcode_reader);
/* harmony default export */ var i2of5_reader =
i2of5_reader_I2of5Reader;
// CONCATENATED MODULE: ./src/reader/2of5_reader.ts
function _2of5_reader_createSuper(Derived) {
var hasNativeReflectConstruct =
_2of5_reader_isNativeReflectConstruct();
return function _createSuperInternal() {
var Super = getPrototypeOf_default()(Derived),
result;
if (hasNativeReflectConstruct) {
var NewTarget =
getPrototypeOf_default()(this).constructor;
result = Reflect.construct(
Super,
arguments,
NewTarget
);
} else {
result = Super.apply(this, arguments);
}
return possibleConstructorReturn_default()(
this,
result
);
};
}
function _2of5_reader_isNativeReflectConstruct() {
if (typeof Reflect === "undefined" || !Reflect.construct)
return false;
if (Reflect.construct.sham) return false;
if (typeof Proxy === "function") return true;
try {
Boolean.prototype.valueOf.call(
Reflect.construct(Boolean, [], function () {})
);
return true;
} catch (e) {
return false;
}
}
var _2of5_reader_N = 1;
var _2of5_reader_W = 3;
var _2of5_reader_START_PATTERN = [
_2of5_reader_W,
_2of5_reader_N,
_2of5_reader_W,
_2of5_reader_N,
_2of5_reader_N,
_2of5_reader_N,
];
var STOP_PATTERN = [
_2of5_reader_W,
_2of5_reader_N,
_2of5_reader_N,
_2of5_reader_N,
_2of5_reader_W,
];
var _2of5_reader_CODE_PATTERN = [
[
_2of5_reader_N,
_2of5_reader_N,
_2of5_reader_W,
_2of5_reader_W,
_2of5_reader_N,
],
[
_2of5_reader_W,
_2of5_reader_N,
_2of5_reader_N,
_2of5_reader_N,
_2of5_reader_W,
],
[
_2of5_reader_N,
_2of5_reader_W,
_2of5_reader_N,
_2of5_reader_N,
_2of5_reader_W,
],
[
_2of5_reader_W,
_2of5_reader_W,
_2of5_reader_N,
_2of5_reader_N,
_2of5_reader_N,
],
[
_2of5_reader_N,
_2of5_reader_N,
_2of5_reader_W,
_2of5_reader_N,
_2of5_reader_W,
],
[
_2of5_reader_W,
_2of5_reader_N,
_2of5_reader_W,
_2of5_reader_N,
_2of5_reader_N,
],
[
_2of5_reader_N,
_2of5_reader_W,
_2of5_reader_W,
_2of5_reader_N,
_2of5_reader_N,
],
[
_2of5_reader_N,
_2of5_reader_N,
_2of5_reader_N,
_2of5_reader_W,
_2of5_reader_W,
],
[
_2of5_reader_W,
_2of5_reader_N,
_2of5_reader_N,
_2of5_reader_W,
_2of5_reader_N,
],
[
_2of5_reader_N,
_2of5_reader_W,
_2of5_reader_N,
_2of5_reader_W,
_2of5_reader_N,
],
];
var START_PATTERN_LENGTH = _2of5_reader_START_PATTERN.reduce(
function (sum, val) {
return sum + val;
},
0
);
var _2of5_reader_TwoOfFiveReader = /*#__PURE__*/ (function (
_BarcodeReader
) {
inherits_default()(TwoOfFiveReader, _BarcodeReader);
var _super = _2of5_reader_createSuper(TwoOfFiveReader);
function TwoOfFiveReader() {
var _this;
classCallCheck_default()(this, TwoOfFiveReader);
for (
var _len = arguments.length,
args = new Array(_len),
_key = 0;
_key < _len;
_key++
) {
args[_key] = arguments[_key];
}
_this = _super.call.apply(_super, [this].concat(args));
defineProperty_default()(
assertThisInitialized_default()(_this),
"barSpaceRatio",
[1, 1]
);
defineProperty_default()(
assertThisInitialized_default()(_this),
"FORMAT",
"2of5"
);
defineProperty_default()(
assertThisInitialized_default()(_this),
"SINGLE_CODE_ERROR",
0.78
);
defineProperty_default()(
assertThisInitialized_default()(_this),
"AVG_CODE_ERROR",
0.3
);
return _this;
}
createClass_default()(TwoOfFiveReader, [
{
key: "_findPattern",
value: function _findPattern(pattern, offset) {
var isWhite =
arguments.length > 2 &&
arguments[2] !== undefined
? arguments[2]
: false;
var tryHarder =
arguments.length > 3 &&
arguments[3] !== undefined
? arguments[3]
: false;
var counter = [];
var counterPos = 0;
var bestMatch = {
error: Number.MAX_VALUE,
code: -1,
start: 0,
end: 0,
};
var sum = 0;
var error = 0;
var epsilon = this.AVG_CODE_ERROR;
if (!offset) {
offset = this._nextSet(this._row);
}
for (var i = 0; i < pattern.length; i++) {
counter[i] = 0;
}
for (
var _i = offset;
_i < this._row.length;
_i++
) {
if (this._row[_i] ^ (isWhite ? 1 : 0)) {
counter[counterPos]++;
} else {
if (counterPos === counter.length - 1) {
sum = 0;
for (
var j = 0;
j < counter.length;
j++
) {
sum += counter[j];
}
error = this._matchPattern(
counter,
pattern
);
if (error < epsilon) {
bestMatch.error = error;
bestMatch.start = _i - sum;
bestMatch.end = _i;
return bestMatch;
}
if (tryHarder) {
for (
var _j = 0;
_j < counter.length - 2;
_j++
) {
counter[_j] =
counter[_j + 2];
}
counter[counter.length - 2] = 0;
counter[counter.length - 1] = 0;
counterPos--;
} else {
return null;
}
} else {
counterPos++;
}
counter[counterPos] = 1;
isWhite = !isWhite;
}
}
return null;
},
},
{
key: "_findStart",
value: function _findStart() {
var startInfo = null;
var offset = this._nextSet(this._row);
var narrowBarWidth = 1;
var leadingWhitespaceStart = 0;
while (!startInfo) {
startInfo = this._findPattern(
_2of5_reader_START_PATTERN,
offset,
false,
true
);
if (!startInfo) {
return null;
}
narrowBarWidth = Math.floor(
(startInfo.end - startInfo.start) /
START_PATTERN_LENGTH
);
leadingWhitespaceStart =
startInfo.start - narrowBarWidth * 5;
if (leadingWhitespaceStart >= 0) {
if (
this._matchRange(
leadingWhitespaceStart,
startInfo.start,
0
)
) {
return startInfo;
}
}
offset = startInfo.end;
startInfo = null;
}
return startInfo;
},
},
{
key: "_verifyTrailingWhitespace",
value: function _verifyTrailingWhitespace(endInfo) {
var trailingWhitespaceEnd =
endInfo.end +
(endInfo.end - endInfo.start) / 2;
if (trailingWhitespaceEnd < this._row.length) {
if (
this._matchRange(
endInfo.end,
trailingWhitespaceEnd,
0
)
) {
return endInfo;
}
}
return null;
},
},
{
key: "_findEnd",
value: function _findEnd() {
// TODO: reverse, followed by some calcs, followed by another reverse? really?
this._row.reverse();
var offset = this._nextSet(this._row);
var endInfo = this._findPattern(
STOP_PATTERN,
offset,
false,
true
);
this._row.reverse();
if (endInfo === null) {
return null;
} // reverse numbers
var tmp = endInfo.start;
endInfo.start = this._row.length - endInfo.end;
endInfo.end = this._row.length - tmp;
return endInfo !== null
? this._verifyTrailingWhitespace(endInfo)
: null;
},
},
{
key: "_verifyCounterLength",
value: function _verifyCounterLength(counters) {
return counters.length % 10 === 0;
},
},
{
key: "_decodeCode",
value: function _decodeCode(counter) {
var epsilon = this.AVG_CODE_ERROR;
var bestMatch = {
error: Number.MAX_VALUE,
code: -1,
start: 0,
end: 0,
};
for (
var code = 0;
code < _2of5_reader_CODE_PATTERN.length;
code++
) {
var error = this._matchPattern(
counter,
_2of5_reader_CODE_PATTERN[code]
);
if (error < bestMatch.error) {
bestMatch.code = code;
bestMatch.error = error;
}
}
if (bestMatch.error < epsilon) {
return bestMatch;
}
return null;
},
},
{
key: "_decodePayload",
value: function _decodePayload(
counters,
result,
decodedCodes
) {
var pos = 0;
var counterLength = counters.length;
var counter = [0, 0, 0, 0, 0];
var code = null;
while (pos < counterLength) {
for (var i = 0; i < 5; i++) {
counter[i] =
counters[pos] *
this.barSpaceRatio[0];
pos += 2;
}
code = this._decodeCode(counter);
if (!code) {
return null;
}
result.push("".concat(code.code));
decodedCodes.push(code);
}
return code;
},
},
{
key: "decode",
value: function decode(row, start) {
var startInfo = this._findStart();
if (!startInfo) {
return null;
}
var endInfo = this._findEnd();
if (!endInfo) {
return null;
}
var counters = this._fillCounters(
startInfo.end,
endInfo.start,
false
);
if (!this._verifyCounterLength(counters)) {
return null;
}
var decodedCodes = [];
decodedCodes.push(startInfo);
var result = [];
var code = this._decodePayload(
counters,
result,
decodedCodes
);
if (!code) {
return null;
}
if (result.length < 5) {
return null;
}
decodedCodes.push(endInfo);
return {
code: result.join(""),
start: startInfo.start,
end: endInfo.end,
startInfo: startInfo,
decodedCodes: decodedCodes,
format: this.FORMAT,
};
},
},
]);
return TwoOfFiveReader;
})(barcode_reader);
/* harmony default export */ var _2of5_reader =
_2of5_reader_TwoOfFiveReader;
// CONCATENATED MODULE: ./src/reader/code_93_reader.ts
function code_93_reader_createSuper(Derived) {
var hasNativeReflectConstruct =
code_93_reader_isNativeReflectConstruct();
return function _createSuperInternal() {
var Super = getPrototypeOf_default()(Derived),
result;
if (hasNativeReflectConstruct) {
var NewTarget =
getPrototypeOf_default()(this).constructor;
result = Reflect.construct(
Super,
arguments,
NewTarget
);
} else {
result = Super.apply(this, arguments);
}
return possibleConstructorReturn_default()(
this,
result
);
};
}
function code_93_reader_isNativeReflectConstruct() {
if (typeof Reflect === "undefined" || !Reflect.construct)
return false;
if (Reflect.construct.sham) return false;
if (typeof Proxy === "function") return true;
try {
Boolean.prototype.valueOf.call(
Reflect.construct(Boolean, [], function () {})
);
return true;
} catch (e) {
return false;
}
}
var code_93_reader_ALPHABETH_STRING =
"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ-. $/+%abcd*";
var code_93_reader_ALPHABET = new Uint16Array(
toConsumableArray_default()(
code_93_reader_ALPHABETH_STRING
).map(function (_char) {
return _char.charCodeAt(0);
})
);
var code_93_reader_CHARACTER_ENCODINGS = new Uint16Array([
0x114, 0x148, 0x144, 0x142, 0x128, 0x124, 0x122, 0x150,
0x112, 0x10a, 0x1a8, 0x1a4, 0x1a2, 0x194, 0x192, 0x18a,
0x168, 0x164, 0x162, 0x134, 0x11a, 0x158, 0x14c, 0x146,
0x12c, 0x116, 0x1b4, 0x1b2, 0x1ac, 0x1a6, 0x196, 0x19a,
0x16c, 0x166, 0x136, 0x13a, 0x12e, 0x1d4, 0x1d2, 0x1ca,
0x16e, 0x176, 0x1ae, 0x126, 0x1da, 0x1d6, 0x132, 0x15e,
]);
var code_93_reader_ASTERISK = 0x15e;
var code_93_reader_Code93Reader = /*#__PURE__*/ (function (
_BarcodeReader
) {
inherits_default()(Code93Reader, _BarcodeReader);
var _super = code_93_reader_createSuper(Code93Reader);
function Code93Reader() {
var _this;
classCallCheck_default()(this, Code93Reader);
for (
var _len = arguments.length,
args = new Array(_len),
_key = 0;
_key < _len;
_key++
) {
args[_key] = arguments[_key];
}
_this = _super.call.apply(_super, [this].concat(args));
defineProperty_default()(
assertThisInitialized_default()(_this),
"FORMAT",
"code_93"
);
return _this;
}
createClass_default()(Code93Reader, [
{
key: "_patternToChar",
value: function _patternToChar(pattern) {
for (
var i = 0;
i <
code_93_reader_CHARACTER_ENCODINGS.length;
i++
) {
if (
code_93_reader_CHARACTER_ENCODINGS[
i
] === pattern
) {
return String.fromCharCode(
code_93_reader_ALPHABET[i]
);
}
}
return null;
},
},
{
key: "_toPattern",
value: function _toPattern(counters) {
var numCounters = counters.length;
var sum = counters.reduce(function (
prev,
next
) {
return prev + next;
},
0);
var pattern = 0;
for (var i = 0; i < numCounters; i++) {
var normalized = Math.round(
(counters[i] * 9) / sum
);
if (normalized < 1 || normalized > 4) {
return -1;
}
if ((i & 1) === 0) {
for (var j = 0; j < normalized; j++) {
pattern = (pattern << 1) | 1;
}
} else {
pattern <<= normalized;
}
}
return pattern;
},
},
{
key: "_findStart",
value: function _findStart() {
var offset = this._nextSet(this._row);
var patternStart = offset;
var counter = new Uint16Array([
0, 0, 0, 0, 0, 0,
]);
var counterPos = 0;
var isWhite = false;
for (
var i = offset;
i < this._row.length;
i++
) {
if (this._row[i] ^ (isWhite ? 1 : 0)) {
counter[counterPos]++;
} else {
if (counterPos === counter.length - 1) {
// find start pattern
if (
this._toPattern(counter) ===
code_93_reader_ASTERISK
) {
var whiteSpaceMustStart =
Math.floor(
Math.max(
0,
patternStart -
(i -
patternStart) /
4
)
);
if (
this._matchRange(
whiteSpaceMustStart,
patternStart,
0
)
) {
return {
start: patternStart,
end: i,
};
}
}
patternStart +=
counter[0] + counter[1];
for (var j = 0; j < 4; j++) {
counter[j] = counter[j + 2];
}
counter[4] = 0;
counter[5] = 0;
counterPos--;
} else {
counterPos++;
}
counter[counterPos] = 1;
isWhite = !isWhite;
}
}
return null;
},
},
{
key: "_verifyEnd",
value: function _verifyEnd(lastStart, nextStart) {
if (
lastStart === nextStart ||
!this._row[nextStart]
) {
return false;
}
return true;
},
},
{
key: "_decodeExtended",
value: function _decodeExtended(charArray) {
var length = charArray.length;
var result = [];
for (var i = 0; i < length; i++) {
var _char2 = charArray[i];
if (_char2 >= "a" && _char2 <= "d") {
if (i > length - 2) {
return null;
}
var nextChar = charArray[++i];
var nextCharCode =
nextChar.charCodeAt(0);
var decodedChar = void 0;
switch (_char2) {
case "a":
if (
nextChar >= "A" &&
nextChar <= "Z"
) {
decodedChar =
String.fromCharCode(
nextCharCode - 64
);
} else {
return null;
}
break;
case "b":
if (
nextChar >= "A" &&
nextChar <= "E"
) {
decodedChar =
String.fromCharCode(
nextCharCode - 38
);
} else if (
nextChar >= "F" &&
nextChar <= "J"
) {
decodedChar =
String.fromCharCode(
nextCharCode - 11
);
} else if (
nextChar >= "K" &&
nextChar <= "O"
) {
decodedChar =
String.fromCharCode(
nextCharCode + 16
);
} else if (
nextChar >= "P" &&
nextChar <= "S"
) {
decodedChar =
String.fromCharCode(
nextCharCode + 43
);
} else if (
nextChar >= "T" &&
nextChar <= "Z"
) {
decodedChar =
String.fromCharCode(
127
);
} else {
return null;
}
break;
case "c":
if (
nextChar >= "A" &&
nextChar <= "O"
) {
decodedChar =
String.fromCharCode(
nextCharCode - 32
);
} else if (nextChar === "Z") {
decodedChar = ":";
} else {
return null;
}
break;
case "d":
if (
nextChar >= "A" &&
nextChar <= "Z"
) {
decodedChar =
String.fromCharCode(
nextCharCode + 32
);
} else {
return null;
}
break;
default:
console.warn(
"* code_93_reader _decodeExtended hit default case, this may be an error",
decodedChar
);
return null;
}
result.push(decodedChar);
} else {
result.push(_char2);
}
}
return result;
},
},
{
key: "_matchCheckChar",
value: function _matchCheckChar(
charArray,
index,
maxWeight
) {
var arrayToCheck = charArray.slice(0, index);
var length = arrayToCheck.length;
var weightedSums = arrayToCheck.reduce(
function (sum, _char3, i) {
var weight =
((i * -1 + (length - 1)) %
maxWeight) +
1;
var value =
code_93_reader_ALPHABET.indexOf(
_char3.charCodeAt(0)
);
return sum + weight * value;
},
0
);
var checkChar =
code_93_reader_ALPHABET[weightedSums % 47];
return (
checkChar === charArray[index].charCodeAt(0)
);
},
},
{
key: "_verifyChecksums",
value: function _verifyChecksums(charArray) {
return (
this._matchCheckChar(
charArray,
charArray.length - 2,
20
) &&
this._matchCheckChar(
charArray,
charArray.length - 1,
15
)
);
},
},
{
key: "decode",
value: function decode(row, start) {
start = this._findStart();
if (!start) {
return null;
}
var counters = new Uint16Array([
0, 0, 0, 0, 0, 0,
]);
var result = [];
var nextStart = this._nextSet(
this._row,
start.end
);
var lastStart;
var decodedChar;
do {
counters = this._toCounters(
nextStart,
counters
);
var pattern = this._toPattern(counters);
if (pattern < 0) {
return null;
}
decodedChar = this._patternToChar(pattern);
if (decodedChar === null) {
return null;
}
result.push(decodedChar);
lastStart = nextStart;
nextStart +=
array_helper["a" /* default */].sum(
counters
);
nextStart = this._nextSet(
this._row,
nextStart
);
} while (decodedChar !== "*");
result.pop();
if (!result.length) {
return null;
}
if (!this._verifyEnd(lastStart, nextStart)) {
return null;
}
if (!this._verifyChecksums(result)) {
return null;
}
result = result.slice(0, result.length - 2); // yes, this is an assign inside an if.
if (
(result = this._decodeExtended(result)) ===
null
) {
return null;
}
return {
code: result.join(""),
start: start.start,
end: nextStart,
startInfo: start,
decodedCodes: result,
format: this.FORMAT,
};
},
},
]);
return Code93Reader;
})(barcode_reader);
/* harmony default export */ var code_93_reader =
code_93_reader_Code93Reader;
// CONCATENATED MODULE: ./src/reader/code_32_reader.ts
function code_32_reader_createSuper(Derived) {
var hasNativeReflectConstruct =
code_32_reader_isNativeReflectConstruct();
return function _createSuperInternal() {
var Super = getPrototypeOf_default()(Derived),
result;
if (hasNativeReflectConstruct) {
var NewTarget =
getPrototypeOf_default()(this).constructor;
result = Reflect.construct(
Super,
arguments,
NewTarget
);
} else {
result = Super.apply(this, arguments);
}
return possibleConstructorReturn_default()(
this,
result
);
};
}
function code_32_reader_isNativeReflectConstruct() {
if (typeof Reflect === "undefined" || !Reflect.construct)
return false;
if (Reflect.construct.sham) return false;
if (typeof Proxy === "function") return true;
try {
Boolean.prototype.valueOf.call(
Reflect.construct(Boolean, [], function () {})
);
return true;
} catch (e) {
return false;
}
}
var code_32_reader_patterns = {
AEIO: /[AEIO]/g,
AZ09: /[A-Z0-9]/,
};
var code32set = "0123456789BCDFGHJKLMNPQRSTUVWXYZ";
var code_32_reader_Code32Reader = /*#__PURE__*/ (function (
_Code39Reader
) {
inherits_default()(Code32Reader, _Code39Reader);
var _super = code_32_reader_createSuper(Code32Reader);
function Code32Reader() {
var _this;
classCallCheck_default()(this, Code32Reader);
for (
var _len = arguments.length,
args = new Array(_len),
_key = 0;
_key < _len;
_key++
) {
args[_key] = arguments[_key];
}
_this = _super.call.apply(_super, [this].concat(args));
defineProperty_default()(
assertThisInitialized_default()(_this),
"FORMAT",
"code_32_reader"
);
return _this;
}
createClass_default()(Code32Reader, [
{
key: "_decodeCode32",
value: function _decodeCode32(code) {
if (/[^0-9BCDFGHJKLMNPQRSTUVWXYZ]/.test(code)) {
return null;
}
var res = 0;
for (var i = 0; i < code.length; i++) {
res = res * 32 + code32set.indexOf(code[i]);
}
var code32 = "" + res;
if (code32.length < 9) {
code32 = ("000000000" + code32).slice(-9);
}
return "A" + code32;
}, // TODO (this was todo in original repo, no text was there. sorry.)
},
{
key: "_checkChecksum",
value: function _checkChecksum(code) {
return !!code;
},
},
{
key: "decode",
value: function decode(row, start) {
var result = get_default()(
getPrototypeOf_default()(
Code32Reader.prototype
),
"decode",
this
).call(this, row, start);
if (!result) {
return null;
}
var code = result.code;
if (!code) {
return null;
}
code = code.replace(
code_32_reader_patterns.AEIO,
""
);
if (!this._checkChecksum(code)) {
return null;
}
var code32 = this._decodeCode32(code);
if (!code32) {
return null;
}
result.code = code32;
return result;
},
},
]);
return Code32Reader;
})(code_39_reader);
/* harmony default export */ var code_32_reader =
code_32_reader_Code32Reader;
// CONCATENATED MODULE: ./src/decoder/barcode_decoder.js
var READERS = {
code_128_reader: code_128_reader,
ean_reader: ean_reader,
ean_5_reader: ean_5_reader,
ean_2_reader: ean_2_reader,
ean_8_reader: ean_8_reader,
code_39_reader: code_39_reader,
code_39_vin_reader: code_39_vin_reader,
codabar_reader: codabar_reader,
upc_reader: upc_reader,
upc_e_reader: upc_e_reader,
i2of5_reader: i2of5_reader,
"2of5_reader": _2of5_reader,
code_93_reader: code_93_reader,
code_32_reader: code_32_reader,
};
/* harmony default export */ var barcode_decoder = {
registerReader: function registerReader(name, reader) {
READERS[name] = reader;
},
create: function create(config, inputImageWrapper) {
var _canvas = {
ctx: {
frequency: null,
pattern: null,
overlay: null,
},
dom: {
frequency: null,
pattern: null,
overlay: null,
},
};
var _barcodeReaders = [];
initCanvas();
initReaders();
initConfig();
function initCanvas() {
if (true && typeof document !== "undefined") {
var $debug =
document.querySelector("#debug.detection");
_canvas.dom.frequency =
document.querySelector("canvas.frequency");
if (!_canvas.dom.frequency) {
_canvas.dom.frequency =
document.createElement("canvas");
_canvas.dom.frequency.className =
"frequency";
if ($debug) {
$debug.appendChild(
_canvas.dom.frequency
);
}
}
_canvas.ctx.frequency =
_canvas.dom.frequency.getContext("2d");
_canvas.dom.pattern = document.querySelector(
"canvas.patternBuffer"
);
if (!_canvas.dom.pattern) {
_canvas.dom.pattern =
document.createElement("canvas");
_canvas.dom.pattern.className =
"patternBuffer";
if ($debug) {
$debug.appendChild(_canvas.dom.pattern);
}
}
_canvas.ctx.pattern =
_canvas.dom.pattern.getContext("2d");
_canvas.dom.overlay = document.querySelector(
"canvas.drawingBuffer"
);
if (_canvas.dom.overlay) {
_canvas.ctx.overlay =
_canvas.dom.overlay.getContext("2d");
}
}
}
function initReaders() {
config.readers.forEach(function (readerConfig) {
var reader;
var configuration = {};
var supplements = [];
if (
typeof_default()(readerConfig) === "object"
) {
reader = readerConfig.format;
configuration = readerConfig.config;
} else if (typeof readerConfig === "string") {
reader = readerConfig;
}
if (true) {
console.log(
"Before registering reader: ",
reader
);
}
if (configuration.supplements) {
supplements = configuration.supplements.map(
function (supplement) {
return new READERS[supplement]();
}
);
}
try {
var readerObj = new READERS[reader](
configuration,
supplements
);
_barcodeReaders.push(readerObj);
} catch (err) {
console.error(
"* Error constructing reader ",
reader,
err
);
throw err;
}
});
if (true) {
console.log(
"Registered Readers: ".concat(
_barcodeReaders
.map(function (reader) {
return JSON.stringify({
format: reader.FORMAT,
config: reader.config,
});
})
.join(", ")
)
);
}
}
function initConfig() {
if (true && typeof document !== "undefined") {
var i;
var vis = [
{
node: _canvas.dom.frequency,
prop: config.debug.showFrequency,
},
{
node: _canvas.dom.pattern,
prop: config.debug.showPattern,
},
];
for (i = 0; i < vis.length; i++) {
if (vis[i].prop === true) {
vis[i].node.style.display = "block";
} else {
vis[i].node.style.display = "none";
}
}
}
}
/**
* extend the line on both ends
* @param {Array} line
* @param {Number} angle
*/
function getExtendedLine(line, angle, ext) {
function extendLine(amount) {
var extension = {
y: amount * Math.sin(angle),
x: amount * Math.cos(angle),
};
/* eslint-disable no-param-reassign */
line[0].y -= extension.y;
line[0].x -= extension.x;
line[1].y += extension.y;
line[1].x += extension.x;
/* eslint-enable no-param-reassign */
} // check if inside image
extendLine(ext);
while (
ext > 1 &&
(!inputImageWrapper.inImageWithBorder(
line[0]
) ||
!inputImageWrapper.inImageWithBorder(
line[1]
))
) {
// eslint-disable-next-line no-param-reassign
ext -= Math.ceil(ext / 2);
extendLine(-ext);
}
return line;
}
function getLine(box) {
return [
{
x: (box[1][0] - box[0][0]) / 2 + box[0][0],
y: (box[1][1] - box[0][1]) / 2 + box[0][1],
},
{
x: (box[3][0] - box[2][0]) / 2 + box[2][0],
y: (box[3][1] - box[2][1]) / 2 + box[2][1],
},
];
}
function tryDecode(line) {
var result = null;
var i;
var barcodeLine = bresenham.getBarcodeLine(
inputImageWrapper,
line[0],
line[1]
);
if (true && config.debug.showFrequency) {
image_debug["a" /* default */].drawPath(
line,
{
x: "x",
y: "y",
},
_canvas.ctx.overlay,
{
color: "red",
lineWidth: 3,
}
);
bresenham.debug.printFrequency(
barcodeLine.line,
_canvas.dom.frequency
);
}
bresenham.toBinaryLine(barcodeLine);
if (true && config.debug.showPattern) {
bresenham.debug.printPattern(
barcodeLine.line,
_canvas.dom.pattern
);
}
for (
i = 0;
i < _barcodeReaders.length && result === null;
i++
) {
result = _barcodeReaders[i].decodePattern(
barcodeLine.line
);
}
if (result === null) {
return null;
}
return {
codeResult: result,
barcodeLine: barcodeLine,
};
}
/**
* This method slices the given area apart and tries to detect a barcode-pattern
* for each slice. It returns the decoded barcode, or null if nothing was found
* @param {Array} box
* @param {Array} line
* @param {Number} lineAngle
*/
function tryDecodeBruteForce(box, line, lineAngle) {
var sideLength = Math.sqrt(
Math.pow(box[1][0] - box[0][0], 2) +
Math.pow(box[1][1] - box[0][1], 2)
);
var i;
var slices = 16;
var result = null;
var dir;
var extension;
var xdir = Math.sin(lineAngle);
var ydir = Math.cos(lineAngle);
for (i = 1; i < slices && result === null; i++) {
// move line perpendicular to angle
// eslint-disable-next-line no-mixed-operators
dir =
(sideLength / slices) *
i *
(i % 2 === 0 ? -1 : 1);
extension = {
y: dir * xdir,
x: dir * ydir,
};
/* eslint-disable no-param-reassign */
line[0].y += extension.x;
line[0].x -= extension.y;
line[1].y += extension.x;
line[1].x -= extension.y;
/* eslint-enable no-param-reassign */
result = tryDecode(line);
}
return result;
}
function getLineLength(line) {
return Math.sqrt(
Math.pow(Math.abs(line[1].y - line[0].y), 2) +
Math.pow(Math.abs(line[1].x - line[0].x), 2)
);
}
function _decodeFromImage(imageWrapper) {
var result = null;
for (
var i = 0;
i < _barcodeReaders.length && result === null;
i++
) {
result = _barcodeReaders[i].decodeImage
? _barcodeReaders[i].decodeImage(
imageWrapper
)
: null;
}
return result;
}
/**
* With the help of the configured readers (Code128 or EAN) this function tries to detect a
* valid barcode pattern within the given area.
* @param {Object} box The area to search in
* @returns {Object} the result {codeResult, line, angle, pattern, threshold}
*/
function _decodeFromBoundingBox(box) {
var line;
var ctx = _canvas.ctx.overlay;
var result;
if (true) {
if (config.debug.drawBoundingBox && ctx) {
image_debug["a" /* default */].drawPath(
box,
{
x: 0,
y: 1,
},
ctx,
{
color: "blue",
lineWidth: 2,
}
);
}
}
line = getLine(box);
var lineLength = getLineLength(line);
var lineAngle = Math.atan2(
line[1].y - line[0].y,
line[1].x - line[0].x
);
line = getExtendedLine(
line,
lineAngle,
Math.floor(lineLength * 0.1)
);
if (line === null) {
return null;
}
result = tryDecode(line);
if (result === null) {
result = tryDecodeBruteForce(
box,
line,
lineAngle
);
}
if (result === null) {
return null;
}
if (
true &&
result &&
config.debug.drawScanline &&
ctx
) {
image_debug["a" /* default */].drawPath(
line,
{
x: "x",
y: "y",
},
ctx,
{
color: "red",
lineWidth: 3,
}
);
}
return {
codeResult: result.codeResult,
line: line,
angle: lineAngle,
pattern: result.barcodeLine.line,
threshold: result.barcodeLine.threshold,
};
}
return {
decodeFromBoundingBox:
function decodeFromBoundingBox(box) {
return _decodeFromBoundingBox(box);
},
decodeFromBoundingBoxes:
function decodeFromBoundingBoxes(boxes) {
var i;
var result;
var barcodes = [];
var multiple = config.multiple;
for (i = 0; i < boxes.length; i++) {
var box = boxes[i];
result =
_decodeFromBoundingBox(box) || {};
result.box = box;
if (multiple) {
barcodes.push(result);
} else if (result.codeResult) {
return result;
}
}
if (multiple) {
return {
barcodes: barcodes,
};
}
},
decodeFromImage: function decodeFromImage(
inputImageWrapper
) {
var result =
_decodeFromImage(inputImageWrapper);
return result;
},
registerReader: function registerReader(
name,
reader
) {
if (READERS[name]) {
throw new Error(
"cannot register existing reader",
name
);
}
READERS[name] = reader;
},
setReaders: function setReaders(readers) {
// eslint-disable-next-line no-param-reassign
config.readers = readers;
_barcodeReaders.length = 0;
initReaders();
},
};
},
};
// CONCATENATED MODULE: ./src/reader/index.ts
// CONCATENATED MODULE: ./src/common/events.ts
/* harmony default export */ var events =
(function EventInterface() {
var events = {};
function getEvent(eventName) {
if (!events[eventName]) {
events[eventName] = {
subscribers: [],
};
}
return events[eventName];
}
function clearEvents() {
events = {};
}
function publishSubscription(subscription, data) {
if (subscription.async) {
setTimeout(function () {
subscription.callback(data);
}, 4);
} else {
subscription.callback(data);
}
}
function _subscribe(event, callback, async) {
var subscription;
if (typeof callback === "function") {
subscription = {
callback: callback,
async: async,
};
} else {
subscription = callback;
if (!subscription.callback) {
throw new Error(
"Callback was not specified on options"
);
}
}
getEvent(event).subscribers.push(subscription);
}
return {
subscribe: function subscribe(
event,
callback,
async
) {
return _subscribe(event, callback, async);
},
publish: function publish(eventName, data) {
var event = getEvent(eventName);
var subscribers = event.subscribers; // Publish one-time subscriptions
subscribers
.filter(function (subscriber) {
return !!subscriber.once;
})
.forEach(function (subscriber) {
publishSubscription(subscriber, data);
}); // remove them from the subscriber
event.subscribers = subscribers.filter(
function (subscriber) {
return !subscriber.once;
}
); // publish the rest
event.subscribers.forEach(function (
subscriber
) {
publishSubscription(subscriber, data);
});
},
once: function once(event, callback) {
var async =
arguments.length > 2 &&
arguments[2] !== undefined
? arguments[2]
: false;
_subscribe(event, {
callback: callback,
async: async,
once: true,
});
},
unsubscribe: function unsubscribe(
eventName,
callback
) {
if (eventName) {
var _event = getEvent(eventName);
if (_event && callback) {
_event.subscribers =
_event.subscribers.filter(function (
subscriber
) {
return (
subscriber.callback !==
callback
);
});
} else {
_event.subscribers = [];
}
} else {
clearEvents();
}
},
};
})();
// EXTERNAL MODULE: ./node_modules/@babel/runtime/helpers/asyncToGenerator.js
var asyncToGenerator = __webpack_require__(20);
var asyncToGenerator_default =
/*#__PURE__*/ __webpack_require__.n(asyncToGenerator);
// EXTERNAL MODULE: ./node_modules/@babel/runtime/regenerator/index.js
var regenerator = __webpack_require__(12);
var regenerator_default =
/*#__PURE__*/ __webpack_require__.n(regenerator);
// EXTERNAL MODULE: ./node_modules/lodash/pick.js
var pick = __webpack_require__(85);
var pick_default = /*#__PURE__*/ __webpack_require__.n(pick);
// EXTERNAL MODULE: ./node_modules/@babel/runtime/helpers/wrapNativeSuper.js
var wrapNativeSuper = __webpack_require__(86);
var wrapNativeSuper_default =
/*#__PURE__*/ __webpack_require__.n(wrapNativeSuper);
// CONCATENATED MODULE: ./src/quagga/Exception.ts
function Exception_createSuper(Derived) {
var hasNativeReflectConstruct =
Exception_isNativeReflectConstruct();
return function _createSuperInternal() {
var Super = getPrototypeOf_default()(Derived),
result;
if (hasNativeReflectConstruct) {
var NewTarget =
getPrototypeOf_default()(this).constructor;
result = Reflect.construct(
Super,
arguments,
NewTarget
);
} else {
result = Super.apply(this, arguments);
}
return possibleConstructorReturn_default()(
this,
result
);
};
}
function Exception_isNativeReflectConstruct() {
if (typeof Reflect === "undefined" || !Reflect.construct)
return false;
if (Reflect.construct.sham) return false;
if (typeof Proxy === "function") return true;
try {
Boolean.prototype.valueOf.call(
Reflect.construct(Boolean, [], function () {})
);
return true;
} catch (e) {
return false;
}
}
var Exception_Exception = /*#__PURE__*/ (function (_Error) {
inherits_default()(Exception, _Error);
var _super = Exception_createSuper(Exception);
function Exception(m, code) {
var _this;
classCallCheck_default()(this, Exception);
_this = _super.call(this, m);
defineProperty_default()(
assertThisInitialized_default()(_this),
"code",
void 0
);
_this.code = code;
Object.setPrototypeOf(
assertThisInitialized_default()(_this),
Exception.prototype
);
return _this;
}
return Exception;
})(/*#__PURE__*/ wrapNativeSuper_default()(Error));
// CONCATENATED MODULE: ./src/common/mediaDevices.ts
var ERROR_DESC =
"This may mean that the user has declined camera access, or the browser does not support media APIs. If you are running in iOS, you must use Safari.";
function enumerateDevices() {
try {
return navigator.mediaDevices.enumerateDevices();
} catch (err) {
var error = new Exception_Exception(
"enumerateDevices is not defined. ".concat(
ERROR_DESC
),
-1
);
return Promise.reject(error);
}
}
function getUserMedia(constraints) {
try {
return navigator.mediaDevices.getUserMedia(constraints);
} catch (err) {
var error = new Exception_Exception(
"getUserMedia is not defined. ".concat(ERROR_DESC),
-1
);
return Promise.reject(error);
}
}
// CONCATENATED MODULE: ./src/input/camera_access.ts
var streamRef;
function waitForVideo(video) {
return new Promise(function (resolve, reject) {
var attempts = 10;
function checkVideo() {
if (attempts > 0) {
if (
video.videoWidth > 10 &&
video.videoHeight > 10
) {
if (true) {
console.log(
"* dev: checkVideo found "
.concat(
video.videoWidth,
"px x "
)
.concat(video.videoHeight, "px")
);
}
resolve();
} else {
window.setTimeout(checkVideo, 500);
}
} else {
reject(
new Exception_Exception(
"Unable to play video stream. Is webcam working?",
-1
)
); // TODO: add error code
}
attempts--;
}
checkVideo();
});
}
/**
* Tries to attach the camera-stream to a given video-element
* and calls the callback function when the content is ready
* @param {Object} constraints
* @param {Object} video
*/
function initCamera(_x, _x2) {
return _initCamera.apply(this, arguments);
}
function _initCamera() {
_initCamera = asyncToGenerator_default()(
/*#__PURE__*/ regenerator_default.a.mark(
function _callee2(video, constraints) {
var stream;
return regenerator_default.a.wrap(
function _callee2$(_context2) {
while (1) {
switch (
(_context2.prev =
_context2.next)
) {
case 0:
_context2.next = 2;
return getUserMedia(
constraints
);
case 2:
stream = _context2.sent;
streamRef = stream;
if (!video) {
_context2.next = 11;
break;
}
video.setAttribute(
"autoplay",
"true"
);
video.setAttribute(
"muted",
"true"
);
video.setAttribute(
"playsinline",
"true"
); // not listed on MDN...
// eslint-disable-next-line no-param-reassign
video.srcObject = stream;
video.addEventListener(
"loadedmetadata",
function () {
video.play();
}
);
return _context2.abrupt(
"return",
waitForVideo(video)
);
case 11:
return _context2.abrupt(
"return",
Promise.resolve()
);
case 12:
case "end":
return _context2.stop();
}
}
},
_callee2
);
}
)
);
return _initCamera.apply(this, arguments);
}
function deprecatedConstraints(videoConstraints) {
var normalized = pick_default()(videoConstraints, [
"width",
"height",
"facingMode",
"aspectRatio",
"deviceId",
]);
if (
typeof videoConstraints.minAspectRatio !==
"undefined" &&
videoConstraints.minAspectRatio > 0
) {
normalized.aspectRatio =
videoConstraints.minAspectRatio;
console.log(
"WARNING: Constraint 'minAspectRatio' is deprecated; Use 'aspectRatio' instead"
);
}
if (typeof videoConstraints.facing !== "undefined") {
normalized.facingMode = videoConstraints.facing;
console.log(
"WARNING: Constraint 'facing' is deprecated. Use 'facingMode' instead'"
);
}
return normalized;
} // TODO: #192 I don't think there's any good reason pickConstraints should return a Promise,
// I think it was just that way so it could be chained to other functions that did return a Promise.
// That's not necessary with async functions being a thing, so that should be fixed.
function pickConstraints() {
var videoConstraints =
arguments.length > 0 && arguments[0] !== undefined
? arguments[0]
: {};
var video = deprecatedConstraints(videoConstraints);
if (video && video.deviceId && video.facingMode) {
delete video.facingMode;
}
return Promise.resolve({
audio: false,
video: video,
});
}
function enumerateVideoDevices() {
return _enumerateVideoDevices.apply(this, arguments);
}
function _enumerateVideoDevices() {
_enumerateVideoDevices = asyncToGenerator_default()(
/*#__PURE__*/ regenerator_default.a.mark(
function _callee3() {
var devices;
return regenerator_default.a.wrap(
function _callee3$(_context3) {
while (1) {
switch (
(_context3.prev =
_context3.next)
) {
case 0:
_context3.next = 2;
return enumerateDevices();
case 2:
devices = _context3.sent;
return _context3.abrupt(
"return",
devices.filter(
function (device) {
return (
device.kind ===
"videoinput"
);
}
)
);
case 4:
case "end":
return _context3.stop();
}
}
},
_callee3
);
}
)
);
return _enumerateVideoDevices.apply(this, arguments);
}
function getActiveTrack() {
if (!streamRef) {
return null;
}
var tracks = streamRef.getVideoTracks();
return tracks &&
tracks !== null &&
tracks !== void 0 &&
tracks.length
? tracks[0]
: null;
}
/**
* Used for accessing information about the active stream track and available video devices.
*/
var QuaggaJSCameraAccess = {
requestedVideoElement: null,
request: function request(video, videoConstraints) {
return asyncToGenerator_default()(
/*#__PURE__*/ regenerator_default.a.mark(
function _callee() {
var newConstraints;
return regenerator_default.a.wrap(
function _callee$(_context) {
while (1) {
switch (
(_context.prev =
_context.next)
) {
case 0:
QuaggaJSCameraAccess.requestedVideoElement =
video;
_context.next = 3;
return pickConstraints(
videoConstraints
);
case 3:
newConstraints =
_context.sent;
return _context.abrupt(
"return",
initCamera(
video,
newConstraints
)
);
case 5:
case "end":
return _context.stop();
}
}
},
_callee
);
}
)
)();
},
release: function release() {
var tracks = streamRef && streamRef.getVideoTracks();
if (
QuaggaJSCameraAccess.requestedVideoElement !== null
) {
QuaggaJSCameraAccess.requestedVideoElement.pause();
}
return new Promise(function (resolve) {
setTimeout(function () {
if (tracks && tracks.length) {
tracks[0].stop();
}
streamRef = null;
QuaggaJSCameraAccess.requestedVideoElement =
null;
resolve();
}, 0);
});
},
enumerateVideoDevices: enumerateVideoDevices,
getActiveStreamLabel: function getActiveStreamLabel() {
var track = getActiveTrack();
return track ? track.label : "";
},
getActiveTrack: getActiveTrack,
};
/* harmony default export */ var camera_access =
QuaggaJSCameraAccess;
// CONCATENATED MODULE: ./src/analytics/result_collector.ts
function contains(codeResult, list) {
return (
list &&
list.some(function (item) {
var keys = Object.keys(item);
return keys.every(function (key) {
return item[key] === codeResult[key];
});
})
);
}
function passesFilter(codeResult, filter) {
return typeof filter === "function"
? filter(codeResult)
: true;
}
/* harmony default export */ var result_collector = {
create: function create(config) {
var _config$capacity;
var canvas = document.createElement("canvas");
var ctx = canvas.getContext("2d");
var results = [];
var capacity =
(_config$capacity = config.capacity) !== null &&
_config$capacity !== void 0
? _config$capacity
: 20;
var capture = config.capture === true;
function matchesConstraints(codeResult) {
return (
!!capacity &&
codeResult &&
!contains(codeResult, config.blacklist) &&
passesFilter(codeResult, config.filter)
);
}
return {
addResult: function addResult(
data,
imageSize,
codeResult
) {
var result = {}; // this is 'any' to avoid having to construct a whole QuaggaJSCodeResult :|
if (matchesConstraints(codeResult)) {
capacity--;
result.codeResult = codeResult;
if (capture) {
canvas.width = imageSize.x;
canvas.height = imageSize.y;
image_debug[
"a" /* default */
].drawImage(data, imageSize, ctx);
result.frame = canvas.toDataURL();
}
results.push(result);
}
},
getResults: function getResults() {
return results;
},
};
},
};
// CONCATENATED MODULE: ./src/config/config.dev.ts
var DevConfig = {
inputStream: {
name: "Live",
type: "LiveStream",
constraints: {
width: 640,
height: 480,
// aspectRatio: 640/480, // optional
facingMode: "environment", // or user
// deviceId: "38745983457387598375983759834"
},
area: {
top: "0%",
right: "0%",
left: "0%",
bottom: "0%",
},
singleChannel: false, // true: only the red color-channel is read
},
locate: true,
numOfWorkers: 0,
decoder: {
readers: ["code_128_reader"],
debug: {
drawBoundingBox: false,
showFrequency: false,
drawScanline: false,
showPattern: false,
},
},
locator: {
halfSample: true,
patchSize: "medium",
// x-small, small, medium, large, x-large
debug: {
showCanvas: false,
showPatches: false,
showFoundPatches: false,
showSkeleton: false,
showLabels: false,
showPatchLabels: false,
showRemainingPatchLabels: false,
boxFromPatches: {
showTransformed: false,
showTransformedBox: false,
showBB: false,
},
},
},
};
/* harmony default export */ var config_dev = DevConfig;
// CONCATENATED MODULE: ./src/config/config.node.ts
var NodeConfig = {
inputStream: {
type: "ImageStream",
sequence: false,
size: 800,
area: {
top: "0%",
right: "0%",
left: "0%",
bottom: "0%",
},
singleChannel: false, // true: only the red color-channel is read
},
locate: true,
numOfWorkers: 0,
decoder: {
readers: ["code_128_reader"],
},
locator: {
halfSample: true,
patchSize: "medium", // x-small, small, medium, large, x-large
},
};
/* harmony default export */ var config_node = NodeConfig;
// CONCATENATED MODULE: ./src/config/config.prod.ts
var ProdConfig = {
inputStream: {
name: "Live",
type: "LiveStream",
constraints: {
width: 640,
height: 480,
// aspectRatio: 640/480, // optional
facingMode: "environment", // or user
// deviceId: "38745983457387598375983759834"
},
area: {
top: "0%",
right: "0%",
left: "0%",
bottom: "0%",
},
singleChannel: false, // true: only the red color-channel is read
},
locate: true,
numOfWorkers: 4,
decoder: {
readers: ["code_128_reader"],
},
locator: {
halfSample: true,
patchSize: "medium", // x-small, small, medium, large, x-large
},
};
/* harmony default export */ var config_prod = ProdConfig;
// CONCATENATED MODULE: ./src/config/config.ts
// @ts-ignore // TODO: this produces a bizarre typescript error
// eslint-disable-next-line no-nested-ternary
var QuaggaConfig = true ? config_dev : undefined;
/* harmony default export */ var config_config = QuaggaConfig;
// EXTERNAL MODULE: ./node_modules/gl-vec2/index.js
var gl_vec2 = __webpack_require__(7);
// CONCATENATED MODULE: ./src/QuaggaContext.ts
var QuaggaContext_QuaggaContext = function QuaggaContext() {
classCallCheck_default()(this, QuaggaContext);
defineProperty_default()(this, "config", void 0);
defineProperty_default()(this, "inputStream", void 0);
defineProperty_default()(this, "framegrabber", void 0);
defineProperty_default()(this, "inputImageWrapper", void 0);
defineProperty_default()(this, "stopped", false);
defineProperty_default()(this, "boxSize", void 0);
defineProperty_default()(this, "resultCollector", void 0);
defineProperty_default()(this, "decoder", void 0);
defineProperty_default()(this, "workerPool", []);
defineProperty_default()(this, "onUIThread", true);
defineProperty_default()(
this,
"canvasContainer",
new QuaggaContext_CanvasContainer()
);
};
var QuaggaContext_CanvasInfo = function CanvasInfo() {
classCallCheck_default()(this, CanvasInfo);
defineProperty_default()(this, "image", void 0);
defineProperty_default()(this, "overlay", void 0);
};
var QuaggaContext_CanvasContainer = function CanvasContainer() {
classCallCheck_default()(this, CanvasContainer);
defineProperty_default()(this, "ctx", void 0);
defineProperty_default()(this, "dom", void 0);
this.ctx = new QuaggaContext_CanvasInfo();
this.dom = new QuaggaContext_CanvasInfo();
};
// EXTERNAL MODULE: ./src/locator/barcode_locator.js
var barcode_locator = __webpack_require__(23);
// CONCATENATED MODULE: ./src/quagga/initBuffers.ts
// TODO: need typescript def for BarcodeLocator
function initBuffers_initBuffers(
inputStream,
imageWrapper,
locator
) {
var inputImageWrapper =
imageWrapper ||
new image_wrapper["a" /* default */]({
x: inputStream.getWidth(),
y: inputStream.getHeight(),
type: "XYSize",
});
if (true) {
console.log(
"image wrapper size ".concat(inputImageWrapper.size)
);
}
var boxSize = [
Object(gl_vec2["clone"])([0, 0]),
Object(gl_vec2["clone"])([0, inputImageWrapper.size.y]),
Object(gl_vec2["clone"])([
inputImageWrapper.size.x,
inputImageWrapper.size.y,
]),
Object(gl_vec2["clone"])([inputImageWrapper.size.x, 0]),
];
barcode_locator["a" /* default */].init(
inputImageWrapper,
locator
);
return {
inputImageWrapper: inputImageWrapper,
boxSize: boxSize,
};
}
// CONCATENATED MODULE: ./src/quagga/getViewPort.ts
function getViewPort_getViewPort(target) {
if (typeof document === "undefined") {
return null;
} // Check if target is already a DOM element
if (
target instanceof HTMLElement &&
target.nodeName &&
target.nodeType === 1
) {
return target;
} // Use '#interactive.viewport' as a fallback selector (backwards compatibility)
var selector =
typeof target === "string"
? target
: "#interactive.viewport";
return document.querySelector(selector);
}
// CONCATENATED MODULE: ./src/quagga/initCanvas.ts
function findOrCreateCanvas(selector, className) {
var canvas = document.querySelector(selector);
if (!canvas) {
canvas = document.createElement("canvas");
canvas.className = className;
}
return canvas;
}
function getCanvasAndContext(selector, className) {
var canvas = findOrCreateCanvas(selector, className);
var context = canvas.getContext("2d");
return {
canvas: canvas,
context: context,
};
}
function initCanvases(canvasSize) {
if (typeof document !== "undefined") {
var image = getCanvasAndContext(
"canvas.imgBuffer",
"imgBuffer"
);
var overlay = getCanvasAndContext(
"canvas.drawingBuffer",
"drawingBuffer"
);
image.canvas.width = overlay.canvas.width =
canvasSize.x;
image.canvas.height = overlay.canvas.height =
canvasSize.y;
return {
dom: {
image: image.canvas,
overlay: overlay.canvas,
},
ctx: {
image: image.context,
overlay: overlay.context,
},
};
}
return null;
}
function initCanvas_initCanvas(context) {
var _context$config,
_context$config$input,
_context$config2,
_context$config2$inpu;
var viewport = getViewPort_getViewPort(
context === null || context === void 0
? void 0
: (_context$config = context.config) === null ||
_context$config === void 0
? void 0
: (_context$config$input =
_context$config.inputStream) === null ||
_context$config$input === void 0
? void 0
: _context$config$input.target
);
var type =
context === null || context === void 0
? void 0
: (_context$config2 = context.config) === null ||
_context$config2 === void 0
? void 0
: (_context$config2$inpu =
_context$config2.inputStream) === null ||
_context$config2$inpu === void 0
? void 0
: _context$config2$inpu.type;
if (!type) return null;
var container = initCanvases(
context.inputStream.getCanvasSize()
);
if (!container)
return {
dom: {
image: null,
overlay: null,
},
ctx: {
image: null,
overlay: null,
},
};
var dom = container.dom;
if (typeof document !== "undefined") {
if (viewport) {
if (
type === "ImageStream" &&
!viewport.contains(dom.image)
) {
viewport.appendChild(dom.image);
}
if (!viewport.contains(dom.overlay)) {
viewport.appendChild(dom.overlay);
}
}
}
return container;
}
// CONCATENATED MODULE: ./src/input/exif_helper.js
// NOTE: (SOME OF) THIS IS BROWSER ONLY CODE. Node does not have 'atob' built in, nor XMLHttpRequest.
// How exactly is this set of functions used in Quagga? Do we need the browser specific code? Do we
// need to port any part of this that doesn't work in Node to node?
// Tags scraped from https://github.com/exif-js/exif-js
var ExifTags = {
0x0112: "orientation",
};
var AvailableTags = Object.keys(ExifTags).map(function (key) {
return ExifTags[key];
});
function findTagsInObjectURL(src) {
var tags =
arguments.length > 1 && arguments[1] !== undefined
? arguments[1]
: AvailableTags;
if (/^blob:/i.test(src)) {
return objectURLToBlob(src)
.then(readToBuffer)
.then(function (buffer) {
return findTagsInBuffer(buffer, tags);
});
}
return Promise.resolve(null);
}
function base64ToArrayBuffer(dataUrl) {
var base64 = dataUrl.replace(
/^data:([^;]+);base64,/gim,
""
);
var binary = atob(base64);
var len = binary.length;
var buffer = new ArrayBuffer(len);
var view = new Uint8Array(buffer);
for (var i = 0; i < len; i++) {
view[i] = binary.charCodeAt(i);
}
return buffer;
}
function readToBuffer(blob) {
return new Promise(function (resolve) {
var fileReader = new FileReader();
fileReader.onload = function (e) {
return resolve(e.target.result);
};
fileReader.readAsArrayBuffer(blob);
});
}
function objectURLToBlob(url) {
return new Promise(function (resolve, reject) {
var http = new XMLHttpRequest();
http.open("GET", url, true);
http.responseType = "blob";
http.onreadystatechange = function () {
if (
http.readyState === XMLHttpRequest.DONE &&
(http.status === 200 || http.status === 0)
) {
resolve(this.response);
}
};
http.onerror = reject;
http.send();
});
}
function findTagsInBuffer(file) {
var selectedTags =
arguments.length > 1 && arguments[1] !== undefined
? arguments[1]
: AvailableTags;
var dataView = new DataView(file);
var length = file.byteLength;
var exifTags = selectedTags.reduce(function (
result,
selectedTag
) {
var exifTag = Object.keys(ExifTags).filter(function (
tag
) {
return ExifTags[tag] === selectedTag;
})[0];
if (exifTag) {
result[exifTag] = selectedTag;
}
return result;
},
{});
var offset = 2;
var marker;
if (
dataView.getUint8(0) !== 0xff ||
dataView.getUint8(1) !== 0xd8
) {
return false;
}
while (offset < length) {
if (dataView.getUint8(offset) !== 0xff) {
return false;
}
marker = dataView.getUint8(offset + 1);
if (marker === 0xe1) {
return readEXIFData(dataView, offset + 4, exifTags);
}
offset += 2 + dataView.getUint16(offset + 2);
}
return false;
}
function readEXIFData(file, start, exifTags) {
if (getStringFromBuffer(file, start, 4) !== "Exif") {
return false;
}
var tiffOffset = start + 6;
var bigEnd;
if (file.getUint16(tiffOffset) === 0x4949) {
bigEnd = false;
} else if (file.getUint16(tiffOffset) === 0x4d4d) {
bigEnd = true;
} else {
return false;
}
if (file.getUint16(tiffOffset + 2, !bigEnd) !== 0x002a) {
return false;
}
var firstIFDOffset = file.getUint32(
tiffOffset + 4,
!bigEnd
);
if (firstIFDOffset < 0x00000008) {
return false;
}
var tags = readTags(
file,
tiffOffset,
tiffOffset + firstIFDOffset,
exifTags,
bigEnd
);
return tags;
}
function readTags(file, tiffStart, dirStart, strings, bigEnd) {
var entries = file.getUint16(dirStart, !bigEnd);
var tags = {};
for (var i = 0; i < entries; i++) {
var entryOffset = dirStart + i * 12 + 2;
var tag = strings[file.getUint16(entryOffset, !bigEnd)];
if (tag) {
tags[tag] = readTagValue(
file,
entryOffset,
tiffStart,
dirStart,
bigEnd
);
}
}
return tags;
}
function readTagValue(
file,
entryOffset,
tiffStart,
dirStart,
bigEnd
) {
var type = file.getUint16(entryOffset + 2, !bigEnd);
var numValues = file.getUint32(entryOffset + 4, !bigEnd);
switch (type) {
case 3:
if (numValues === 1) {
return file.getUint16(entryOffset + 8, !bigEnd);
}
}
return null;
}
function getStringFromBuffer(buffer, start, length) {
var outstr = "";
for (var n = start; n < start + length; n++) {
outstr += String.fromCharCode(buffer.getUint8(n));
}
return outstr;
}
// CONCATENATED MODULE: ./src/input/image_loader.js
var ImageLoader = {};
ImageLoader.load = function (
directory,
callback,
offset,
size,
sequence
) {
var htmlImagesSrcArray = new Array(size);
var htmlImagesArray = new Array(htmlImagesSrcArray.length);
var i;
var img;
var num;
if (sequence === false) {
htmlImagesSrcArray[0] = directory;
} else {
for (i = 0; i < htmlImagesSrcArray.length; i++) {
num = offset + i;
htmlImagesSrcArray[i] = ""
.concat(directory, "image-")
.concat("00".concat(num).slice(-3), ".jpg");
}
}
htmlImagesArray.notLoaded = [];
htmlImagesArray.addImage = function (image) {
htmlImagesArray.notLoaded.push(image);
};
htmlImagesArray.loaded = function (loadedImg) {
var notloadedImgs = htmlImagesArray.notLoaded;
for (var x = 0; x < notloadedImgs.length; x++) {
if (notloadedImgs[x] === loadedImg) {
notloadedImgs.splice(x, 1);
for (
var y = 0;
y < htmlImagesSrcArray.length;
y++
) {
var imgName = htmlImagesSrcArray[y].substr(
htmlImagesSrcArray[y].lastIndexOf("/")
);
if (
loadedImg.src.lastIndexOf(imgName) !==
-1
) {
htmlImagesArray[y] = {
img: loadedImg,
};
break;
}
}
break;
}
}
if (notloadedImgs.length === 0) {
if (true) {
console.log("Images loaded");
}
if (sequence === false) {
findTagsInObjectURL(directory, ["orientation"])
.then(function (tags) {
htmlImagesArray[0].tags = tags;
callback(htmlImagesArray);
})
["catch"](function (e) {
console.log(e);
callback(htmlImagesArray);
});
} else {
callback(htmlImagesArray);
}
}
};
for (i = 0; i < htmlImagesSrcArray.length; i++) {
img = new Image();
htmlImagesArray.addImage(img);
addOnloadHandler(img, htmlImagesArray);
img.src = htmlImagesSrcArray[i];
}
};
function addOnloadHandler(img, htmlImagesArray) {
img.onload = function () {
htmlImagesArray.loaded(this);
};
}
/* harmony default export */ var image_loader = ImageLoader;
// CONCATENATED MODULE: ./src/input/input_stream/input_stream_browser.ts
/* eslint-disable @typescript-eslint/no-explicit-any */
var inputStreamFactory = {
createVideoStream: function createVideoStream(video) {
var _config = null;
var _eventNames = ["canrecord", "ended"];
var _eventHandlers = {};
var _calculatedWidth;
var _calculatedHeight;
var _topRight = {
x: 0,
y: 0,
type: "Point",
};
var _canvasSize = {
x: 0,
y: 0,
type: "XYSize",
};
function initSize() {
var _config2, _config3;
var width = video.videoWidth;
var height = video.videoHeight; // eslint-disable-next-line no-nested-ternary
_calculatedWidth =
(_config2 = _config) !== null &&
_config2 !== void 0 &&
_config2.size
? width / height > 1
? _config.size
: Math.floor(
(width / height) * _config.size
)
: width; // eslint-disable-next-line no-nested-ternary
_calculatedHeight =
(_config3 = _config) !== null &&
_config3 !== void 0 &&
_config3.size
? width / height > 1
? Math.floor(
(height / width) * _config.size
)
: _config.size
: height;
_canvasSize.x = _calculatedWidth;
_canvasSize.y = _calculatedHeight;
}
var inputStream = {
getRealWidth: function getRealWidth() {
return video.videoWidth;
},
getRealHeight: function getRealHeight() {
return video.videoHeight;
},
getWidth: function getWidth() {
return _calculatedWidth;
},
getHeight: function getHeight() {
return _calculatedHeight;
},
setWidth: function setWidth(width) {
_calculatedWidth = width;
},
setHeight: function setHeight(height) {
_calculatedHeight = height;
},
setInputStream: function setInputStream(config) {
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
_config = config; // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
this.setAttribute(
"src",
typeof config.src !== "undefined"
? config.src
: ""
);
},
ended: function ended() {
return video.ended;
},
getConfig: function getConfig() {
return _config;
},
setAttribute: function setAttribute(name, value) {
if (video) {
video.setAttribute(name, value);
}
},
pause: function pause() {
video.pause();
},
play: function play() {
// eslint-disable-next-line @typescript-eslint/no-floating-promises
video.play();
},
setCurrentTime: function setCurrentTime(time) {
var _config4;
if (
((_config4 = _config) === null ||
_config4 === void 0
? void 0
: _config4.type) !== "LiveStream"
) {
this.setAttribute(
"currentTime",
time.toString()
);
}
},
addEventListener: function addEventListener(
event,
f,
bool
) {
if (_eventNames.indexOf(event) !== -1) {
if (!_eventHandlers[event]) {
_eventHandlers[event] = [];
}
_eventHandlers[event].push(f);
} else {
video.addEventListener(event, f, bool);
}
},
clearEventHandlers: function clearEventHandlers() {
_eventNames.forEach(function (eventName) {
var handlers = _eventHandlers[eventName];
if (handlers && handlers.length > 0) {
handlers.forEach(function (handler) {
video.removeEventListener(
eventName,
handler
);
});
}
});
},
trigger: function trigger(eventName, args) {
var j; // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
var handlers = _eventHandlers[eventName];
if (eventName === "canrecord") {
initSize();
}
if (handlers && handlers.length > 0) {
for (j = 0; j < handlers.length; j++) {
handlers[j].apply(inputStream, args);
}
}
},
setTopRight: function setTopRight(topRight) {
_topRight.x = topRight.x;
_topRight.y = topRight.y;
},
getTopRight: function getTopRight() {
return _topRight;
},
setCanvasSize: function setCanvasSize(size) {
_canvasSize.x = size.x;
_canvasSize.y = size.y;
},
getCanvasSize: function getCanvasSize() {
return _canvasSize;
},
getFrame: function getFrame() {
return video;
},
};
return inputStream;
},
createLiveStream: function createLiveStream(video) {
if (video) {
video.setAttribute("autoplay", "true");
}
var that = inputStreamFactory.createVideoStream(video);
that.ended = function ended() {
return false;
};
return that;
},
createImageStream: function createImageStream() {
var _config = null;
var width = 0;
var height = 0;
var frameIdx = 0;
var paused = true;
var loaded = false;
var imgArray = null;
var size = 0;
var offset = 1;
var baseUrl = null;
var _ended = false;
var calculatedWidth;
var calculatedHeight;
var _eventNames = ["canrecord", "ended"];
var _eventHandlers = {};
var _topRight = {
x: 0,
y: 0,
type: "Point",
};
var _canvasSize = {
x: 0,
y: 0,
type: "XYSize",
};
function loadImages() {
var _config7;
loaded = false;
image_loader.load(
baseUrl,
function (imgs) {
var _config5, _config6;
imgArray = imgs; // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
if (
imgs[0].tags &&
imgs[0].tags.orientation
) {
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
switch (imgs[0].tags.orientation) {
case 6:
case 8:
width = imgs[0].img.height;
height = imgs[0].img.width;
break;
default:
width = imgs[0].img.width;
height = imgs[0].img.height;
}
} else {
width = imgs[0].img.width;
height = imgs[0].img.height;
} // eslint-disable-next-line no-nested-ternary
calculatedWidth =
(_config5 = _config) !== null &&
_config5 !== void 0 &&
_config5.size
? width / height > 1
? _config.size
: Math.floor(
(width / height) *
_config.size
)
: width; // eslint-disable-next-line no-nested-ternary
calculatedHeight =
(_config6 = _config) !== null &&
_config6 !== void 0 &&
_config6.size
? width / height > 1
? Math.floor(
(height / width) *
_config.size
)
: _config.size
: height;
_canvasSize.x = calculatedWidth;
_canvasSize.y = calculatedHeight;
loaded = true;
frameIdx = 0;
setTimeout(function () {
// eslint-disable-next-line @typescript-eslint/no-use-before-define
publishEvent("canrecord", []);
}, 0);
},
offset,
size,
(_config7 = _config) === null ||
_config7 === void 0
? void 0
: _config7.sequence
);
}
function publishEvent(eventName, args) {
var j;
var handlers = _eventHandlers[eventName];
if (handlers && handlers.length > 0) {
for (j = 0; j < handlers.length; j++) {
// eslint-disable-next-line @typescript-eslint/no-use-before-define
handlers[j].apply(inputStream, args); // TODO: typescript complains that any[] is not valid for a second arg for apply?!
}
}
} // TODO: any code shared with the first InputStream above should be shared not copied
// TODO: publishEvent needs access to inputStream, but inputStream needs access to publishEvent
// TODO: This is why it's a 'var', so it hoists back. This is ugly, and should be changed.
// eslint-disable-next-line no-var,vars-on-top
var inputStream = {
trigger: publishEvent,
getWidth: function getWidth() {
return calculatedWidth;
},
getHeight: function getHeight() {
return calculatedHeight;
},
setWidth: function setWidth(newWidth) {
calculatedWidth = newWidth;
},
setHeight: function setHeight(newHeight) {
calculatedHeight = newHeight;
},
getRealWidth: function getRealWidth() {
return width;
},
getRealHeight: function getRealHeight() {
return height;
},
setInputStream: function setInputStream(stream) {
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
_config = stream; // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
if (stream.sequence === false) {
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment,@typescript-eslint/no-unsafe-member-access
baseUrl = stream.src;
size = 1;
} else {
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment,@typescript-eslint/no-unsafe-member-access
baseUrl = stream.src; // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment,@typescript-eslint/no-unsafe-member-access
size = stream.length;
}
loadImages();
},
ended: function ended() {
return _ended;
},
setAttribute: function setAttribute() {},
getConfig: function getConfig() {
return _config;
},
pause: function pause() {
paused = true;
},
play: function play() {
paused = false;
},
setCurrentTime: function setCurrentTime(time) {
frameIdx = time;
},
addEventListener: function addEventListener(
event,
f
) {
if (_eventNames.indexOf(event) !== -1) {
if (!_eventHandlers[event]) {
_eventHandlers[event] = [];
}
_eventHandlers[event].push(f);
}
},
clearEventHandlers: function clearEventHandlers() {
Object.keys(_eventHandlers).forEach(function (
ind
) {
return delete _eventHandlers[ind];
});
},
setTopRight: function setTopRight(topRight) {
_topRight.x = topRight.x;
_topRight.y = topRight.y;
},
getTopRight: function getTopRight() {
return _topRight;
},
setCanvasSize: function setCanvasSize(canvasSize) {
_canvasSize.x = canvasSize.x;
_canvasSize.y = canvasSize.y;
},
getCanvasSize: function getCanvasSize() {
return _canvasSize;
},
getFrame: function getFrame() {
var frame;
if (!loaded) {
return null;
}
if (!paused) {
var _imgArray;
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
frame =
(_imgArray = imgArray) === null ||
_imgArray === void 0
? void 0
: _imgArray[frameIdx];
if (frameIdx < size - 1) {
frameIdx++;
} else {
setTimeout(function () {
_ended = true;
publishEvent("ended", []);
}, 0);
}
} // eslint-disable-next-line @typescript-eslint/no-unsafe-return
return frame;
},
};
return inputStream;
},
};
/* harmony default export */ var input_stream_browser =
inputStreamFactory;
// EXTERNAL MODULE: ./src/common/cv_utils.js + 1 modules
var cv_utils = __webpack_require__(8);
// CONCATENATED MODULE: ./src/input/frame_grabber_browser.js
// NOTE FOR ANYONE IN HERE IN THE FUTURE:
// webpack.config.js replaces the frame_grabber module with THIS module when it is building for a Browser environment.
var TO_RADIANS = Math.PI / 180;
function adjustCanvasSize(canvas, targetSize) {
if (canvas.width !== targetSize.x) {
if (true) {
console.log(
"WARNING: canvas-size needs to be adjusted"
);
}
canvas.width = targetSize.x;
}
if (canvas.height !== targetSize.y) {
if (true) {
console.log(
"WARNING: canvas-size needs to be adjusted"
);
}
canvas.height = targetSize.y;
}
}
var FrameGrabber = {};
FrameGrabber.create = function (inputStream, canvas) {
var _that = {};
var _streamConfig = inputStream.getConfig();
var _videoSize = Object(cv_utils["h" /* imageRef */])(
inputStream.getRealWidth(),
inputStream.getRealHeight()
);
var _canvasSize = inputStream.getCanvasSize();
var _size = Object(cv_utils["h" /* imageRef */])(
inputStream.getWidth(),
inputStream.getHeight()
);
var topRight = inputStream.getTopRight();
var _sx = topRight.x;
var _sy = topRight.y;
var _canvas;
var _ctx = null;
var _data = null;
_canvas = canvas || document.createElement("canvas");
_canvas.width = _canvasSize.x;
_canvas.height = _canvasSize.y;
_ctx = _canvas.getContext("2d");
_data = new Uint8Array(_size.x * _size.y);
if (true) {
console.log(
"FrameGrabber",
JSON.stringify({
size: _size,
topRight: topRight,
videoSize: _videoSize,
canvasSize: _canvasSize,
})
);
}
/**
* Uses the given array as frame-buffer
*/
_that.attachData = function (data) {
_data = data;
};
/**
* Returns the used frame-buffer
*/
_that.getData = function () {
return _data;
};
/**
* Fetches a frame from the input-stream and puts into the frame-buffer.
* The image-data is converted to gray-scale and then half-sampled if configured.
*/
_that.grab = function () {
var doHalfSample = _streamConfig.halfSample;
var frame = inputStream.getFrame();
var drawable = frame;
var drawAngle = 0;
var ctxData;
if (drawable) {
adjustCanvasSize(_canvas, _canvasSize);
if (_streamConfig.type === "ImageStream") {
drawable = frame.img;
if (frame.tags && frame.tags.orientation) {
switch (frame.tags.orientation) {
case 6:
drawAngle = 90 * TO_RADIANS;
break;
case 8:
drawAngle = -90 * TO_RADIANS;
break;
}
}
}
if (drawAngle !== 0) {
_ctx.translate(
_canvasSize.x / 2,
_canvasSize.y / 2
);
_ctx.rotate(drawAngle);
_ctx.drawImage(
drawable,
-_canvasSize.y / 2,
-_canvasSize.x / 2,
_canvasSize.y,
_canvasSize.x
);
_ctx.rotate(-drawAngle);
_ctx.translate(
-_canvasSize.x / 2,
-_canvasSize.y / 2
);
} else {
_ctx.drawImage(
drawable,
0,
0,
_canvasSize.x,
_canvasSize.y
);
}
ctxData = _ctx.getImageData(
_sx,
_sy,
_size.x,
_size.y
).data;
if (doHalfSample) {
Object(
cv_utils[
"e" /* grayAndHalfSampleFromCanvasData */
]
)(ctxData, _size, _data);
} else {
Object(cv_utils["c" /* computeGray */])(
ctxData,
_data,
_streamConfig
);
}
return true;
}
return false;
};
_that.getSize = function () {
return _size;
};
return _that;
};
/* harmony default export */ var frame_grabber_browser =
FrameGrabber;
// CONCATENATED MODULE: ./src/quagga/qworker.ts
function qworker_ownKeys(object, enumerableOnly) {
var keys = Object.keys(object);
if (Object.getOwnPropertySymbols) {
var symbols = Object.getOwnPropertySymbols(object);
if (enumerableOnly) {
symbols = symbols.filter(function (sym) {
return Object.getOwnPropertyDescriptor(
object,
sym
).enumerable;
});
}
keys.push.apply(keys, symbols);
}
return keys;
}
function qworker_objectSpread(target) {
for (var i = 1; i < arguments.length; i++) {
var source = arguments[i] != null ? arguments[i] : {};
if (i % 2) {
qworker_ownKeys(Object(source), true).forEach(
function (key) {
defineProperty_default()(
target,
key,
source[key]
);
}
);
} else if (Object.getOwnPropertyDescriptors) {
Object.defineProperties(
target,
Object.getOwnPropertyDescriptors(source)
);
} else {
qworker_ownKeys(Object(source)).forEach(function (
key
) {
Object.defineProperty(
target,
key,
Object.getOwnPropertyDescriptor(source, key)
);
});
}
}
return target;
}
/* Worker functions. These are straight from the original quagga.js file.
* Not presently used, as worker support is non-functional. Keeping them around temporarily
* to refer to until it is re-implemented. We may be able to fix/use some of this.
*/
// TODO: need a typescript interface for FrameGrabber
var workerPool = [];
function updateWorkers(frameGrabber) {
var availableWorker;
if (workerPool.length) {
availableWorker = workerPool.filter(function (
workerThread
) {
return !workerThread.busy;
})[0];
if (availableWorker) {
frameGrabber.attachData(availableWorker.imageData);
if (frameGrabber.grab()) {
availableWorker.busy = true;
availableWorker.worker.postMessage(
{
cmd: "process",
imageData: availableWorker.imageData,
},
[availableWorker.imageData.buffer]
);
}
return true;
} else {
return false;
}
}
return null;
}
function configForWorker(config) {
return qworker_objectSpread(
qworker_objectSpread({}, config),
{},
{
inputStream: qworker_objectSpread(
qworker_objectSpread({}, config.inputStream),
{},
{
target: null,
}
),
}
);
} // @ts-ignore
function workerInterface(factory) {
if (factory) {
var Quagga = factory()["default"];
if (!Quagga) {
// @ts-ignore
self.postMessage({
event: "error",
message: "Quagga could not be created",
});
return;
}
} // @ts-ignore
var imageWrapper; // @ts-ignore
function onProcessed(result) {
self.postMessage(
{
event: "processed",
// @ts-ignore
imageData: imageWrapper.data,
result: result, // @ts-ignore
},
[imageWrapper.data.buffer]
);
}
function workerInterfaceReady() {
self.postMessage(
{
event: "initialized",
// @ts-ignore
imageData: imageWrapper.data, // @ts-ignore
},
[imageWrapper.data.buffer]
);
} // @ts-ignore
self.onmessage = function (e) {
if (e.data.cmd === "init") {
var config = e.data.config;
config.numOfWorkers = 0;
imageWrapper = new Quagga.ImageWrapper(
{
x: e.data.size.x,
y: e.data.size.y,
},
new Uint8Array(e.data.imageData)
);
Quagga.init(
config,
workerInterfaceReady,
imageWrapper
);
Quagga.onProcessed(onProcessed);
} else if (e.data.cmd === "process") {
// @ts-ignore
imageWrapper.data = new Uint8Array(
e.data.imageData
);
Quagga.start();
} else if (e.data.cmd === "setReaders") {
Quagga.setReaders(e.data.readers);
} else if (e.data.cmd === "registerReader") {
Quagga.registerReader(e.data.name, e.data.reader);
}
};
}
function generateWorkerBlob() {
var blob, factorySource;
/* jshint ignore:start */
// @ts-ignore
if (typeof __factorySource__ !== "undefined") {
// @ts-ignore
factorySource = __factorySource__; // eslint-disable-line no-undef
}
/* jshint ignore:end */
blob = new Blob(
[
"(" +
workerInterface.toString() +
")(" +
factorySource +
");",
],
{
type: "text/javascript",
}
);
return window.URL.createObjectURL(blob);
}
function initWorker(config, inputStream, cb) {
var blobURL = generateWorkerBlob();
var worker = new Worker(blobURL);
var workerThread = {
worker: worker,
imageData: new Uint8Array(
inputStream.getWidth() * inputStream.getHeight()
),
busy: true,
};
workerThread.worker.onmessage = function (e) {
if (e.data.event === "initialized") {
URL.revokeObjectURL(blobURL);
workerThread.busy = false;
workerThread.imageData = new Uint8Array(
e.data.imageData
);
if (true) {
console.log("Worker initialized");
}
cb(workerThread);
} else if (e.data.event === "processed") {
workerThread.imageData = new Uint8Array(
e.data.imageData
);
workerThread.busy = false; // TODO: how to thread publishResult into here?
// publishResult(e.data.result, workerThread.imageData);
} else if (e.data.event === "error") {
if (true) {
console.log("Worker error: " + e.data.message);
}
}
};
workerThread.worker.postMessage(
{
cmd: "init",
size: {
x: inputStream.getWidth(),
y: inputStream.getHeight(),
},
imageData: workerThread.imageData,
config: configForWorker(config),
},
[workerThread.imageData.buffer]
);
}
function adjustWorkerPool(capacity, config, inputStream, cb) {
var increaseBy = capacity - workerPool.length;
if (increaseBy === 0 && cb) {
cb();
} else if (increaseBy < 0) {
var workersToTerminate = workerPool.slice(increaseBy);
workersToTerminate.forEach(function (workerThread) {
workerThread.worker.terminate();
if (true) {
console.log("Worker terminated!");
}
});
workerPool = workerPool.slice(0, increaseBy);
if (cb) {
cb();
}
} else {
var workerInitialized = function workerInitialized(
workerThread
) {
workerPool.push(workerThread);
if (workerPool.length >= capacity && cb) {
cb();
}
};
if (config) {
for (var i = 0; i < increaseBy; i++) {
initWorker(
config,
inputStream,
workerInitialized
);
}
}
}
}
function qworker_setReaders(readers) {
workerPool.forEach(function (workerThread) {
return workerThread.worker.postMessage({
cmd: "setReaders",
readers: readers,
});
});
}
function qworker_registerReader(name, reader) {
workerPool.forEach(function (workerThread) {
return workerThread.worker.postMessage({
cmd: "registerReader",
name: name,
reader: reader,
});
});
}
// CONCATENATED MODULE: ./src/quagga/setupInputStream.ts
// TODO: need to create an InputStream typescript interface, so we don't have an "any" in the next line
function setupInputStream() {
var type =
arguments.length > 0 && arguments[0] !== undefined
? arguments[0]
: "LiveStream";
var viewport =
arguments.length > 1 ? arguments[1] : undefined;
var InputStream =
arguments.length > 2 ? arguments[2] : undefined;
switch (type) {
case "VideoStream": {
var video = document.createElement("video");
return {
video: video,
inputStream:
InputStream.createVideoStream(video),
};
}
case "ImageStream":
return {
inputStream: InputStream.createImageStream(),
};
case "LiveStream": {
var _video = null;
if (viewport) {
_video = viewport.querySelector("video");
if (!_video) {
_video = document.createElement("video");
viewport.appendChild(_video);
}
}
return {
video: _video,
inputStream:
InputStream.createLiveStream(_video),
};
}
default:
console.error(
"* setupInputStream invalid type ".concat(type)
);
return {
video: null,
inputStream: null,
};
}
}
// CONCATENATED MODULE: ./src/quagga/transform.ts
/* eslint-disable no-param-reassign */
function moveBox(box, xOffset, yOffset) {
var corner = box.length;
while (corner--) {
box[corner][0] += xOffset;
box[corner][1] += yOffset;
}
}
function moveLine(line, xOffset, yOffset) {
line[0].x += xOffset;
line[0].y += yOffset;
line[1].x += xOffset;
line[1].y += yOffset;
}
// CONCATENATED MODULE: ./src/quagga/quagga.ts
var quagga_Quagga = /*#__PURE__*/ (function () {
function Quagga() {
var _this = this;
classCallCheck_default()(this, Quagga);
defineProperty_default()(
this,
"context",
new QuaggaContext_QuaggaContext()
);
defineProperty_default()(
this,
"canRecord",
function (callback) {
var _this$context$config;
if (!_this.context.config) {
return;
}
barcode_locator[
"a" /* default */
].checkImageConstraints(
_this.context.inputStream,
(_this$context$config =
_this.context.config) === null ||
_this$context$config === void 0
? void 0
: _this$context$config.locator
);
_this.initCanvas();
_this.context.framegrabber =
frame_grabber_browser.create(
_this.context.inputStream,
_this.context.canvasContainer.dom.image
);
if (
_this.context.config.numOfWorkers ===
undefined
) {
_this.context.config.numOfWorkers = 0;
}
adjustWorkerPool(
_this.context.config.numOfWorkers,
_this.context.config,
_this.context.inputStream,
function () {
var _this$context$config2;
if (
((_this$context$config2 =
_this.context.config) ===
null ||
_this$context$config2 === void 0
? void 0
: _this$context$config2.numOfWorkers) ===
0
) {
_this.initializeData();
}
_this.ready(callback);
}
);
}
);
defineProperty_default()(this, "update", function () {
if (_this.context.onUIThread) {
var workersUpdated = updateWorkers(
_this.context.framegrabber
);
if (!workersUpdated) {
var _this$context$inputIm;
_this.context.framegrabber.attachData(
(_this$context$inputIm =
_this.context.inputImageWrapper) ===
null ||
_this$context$inputIm === void 0
? void 0
: _this$context$inputIm.data
);
if (_this.context.framegrabber.grab()) {
if (!workersUpdated) {
_this.locateAndDecode();
}
}
}
} else {
var _this$context$inputIm2;
_this.context.framegrabber.attachData(
(_this$context$inputIm2 =
_this.context.inputImageWrapper) ===
null ||
_this$context$inputIm2 === void 0
? void 0
: _this$context$inputIm2.data
);
_this.context.framegrabber.grab();
_this.locateAndDecode();
}
});
}
createClass_default()(Quagga, [
{
key: "initBuffers",
value: function initBuffers(imageWrapper) {
if (!this.context.config) {
return;
}
var _initBuffers2 = initBuffers_initBuffers(
this.context.inputStream,
imageWrapper,
this.context.config.locator
),
inputImageWrapper =
_initBuffers2.inputImageWrapper,
boxSize = _initBuffers2.boxSize;
this.context.inputImageWrapper =
inputImageWrapper;
this.context.boxSize = boxSize;
},
},
{
key: "initializeData",
value: function initializeData(imageWrapper) {
if (!this.context.config) {
return;
}
this.initBuffers(imageWrapper);
this.context.decoder = barcode_decoder.create(
this.context.config.decoder,
this.context.inputImageWrapper
);
},
},
{
key: "getViewPort",
value: function getViewPort() {
if (
!this.context.config ||
!this.context.config.inputStream
) {
return null;
}
var target =
this.context.config.inputStream.target;
return getViewPort_getViewPort(target);
},
},
{
key: "ready",
value: function ready(callback) {
this.context.inputStream.play();
callback();
},
},
{
key: "initCanvas",
value: function initCanvas() {
var container = initCanvas_initCanvas(
this.context
);
if (!container) {
return;
}
var ctx = container.ctx,
dom = container.dom;
this.context.canvasContainer.dom.image =
dom.image;
this.context.canvasContainer.dom.overlay =
dom.overlay;
this.context.canvasContainer.ctx.image =
ctx.image;
this.context.canvasContainer.ctx.overlay =
ctx.overlay;
},
},
{
key: "initInputStream",
value: function initInputStream(callback) {
if (
!this.context.config ||
!this.context.config.inputStream
) {
return;
}
var _this$context$config$ =
this.context.config.inputStream,
inputType = _this$context$config$.type,
constraints =
_this$context$config$.constraints;
var _setupInputStream = setupInputStream(
inputType,
this.getViewPort(),
input_stream_browser
),
video = _setupInputStream.video,
inputStream = _setupInputStream.inputStream;
if (inputType === "LiveStream" && video) {
camera_access
.request(video, constraints)
.then(function () {
return inputStream.trigger(
"canrecord"
);
})
["catch"](function (err) {
return callback(err);
});
}
inputStream.setAttribute("preload", "auto");
inputStream.setInputStream(
this.context.config.inputStream
);
inputStream.addEventListener(
"canrecord",
this.canRecord.bind(undefined, callback)
);
this.context.inputStream = inputStream;
},
},
{
key: "getBoundingBoxes",
value: function getBoundingBoxes() {
var _this$context$config3;
return (_this$context$config3 =
this.context.config) !== null &&
_this$context$config3 !== void 0 &&
_this$context$config3.locate
? barcode_locator[
"a" /* default */
].locate()
: [
[
Object(gl_vec2["clone"])(
this.context.boxSize[0]
),
Object(gl_vec2["clone"])(
this.context.boxSize[1]
),
Object(gl_vec2["clone"])(
this.context.boxSize[2]
),
Object(gl_vec2["clone"])(
this.context.boxSize[3]
),
],
];
}, // TODO: need a typescript type for result here.
// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
},
{
key: "transformResult",
value: function transformResult(result) {
var _this2 = this;
var topRight =
this.context.inputStream.getTopRight();
var xOffset = topRight.x;
var yOffset = topRight.y;
if (xOffset === 0 && yOffset === 0) {
return;
}
if (result.barcodes) {
// TODO: BarcodeInfo may not be the right type here.
result.barcodes.forEach(function (barcode) {
return _this2.transformResult(barcode);
});
}
if (result.line && result.line.length === 2) {
moveLine(result.line, xOffset, yOffset);
}
if (result.box) {
moveBox(result.box, xOffset, yOffset);
}
if (result.boxes && result.boxes.length > 0) {
for (
var i = 0;
i < result.boxes.length;
i++
) {
moveBox(
result.boxes[i],
xOffset,
yOffset
);
}
}
},
},
{
key: "addResult",
value: function addResult(result, imageData) {
var _this3 = this;
if (
!imageData ||
!this.context.resultCollector
) {
return;
} // TODO: Figure out what data structure holds a "barcodes" result, if any...
if (result.barcodes) {
result.barcodes
.filter(function (barcode) {
return barcode.codeResult;
})
.forEach(function (barcode) {
return _this3.addResult(
barcode,
imageData
);
});
} else if (result.codeResult) {
this.context.resultCollector.addResult(
imageData,
this.context.inputStream.getCanvasSize(),
result.codeResult
);
}
}, // eslint-disable-next-line class-methods-use-this
},
{
key: "hasCodeResult",
value: function hasCodeResult(result) {
return !!(
result &&
(result.barcodes
? result.barcodes.some(function (
barcode
) {
return barcode.codeResult;
})
: result.codeResult)
);
}, // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
},
{
key: "publishResult",
value: function publishResult() {
var result =
arguments.length > 0 &&
arguments[0] !== undefined
? arguments[0]
: null;
var imageData =
arguments.length > 1
? arguments[1]
: undefined;
var resultToPublish = result;
if (result && this.context.onUIThread) {
this.transformResult(result);
this.addResult(result, imageData);
resultToPublish = result.barcodes || result;
}
events.publish("processed", resultToPublish);
if (this.hasCodeResult(result)) {
events.publish("detected", resultToPublish);
}
},
},
{
key: "locateAndDecode",
value: function locateAndDecode() {
var boxes = this.getBoundingBoxes();
if (boxes) {
var _this$context$inputIm3;
var decodeResult =
this.context.decoder.decodeFromBoundingBoxes(
boxes
) || {};
decodeResult.boxes = boxes;
this.publishResult(
decodeResult,
(_this$context$inputIm3 =
this.context.inputImageWrapper) ===
null ||
_this$context$inputIm3 === void 0
? void 0
: _this$context$inputIm3.data
);
} else {
var imageResult =
this.context.decoder.decodeFromImage(
this.context.inputImageWrapper
);
if (imageResult) {
var _this$context$inputIm4;
this.publishResult(
imageResult,
(_this$context$inputIm4 =
this.context
.inputImageWrapper) ===
null ||
_this$context$inputIm4 ===
void 0
? void 0
: _this$context$inputIm4.data
);
} else {
this.publishResult();
}
}
},
},
{
key: "startContinuousUpdate",
value: function startContinuousUpdate() {
var _this$context$config4,
_this4 = this;
var next = null;
var delay =
1000 /
(((_this$context$config4 =
this.context.config) === null ||
_this$context$config4 === void 0
? void 0
: _this$context$config4.frequency) ||
60);
this.context.stopped = false;
var context = this.context;
var newFrame = function newFrame(timestamp) {
next = next || timestamp;
if (!context.stopped) {
if (timestamp >= next) {
next += delay;
_this4.update();
}
window.requestAnimationFrame(newFrame);
}
};
newFrame(performance.now());
},
},
{
key: "start",
value: function start() {
var _this$context$config5,
_this$context$config6;
if (
this.context.onUIThread &&
((_this$context$config5 =
this.context.config) === null ||
_this$context$config5 === void 0
? void 0
: (_this$context$config6 =
_this$context$config5.inputStream) ===
null ||
_this$context$config6 === void 0
? void 0
: _this$context$config6.type) ===
"LiveStream"
) {
this.startContinuousUpdate();
} else {
this.update();
}
},
},
{
key: "stop",
value: (function () {
var _stop = asyncToGenerator_default()(
/*#__PURE__*/ regenerator_default.a.mark(
function _callee() {
var _this$context$config7;
return regenerator_default.a.wrap(
function _callee$(_context) {
while (1) {
switch (
(_context.prev =
_context.next)
) {
case 0:
this.context.stopped = true;
adjustWorkerPool(
0
);
if (
!(
(_this$context$config7 =
this
.context
.config) !==
null &&
_this$context$config7 !==
void 0 &&
_this$context$config7.inputStream &&
this
.context
.config
.inputStream
.type ===
"LiveStream"
)
) {
_context.next = 6;
break;
}
_context.next = 5;
return camera_access.release();
case 5:
this.context.inputStream.clearEventHandlers();
case 6:
case "end":
return _context.stop();
}
}
},
_callee,
this
);
}
)
);
function stop() {
return _stop.apply(this, arguments);
}
return stop;
})(),
},
{
key: "setReaders",
value: function setReaders(readers) {
if (this.context.decoder) {
this.context.decoder.setReaders(readers);
}
qworker_setReaders(readers);
},
},
{
key: "registerReader",
value: function registerReader(name, reader) {
barcode_decoder.registerReader(name, reader);
if (this.context.decoder) {
this.context.decoder.registerReader(
name,
reader
);
}
qworker_registerReader(name, reader);
},
},
]);
return Quagga;
})();
// CONCATENATED MODULE: ./src/quagga.js
// eslint-disable-line no-unused-vars
var instance = new quagga_Quagga();
var quagga_context = instance.context;
var QuaggaJSStaticInterface = {
init: function init(config, cb, imageWrapper) {
var quaggaInstance =
arguments.length > 3 && arguments[3] !== undefined
? arguments[3]
: instance;
var promise;
if (!cb) {
promise = new Promise(function (resolve, reject) {
cb = function cb(err) {
err ? reject(err) : resolve();
};
});
}
quaggaInstance.context.config = merge_default()(
{},
config_config,
config
); // TODO #179: pending restructure in Issue #179, we are temp disabling workers
if (quaggaInstance.context.config.numOfWorkers > 0) {
quaggaInstance.context.config.numOfWorkers = 0;
}
if (imageWrapper) {
quaggaInstance.context.onUIThread = false;
quaggaInstance.initializeData(imageWrapper);
if (cb) {
cb();
}
} else {
quaggaInstance.initInputStream(cb);
}
return promise;
},
start: function start() {
return instance.start();
},
stop: function stop() {
return instance.stop();
},
pause: function pause() {
quagga_context.stopped = true;
},
onDetected: function onDetected(callback) {
if (
!callback ||
(typeof callback !== "function" &&
(typeof_default()(callback) !== "object" ||
!callback.callback))
) {
console.trace(
"* warning: Quagga.onDetected called with invalid callback, ignoring"
);
return;
}
events.subscribe("detected", callback);
},
offDetected: function offDetected(callback) {
events.unsubscribe("detected", callback);
},
onProcessed: function onProcessed(callback) {
if (
!callback ||
(typeof callback !== "function" &&
(typeof_default()(callback) !== "object" ||
!callback.callback))
) {
console.trace(
"* warning: Quagga.onProcessed called with invalid callback, ignoring"
);
return;
}
events.subscribe("processed", callback);
},
offProcessed: function offProcessed(callback) {
events.unsubscribe("processed", callback);
},
setReaders: function setReaders(readers) {
if (!readers) {
console.trace(
"* warning: Quagga.setReaders called with no readers, ignoring"
);
return;
}
instance.setReaders(readers);
},
registerReader: function registerReader(name, reader) {
if (!name) {
console.trace(
"* warning: Quagga.registerReader called with no name, ignoring"
);
return;
}
if (!reader) {
console.trace(
"* warning: Quagga.registerReader called with no reader, ignoring"
);
return;
}
instance.registerReader(name, reader);
},
registerResultCollector: function registerResultCollector(
resultCollector
) {
if (
resultCollector &&
typeof resultCollector.addResult === "function"
) {
quagga_context.resultCollector = resultCollector;
}
},
get canvas() {
return quagga_context.canvasContainer;
},
decodeSingle: function decodeSingle(
config,
resultCallback
) {
var _this = this;
var quaggaInstance = new quagga_Quagga();
config = merge_default()(
{
inputStream: {
type: "ImageStream",
sequence: false,
size: 800,
src: config.src,
},
numOfWorkers: true && config.debug ? 0 : 1,
locator: {
halfSample: false,
},
},
config
); // TODO #175: restructure worker support so that it will work with typescript using worker-loader
// https://webpack.js.org/loaders/worker-loader/
if (config.numOfWorkers > 0) {
config.numOfWorkers = 0;
} // workers require Worker and Blob support presently, so if no Blob or Worker then set
// workers to 0.
if (
config.numOfWorkers > 0 &&
(typeof Blob === "undefined" ||
typeof Worker === "undefined")
) {
console.warn(
"* no Worker and/or Blob support - forcing numOfWorkers to 0"
);
config.numOfWorkers = 0;
}
return new Promise(function (resolve, reject) {
try {
_this.init(
config,
function () {
events.once(
"processed",
function (result) {
quaggaInstance.stop();
if (resultCallback) {
resultCallback.call(
null,
result
);
}
resolve(result);
},
true
);
quaggaInstance.start();
},
null,
quaggaInstance
);
} catch (err) {
reject(err);
}
});
},
// add the usually expected "default" for use with require, build step won't allow us to
// write to module.exports so do it here.
get default() {
return QuaggaJSStaticInterface;
},
Readers: reader_namespaceObject,
CameraAccess: camera_access,
ImageDebug: image_debug["a" /* default */],
ImageWrapper: image_wrapper["a" /* default */],
ResultCollector: result_collector,
};
/* harmony default export */ var quagga = (__webpack_exports__[
"default"
] = QuaggaJSStaticInterface); // export BarcodeReader and other utilities for external plugins
/***/
},
/******/
]
)["default"];
});
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_minifier/tests/fixture/issues/quagga2/1.4.2/1/output.js | JavaScript | !function(root, factory) {
"object" == typeof exports && "object" == typeof module ? module.exports = factory() : "function" == typeof define && define.amd ? define([], factory) : "object" == typeof exports ? exports.Quagga = factory() : root.Quagga = factory();
}(window, function() {
return /******/ 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 module1 = installedModules[moduleId] = {
/******/ i: moduleId,
/******/ l: !1,
/******/ exports: {}
};
/******/ /******/ // Return the exports of the module
/******/ return(/******/ /******/ // Execute the module function
/******/ modules[moduleId].call(module1.exports, module1, module1.exports, __webpack_require__), /******/ /******/ // Flag the module as loaded
/******/ module1.l = !0, module1.exports);
/******/ }
/******/ /******/ /******/ // Load entry module and return exports
/******/ return(/******/ /******/ /******/ // 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(exports1, name, getter) {
/******/ __webpack_require__.o(exports1, name) || /******/ Object.defineProperty(exports1, name, {
enumerable: !0,
get: getter
});
/******/ }, /******/ /******/ // define __esModule on exports
/******/ __webpack_require__.r = function(exports1) {
"undefined" != typeof Symbol && Symbol.toStringTag && /******/ Object.defineProperty(exports1, Symbol.toStringTag, {
value: "Module"
}), /******/ Object.defineProperty(exports1, "__esModule", {
value: !0
});
/******/ }, /******/ /******/ // 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 (1 & mode && (value = __webpack_require__(value)), 8 & mode || 4 & mode && "object" == typeof value && value && value.__esModule) return value;
/******/ var ns = Object.create(null);
/******/ if (/******/ __webpack_require__.r(ns), /******/ Object.defineProperty(ns, "default", {
enumerable: !0,
value: value
}), 2 & mode && "string" != typeof value) 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(module1) {
/******/ var getter = module1 && module1.__esModule ? /******/ function() {
return module1.default;
} : /******/ function() {
return module1;
};
/******/ return /******/ __webpack_require__.d(getter, "a", getter), getter;
/******/ }, /******/ /******/ // Object.prototype.hasOwnProperty.call
/******/ __webpack_require__.o = function(object, property) {
return Object.prototype.hasOwnProperty.call(object, property);
}, /******/ /******/ // __webpack_public_path__
/******/ __webpack_require__.p = "/", __webpack_require__(__webpack_require__.s = 89));
/******/ }(/************************************************************************/ /******/ [
/* 0 */ /***/ function(module1, exports1) {
module1.exports = function(obj, key, value) {
return key in obj ? Object.defineProperty(obj, key, {
value: value,
enumerable: !0,
configurable: !0,
writable: !0
}) : obj[key] = value, obj;
}, module1.exports.default = module1.exports, module1.exports.__esModule = !0;
/***/ },
/* 1 */ /***/ function(module1, exports1) {
module1.exports = function(self1) {
if (void 0 === self1) throw ReferenceError("this hasn't been initialised - super() hasn't been called");
return self1;
}, module1.exports.default = module1.exports, module1.exports.__esModule = !0;
/***/ },
/* 2 */ /***/ function(module1, exports1) {
function _getPrototypeOf(o) {
return module1.exports = _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function(o) {
return o.__proto__ || Object.getPrototypeOf(o);
}, module1.exports.default = module1.exports, module1.exports.__esModule = !0, _getPrototypeOf(o);
}
module1.exports = _getPrototypeOf, module1.exports.default = module1.exports, module1.exports.__esModule = !0;
/***/ },
/* 3 */ /***/ function(module1, exports1) {
module1.exports = function(instance, Constructor) {
if (!(instance instanceof Constructor)) throw TypeError("Cannot call a class as a function");
}, module1.exports.default = module1.exports, module1.exports.__esModule = !0;
/***/ },
/* 4 */ /***/ function(module1, exports1) {
function _defineProperties(target, props) {
for(var i = 0; i < props.length; i++){
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || !1, descriptor.configurable = !0, "value" in descriptor && (descriptor.writable = !0), Object.defineProperty(target, descriptor.key, descriptor);
}
}
module1.exports = function(Constructor, protoProps, staticProps) {
return protoProps && _defineProperties(Constructor.prototype, protoProps), staticProps && _defineProperties(Constructor, staticProps), Constructor;
}, module1.exports.default = module1.exports, module1.exports.__esModule = !0;
/***/ },
/* 5 */ /***/ function(module1, exports1, __webpack_require__) {
var _typeof = __webpack_require__(19).default, assertThisInitialized = __webpack_require__(1);
module1.exports = function(self1, call) {
if (call && ("object" === _typeof(call) || "function" == typeof call)) return call;
if (void 0 !== call) throw TypeError("Derived constructors may only return object or undefined");
return assertThisInitialized(self1);
}, module1.exports.default = module1.exports, module1.exports.__esModule = !0;
/***/ },
/* 6 */ /***/ function(module1, exports1, __webpack_require__) {
var setPrototypeOf = __webpack_require__(41);
module1.exports = function(subClass, superClass) {
if ("function" != typeof superClass && null !== superClass) throw TypeError("Super expression must either be null or a function");
subClass.prototype = Object.create(superClass && superClass.prototype, {
constructor: {
value: subClass,
writable: !0,
configurable: !0
}
}), superClass && setPrototypeOf(subClass, superClass);
}, module1.exports.default = module1.exports, module1.exports.__esModule = !0;
/***/ },
/* 7 */ /***/ function(module1, exports1, __webpack_require__) {
module1.exports = {
EPSILON: __webpack_require__(62),
create: __webpack_require__(63),
clone: __webpack_require__(156),
fromValues: __webpack_require__(157),
copy: __webpack_require__(158),
set: __webpack_require__(159),
equals: __webpack_require__(160),
exactEquals: __webpack_require__(161),
add: __webpack_require__(162),
subtract: __webpack_require__(64),
sub: __webpack_require__(163),
multiply: __webpack_require__(65),
mul: __webpack_require__(164),
divide: __webpack_require__(66),
div: __webpack_require__(165),
inverse: __webpack_require__(166),
min: __webpack_require__(167),
max: __webpack_require__(168),
rotate: __webpack_require__(169),
floor: __webpack_require__(170),
ceil: __webpack_require__(171),
round: __webpack_require__(172),
scale: __webpack_require__(173),
scaleAndAdd: __webpack_require__(174),
distance: __webpack_require__(67),
dist: __webpack_require__(175),
squaredDistance: __webpack_require__(68),
sqrDist: __webpack_require__(176),
length: __webpack_require__(69),
len: __webpack_require__(177),
squaredLength: __webpack_require__(70),
sqrLen: __webpack_require__(178),
negate: __webpack_require__(179),
normalize: __webpack_require__(180),
dot: __webpack_require__(181),
cross: __webpack_require__(182),
lerp: __webpack_require__(183),
random: __webpack_require__(184),
transformMat2: __webpack_require__(185),
transformMat2d: __webpack_require__(186),
transformMat3: __webpack_require__(187),
transformMat4: __webpack_require__(188),
forEach: __webpack_require__(189),
limit: __webpack_require__(190)
};
/***/ },
/* 8 */ /***/ function(module1, __webpack_exports__, __webpack_require__) {
"use strict";
// EXPORTS
__webpack_require__.d(__webpack_exports__, "h", function() {
return /* binding */ imageRef;
}), __webpack_require__.d(__webpack_exports__, "i", function() {
return /* binding */ otsuThreshold;
}), __webpack_require__.d(__webpack_exports__, "b", function() {
return /* binding */ cv_utils_cluster;
}), __webpack_require__.d(__webpack_exports__, "j", function() {
return /* binding */ topGeneric;
}), __webpack_require__.d(__webpack_exports__, "e", function() {
return /* binding */ grayAndHalfSampleFromCanvasData;
}), __webpack_require__.d(__webpack_exports__, "c", function() {
return /* binding */ computeGray;
}), __webpack_require__.d(__webpack_exports__, "f", function() {
return /* binding */ halfSample;
}), __webpack_require__.d(__webpack_exports__, "g", function() {
return /* binding */ hsv2rgb;
}), __webpack_require__.d(__webpack_exports__, "a", function() {
return /* binding */ calculatePatchSize;
}), __webpack_require__.d(__webpack_exports__, "d", function() {
return /* binding */ computeImageArea;
});
// UNUSED EXPORTS: computeIntegralImage2, computeIntegralImage, thresholdImage, computeHistogram, sharpenLine, determineOtsuThreshold, computeBinaryImage, Tracer, DILATE, ERODE, dilate, erode, subtract, bitwiseOr, countNonZero, grayArrayFromImage, grayArrayFromContext, loadImageArray, _computeDivisors, _parseCSSDimensionValues, _dimensionsConverters
// EXTERNAL MODULE: ./node_modules/gl-vec2/index.js
var gl_vec2 = __webpack_require__(7), gl_vec3 = __webpack_require__(84), vec2 = {
clone: gl_vec2.clone,
dot: gl_vec2.dot
}, cluster = {
create: function(point, threshold) {
var points = [], center = {
rad: 0,
vec: vec2.clone([
0,
0
])
}, pointMap = {};
function _add(pointToAdd) {
pointMap[pointToAdd.id] = pointToAdd, points.push(pointToAdd);
}
function updateCenter() {
var i, sum = 0;
for(i = 0; i < points.length; i++)sum += points[i].rad;
center.rad = sum / points.length, center.vec = vec2.clone([
Math.cos(center.rad),
Math.sin(center.rad)
]);
}
return _add(point), updateCenter(), {
add: function(pointToAdd) {
pointMap[pointToAdd.id] || (_add(pointToAdd), updateCenter());
},
fits: function(otherPoint) {
return Math.abs(vec2.dot(otherPoint.point.vec, center.vec)) > threshold;
},
getPoints: function() {
return points;
},
getCenter: function() {
return center;
}
};
},
createPoint: function(newPoint, id, property) {
return {
rad: newPoint[property],
point: newPoint,
id: id
};
}
}, array_helper = __webpack_require__(10), cv_utils_vec2 = {
clone: gl_vec2.clone
}, vec3 = {
clone: gl_vec3.clone
};
/**
* @param x x-coordinate
* @param y y-coordinate
* @return ImageReference {x,y} Coordinate
*/ function imageRef(x, y) {
return {
x: x,
y: y,
toVec2: function() {
return cv_utils_vec2.clone([
this.x,
this.y
]);
},
toVec3: function() {
return vec3.clone([
this.x,
this.y,
1
]);
},
round: function() {
return this.x = this.x > 0.0 ? Math.floor(this.x + 0.5) : Math.floor(this.x - 0.5), this.y = this.y > 0.0 ? Math.floor(this.y + 0.5) : Math.floor(this.y - 0.5), this;
}
};
}
function otsuThreshold(imageWrapper, targetWrapper) {
var threshold = function(imageWrapper) {
var hist, bitsPerPixel = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : 8, bitShift = 8 - bitsPerPixel;
function px(init, end) {
for(var sum = 0, i = init; i <= end; i++)sum += hist[i];
return sum;
}
function mx(init, end) {
for(var sum = 0, i = init; i <= end; i++)sum += i * hist[i];
return sum;
}
return function() {
var p1, p2, p12, m12, vet = [
0
], max = (1 << bitsPerPixel) - 1;
hist = function(imageWrapper, bitsPerPixel) {
bitsPerPixel || // eslint-disable-next-line no-param-reassign
(bitsPerPixel = 8);
for(var imageData = imageWrapper.data, length = imageData.length, bitShift = 8 - bitsPerPixel, hist = new Int32Array(1 << bitsPerPixel); length--;)hist[imageData[length] >> bitShift]++;
return hist;
}(imageWrapper, bitsPerPixel);
for(var k = 1; k < max; k++)0 == (p12 = (p1 = px(0, k)) * (p2 = px(k + 1, max))) && (p12 = 1), m12 = mx(0, k) * p2 - mx(k + 1, max) * p1, vet[k] = m12 * m12 / p12;
return array_helper.a.maxIndex(vet);
}() << bitShift;
}(imageWrapper);
return !function(imageWrapper, threshold, targetWrapper) {
targetWrapper || // eslint-disable-next-line no-param-reassign
(targetWrapper = imageWrapper);
for(var imageData = imageWrapper.data, length = imageData.length, targetData = targetWrapper.data; length--;)targetData[length] = +(imageData[length] < threshold);
}(imageWrapper, threshold, targetWrapper), threshold;
} // local thresholding
function cv_utils_cluster(points, threshold, property) {
var i, k, thisCluster, point, clusters = [];
for(property || // eslint-disable-next-line no-param-reassign
(property = "rad"), i = 0; i < points.length; i++)!function(newPoint) {
var found = !1;
for(k = 0; k < clusters.length; k++)(thisCluster = clusters[k]).fits(newPoint) && (thisCluster.add(newPoint), found = !0);
return found;
} // iterate over each cloud
(point = cluster.createPoint(points[i], i, property)) && clusters.push(cluster.create(point, threshold));
return clusters;
}
function topGeneric(list, top, scoreFunc) {
var i, score, hit, pos, minIdx = 0, min = 0, queue = [];
for(i = 0; i < top; i++)queue[i] = {
score: 0,
item: null
};
for(i = 0; i < list.length; i++)if ((score = scoreFunc.apply(this, [
list[i]
])) > min) for(pos = 0, (hit = queue[minIdx]).score = score, hit.item = list[i], min = Number.MAX_VALUE; pos < top; pos++)queue[pos].score < min && (min = queue[pos].score, minIdx = pos);
return queue;
}
function grayAndHalfSampleFromCanvasData(canvasData, size, outArray) {
for(var i, topRowIdx = 0, bottomRowIdx = size.x, endIdx = Math.floor(canvasData.length / 4), outWidth = size.x / 2, outImgIdx = 0, inWidth = size.x; bottomRowIdx < endIdx;){
for(i = 0; i < outWidth; i++)// eslint-disable-next-line no-param-reassign
outArray[outImgIdx] = (0.299 * canvasData[4 * topRowIdx + 0] + 0.587 * canvasData[4 * topRowIdx + 1] + 0.114 * canvasData[4 * topRowIdx + 2] + (0.299 * canvasData[(topRowIdx + 1) * 4 + 0] + 0.587 * canvasData[(topRowIdx + 1) * 4 + 1] + 0.114 * canvasData[(topRowIdx + 1) * 4 + 2]) + (0.299 * canvasData[4 * bottomRowIdx + 0] + 0.587 * canvasData[4 * bottomRowIdx + 1] + 0.114 * canvasData[4 * bottomRowIdx + 2]) + (0.299 * canvasData[(bottomRowIdx + 1) * 4 + 0] + 0.587 * canvasData[(bottomRowIdx + 1) * 4 + 1] + 0.114 * canvasData[(bottomRowIdx + 1) * 4 + 2])) / 4, outImgIdx++, topRowIdx += 2, bottomRowIdx += 2;
topRowIdx += inWidth, bottomRowIdx += inWidth;
}
}
function computeGray(imageData, outArray, config) {
var l = imageData.length / 4 | 0;
if (config && !0 === config.singleChannel) for(var i = 0; i < l; i++)// eslint-disable-next-line no-param-reassign
outArray[i] = imageData[4 * i + 0];
else for(var _i = 0; _i < l; _i++)// eslint-disable-next-line no-param-reassign
outArray[_i] = 0.299 * imageData[4 * _i + 0] + 0.587 * imageData[4 * _i + 1] + 0.114 * imageData[4 * _i + 2];
}
/**
* @param inImg {ImageWrapper} input image to be sampled
* @param outImg {ImageWrapper} to be stored in
*/ function halfSample(inImgWrapper, outImgWrapper) {
for(var inImg = inImgWrapper.data, inWidth = inImgWrapper.size.x, outImg = outImgWrapper.data, topRowIdx = 0, bottomRowIdx = inWidth, endIdx = inImg.length, outWidth = inWidth / 2, outImgIdx = 0; bottomRowIdx < endIdx;){
for(var i = 0; i < outWidth; i++)outImg[outImgIdx] = Math.floor((inImg[topRowIdx] + inImg[topRowIdx + 1] + inImg[bottomRowIdx] + inImg[bottomRowIdx + 1]) / 4), outImgIdx++, topRowIdx += 2, bottomRowIdx += 2;
topRowIdx += inWidth, bottomRowIdx += inWidth;
}
}
function hsv2rgb(hsv) {
var rgb = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : [
0,
0,
0
], h = hsv[0], s = hsv[1], v = hsv[2], c = v * s, x = c * (1 - Math.abs(h / 60 % 2 - 1)), m = v - c, r = 0, g = 0, b = 0;
return h < 60 ? (r = c, g = x) : h < 120 ? (r = x, g = c) : h < 180 ? (g = c, b = x) : h < 240 ? (g = x, b = c) : h < 300 ? (r = x, b = c) : h < 360 && (r = c, b = x), rgb[0] = (r + m) * 255 | 0, rgb[1] = (g + m) * 255 | 0, rgb[2] = (b + m) * 255 | 0, rgb;
}
function _computeDivisors(n) {
for(var largeDivisors = [], divisors = [], i = 1; i < Math.sqrt(n) + 1; i++)n % i == 0 && (divisors.push(i), i !== n / i && largeDivisors.unshift(Math.floor(n / i)));
return divisors.concat(largeDivisors);
}
function calculatePatchSize(patchSize, imgSize) {
var optimalPatchSize, divisorsX = _computeDivisors(imgSize.x), divisorsY = _computeDivisors(imgSize.y), wideSide = Math.max(imgSize.x, imgSize.y), common = function(arr1, arr2) {
for(var i = 0, j = 0, result = []; i < arr1.length && j < arr2.length;)arr1[i] === arr2[j] ? (result.push(arr1[i]), i++, j++) : arr1[i] > arr2[j] ? j++ : i++;
return result;
}(divisorsX, divisorsY), nrOfPatchesList = [
8,
10,
15,
20,
32,
60,
80
], nrOfPatchesMap = {
"x-small": 5,
small: 4,
medium: 3,
large: 2,
"x-large": 1
}, nrOfPatchesIdx = nrOfPatchesMap[patchSize] || nrOfPatchesMap.medium, nrOfPatches = nrOfPatchesList[nrOfPatchesIdx], desiredPatchSize = Math.floor(wideSide / nrOfPatches);
function findPatchSizeForDivisors(divisors) {
for(var i = 0, found = divisors[Math.floor(divisors.length / 2)]; i < divisors.length - 1 && divisors[i] < desiredPatchSize;)i++;
return (i > 0 && (found = Math.abs(divisors[i] - desiredPatchSize) > Math.abs(divisors[i - 1] - desiredPatchSize) ? divisors[i - 1] : divisors[i]), desiredPatchSize / found < nrOfPatchesList[nrOfPatchesIdx + 1] / nrOfPatchesList[nrOfPatchesIdx] && desiredPatchSize / found > nrOfPatchesList[nrOfPatchesIdx - 1] / nrOfPatchesList[nrOfPatchesIdx]) ? {
x: found,
y: found
} : null;
}
return (optimalPatchSize = findPatchSizeForDivisors(common)) || (optimalPatchSize = findPatchSizeForDivisors(_computeDivisors(wideSide))) || (optimalPatchSize = findPatchSizeForDivisors(_computeDivisors(desiredPatchSize * nrOfPatches))), optimalPatchSize;
}
var _dimensionsConverters = {
top: function(dimension, context) {
return "%" === dimension.unit ? Math.floor(context.height * (dimension.value / 100)) : null;
},
right: function(dimension, context) {
return "%" === dimension.unit ? Math.floor(context.width - context.width * (dimension.value / 100)) : null;
},
bottom: function(dimension, context) {
return "%" === dimension.unit ? Math.floor(context.height - context.height * (dimension.value / 100)) : null;
},
left: function(dimension, context) {
return "%" === dimension.unit ? Math.floor(context.width * (dimension.value / 100)) : null;
}
};
function computeImageArea(inputWidth, inputHeight, area) {
var context = {
width: inputWidth,
height: inputHeight
}, parsedArea = Object.keys(area).reduce(function(result, key) {
var value, parsed = {
value: parseFloat(value = area[key]),
unit: (value.indexOf("%"), value.length, "%")
}, calculated = _dimensionsConverters[key](parsed, context);
return result[key] = calculated, result;
}, {});
return {
sx: parsedArea.left,
sy: parsedArea.top,
sw: parsedArea.right - parsedArea.left,
sh: parsedArea.bottom - parsedArea.top
};
}
/***/ },
/* 9 */ /***/ function(module1, __webpack_exports__, __webpack_require__) {
"use strict";
// TODO: XYPosition should be an XYObject, but that breaks XYDefinition, which breaks drawPath() below.
// XYDefinition tells us which component of a given array or object is the "X" and which is the "Y".
// Usually this is 0 for X and 1 for Y, but might be used as 'x' for x and 'y' for Y.
/* harmony default export */ __webpack_exports__.a = {
drawRect: function(pos, size, ctx, style) {
ctx.strokeStyle = style.color, ctx.fillStyle = style.color, ctx.lineWidth = style.lineWidth || 1, ctx.beginPath(), ctx.strokeRect(pos.x, pos.y, size.x, size.y);
},
drawPath: function(path, def, ctx, style) {
ctx.strokeStyle = style.color, ctx.fillStyle = style.color, ctx.lineWidth = style.lineWidth, ctx.beginPath(), ctx.moveTo(path[0][def.x], path[0][def.y]);
for(var j = 1; j < path.length; j++)ctx.lineTo(path[j][def.x], path[j][def.y]);
ctx.closePath(), ctx.stroke();
},
drawImage: function(imageData, size, ctx) {
var canvasData = ctx.getImageData(0, 0, size.x, size.y), data = canvasData.data, canvasDataPos = data.length, imageDataPos = imageData.length;
if (canvasDataPos / imageDataPos != 4) return !1;
for(; imageDataPos--;){
var value = imageData[imageDataPos];
data[--canvasDataPos] = 255, data[--canvasDataPos] = value, data[--canvasDataPos] = value, data[--canvasDataPos] = value;
}
return ctx.putImageData(canvasData, 0, 0), !0;
}
};
/***/ },
/* 10 */ /***/ function(module1, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony default export */ __webpack_exports__.a = {
init: function(arr, val) {
for(// arr.fill(val);
var l = arr.length; l--;)arr[l] = val;
},
/**
* Shuffles the content of an array
*/ shuffle: function(arr) {
for(var i = arr.length - 1; i >= 0; i--){
var j = Math.floor(Math.random() * i), x = arr[i];
arr[i] = arr[j], arr[j] = x;
}
return arr;
},
toPointList: function(arr) {
var rows = arr.reduce(function(p, n) {
var row = "[".concat(n.join(","), "]");
return p.push(row), p;
}, []);
return "[".concat(rows.join(",\r\n"), "]");
},
/**
* returns the elements which's score is bigger than the threshold
*/ threshold: function(arr, _threshold, scoreFunc) {
return arr.reduce(function(prev, next) {
return scoreFunc.apply(arr, [
next
]) >= _threshold && prev.push(next), prev;
}, []);
},
maxIndex: function(arr) {
for(var max = 0, i = 0; i < arr.length; i++)arr[i] > arr[max] && (max = i);
return max;
},
max: function(arr) {
for(var max = 0, i = 0; i < arr.length; i++)arr[i] > max && (max = arr[i]);
return max;
},
sum: function(arr) {
for(var length = arr.length, sum = 0; length--;)sum += arr[length];
return sum;
}
};
/***/ },
/* 11 */ /***/ function(module1, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony import */ var _babel_runtime_helpers_slicedToArray__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(83), _babel_runtime_helpers_slicedToArray__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/ __webpack_require__.n(_babel_runtime_helpers_slicedToArray__WEBPACK_IMPORTED_MODULE_0__), _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(3), _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/ __webpack_require__.n(_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_1__), _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(4), _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/ __webpack_require__.n(_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_2__), _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(0), _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/ __webpack_require__.n(_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_3__), gl_vec2__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(7), _cv_utils__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(8), _array_helper__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(10), vec2 = {
clone: gl_vec2__WEBPACK_IMPORTED_MODULE_4__.clone
};
function assertNumberPositive(val) {
if (val < 0) throw Error("expected positive number, received ".concat(val));
}
/* harmony default export */ __webpack_exports__.a = /*#__PURE__*/ function() {
// Represents a basic image combining the data and size. In addition, some methods for
// manipulation are contained within.
function ImageWrapper(size, data) {
var ArrayType = arguments.length > 2 && void 0 !== arguments[2] ? arguments[2] : Uint8Array, initialize = arguments.length > 3 ? arguments[3] : void 0;
_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_1___default()(this, ImageWrapper), _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_3___default()(this, "data", void 0), _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_3___default()(this, "size", void 0), _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_3___default()(this, "indexMapping", void 0), data ? this.data = data : (this.data = new ArrayType(size.x * size.y), initialize && _array_helper__WEBPACK_IMPORTED_MODULE_6__./* default */ a.init(this.data, 0)), this.size = size;
} // tests if a position is within the image, extended out by a border on each side
return _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_2___default()(ImageWrapper, [
{
key: "inImageWithBorder",
value: function(imgRef) {
var border = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : 0;
// TODO: this doesn't make much sense to me, why does it go negative? Tests are not affected by
// returning false, but the whole code_128 reader blows up when i throw on negative imgRef.
// assertNumberPositive(imgRef.x);
// assertNumberPositive(imgRef.y);
return assertNumberPositive(border), imgRef.x >= 0 && imgRef.y >= 0 && imgRef.x < this.size.x + 2 * border && imgRef.y < this.size.y + 2 * border;
}
},
{
key: "subImageAsCopy",
value: function(imageWrapper, from) {
assertNumberPositive(from.x), assertNumberPositive(from.y);
for(var _imageWrapper$size = imageWrapper.size, sizeX = _imageWrapper$size.x, sizeY = _imageWrapper$size.y, x = 0; x < sizeX; x++)for(var y = 0; y < sizeY; y++)// eslint-disable-next-line no-param-reassign
imageWrapper.data[y * sizeX + x] = this.data[(from.y + y) * this.size.x + from.x + x];
return imageWrapper; // TODO: this function really probably should call into ImageWrapper somewhere to make
// sure that all of it's parameters are set properly, something like
// ImageWrapper.UpdateFrom()
// that might take a provided data and size, and make sure there's no invalid indexMapping
// hanging around, and such.
}
},
{
key: "get",
value: function(x, y) {
return this.data[y * this.size.x + x];
}
},
{
key: "getSafe",
value: function(x, y) {
// cache indexMapping because if we're using it once, we'll probably need it a bunch more
// too
if (!this.indexMapping) {
this.indexMapping = {
x: [],
y: []
};
for(var i = 0; i < this.size.x; i++)this.indexMapping.x[i] = i, this.indexMapping.x[i + this.size.x] = i;
for(var _i = 0; _i < this.size.y; _i++)this.indexMapping.y[_i] = _i, this.indexMapping.y[_i + this.size.y] = _i;
}
return this.data[this.indexMapping.y[y + this.size.y] * this.size.x + this.indexMapping.x[x + this.size.x]];
}
},
{
key: "set",
value: function(x, y, value) {
return this.data[y * this.size.x + x] = value, delete this.indexMapping, this;
}
},
{
key: "zeroBorder",
value: function() {
for(var _this$size = this.size, width = _this$size.x, height = _this$size.y, i = 0; i < width; i++)// eslint-disable-next-line no-multi-assign
this.data[i] = this.data[(height - 1) * width + i] = 0;
for(var _i2 = 1; _i2 < height - 1; _i2++)// eslint-disable-next-line no-multi-assign
this.data[_i2 * width] = this.data[_i2 * width + (width - 1)] = 0;
return delete this.indexMapping, this;
}
},
{
key: "moments",
value: function(labelCount) {
var x, y, val, ysq, i, label, mu11, x_, y_, tmp, data = this.data, height = this.size.y, width = this.size.x, labelSum = [], result = [], PI = Math.PI, PI_4 = PI / 4;
if (labelCount <= 0) return result;
for(i = 0; i < labelCount; i++)labelSum[i] = {
m00: 0,
m01: 0,
m10: 0,
m11: 0,
m02: 0,
m20: 0,
theta: 0,
rad: 0
};
for(y = 0; y < height; y++)for(x = 0, ysq = y * y; x < width; x++)(val = data[y * width + x]) > 0 && (label = labelSum[val - 1], label.m00 += 1, label.m01 += y, label.m10 += x, label.m11 += x * y, label.m02 += ysq, label.m20 += x * x);
for(i = 0; i < labelCount; i++)isNaN((label = labelSum[i]).m00) || 0 === label.m00 || (x_ = label.m10 / label.m00, y_ = label.m01 / label.m00, mu11 = label.m11 / label.m00 - x_ * y_, tmp = 0.5 * Math.atan(tmp = (label.m02 / label.m00 - y_ * y_ - (label.m20 / label.m00 - x_ * x_)) / (2 * mu11)) + (mu11 >= 0 ? PI_4 : -PI_4) + PI, label.theta = (180 * tmp / PI + 90) % 180 - 90, label.theta < 0 && (label.theta += 180), label.rad = tmp > PI ? tmp - PI : tmp, label.vec = vec2.clone([
Math.cos(tmp),
Math.sin(tmp)
]), result.push(label));
return result;
}
},
{
key: "getAsRGBA",
value: function() {
for(var scale = arguments.length > 0 && void 0 !== arguments[0] ? arguments[0] : 1.0, ret = new Uint8ClampedArray(4 * this.size.x * this.size.y), y = 0; y < this.size.y; y++)for(var x = 0; x < this.size.x; x++){
var pixel = y * this.size.x + x, current = this.get(x, y) * scale;
ret[4 * pixel + 0] = current, ret[4 * pixel + 1] = current, ret[4 * pixel + 2] = current, ret[4 * pixel + 3] = 255;
}
return ret;
}
},
{
key: "show",
value: function(canvas) {
var scale = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : 1.0, ctx = canvas.getContext("2d");
if (!ctx) throw Error("Unable to get canvas context");
var frame = ctx.getImageData(0, 0, canvas.width, canvas.height), data = this.getAsRGBA(scale);
canvas.width = this.size.x, canvas.height = this.size.y;
var newFrame = new ImageData(data, frame.width, frame.height);
ctx.putImageData(newFrame, 0, 0);
}
},
{
key: "overlay",
value: function(canvas, inScale, from) {
var adjustedScale = inScale < 0 || inScale > 360 ? 360 : inScale, hsv = [
0,
1,
1
], rgb = [
0,
0,
0
], whiteRgb = [
255,
255,
255
], blackRgb = [
0,
0,
0
], result = [], ctx = canvas.getContext("2d");
if (!ctx) throw Error("Unable to get canvas context");
for(var frame = ctx.getImageData(from.x, from.y, this.size.x, this.size.y), data = frame.data, length = this.data.length; length--;){
hsv[0] = this.data[length] * adjustedScale, result = hsv[0] <= 0 ? whiteRgb : hsv[0] >= 360 ? blackRgb : Object(_cv_utils__WEBPACK_IMPORTED_MODULE_5__./* hsv2rgb */ g)(hsv, rgb);
var pos = 4 * length, _result = result, _result2 = _babel_runtime_helpers_slicedToArray__WEBPACK_IMPORTED_MODULE_0___default()(_result, 3);
data[pos] = _result2[0], data[pos + 1] = _result2[1], data[pos + 2] = _result2[2], data[pos + 3] = 255;
}
ctx.putImageData(frame, from.x, from.y);
}
}
]), ImageWrapper;
}();
/***/ },
/* 12 */ /***/ function(module1, exports1, __webpack_require__) {
module1.exports = __webpack_require__(228);
/***/ },
/* 13 */ /***/ function(module1, exports1, __webpack_require__) {
var superPropBase = __webpack_require__(227);
function _get(target, property, receiver) {
return "undefined" != typeof Reflect && Reflect.get ? module1.exports = _get = Reflect.get : module1.exports = _get = function(target, property, receiver) {
var base = superPropBase(target, property);
if (base) {
var desc = Object.getOwnPropertyDescriptor(base, property);
return desc.get ? desc.get.call(receiver) : desc.value;
}
}, module1.exports.default = module1.exports, module1.exports.__esModule = !0, _get(target, property, receiver || target);
}
module1.exports = _get, module1.exports.default = module1.exports, module1.exports.__esModule = !0;
/***/ },
/* 14 */ /***/ function(module1, exports1) {
module1.exports = /**
* 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(value) {
var type = typeof value;
return null != value && ("object" == type || "function" == type);
};
/***/ },
/* 15 */ /***/ function(module1, exports1) {
module1.exports = Array.isArray;
/***/ },
/* 16 */ /***/ function(module1, exports1, __webpack_require__) {
var baseMerge = __webpack_require__(90);
module1.exports = __webpack_require__(145)(function(object, source, srcIndex) {
baseMerge(object, source, srcIndex);
});
/***/ },
/* 17 */ /***/ function(module1, exports1, __webpack_require__) {
var freeGlobal = __webpack_require__(45), freeSelf = "object" == typeof self && self && self.Object === Object && self;
module1.exports = freeGlobal || freeSelf || Function("return this")();
/***/ },
/* 18 */ /***/ function(module1, exports1) {
module1.exports = /**
* 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(value) {
return null != value && "object" == typeof value;
};
/***/ },
/* 19 */ /***/ function(module1, exports1) {
function _typeof(obj) {
return "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? module1.exports = _typeof = function(obj) {
return typeof obj;
} : module1.exports = _typeof = function(obj) {
return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
}, module1.exports.default = module1.exports, module1.exports.__esModule = !0, _typeof(obj);
}
module1.exports = _typeof, module1.exports.default = module1.exports, module1.exports.__esModule = !0;
/***/ },
/* 20 */ /***/ function(module1, exports1) {
function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
try {
var info = gen[key](arg), value = info.value;
} catch (error) {
reject(error);
return;
}
info.done ? resolve(value) : Promise.resolve(value).then(_next, _throw);
}
module1.exports = function(fn) {
return function() {
var self1 = this, args = arguments;
return new Promise(function(resolve, reject) {
var gen = fn.apply(self1, args);
function _next(value) {
asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
}
function _throw(err) {
asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
}
_next(void 0);
});
};
}, module1.exports.default = module1.exports, module1.exports.__esModule = !0;
/***/ },
/* 21 */ /***/ function(module1, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony default export */ __webpack_exports__.a = {
searchDirections: [
[
0,
1
],
[
1,
1
],
[
1,
0
],
[
1,
-1
],
[
0,
-1
],
[
-1,
-1
],
[
-1,
0
],
[
-1,
1
]
],
create: function(imageWrapper, labelWrapper) {
var pos, imageData = imageWrapper.data, labelData = labelWrapper.data, searchDirections = this.searchDirections, width = imageWrapper.size.x;
function _trace(current, color, label, edgelabel) {
var i, y, x;
for(i = 0; i < 7; i++){
if (imageData[pos = (y = current.cy + searchDirections[current.dir][0]) * width + (x = current.cx + searchDirections[current.dir][1])] === color && (0 === labelData[pos] || labelData[pos] === label)) return labelData[pos] = label, current.cy = y, current.cx = x, !0;
0 === labelData[pos] && (labelData[pos] = edgelabel), current.dir = (current.dir + 1) % 8;
}
return !1;
}
function vertex2D(x, y, dir) {
return {
dir: dir,
x: x,
y: y,
next: null,
prev: null
};
}
return {
trace: function(current, color, label, edgelabel) {
return _trace(current, color, label, edgelabel);
},
contourTracing: function(sy, sx, label, color, edgelabel) {
return function(sy, sx, label, color, edgelabel) {
var Cv, P, ldir, Fv = null, current = {
cx: sx,
cy: sy,
dir: 0
};
if (_trace(current, color, label, edgelabel)) {
Cv = Fv = vertex2D(sx, sy, current.dir), ldir = current.dir, (P = vertex2D(current.cx, current.cy, 0)).prev = Cv, Cv.next = P, P.next = null, Cv = P;
do current.dir = (current.dir + 6) % 8, _trace(current, color, label, edgelabel), ldir !== current.dir ? (Cv.dir = current.dir, (P = vertex2D(current.cx, current.cy, 0)).prev = Cv, Cv.next = P, P.next = null, Cv = P) : (Cv.dir = ldir, Cv.x = current.cx, Cv.y = current.cy), ldir = current.dir;
while (current.cx !== sx || current.cy !== sy)
Fv.prev = Cv.prev, Cv.prev.next = Fv;
}
return Fv;
}(sy, sx, label, color, edgelabel);
}
};
}
};
/***/ },
/* 22 */ /***/ function(module1, exports1, __webpack_require__) {
var Symbol1 = __webpack_require__(27), getRawTag = __webpack_require__(103), objectToString = __webpack_require__(104), symToStringTag = Symbol1 ? Symbol1.toStringTag : void 0;
module1.exports = /**
* The base implementation of `getTag` without fallbacks for buggy environments.
*
* @private
* @param {*} value The value to query.
* @returns {string} Returns the `toStringTag`.
*/ function(value) {
return null == value ? void 0 === value ? "[object Undefined]" : "[object Null]" : symToStringTag && symToStringTag in Object(value) ? getRawTag(value) : objectToString(value);
};
/***/ },
/* 23 */ /***/ function(module1, __webpack_exports__, __webpack_require__) {
"use strict";
/* WEBPACK VAR INJECTION */ (function(global) {
/* harmony import */ var _config, _currentImageWrapper, _skelImageWrapper, _subImageWrapper, _labelImageWrapper, _patchGrid, _patchLabelGrid, _imageToPatchGrid, _binaryImageWrapper, _patchSize, _inputImageWrapper, _skeletonizer, gl_vec2__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(7), gl_mat2__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(34), _common_image_wrapper__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(11), _common_cv_utils__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(8), _common_array_helper__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(10), _common_image_debug__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(9), _rasterizer__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(87), _tracer__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(21), _skeletonizer__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(88), _canvasContainer = {
ctx: {
binary: null
},
dom: {
binary: null
}
}, _numPatches = {
x: 0,
y: 0
};
/* harmony default export */ __webpack_exports__.a = {
init: function(inputImageWrapper, config) {
var skeletonImageData;
_config = config, _inputImageWrapper = inputImageWrapper, _currentImageWrapper = _config.halfSample ? new _common_image_wrapper__WEBPACK_IMPORTED_MODULE_2__./* default */ a({
// eslint-disable-next-line no-bitwise
x: _inputImageWrapper.size.x / 2 | 0,
// eslint-disable-next-line no-bitwise
y: _inputImageWrapper.size.y / 2 | 0
}) : _inputImageWrapper, _patchSize = Object(_common_cv_utils__WEBPACK_IMPORTED_MODULE_3__./* calculatePatchSize */ a)(_config.patchSize, _currentImageWrapper.size), _numPatches.x = _currentImageWrapper.size.x / _patchSize.x | 0, _numPatches.y = _currentImageWrapper.size.y / _patchSize.y | 0, _binaryImageWrapper = new _common_image_wrapper__WEBPACK_IMPORTED_MODULE_2__./* default */ a(_currentImageWrapper.size, void 0, Uint8Array, !1), _labelImageWrapper = new _common_image_wrapper__WEBPACK_IMPORTED_MODULE_2__./* default */ a(_patchSize, void 0, Array, !0), skeletonImageData = new ArrayBuffer(65536), _subImageWrapper = new _common_image_wrapper__WEBPACK_IMPORTED_MODULE_2__./* default */ a(_patchSize, new Uint8Array(skeletonImageData, 0, _patchSize.x * _patchSize.y)), _skelImageWrapper = new _common_image_wrapper__WEBPACK_IMPORTED_MODULE_2__./* default */ a(_patchSize, new Uint8Array(skeletonImageData, _patchSize.x * _patchSize.y * 3, _patchSize.x * _patchSize.y), void 0, !0), _skeletonizer = Object(_skeletonizer__WEBPACK_IMPORTED_MODULE_8__./* default */ a)("undefined" != typeof window ? window : "undefined" != typeof self ? self : global, {
size: _patchSize.x
}, skeletonImageData), _imageToPatchGrid = new _common_image_wrapper__WEBPACK_IMPORTED_MODULE_2__./* default */ a({
// eslint-disable-next-line no-bitwise
x: _currentImageWrapper.size.x / _subImageWrapper.size.x | 0,
// eslint-disable-next-line no-bitwise
y: _currentImageWrapper.size.y / _subImageWrapper.size.y | 0
}, void 0, Array, !0), _patchGrid = new _common_image_wrapper__WEBPACK_IMPORTED_MODULE_2__./* default */ a(_imageToPatchGrid.size, void 0, void 0, !0), _patchLabelGrid = new _common_image_wrapper__WEBPACK_IMPORTED_MODULE_2__./* default */ a(_imageToPatchGrid.size, void 0, Int32Array, !0), _config.useWorker || "undefined" == typeof document || (_canvasContainer.dom.binary = document.createElement("canvas"), _canvasContainer.dom.binary.className = "binaryBuffer", !0 === _config.debug.showCanvas && document.querySelector("#debug").appendChild(_canvasContainer.dom.binary), _canvasContainer.ctx.binary = _canvasContainer.dom.binary.getContext("2d"), _canvasContainer.dom.binary.width = _binaryImageWrapper.size.x, _canvasContainer.dom.binary.height = _binaryImageWrapper.size.y);
},
locate: function() {
_config.halfSample && Object(_common_cv_utils__WEBPACK_IMPORTED_MODULE_3__./* halfSample */ f)(_inputImageWrapper, _currentImageWrapper), Object(_common_cv_utils__WEBPACK_IMPORTED_MODULE_3__./* otsuThreshold */ i)(_currentImageWrapper, _binaryImageWrapper), _binaryImageWrapper.zeroBorder(), _config.debug.showCanvas && _binaryImageWrapper.show(_canvasContainer.dom.binary, 255);
var patchesFound = /**
* Iterate over the entire image
* extract patches
*/ function() {
var x, y, i, j, x1, y1, moments, rasterResult, patch, patchesFound = [];
for(i = 0; i < _numPatches.x; i++)for(j = 0; j < _numPatches.y; j++)x = x1 = _subImageWrapper.size.x * i, y = y1 = _subImageWrapper.size.y * j, _binaryImageWrapper.subImageAsCopy(_subImageWrapper, Object(_common_cv_utils__WEBPACK_IMPORTED_MODULE_3__./* imageRef */ h)(x, y)), _skeletonizer.skeletonize(), _config.debug.showSkeleton && _skelImageWrapper.overlay(_canvasContainer.dom.binary, 360, Object(_common_cv_utils__WEBPACK_IMPORTED_MODULE_3__./* imageRef */ h)(x, y)), _skelImageWrapper.zeroBorder(), _common_array_helper__WEBPACK_IMPORTED_MODULE_4__./* default */ a.init(_labelImageWrapper.data, 0), rasterResult = _rasterizer__WEBPACK_IMPORTED_MODULE_6__./* default */ a.create(_skelImageWrapper, _labelImageWrapper).rasterize(0), _config.debug.showLabels && _labelImageWrapper.overlay(_canvasContainer.dom.binary, Math.floor(360 / rasterResult.count), {
x: x1,
y: y1
}), moments = _labelImageWrapper.moments(rasterResult.count), patchesFound = patchesFound.concat(/**
* Extracts and describes those patches which seem to contain a barcode pattern
* @param {Array} moments
* @param {Object} patchPos,
* @param {Number} x
* @param {Number} y
* @returns {Array} list of patches
*/ function(moments, patchPos, x, y) {
var k, avg, matchingMoments, patch, eligibleMoments = [], patchesFound = [], minComponentWeight = Math.ceil(_patchSize.x / 3);
if (moments.length >= 2) {
// only collect moments which's area covers at least minComponentWeight pixels.
for(k = 0; k < moments.length; k++)moments[k].m00 > minComponentWeight && eligibleMoments.push(moments[k]);
// if at least 2 moments are found which have at least minComponentWeights covered
if (eligibleMoments.length >= 2) {
for(k = 0, matchingMoments = /**
* Find similar moments (via cluster)
* @param {Object} moments
*/ function(moments) {
var clusters = Object(_common_cv_utils__WEBPACK_IMPORTED_MODULE_3__./* cluster */ b)(moments, 0.9), topCluster = Object(_common_cv_utils__WEBPACK_IMPORTED_MODULE_3__./* topGeneric */ j)(clusters, 1, function(e) {
return e.getPoints().length;
}), points = [], result = [];
if (1 === topCluster.length) {
points = topCluster[0].item.getPoints();
for(var i = 0; i < points.length; i++)result.push(points[i].point);
}
return result;
}(eligibleMoments), avg = 0; k < matchingMoments.length; k++)avg += matchingMoments[k].rad;
// Only two of the moments are allowed not to fit into the equation
matchingMoments.length > 1 && matchingMoments.length >= eligibleMoments.length / 4 * 3 && matchingMoments.length > moments.length / 4 && (avg /= matchingMoments.length, patch = {
index: patchPos[1] * _numPatches.x + patchPos[0],
pos: {
x: x,
y: y
},
box: [
gl_vec2__WEBPACK_IMPORTED_MODULE_0__.clone([
x,
y
]),
gl_vec2__WEBPACK_IMPORTED_MODULE_0__.clone([
x + _subImageWrapper.size.x,
y
]),
gl_vec2__WEBPACK_IMPORTED_MODULE_0__.clone([
x + _subImageWrapper.size.x,
y + _subImageWrapper.size.y
]),
gl_vec2__WEBPACK_IMPORTED_MODULE_0__.clone([
x,
y + _subImageWrapper.size.y
])
],
moments: matchingMoments,
rad: avg,
vec: gl_vec2__WEBPACK_IMPORTED_MODULE_0__.clone([
Math.cos(avg),
Math.sin(avg)
])
}, patchesFound.push(patch));
}
}
return patchesFound;
}(moments, [
i,
j
], x1, y1));
if (_config.debug.showFoundPatches) for(i = 0; i < patchesFound.length; i++)patch = patchesFound[i], _common_image_debug__WEBPACK_IMPORTED_MODULE_5__./* default */ a.drawRect(patch.pos, _subImageWrapper.size, _canvasContainer.ctx.binary, {
color: "#99ff00",
lineWidth: 2
});
return patchesFound;
}(); // return unless 5% or more patches are found
if (patchesFound.length < _numPatches.x * _numPatches.y * 0.05) return null;
// rasterrize area by comparing angular similarity;
var maxLabel = /**
* finds patches which are connected and share the same orientation
* @param {Object} patchesFound
*/ function(patchesFound) {
var j, patch, label = 0, currIdx = 0, hsv = [
0,
1,
1
], rgb = [
0,
0,
0
];
for(_common_array_helper__WEBPACK_IMPORTED_MODULE_4__./* default */ a.init(_patchGrid.data, 0), _common_array_helper__WEBPACK_IMPORTED_MODULE_4__./* default */ a.init(_patchLabelGrid.data, 0), _common_array_helper__WEBPACK_IMPORTED_MODULE_4__./* default */ a.init(_imageToPatchGrid.data, null), j = 0; j < patchesFound.length; j++)patch = patchesFound[j], _imageToPatchGrid.data[patch.index] = patch, _patchGrid.data[patch.index] = 1;
// rasterize the patches found to determine area
for(_patchGrid.zeroBorder(); (currIdx = function() {
var i;
for(i = 0; i < _patchLabelGrid.data.length; i++)if (0 === _patchLabelGrid.data[i] && 1 === _patchGrid.data[i]) return i;
return _patchLabelGrid.length;
}()) < _patchLabelGrid.data.length;)label++, function trace(currentIdx) {
var x, y, currentPatch, idx, dir, current = {
x: currentIdx % _patchLabelGrid.size.x,
y: currentIdx / _patchLabelGrid.size.x | 0
};
if (currentIdx < _patchLabelGrid.data.length) for(dir = 0, currentPatch = _imageToPatchGrid.data[currentIdx], _patchLabelGrid.data[currentIdx] = label; dir < _tracer__WEBPACK_IMPORTED_MODULE_7__./* default */ a.searchDirections.length; dir++){
if (y = current.y + _tracer__WEBPACK_IMPORTED_MODULE_7__./* default */ a.searchDirections[dir][0], x = current.x + _tracer__WEBPACK_IMPORTED_MODULE_7__./* default */ a.searchDirections[dir][1], idx = y * _patchLabelGrid.size.x + x, 0 === _patchGrid.data[idx]) {
_patchLabelGrid.data[idx] = Number.MAX_VALUE; // eslint-disable-next-line no-continue
continue;
}
0 === _patchLabelGrid.data[idx] && Math.abs(gl_vec2__WEBPACK_IMPORTED_MODULE_0__.dot(_imageToPatchGrid.data[idx].vec, currentPatch.vec)) > 0.95 && trace(idx);
}
} // prepare for finding the right patches
(currIdx);
// draw patch-labels if requested
if (_config.debug.showPatchLabels) for(j = 0; j < _patchLabelGrid.data.length; j++)_patchLabelGrid.data[j] > 0 && _patchLabelGrid.data[j] <= label && (patch = _imageToPatchGrid.data[j], hsv[0] = _patchLabelGrid.data[j] / (label + 1) * 360, Object(_common_cv_utils__WEBPACK_IMPORTED_MODULE_3__./* hsv2rgb */ g)(hsv, rgb), _common_image_debug__WEBPACK_IMPORTED_MODULE_5__./* default */ a.drawRect(patch.pos, _subImageWrapper.size, _canvasContainer.ctx.binary, {
color: "rgb(".concat(rgb.join(","), ")"),
lineWidth: 2
}));
return label;
}(patchesFound);
if (maxLabel < 1) return null;
// search for area with the most patches (biggest connected area)
var topLabels = /**
* Finds those connected areas which contain at least 6 patches
* and returns them ordered DESC by the number of contained patches
* @param {Number} maxLabel
*/ function(maxLabel) {
var i, sum, labelHist = [];
for(i = 0; i < maxLabel; i++)labelHist.push(0);
for(sum = _patchLabelGrid.data.length; sum--;)_patchLabelGrid.data[sum] > 0 && labelHist[_patchLabelGrid.data[sum] - 1]++;
return (labelHist = labelHist.map(function(val, idx) {
return {
val: val,
label: idx + 1
};
})).sort(function(a, b) {
return b.val - a.val;
}), labelHist.filter(function(el) {
return el.val >= 5;
});
}(maxLabel);
return 0 === topLabels.length ? null : /**
*
*/ function(topLabels, maxLabel) {
var i, j, sum, patch, box, patches = [], boxes = [], hsv = [
0,
1,
1
], rgb = [
0,
0,
0
];
for(i = 0; i < topLabels.length; i++){
for(sum = _patchLabelGrid.data.length, patches.length = 0; sum--;)_patchLabelGrid.data[sum] === topLabels[i].label && (patch = _imageToPatchGrid.data[sum], patches.push(patch));
if ((box = /**
* Creates a bounding box which encloses all the given patches
* @returns {Array} The minimal bounding box
*/ function(patches) {
var overAvg, i, j, patch, transMat, box, scale, minx = _binaryImageWrapper.size.x, miny = _binaryImageWrapper.size.y, maxx = -_binaryImageWrapper.size.x, maxy = -_binaryImageWrapper.size.y;
for(i = 0, overAvg = 0; i < patches.length; i++)overAvg += (patch = patches[i]).rad, _config.debug.showPatches && _common_image_debug__WEBPACK_IMPORTED_MODULE_5__./* default */ a.drawRect(patch.pos, _subImageWrapper.size, _canvasContainer.ctx.binary, {
color: "red"
});
for(overAvg /= patches.length, (overAvg = (180 * overAvg / Math.PI + 90) % 180 - 90) < 0 && (overAvg += 180), overAvg = (180 - overAvg) * Math.PI / 180, transMat = gl_mat2__WEBPACK_IMPORTED_MODULE_1__.copy(gl_mat2__WEBPACK_IMPORTED_MODULE_1__.create(), [
Math.cos(overAvg),
Math.sin(overAvg),
-Math.sin(overAvg),
Math.cos(overAvg)
]), i = 0; i < patches.length; i++){
for(j = 0, patch = patches[i]; j < 4; j++)gl_vec2__WEBPACK_IMPORTED_MODULE_0__.transformMat2(patch.box[j], patch.box[j], transMat);
_config.debug.boxFromPatches.showTransformed && _common_image_debug__WEBPACK_IMPORTED_MODULE_5__./* default */ a.drawPath(patch.box, {
x: 0,
y: 1
}, _canvasContainer.ctx.binary, {
color: "#99ff00",
lineWidth: 2
});
} // find bounding box
for(i = 0; i < patches.length; i++)for(j = 0, patch = patches[i]; j < 4; j++)patch.box[j][0] < minx && (minx = patch.box[j][0]), patch.box[j][0] > maxx && (maxx = patch.box[j][0]), patch.box[j][1] < miny && (miny = patch.box[j][1]), patch.box[j][1] > maxy && (maxy = patch.box[j][1]);
for(box = [
[
minx,
miny
],
[
maxx,
miny
],
[
maxx,
maxy
],
[
minx,
maxy
]
], _config.debug.boxFromPatches.showTransformedBox && _common_image_debug__WEBPACK_IMPORTED_MODULE_5__./* default */ a.drawPath(box, {
x: 0,
y: 1
}, _canvasContainer.ctx.binary, {
color: "#ff0000",
lineWidth: 2
}), scale = _config.halfSample ? 2 : 1, transMat = gl_mat2__WEBPACK_IMPORTED_MODULE_1__.invert(transMat, transMat), j = 0; j < 4; j++)gl_vec2__WEBPACK_IMPORTED_MODULE_0__.transformMat2(box[j], box[j], transMat);
for(_config.debug.boxFromPatches.showBB && _common_image_debug__WEBPACK_IMPORTED_MODULE_5__./* default */ a.drawPath(box, {
x: 0,
y: 1
}, _canvasContainer.ctx.binary, {
color: "#ff0000",
lineWidth: 2
}), j = 0; j < 4; j++)gl_vec2__WEBPACK_IMPORTED_MODULE_0__.scale(box[j], box[j], scale);
return box;
}(patches)) && (boxes.push(box), _config.debug.showRemainingPatchLabels)) for(j = 0; j < patches.length; j++)patch = patches[j], hsv[0] = topLabels[i].label / (maxLabel + 1) * 360, Object(_common_cv_utils__WEBPACK_IMPORTED_MODULE_3__./* hsv2rgb */ g)(hsv, rgb), _common_image_debug__WEBPACK_IMPORTED_MODULE_5__./* default */ a.drawRect(patch.pos, _subImageWrapper.size, _canvasContainer.ctx.binary, {
color: "rgb(".concat(rgb.join(","), ")"),
lineWidth: 2
});
}
return boxes;
}(topLabels, maxLabel);
},
checkImageConstraints: function(inputStream, config) {
var patchSize, area, width = inputStream.getWidth(), height = inputStream.getHeight(), thisHalfSample = config.halfSample ? 0.5 : 1;
inputStream.getConfig().area && (area = Object(_common_cv_utils__WEBPACK_IMPORTED_MODULE_3__./* computeImageArea */ d)(width, height, inputStream.getConfig().area), inputStream.setTopRight({
x: area.sx,
y: area.sy
}), inputStream.setCanvasSize({
x: width,
y: height
}), width = area.sw, height = area.sh);
var size = {
x: Math.floor(width * thisHalfSample),
y: Math.floor(height * thisHalfSample)
};
if (patchSize = Object(_common_cv_utils__WEBPACK_IMPORTED_MODULE_3__./* calculatePatchSize */ a)(config.patchSize, size), console.log("Patch-Size: ".concat(JSON.stringify(patchSize))), inputStream.setWidth(Math.floor(Math.floor(size.x / patchSize.x) * (1 / thisHalfSample) * patchSize.x)), inputStream.setHeight(Math.floor(Math.floor(size.y / patchSize.y) * (1 / thisHalfSample) * patchSize.y)), inputStream.getWidth() % patchSize.x == 0 && inputStream.getHeight() % patchSize.y == 0) return !0;
throw Error("Image dimensions do not comply with the current settings: Width (".concat(width, " )and height (").concat(height, ") must a multiple of ").concat(patchSize.x));
}
};
/* WEBPACK VAR INJECTION */ }).call(this, __webpack_require__(46));
/***/ },
/* 24 */ /***/ function(module1, exports1, __webpack_require__) {
var listCacheClear = __webpack_require__(92), listCacheDelete = __webpack_require__(93), listCacheGet = __webpack_require__(94), listCacheHas = __webpack_require__(95), listCacheSet = __webpack_require__(96);
/**
* Creates an list cache object.
*
* @private
* @constructor
* @param {Array} [entries] The key-value pairs to cache.
*/ function ListCache(entries) {
var index = -1, length = null == entries ? 0 : entries.length;
for(this.clear(); ++index < length;){
var entry = entries[index];
this.set(entry[0], entry[1]);
}
} // Add methods to `ListCache`.
ListCache.prototype.clear = listCacheClear, ListCache.prototype.delete = listCacheDelete, ListCache.prototype.get = listCacheGet, ListCache.prototype.has = listCacheHas, ListCache.prototype.set = listCacheSet, module1.exports = ListCache;
/***/ },
/* 25 */ /***/ function(module1, exports1, __webpack_require__) {
var eq = __webpack_require__(26);
module1.exports = /**
* 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(array, key) {
for(var length = array.length; length--;)if (eq(array[length][0], key)) return length;
return -1;
};
/***/ },
/* 26 */ /***/ function(module1, exports1) {
module1.exports = /**
* 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(value, other) {
return value === other || value != value && other != other;
};
/***/ },
/* 27 */ /***/ function(module1, exports1, __webpack_require__) {
module1.exports = __webpack_require__(17).Symbol;
/***/ },
/* 28 */ /***/ function(module1, exports1, __webpack_require__) {
module1.exports = __webpack_require__(35)(Object, "create");
/***/ },
/* 29 */ /***/ function(module1, exports1, __webpack_require__) {
var isKeyable = __webpack_require__(117);
module1.exports = /**
* 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(map, key) {
var data = map.__data__;
return isKeyable(key) ? data["string" == typeof key ? "string" : "hash"] : data.map;
};
/***/ },
/* 30 */ /***/ function(module1, exports1, __webpack_require__) {
var baseIsArguments = __webpack_require__(132), isObjectLike = __webpack_require__(18), objectProto = Object.prototype, hasOwnProperty = objectProto.hasOwnProperty, propertyIsEnumerable = objectProto.propertyIsEnumerable;
module1.exports = baseIsArguments(function() {
return arguments;
}()) ? baseIsArguments : function(value) {
return isObjectLike(value) && hasOwnProperty.call(value, "callee") && !propertyIsEnumerable.call(value, "callee");
};
/***/ },
/* 31 */ /***/ function(module1, exports1) {
/** Used to detect unsigned integer values. */ var reIsUint = /^(?:0|[1-9]\d*)$/;
module1.exports = /**
* 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(value, length) {
var type = typeof value;
return !!(length = null == length ? 9007199254740991 : length) && ("number" == type || "symbol" != type && reIsUint.test(value)) && value > -1 && value % 1 == 0 && value < length;
};
/***/ },
/* 32 */ /***/ function(module1, exports1, __webpack_require__) {
var isArray = __webpack_require__(15), isKey = __webpack_require__(232), stringToPath = __webpack_require__(233), toString = __webpack_require__(236);
module1.exports = /**
* 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(value, object) {
return isArray(value) ? value : isKey(value, object) ? [
value
] : stringToPath(toString(value));
};
/***/ },
/* 33 */ /***/ function(module1, exports1, __webpack_require__) {
var arrayWithoutHoles = __webpack_require__(224), iterableToArray = __webpack_require__(225), unsupportedIterableToArray = __webpack_require__(60), nonIterableSpread = __webpack_require__(226);
module1.exports = function(arr) {
return arrayWithoutHoles(arr) || iterableToArray(arr) || unsupportedIterableToArray(arr) || nonIterableSpread();
}, module1.exports.default = module1.exports, module1.exports.__esModule = !0;
/***/ },
/* 34 */ /***/ function(module1, exports1, __webpack_require__) {
module1.exports = {
determinant: __webpack_require__(251),
transpose: __webpack_require__(252),
multiply: __webpack_require__(253),
identity: __webpack_require__(254),
adjoint: __webpack_require__(255),
rotate: __webpack_require__(256),
invert: __webpack_require__(257),
create: __webpack_require__(258),
scale: __webpack_require__(259),
copy: __webpack_require__(260),
frob: __webpack_require__(261),
ldu: __webpack_require__(262)
};
/***/ },
/* 35 */ /***/ function(module1, exports1, __webpack_require__) {
var baseIsNative = __webpack_require__(102), getValue = __webpack_require__(108);
module1.exports = /**
* 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(object, key) {
var value = getValue(object, key);
return baseIsNative(value) ? value : void 0;
};
/***/ },
/* 36 */ /***/ function(module1, exports1, __webpack_require__) {
var baseGetTag = __webpack_require__(22), isObject = __webpack_require__(14);
module1.exports = /**
* 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(value) {
if (!isObject(value)) return !1;
// 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 "[object Function]" == tag || "[object GeneratorFunction]" == tag || "[object AsyncFunction]" == tag || "[object Proxy]" == tag;
};
/***/ },
/* 37 */ /***/ function(module1, exports1, __webpack_require__) {
var defineProperty = __webpack_require__(49);
module1.exports = /**
* 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(object, key, value) {
"__proto__" == key && defineProperty ? defineProperty(object, key, {
configurable: !0,
enumerable: !0,
value: value,
writable: !0
}) : object[key] = value;
};
/***/ },
/* 38 */ /***/ function(module1, exports1) {
module1.exports = function(module1) {
return module1.webpackPolyfill || (module1.deprecate = function() {}, module1.paths = [], module1.children || (module1.children = []), Object.defineProperty(module1, "loaded", {
enumerable: !0,
get: function() {
return module1.l;
}
}), Object.defineProperty(module1, "id", {
enumerable: !0,
get: function() {
return module1.i;
}
}), module1.webpackPolyfill = 1), module1;
};
/***/ },
/* 39 */ /***/ function(module1, exports1, __webpack_require__) {
var isFunction = __webpack_require__(36), isLength = __webpack_require__(40);
module1.exports = /**
* 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(value) {
return null != value && isLength(value.length) && !isFunction(value);
};
/***/ },
/* 40 */ /***/ function(module1, exports1) {
module1.exports = /**
* 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(value) {
return "number" == typeof value && value > -1 && value % 1 == 0 && value <= 9007199254740991;
};
/***/ },
/* 41 */ /***/ function(module1, exports1) {
function _setPrototypeOf(o, p) {
return module1.exports = _setPrototypeOf = Object.setPrototypeOf || function(o, p) {
return o.__proto__ = p, o;
}, module1.exports.default = module1.exports, module1.exports.__esModule = !0, _setPrototypeOf(o, p);
}
module1.exports = _setPrototypeOf, module1.exports.default = module1.exports, module1.exports.__esModule = !0;
/***/ },
/* 42 */ /***/ function(module1, exports1, __webpack_require__) {
var baseGetTag = __webpack_require__(22), isObjectLike = __webpack_require__(18);
module1.exports = /**
* 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(value) {
return "symbol" == typeof value || isObjectLike(value) && "[object Symbol]" == baseGetTag(value);
};
/***/ },
/* 43 */ /***/ function(module1, exports1, __webpack_require__) {
var isSymbol = __webpack_require__(42), INFINITY = 1 / 0;
module1.exports = /**
* 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(value) {
if ("string" == typeof value || isSymbol(value)) return value;
var result = value + "";
return "0" == result && 1 / value == -INFINITY ? "-0" : result;
};
/***/ },
/* 44 */ /***/ function(module1, exports1, __webpack_require__) {
module1.exports = __webpack_require__(35)(__webpack_require__(17), "Map");
/***/ },
/* 45 */ /***/ function(module1, exports1, __webpack_require__) {
/* WEBPACK VAR INJECTION */ (function(global) {
module1.exports = "object" == typeof global && global && global.Object === Object && global;
/* WEBPACK VAR INJECTION */ }).call(this, __webpack_require__(46));
/***/ },
/* 46 */ /***/ function(module1, exports1) {
var g; // This works in non-strict mode
g = function() {
return this;
}();
try {
// This works if eval is allowed (see CSP)
g = g || Function("return this")();
} catch (e) {
// This works if the window reference is available
"object" == typeof window && (g = window);
} // g can still be undefined, but nothing to do about it...
// We return undefined, instead of nothing here, so it's
// easier to handle this case. if(!global) { ...}
module1.exports = g;
/***/ },
/* 47 */ /***/ function(module1, exports1, __webpack_require__) {
var mapCacheClear = __webpack_require__(109), mapCacheDelete = __webpack_require__(116), mapCacheGet = __webpack_require__(118), mapCacheHas = __webpack_require__(119), mapCacheSet = __webpack_require__(120);
/**
* 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 = null == entries ? 0 : entries.length;
for(this.clear(); ++index < length;){
var entry = entries[index];
this.set(entry[0], entry[1]);
}
} // Add methods to `MapCache`.
MapCache.prototype.clear = mapCacheClear, MapCache.prototype.delete = mapCacheDelete, MapCache.prototype.get = mapCacheGet, MapCache.prototype.has = mapCacheHas, MapCache.prototype.set = mapCacheSet, module1.exports = MapCache;
/***/ },
/* 48 */ /***/ function(module1, exports1, __webpack_require__) {
var baseAssignValue = __webpack_require__(37), eq = __webpack_require__(26);
module1.exports = /**
* 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(object, key, value) {
(void 0 === value || eq(object[key], value)) && (void 0 !== value || key in object) || baseAssignValue(object, key, value);
};
/***/ },
/* 49 */ /***/ function(module1, exports1, __webpack_require__) {
var getNative = __webpack_require__(35);
module1.exports = function() {
try {
var func = getNative(Object, "defineProperty");
return func({}, "", {}), func;
} catch (e) {}
}();
/***/ },
/* 50 */ /***/ function(module1, exports1, __webpack_require__) {
module1.exports = __webpack_require__(131)(Object.getPrototypeOf, Object);
/***/ },
/* 51 */ /***/ function(module1, exports1) {
/** Used for built-in method references. */ var objectProto = Object.prototype;
module1.exports = /**
* 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(value) {
var Ctor = value && value.constructor;
return value === ("function" == typeof Ctor && Ctor.prototype || objectProto);
};
/***/ },
/* 52 */ /***/ function(module1, exports1, __webpack_require__) {
/* WEBPACK VAR INJECTION */ (function(module1) {
var root = __webpack_require__(17), stubFalse = __webpack_require__(134), freeExports = exports1 && !exports1.nodeType && exports1, freeModule = freeExports && "object" == typeof module1 && module1 && !module1.nodeType && module1, Buffer = freeModule && freeModule.exports === freeExports ? root.Buffer : void 0;
module1.exports = (Buffer ? Buffer.isBuffer : void 0) || stubFalse;
/* WEBPACK VAR INJECTION */ }).call(this, __webpack_require__(38)(module1));
/***/ },
/* 53 */ /***/ function(module1, exports1, __webpack_require__) {
var baseIsTypedArray = __webpack_require__(136), baseUnary = __webpack_require__(137), nodeUtil = __webpack_require__(138), nodeIsTypedArray = nodeUtil && nodeUtil.isTypedArray;
module1.exports = nodeIsTypedArray ? baseUnary(nodeIsTypedArray) : baseIsTypedArray;
/***/ },
/* 54 */ /***/ function(module1, exports1) {
module1.exports = /**
* 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(object, key) {
if (("constructor" !== key || "function" != typeof object[key]) && "__proto__" != key) return object[key];
};
/***/ },
/* 55 */ /***/ function(module1, exports1, __webpack_require__) {
var baseAssignValue = __webpack_require__(37), eq = __webpack_require__(26), hasOwnProperty = Object.prototype.hasOwnProperty;
module1.exports = /**
* 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(object, key, value) {
var objValue = object[key];
hasOwnProperty.call(object, key) && eq(objValue, value) && (void 0 !== value || key in object) || baseAssignValue(object, key, value);
};
/***/ },
/* 56 */ /***/ function(module1, exports1, __webpack_require__) {
var arrayLikeKeys = __webpack_require__(141), baseKeysIn = __webpack_require__(143), isArrayLike = __webpack_require__(39);
module1.exports = /**
* 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(object) {
return isArrayLike(object) ? arrayLikeKeys(object, !0) : baseKeysIn(object);
};
/***/ },
/* 57 */ /***/ function(module1, exports1) {
module1.exports = /**
* This method returns the first argument it receives.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Util
* @param {*} value Any value.
* @returns {*} Returns `value`.
* @example
*
* var object = { 'a': 1 };
*
* console.log(_.identity(object) === object);
* // => true
*/ function(value) {
return value;
};
/***/ },
/* 58 */ /***/ function(module1, exports1, __webpack_require__) {
var apply = __webpack_require__(147), nativeMax = Math.max;
module1.exports = /**
* 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(func, start, transform) {
return start = nativeMax(void 0 === start ? func.length - 1 : start, 0), function() {
for(var args = arguments, index = -1, length = nativeMax(args.length - start, 0), array = Array(length); ++index < length;)array[index] = args[start + index];
index = -1;
for(var otherArgs = Array(start + 1); ++index < start;)otherArgs[index] = args[index];
return otherArgs[start] = transform(array), apply(func, this, otherArgs);
};
};
/***/ },
/* 59 */ /***/ function(module1, exports1, __webpack_require__) {
var baseSetToString = __webpack_require__(148);
module1.exports = __webpack_require__(150)(baseSetToString);
/***/ },
/* 60 */ /***/ function(module1, exports1, __webpack_require__) {
var arrayLikeToArray = __webpack_require__(61);
module1.exports = function(o, minLen) {
if (o) {
if ("string" == typeof o) return arrayLikeToArray(o, minLen);
var n = Object.prototype.toString.call(o).slice(8, -1);
if ("Object" === n && o.constructor && (n = o.constructor.name), "Map" === n || "Set" === n) return Array.from(o);
if ("Arguments" === n || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return arrayLikeToArray(o, minLen);
}
}, module1.exports.default = module1.exports, module1.exports.__esModule = !0;
/***/ },
/* 61 */ /***/ function(module1, exports1) {
module1.exports = function(arr, len) {
(null == len || len > arr.length) && (len = arr.length);
for(var i = 0, arr2 = Array(len); i < len; i++)arr2[i] = arr[i];
return arr2;
}, module1.exports.default = module1.exports, module1.exports.__esModule = !0;
/***/ },
/* 62 */ /***/ function(module1, exports1) {
module1.exports = 0.000001;
/***/ },
/* 63 */ /***/ function(module1, exports1) {
module1.exports = /**
* Creates a new, empty vec2
*
* @returns {vec2} a new 2D vector
*/ function() {
var out = new Float32Array(2);
return out[0] = 0, out[1] = 0, out;
};
/***/ },
/* 64 */ /***/ function(module1, exports1) {
module1.exports = /**
* Subtracts vector b from vector a
*
* @param {vec2} out the receiving vector
* @param {vec2} a the first operand
* @param {vec2} b the second operand
* @returns {vec2} out
*/ function(out, a, b) {
return out[0] = a[0] - b[0], out[1] = a[1] - b[1], out;
};
/***/ },
/* 65 */ /***/ function(module1, exports1) {
module1.exports = /**
* Multiplies two vec2's
*
* @param {vec2} out the receiving vector
* @param {vec2} a the first operand
* @param {vec2} b the second operand
* @returns {vec2} out
*/ function(out, a, b) {
return out[0] = a[0] * b[0], out[1] = a[1] * b[1], out;
};
/***/ },
/* 66 */ /***/ function(module1, exports1) {
module1.exports = /**
* Divides two vec2's
*
* @param {vec2} out the receiving vector
* @param {vec2} a the first operand
* @param {vec2} b the second operand
* @returns {vec2} out
*/ function(out, a, b) {
return out[0] = a[0] / b[0], out[1] = a[1] / b[1], out;
};
/***/ },
/* 67 */ /***/ function(module1, exports1) {
module1.exports = /**
* Calculates the euclidian distance between two vec2's
*
* @param {vec2} a the first operand
* @param {vec2} b the second operand
* @returns {Number} distance between a and b
*/ function(a, b) {
var x = b[0] - a[0], y = b[1] - a[1];
return Math.sqrt(x * x + y * y);
};
/***/ },
/* 68 */ /***/ function(module1, exports1) {
module1.exports = /**
* Calculates the squared euclidian distance between two vec2's
*
* @param {vec2} a the first operand
* @param {vec2} b the second operand
* @returns {Number} squared distance between a and b
*/ function(a, b) {
var x = b[0] - a[0], y = b[1] - a[1];
return x * x + y * y;
};
/***/ },
/* 69 */ /***/ function(module1, exports1) {
module1.exports = /**
* Calculates the length of a vec2
*
* @param {vec2} a vector to calculate length of
* @returns {Number} length of a
*/ function(a) {
var x = a[0], y = a[1];
return Math.sqrt(x * x + y * y);
};
/***/ },
/* 70 */ /***/ function(module1, exports1) {
module1.exports = /**
* Calculates the squared length of a vec2
*
* @param {vec2} a vector to calculate squared length of
* @returns {Number} squared length of a
*/ function(a) {
var x = a[0], y = a[1];
return x * x + y * y;
};
/***/ },
/* 71 */ /***/ function(module1, exports1) {
module1.exports = 0.000001;
/***/ },
/* 72 */ /***/ function(module1, exports1) {
module1.exports = /**
* Creates a new, empty vec3
*
* @returns {vec3} a new 3D vector
*/ function() {
var out = new Float32Array(3);
return out[0] = 0, out[1] = 0, out[2] = 0, out;
};
/***/ },
/* 73 */ /***/ function(module1, exports1) {
module1.exports = /**
* Creates a new vec3 initialized with the given values
*
* @param {Number} x X component
* @param {Number} y Y component
* @param {Number} z Z component
* @returns {vec3} a new 3D vector
*/ function(x, y, z) {
var out = new Float32Array(3);
return out[0] = x, out[1] = y, out[2] = z, out;
};
/***/ },
/* 74 */ /***/ function(module1, exports1) {
module1.exports = /**
* Normalize a vec3
*
* @param {vec3} out the receiving vector
* @param {vec3} a vector to normalize
* @returns {vec3} out
*/ function(out, a) {
var x = a[0], y = a[1], z = a[2], len = x * x + y * y + z * z;
return len > 0 && (//TODO: evaluate use of glm_invsqrt here?
len = 1 / Math.sqrt(len), out[0] = a[0] * len, out[1] = a[1] * len, out[2] = a[2] * len), out;
};
/***/ },
/* 75 */ /***/ function(module1, exports1) {
module1.exports = /**
* Calculates the dot product of two vec3's
*
* @param {vec3} a the first operand
* @param {vec3} b the second operand
* @returns {Number} dot product of a and b
*/ function(a, b) {
return a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
};
/***/ },
/* 76 */ /***/ function(module1, exports1) {
module1.exports = /**
* Subtracts vector b from vector a
*
* @param {vec3} out the receiving vector
* @param {vec3} a the first operand
* @param {vec3} b the second operand
* @returns {vec3} out
*/ function(out, a, b) {
return out[0] = a[0] - b[0], out[1] = a[1] - b[1], out[2] = a[2] - b[2], out;
};
/***/ },
/* 77 */ /***/ function(module1, exports1) {
module1.exports = /**
* Multiplies two vec3's
*
* @param {vec3} out the receiving vector
* @param {vec3} a the first operand
* @param {vec3} b the second operand
* @returns {vec3} out
*/ function(out, a, b) {
return out[0] = a[0] * b[0], out[1] = a[1] * b[1], out[2] = a[2] * b[2], out;
};
/***/ },
/* 78 */ /***/ function(module1, exports1) {
module1.exports = /**
* Divides two vec3's
*
* @param {vec3} out the receiving vector
* @param {vec3} a the first operand
* @param {vec3} b the second operand
* @returns {vec3} out
*/ function(out, a, b) {
return out[0] = a[0] / b[0], out[1] = a[1] / b[1], out[2] = a[2] / b[2], out;
};
/***/ },
/* 79 */ /***/ function(module1, exports1) {
module1.exports = /**
* Calculates the euclidian distance between two vec3's
*
* @param {vec3} a the first operand
* @param {vec3} b the second operand
* @returns {Number} distance between a and b
*/ function(a, b) {
var x = b[0] - a[0], y = b[1] - a[1], z = b[2] - a[2];
return Math.sqrt(x * x + y * y + z * z);
};
/***/ },
/* 80 */ /***/ function(module1, exports1) {
module1.exports = /**
* Calculates the squared euclidian distance between two vec3's
*
* @param {vec3} a the first operand
* @param {vec3} b the second operand
* @returns {Number} squared distance between a and b
*/ function(a, b) {
var x = b[0] - a[0], y = b[1] - a[1], z = b[2] - a[2];
return x * x + y * y + z * z;
};
/***/ },
/* 81 */ /***/ function(module1, exports1) {
module1.exports = /**
* Calculates the length of a vec3
*
* @param {vec3} a vector to calculate length of
* @returns {Number} length of a
*/ function(a) {
var x = a[0], y = a[1], z = a[2];
return Math.sqrt(x * x + y * y + z * z);
};
/***/ },
/* 82 */ /***/ function(module1, exports1) {
module1.exports = /**
* Calculates the squared length of a vec3
*
* @param {vec3} a vector to calculate squared length of
* @returns {Number} squared length of a
*/ function(a) {
var x = a[0], y = a[1], z = a[2];
return x * x + y * y + z * z;
};
/***/ },
/* 83 */ /***/ function(module1, exports1, __webpack_require__) {
var arrayWithHoles = __webpack_require__(153), iterableToArrayLimit = __webpack_require__(154), unsupportedIterableToArray = __webpack_require__(60), nonIterableRest = __webpack_require__(155);
module1.exports = function(arr, i) {
return arrayWithHoles(arr) || iterableToArrayLimit(arr, i) || unsupportedIterableToArray(arr, i) || nonIterableRest();
}, module1.exports.default = module1.exports, module1.exports.__esModule = !0;
/***/ },
/* 84 */ /***/ function(module1, exports1, __webpack_require__) {
module1.exports = {
EPSILON: __webpack_require__(71),
create: __webpack_require__(72),
clone: __webpack_require__(191),
angle: __webpack_require__(192),
fromValues: __webpack_require__(73),
copy: __webpack_require__(193),
set: __webpack_require__(194),
equals: __webpack_require__(195),
exactEquals: __webpack_require__(196),
add: __webpack_require__(197),
subtract: __webpack_require__(76),
sub: __webpack_require__(198),
multiply: __webpack_require__(77),
mul: __webpack_require__(199),
divide: __webpack_require__(78),
div: __webpack_require__(200),
min: __webpack_require__(201),
max: __webpack_require__(202),
floor: __webpack_require__(203),
ceil: __webpack_require__(204),
round: __webpack_require__(205),
scale: __webpack_require__(206),
scaleAndAdd: __webpack_require__(207),
distance: __webpack_require__(79),
dist: __webpack_require__(208),
squaredDistance: __webpack_require__(80),
sqrDist: __webpack_require__(209),
length: __webpack_require__(81),
len: __webpack_require__(210),
squaredLength: __webpack_require__(82),
sqrLen: __webpack_require__(211),
negate: __webpack_require__(212),
inverse: __webpack_require__(213),
normalize: __webpack_require__(74),
dot: __webpack_require__(75),
cross: __webpack_require__(214),
lerp: __webpack_require__(215),
random: __webpack_require__(216),
transformMat4: __webpack_require__(217),
transformMat3: __webpack_require__(218),
transformQuat: __webpack_require__(219),
rotateX: __webpack_require__(220),
rotateY: __webpack_require__(221),
rotateZ: __webpack_require__(222),
forEach: __webpack_require__(223)
};
/***/ },
/* 85 */ /***/ function(module1, exports1, __webpack_require__) {
var basePick = __webpack_require__(229);
module1.exports = __webpack_require__(243)(function(object, paths) {
return null == object ? {} : basePick(object, paths);
});
/***/ },
/* 86 */ /***/ function(module1, exports1, __webpack_require__) {
var getPrototypeOf = __webpack_require__(2), setPrototypeOf = __webpack_require__(41), isNativeFunction = __webpack_require__(248), construct = __webpack_require__(249);
function _wrapNativeSuper(Class) {
var _cache = "function" == typeof Map ? new Map() : void 0;
return module1.exports = _wrapNativeSuper = function(Class) {
if (null === Class || !isNativeFunction(Class)) return Class;
if ("function" != typeof Class) throw TypeError("Super expression must either be null or a function");
if (void 0 !== _cache) {
if (_cache.has(Class)) return _cache.get(Class);
_cache.set(Class, Wrapper);
}
function Wrapper() {
return construct(Class, arguments, getPrototypeOf(this).constructor);
}
return Wrapper.prototype = Object.create(Class.prototype, {
constructor: {
value: Wrapper,
enumerable: !1,
writable: !0,
configurable: !0
}
}), setPrototypeOf(Wrapper, Class);
}, module1.exports.default = module1.exports, module1.exports.__esModule = !0, _wrapNativeSuper(Class);
}
module1.exports = _wrapNativeSuper, module1.exports.default = module1.exports, module1.exports.__esModule = !0;
/***/ },
/* 87 */ /***/ function(module1, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony import */ var _tracer__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(21), Rasterizer = {
createContour2D: function() {
return {
dir: null,
index: null,
firstVertex: null,
insideContours: null,
nextpeer: null,
prevpeer: null
};
},
CONTOUR_DIR: {
CW_DIR: 0,
CCW_DIR: 1,
UNKNOWN_DIR: 2
},
DIR: {
OUTSIDE_EDGE: -32767,
INSIDE_EDGE: -32766
},
create: function(imageWrapper, labelWrapper) {
var imageData = imageWrapper.data, labelData = labelWrapper.data, width = imageWrapper.size.x, height = imageWrapper.size.y, tracer = _tracer__WEBPACK_IMPORTED_MODULE_0__./* default */ a.create(imageWrapper, labelWrapper);
return {
rasterize: function(depthlabel) {
var color, bc, lc, labelindex, cx, cy, vertex, p, cc, sc, pos, i, colorMap = [], connectedCount = 0;
for(i = 0; i < 400; i++)colorMap[i] = 0;
for(cy = 1, colorMap[0] = imageData[0], cc = null; cy < height - 1; cy++)for(cx = 1, labelindex = 0, bc = colorMap[0]; cx < width - 1; cx++)if (0 === labelData[pos = cy * width + cx]) {
if ((color = imageData[pos]) !== bc) {
if (0 === labelindex) colorMap[lc = connectedCount + 1] = color, bc = color, null !== (vertex = tracer.contourTracing(cy, cx, lc, color, Rasterizer.DIR.OUTSIDE_EDGE)) && (connectedCount++, labelindex = lc, (p = Rasterizer.createContour2D()).dir = Rasterizer.CONTOUR_DIR.CW_DIR, p.index = labelindex, p.firstVertex = vertex, p.nextpeer = cc, p.insideContours = null, null !== cc && (cc.prevpeer = p), cc = p);
else if (null !== (vertex = tracer.contourTracing(cy, cx, Rasterizer.DIR.INSIDE_EDGE, color, labelindex))) {
for((p = Rasterizer.createContour2D()).firstVertex = vertex, p.insideContours = null, 0 === depthlabel ? p.dir = Rasterizer.CONTOUR_DIR.CCW_DIR : p.dir = Rasterizer.CONTOUR_DIR.CW_DIR, p.index = depthlabel, sc = cc; null !== sc && sc.index !== labelindex;)sc = sc.nextpeer;
null !== sc && (p.nextpeer = sc.insideContours, null !== sc.insideContours && (sc.insideContours.prevpeer = p), sc.insideContours = p);
}
} else labelData[pos] = labelindex;
} else labelData[pos] === Rasterizer.DIR.OUTSIDE_EDGE || labelData[pos] === Rasterizer.DIR.INSIDE_EDGE ? (labelindex = 0, bc = labelData[pos] === Rasterizer.DIR.INSIDE_EDGE ? imageData[pos] : colorMap[0]) : bc = colorMap[labelindex = labelData[pos]];
for(sc = cc; null !== sc;)sc.index = depthlabel, sc = sc.nextpeer;
return {
cc: cc,
count: connectedCount
};
},
debug: {
drawContour: function(canvas, firstContour) {
var iq, q, p, ctx = canvas.getContext("2d"), pq = firstContour;
for(ctx.strokeStyle = "red", ctx.fillStyle = "red", ctx.lineWidth = 1, iq = null !== pq ? pq.insideContours : null; null !== pq;){
switch(null !== iq ? (q = iq, iq = iq.nextpeer) : (q = pq, iq = null !== (pq = pq.nextpeer) ? pq.insideContours : null), q.dir){
case Rasterizer.CONTOUR_DIR.CW_DIR:
ctx.strokeStyle = "red";
break;
case Rasterizer.CONTOUR_DIR.CCW_DIR:
ctx.strokeStyle = "blue";
break;
case Rasterizer.CONTOUR_DIR.UNKNOWN_DIR:
ctx.strokeStyle = "green";
}
p = q.firstVertex, ctx.beginPath(), ctx.moveTo(p.x, p.y);
do p = p.next, ctx.lineTo(p.x, p.y);
while (p !== q.firstVertex)
ctx.stroke();
}
}
}
};
}
};
/* harmony default export */ __webpack_exports__.a = Rasterizer;
/***/ },
/* 88 */ /***/ function(module1, __webpack_exports__, __webpack_require__) {
"use strict";
/* @preserve ASM END */ /* harmony default export */ __webpack_exports__.a = /* eslint-disable no-param-reassign */ /* eslint-disable no-bitwise */ /* eslint-disable eqeqeq */ /* @preserve ASM BEGIN */ function(stdlib, foreign, buffer) {
"use asm";
var images = new stdlib.Uint8Array(buffer);
var size = foreign.size | 0;
var imul = stdlib.Math.imul;
function erode(inImagePtr, outImagePtr) {
inImagePtr |= 0;
outImagePtr |= 0;
var v = 0;
var u = 0;
var sum = 0;
var yStart1 = 0;
var yStart2 = 0;
var xStart1 = 0;
var xStart2 = 0;
var offset = 0;
for(v = 1; (v | 0) < (size - 1 | 0); v = v + 1 | 0){
offset = offset + size | 0;
for(u = 1; (u | 0) < (size - 1 | 0); u = u + 1 | 0){
yStart1 = offset - size | 0;
yStart2 = offset + size | 0;
xStart1 = u - 1 | 0;
xStart2 = u + 1 | 0;
sum = (images[inImagePtr + yStart1 + xStart1 | 0] | 0) + (images[inImagePtr + yStart1 + xStart2 | 0] | 0) + (images[inImagePtr + offset + u | 0] | 0) + (images[inImagePtr + yStart2 + xStart1 | 0] | 0) + (images[inImagePtr + yStart2 + xStart2 | 0] | 0) | 0;
if ((sum | 0) == 5) images[outImagePtr + offset + u | 0] = 1;
else images[outImagePtr + offset + u | 0] = 0;
}
}
}
function subtract(aImagePtr, bImagePtr, outImagePtr) {
aImagePtr |= 0;
bImagePtr |= 0;
outImagePtr |= 0;
var length = 0;
length = imul(size, size) | 0;
while((length | 0) > 0){
length = length - 1 | 0;
images[outImagePtr + length | 0] = (images[aImagePtr + length | 0] | 0) - (images[bImagePtr + length | 0] | 0) | 0;
}
}
function bitwiseOr(aImagePtr, bImagePtr, outImagePtr) {
aImagePtr |= 0;
bImagePtr |= 0;
outImagePtr |= 0;
var length = 0;
length = imul(size, size) | 0;
while((length | 0) > 0){
length = length - 1 | 0;
images[outImagePtr + length | 0] = images[aImagePtr + length | 0] | 0 | (images[bImagePtr + length | 0] | 0) | 0;
}
}
function countNonZero(imagePtr) {
imagePtr |= 0;
var sum = 0;
var length = 0;
length = imul(size, size) | 0;
while((length | 0) > 0){
length = length - 1 | 0;
sum = (sum | 0) + (images[imagePtr + length | 0] | 0) | 0;
}
return sum | 0;
}
function init(imagePtr, value) {
imagePtr |= 0;
value |= 0;
var length = 0;
length = imul(size, size) | 0;
while((length | 0) > 0){
length = length - 1 | 0;
images[imagePtr + length | 0] = value;
}
}
function dilate(inImagePtr, outImagePtr) {
inImagePtr |= 0;
outImagePtr |= 0;
var v = 0;
var u = 0;
var sum = 0;
var yStart1 = 0;
var yStart2 = 0;
var xStart1 = 0;
var xStart2 = 0;
var offset = 0;
for(v = 1; (v | 0) < (size - 1 | 0); v = v + 1 | 0){
offset = offset + size | 0;
for(u = 1; (u | 0) < (size - 1 | 0); u = u + 1 | 0){
yStart1 = offset - size | 0;
yStart2 = offset + size | 0;
xStart1 = u - 1 | 0;
xStart2 = u + 1 | 0;
sum = (images[inImagePtr + yStart1 + xStart1 | 0] | 0) + (images[inImagePtr + yStart1 + xStart2 | 0] | 0) + (images[inImagePtr + offset + u | 0] | 0) + (images[inImagePtr + yStart2 + xStart1 | 0] | 0) + (images[inImagePtr + yStart2 + xStart2 | 0] | 0) | 0;
if ((sum | 0) > 0) images[outImagePtr + offset + u | 0] = 1;
else images[outImagePtr + offset + u | 0] = 0;
}
}
}
function memcpy(srcImagePtr, dstImagePtr) {
srcImagePtr |= 0;
dstImagePtr |= 0;
var length = 0;
length = imul(size, size) | 0;
while((length | 0) > 0){
length = length - 1 | 0;
images[dstImagePtr + length | 0] = images[srcImagePtr + length | 0] | 0;
}
}
function zeroBorder(imagePtr) {
imagePtr |= 0;
var x = 0;
var y = 0;
for(x = 0; (x | 0) < (size - 1 | 0); x = x + 1 | 0){
images[imagePtr + x | 0] = 0;
images[imagePtr + y | 0] = 0;
y = y + size - 1 | 0;
images[imagePtr + y | 0] = 0;
y = y + 1 | 0;
}
for(x = 0; (x | 0) < (size | 0); x = x + 1 | 0){
images[imagePtr + y | 0] = 0;
y = y + 1 | 0;
}
}
function skeletonize() {
var subImagePtr = 0;
var erodedImagePtr = 0;
var tempImagePtr = 0;
var skelImagePtr = 0;
var sum = 0;
var done = 0;
erodedImagePtr = imul(size, size) | 0;
tempImagePtr = erodedImagePtr + erodedImagePtr | 0;
skelImagePtr = tempImagePtr + erodedImagePtr | 0; // init skel-image
init(skelImagePtr, 0);
zeroBorder(subImagePtr);
do {
erode(subImagePtr, erodedImagePtr);
dilate(erodedImagePtr, tempImagePtr);
subtract(subImagePtr, tempImagePtr, tempImagePtr);
bitwiseOr(skelImagePtr, tempImagePtr, skelImagePtr);
memcpy(erodedImagePtr, subImagePtr);
sum = countNonZero(subImagePtr) | 0;
done = (sum | 0) == 0 | 0;
}while (!done)
}
return {
skeletonize: skeletonize
};
};
/* eslint-enable eqeqeq */ /***/ },
/* 89 */ /***/ function(module1, exports1, __webpack_require__) {
module1.exports = __webpack_require__(263);
/***/ },
/* 90 */ /***/ function(module1, exports1, __webpack_require__) {
var Stack = __webpack_require__(91), assignMergeValue = __webpack_require__(48), baseFor = __webpack_require__(121), baseMergeDeep = __webpack_require__(123), isObject = __webpack_require__(14), keysIn = __webpack_require__(56), safeGet = __webpack_require__(54);
module1.exports = /**
* 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) {
object !== source && baseFor(source, function(srcValue, key) {
if (stack || (stack = new Stack()), isObject(srcValue)) baseMergeDeep(object, source, key, srcIndex, baseMerge, customizer, stack);
else {
var newValue = customizer ? customizer(safeGet(object, key), srcValue, key + "", object, source, stack) : void 0;
void 0 === newValue && (newValue = srcValue), assignMergeValue(object, key, newValue);
}
}, keysIn);
};
/***/ },
/* 91 */ /***/ function(module1, exports1, __webpack_require__) {
var ListCache = __webpack_require__(24), stackClear = __webpack_require__(97), stackDelete = __webpack_require__(98), stackGet = __webpack_require__(99), stackHas = __webpack_require__(100), stackSet = __webpack_require__(101);
/**
* 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;
} // Add methods to `Stack`.
Stack.prototype.clear = stackClear, Stack.prototype.delete = stackDelete, Stack.prototype.get = stackGet, Stack.prototype.has = stackHas, Stack.prototype.set = stackSet, module1.exports = Stack;
/***/ },
/* 92 */ /***/ function(module1, exports1) {
module1.exports = /**
* Removes all key-value entries from the list cache.
*
* @private
* @name clear
* @memberOf ListCache
*/ function() {
this.__data__ = [], this.size = 0;
};
/***/ },
/* 93 */ /***/ function(module1, exports1, __webpack_require__) {
var assocIndexOf = __webpack_require__(25), splice = Array.prototype.splice;
module1.exports = /**
* 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(key) {
var data = this.__data__, index = assocIndexOf(data, key);
return !(index < 0) && (index == data.length - 1 ? data.pop() : splice.call(data, index, 1), --this.size, !0);
};
/***/ },
/* 94 */ /***/ function(module1, exports1, __webpack_require__) {
var assocIndexOf = __webpack_require__(25);
module1.exports = /**
* 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(key) {
var data = this.__data__, index = assocIndexOf(data, key);
return index < 0 ? void 0 : data[index][1];
};
/***/ },
/* 95 */ /***/ function(module1, exports1, __webpack_require__) {
var assocIndexOf = __webpack_require__(25);
module1.exports = /**
* 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(key) {
return assocIndexOf(this.__data__, key) > -1;
};
/***/ },
/* 96 */ /***/ function(module1, exports1, __webpack_require__) {
var assocIndexOf = __webpack_require__(25);
module1.exports = /**
* 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(key, value) {
var data = this.__data__, index = assocIndexOf(data, key);
return index < 0 ? (++this.size, data.push([
key,
value
])) : data[index][1] = value, this;
};
/***/ },
/* 97 */ /***/ function(module1, exports1, __webpack_require__) {
var ListCache = __webpack_require__(24);
module1.exports = /**
* Removes all key-value entries from the stack.
*
* @private
* @name clear
* @memberOf Stack
*/ function() {
this.__data__ = new ListCache(), this.size = 0;
};
/***/ },
/* 98 */ /***/ function(module1, exports1) {
module1.exports = /**
* 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(key) {
var data = this.__data__, result = data.delete(key);
return this.size = data.size, result;
};
/***/ },
/* 99 */ /***/ function(module1, exports1) {
module1.exports = /**
* 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(key) {
return this.__data__.get(key);
};
/***/ },
/* 100 */ /***/ function(module1, exports1) {
module1.exports = /**
* 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(key) {
return this.__data__.has(key);
};
/***/ },
/* 101 */ /***/ function(module1, exports1, __webpack_require__) {
var ListCache = __webpack_require__(24), Map1 = __webpack_require__(44), MapCache = __webpack_require__(47);
module1.exports = /**
* 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(key, value) {
var data = this.__data__;
if (data instanceof ListCache) {
var pairs = data.__data__;
if (!Map1 || pairs.length < 199) return pairs.push([
key,
value
]), this.size = ++data.size, this;
data = this.__data__ = new MapCache(pairs);
}
return data.set(key, value), this.size = data.size, this;
};
/***/ },
/* 102 */ /***/ function(module1, exports1, __webpack_require__) {
var isFunction = __webpack_require__(36), isMasked = __webpack_require__(105), isObject = __webpack_require__(14), toSource = __webpack_require__(107), reIsHostCtor = /^\[object .+?Constructor\]$/, objectProto = Object.prototype, funcToString = Function.prototype.toString, hasOwnProperty = objectProto.hasOwnProperty, reIsNative = RegExp("^" + funcToString.call(hasOwnProperty).replace(/[\\^$.*+?()[\]{}|]/g, "\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, "$1.*?") + "$");
module1.exports = /**
* 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(value) {
return !(!isObject(value) || isMasked(value)) && (isFunction(value) ? reIsNative : reIsHostCtor).test(toSource(value));
};
/***/ },
/* 103 */ /***/ function(module1, exports1, __webpack_require__) {
var Symbol1 = __webpack_require__(27), objectProto = Object.prototype, hasOwnProperty = objectProto.hasOwnProperty, nativeObjectToString = objectProto.toString, symToStringTag = Symbol1 ? Symbol1.toStringTag : void 0;
module1.exports = /**
* A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values.
*
* @private
* @param {*} value The value to query.
* @returns {string} Returns the raw `toStringTag`.
*/ function(value) {
var isOwn = hasOwnProperty.call(value, symToStringTag), tag = value[symToStringTag];
try {
value[symToStringTag] = void 0;
var unmasked = !0;
} catch (e) {}
var result = nativeObjectToString.call(value);
return unmasked && (isOwn ? value[symToStringTag] = tag : delete value[symToStringTag]), result;
};
/***/ },
/* 104 */ /***/ function(module1, exports1) {
/**
* Used to resolve the
* [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
* of values.
*/ var nativeObjectToString = Object.prototype.toString;
module1.exports = /**
* Converts `value` to a string using `Object.prototype.toString`.
*
* @private
* @param {*} value The value to convert.
* @returns {string} Returns the converted string.
*/ function(value) {
return nativeObjectToString.call(value);
};
/***/ },
/* 105 */ /***/ function(module1, exports1, __webpack_require__) {
var uid, coreJsData = __webpack_require__(106), maskSrcKey = (uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || "")) ? "Symbol(src)_1." + uid : "";
module1.exports = /**
* 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(func) {
return !!maskSrcKey && maskSrcKey in func;
};
/***/ },
/* 106 */ /***/ function(module1, exports1, __webpack_require__) {
module1.exports = __webpack_require__(17)["__core-js_shared__"];
/***/ },
/* 107 */ /***/ function(module1, exports1) {
/** Used to resolve the decompiled source of functions. */ var funcToString = Function.prototype.toString;
module1.exports = /**
* Converts `func` to its source code.
*
* @private
* @param {Function} func The function to convert.
* @returns {string} Returns the source code.
*/ function(func) {
if (null != func) {
try {
return funcToString.call(func);
} catch (e) {}
try {
return func + "";
} catch (e) {}
}
return "";
};
/***/ },
/* 108 */ /***/ function(module1, exports1) {
module1.exports = /**
* 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(object, key) {
return null == object ? void 0 : object[key];
};
/***/ },
/* 109 */ /***/ function(module1, exports1, __webpack_require__) {
var Hash = __webpack_require__(110), ListCache = __webpack_require__(24), Map1 = __webpack_require__(44);
module1.exports = /**
* Removes all key-value entries from the map.
*
* @private
* @name clear
* @memberOf MapCache
*/ function() {
this.size = 0, this.__data__ = {
hash: new Hash(),
map: new (Map1 || ListCache)(),
string: new Hash()
};
};
/***/ },
/* 110 */ /***/ function(module1, exports1, __webpack_require__) {
var hashClear = __webpack_require__(111), hashDelete = __webpack_require__(112), hashGet = __webpack_require__(113), hashHas = __webpack_require__(114), hashSet = __webpack_require__(115);
/**
* Creates a hash object.
*
* @private
* @constructor
* @param {Array} [entries] The key-value pairs to cache.
*/ function Hash(entries) {
var index = -1, length = null == entries ? 0 : entries.length;
for(this.clear(); ++index < length;){
var entry = entries[index];
this.set(entry[0], entry[1]);
}
} // Add methods to `Hash`.
Hash.prototype.clear = hashClear, Hash.prototype.delete = hashDelete, Hash.prototype.get = hashGet, Hash.prototype.has = hashHas, Hash.prototype.set = hashSet, module1.exports = Hash;
/***/ },
/* 111 */ /***/ function(module1, exports1, __webpack_require__) {
var nativeCreate = __webpack_require__(28);
module1.exports = /**
* Removes all key-value entries from the hash.
*
* @private
* @name clear
* @memberOf Hash
*/ function() {
this.__data__ = nativeCreate ? nativeCreate(null) : {}, this.size = 0;
};
/***/ },
/* 112 */ /***/ function(module1, exports1) {
module1.exports = /**
* 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(key) {
var result = this.has(key) && delete this.__data__[key];
return this.size -= +!!result, result;
};
/***/ },
/* 113 */ /***/ function(module1, exports1, __webpack_require__) {
var nativeCreate = __webpack_require__(28), hasOwnProperty = Object.prototype.hasOwnProperty;
module1.exports = /**
* 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(key) {
var data = this.__data__;
if (nativeCreate) {
var result = data[key];
return "__lodash_hash_undefined__" === result ? void 0 : result;
}
return hasOwnProperty.call(data, key) ? data[key] : void 0;
};
/***/ },
/* 114 */ /***/ function(module1, exports1, __webpack_require__) {
var nativeCreate = __webpack_require__(28), hasOwnProperty = Object.prototype.hasOwnProperty;
module1.exports = /**
* 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(key) {
var data = this.__data__;
return nativeCreate ? void 0 !== data[key] : hasOwnProperty.call(data, key);
};
/***/ },
/* 115 */ /***/ function(module1, exports1, __webpack_require__) {
var nativeCreate = __webpack_require__(28);
module1.exports = /**
* 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(key, value) {
var data = this.__data__;
return this.size += +!this.has(key), data[key] = nativeCreate && void 0 === value ? "__lodash_hash_undefined__" : value, this;
};
/***/ },
/* 116 */ /***/ function(module1, exports1, __webpack_require__) {
var getMapData = __webpack_require__(29);
module1.exports = /**
* 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(key) {
var result = getMapData(this, key).delete(key);
return this.size -= +!!result, result;
};
/***/ },
/* 117 */ /***/ function(module1, exports1) {
module1.exports = /**
* 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(value) {
var type = typeof value;
return "string" == type || "number" == type || "symbol" == type || "boolean" == type ? "__proto__" !== value : null === value;
};
/***/ },
/* 118 */ /***/ function(module1, exports1, __webpack_require__) {
var getMapData = __webpack_require__(29);
module1.exports = /**
* 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(key) {
return getMapData(this, key).get(key);
};
/***/ },
/* 119 */ /***/ function(module1, exports1, __webpack_require__) {
var getMapData = __webpack_require__(29);
module1.exports = /**
* 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(key) {
return getMapData(this, key).has(key);
};
/***/ },
/* 120 */ /***/ function(module1, exports1, __webpack_require__) {
var getMapData = __webpack_require__(29);
module1.exports = /**
* 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(key, value) {
var data = getMapData(this, key), size = data.size;
return data.set(key, value), this.size += +(data.size != size), this;
};
/***/ },
/* 121 */ /***/ function(module1, exports1, __webpack_require__) {
module1.exports = __webpack_require__(122)();
/***/ },
/* 122 */ /***/ function(module1, exports1) {
module1.exports = /**
* 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(fromRight) {
return function(object, iteratee, keysFunc) {
for(var index = -1, iterable = Object(object), props = keysFunc(object), length = props.length; length--;){
var key = props[fromRight ? length : ++index];
if (!1 === iteratee(iterable[key], key, iterable)) break;
}
return object;
};
};
/***/ },
/* 123 */ /***/ function(module1, exports1, __webpack_require__) {
var assignMergeValue = __webpack_require__(48), cloneBuffer = __webpack_require__(124), cloneTypedArray = __webpack_require__(125), copyArray = __webpack_require__(128), initCloneObject = __webpack_require__(129), isArguments = __webpack_require__(30), isArray = __webpack_require__(15), isArrayLikeObject = __webpack_require__(133), isBuffer = __webpack_require__(52), isFunction = __webpack_require__(36), isObject = __webpack_require__(14), isPlainObject = __webpack_require__(135), isTypedArray = __webpack_require__(53), safeGet = __webpack_require__(54), toPlainObject = __webpack_require__(139);
module1.exports = /**
* 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(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) : void 0, isCommon = void 0 === newValue;
if (isCommon) {
var isArr = isArray(srcValue), isBuff = !isArr && isBuffer(srcValue), isTyped = !isArr && !isBuff && isTypedArray(srcValue);
newValue = srcValue, isArr || isBuff || isTyped ? isArray(objValue) ? newValue = objValue : isArrayLikeObject(objValue) ? newValue = copyArray(objValue) : isBuff ? (isCommon = !1, newValue = cloneBuffer(srcValue, !0)) : isTyped ? (isCommon = !1, newValue = cloneTypedArray(srcValue, !0)) : newValue = [] : isPlainObject(srcValue) || isArguments(srcValue) ? (newValue = objValue, isArguments(objValue) ? newValue = toPlainObject(objValue) : (!isObject(objValue) || isFunction(objValue)) && (newValue = initCloneObject(srcValue))) : isCommon = !1;
}
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);
};
/***/ },
/* 124 */ /***/ function(module1, exports1, __webpack_require__) {
/* WEBPACK VAR INJECTION */ (function(module1) {
var root = __webpack_require__(17), freeExports = exports1 && !exports1.nodeType && exports1, freeModule = freeExports && "object" == typeof module1 && module1 && !module1.nodeType && module1, Buffer = freeModule && freeModule.exports === freeExports ? root.Buffer : void 0, allocUnsafe = Buffer ? Buffer.allocUnsafe : void 0;
module1.exports = /**
* 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(buffer, isDeep) {
if (isDeep) return buffer.slice();
var length = buffer.length, result = allocUnsafe ? allocUnsafe(length) : new buffer.constructor(length);
return buffer.copy(result), result;
};
/* WEBPACK VAR INJECTION */ }).call(this, __webpack_require__(38)(module1));
/***/ },
/* 125 */ /***/ function(module1, exports1, __webpack_require__) {
var cloneArrayBuffer = __webpack_require__(126);
module1.exports = /**
* 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(typedArray, isDeep) {
var buffer = isDeep ? cloneArrayBuffer(typedArray.buffer) : typedArray.buffer;
return new typedArray.constructor(buffer, typedArray.byteOffset, typedArray.length);
};
/***/ },
/* 126 */ /***/ function(module1, exports1, __webpack_require__) {
var Uint8Array1 = __webpack_require__(127);
module1.exports = /**
* Creates a clone of `arrayBuffer`.
*
* @private
* @param {ArrayBuffer} arrayBuffer The array buffer to clone.
* @returns {ArrayBuffer} Returns the cloned array buffer.
*/ function(arrayBuffer) {
var result = new arrayBuffer.constructor(arrayBuffer.byteLength);
return new Uint8Array1(result).set(new Uint8Array1(arrayBuffer)), result;
};
/***/ },
/* 127 */ /***/ function(module1, exports1, __webpack_require__) {
module1.exports = __webpack_require__(17).Uint8Array;
/***/ },
/* 128 */ /***/ function(module1, exports1) {
module1.exports = /**
* 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(source, array) {
var index = -1, length = source.length;
for(array || (array = Array(length)); ++index < length;)array[index] = source[index];
return array;
};
/***/ },
/* 129 */ /***/ function(module1, exports1, __webpack_require__) {
var baseCreate = __webpack_require__(130), getPrototype = __webpack_require__(50), isPrototype = __webpack_require__(51);
module1.exports = /**
* Initializes an object clone.
*
* @private
* @param {Object} object The object to clone.
* @returns {Object} Returns the initialized clone.
*/ function(object) {
return "function" != typeof object.constructor || isPrototype(object) ? {} : baseCreate(getPrototype(object));
};
/***/ },
/* 130 */ /***/ function(module1, exports1, __webpack_require__) {
var isObject = __webpack_require__(14), objectCreate = Object.create;
module1.exports = function() {
function object() {}
return function(proto) {
if (!isObject(proto)) return {};
if (objectCreate) return objectCreate(proto);
object.prototype = proto;
var result = new object();
return object.prototype = void 0, result;
};
}();
/***/ },
/* 131 */ /***/ function(module1, exports1) {
module1.exports = /**
* 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(func, transform) {
return function(arg) {
return func(transform(arg));
};
};
/***/ },
/* 132 */ /***/ function(module1, exports1, __webpack_require__) {
var baseGetTag = __webpack_require__(22), isObjectLike = __webpack_require__(18);
module1.exports = /**
* The base implementation of `_.isArguments`.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an `arguments` object,
*/ function(value) {
return isObjectLike(value) && "[object Arguments]" == baseGetTag(value);
};
/***/ },
/* 133 */ /***/ function(module1, exports1, __webpack_require__) {
var isArrayLike = __webpack_require__(39), isObjectLike = __webpack_require__(18);
module1.exports = /**
* 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(value) {
return isObjectLike(value) && isArrayLike(value);
};
/***/ },
/* 134 */ /***/ function(module1, exports1) {
module1.exports = /**
* This method returns `false`.
*
* @static
* @memberOf _
* @since 4.13.0
* @category Util
* @returns {boolean} Returns `false`.
* @example
*
* _.times(2, _.stubFalse);
* // => [false, false]
*/ function() {
return !1;
};
/***/ },
/* 135 */ /***/ function(module1, exports1, __webpack_require__) {
var baseGetTag = __webpack_require__(22), getPrototype = __webpack_require__(50), isObjectLike = __webpack_require__(18), objectProto = Object.prototype, funcToString = Function.prototype.toString, hasOwnProperty = objectProto.hasOwnProperty, objectCtorString = funcToString.call(Object);
module1.exports = /**
* 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(value) {
if (!isObjectLike(value) || "[object Object]" != baseGetTag(value)) return !1;
var proto = getPrototype(value);
if (null === proto) return !0;
var Ctor = hasOwnProperty.call(proto, "constructor") && proto.constructor;
return "function" == typeof Ctor && Ctor instanceof Ctor && funcToString.call(Ctor) == objectCtorString;
};
/***/ },
/* 136 */ /***/ function(module1, exports1, __webpack_require__) {
var baseGetTag = __webpack_require__(22), isLength = __webpack_require__(40), isObjectLike = __webpack_require__(18), typedArrayTags = {};
typedArrayTags["[object Float32Array]"] = typedArrayTags["[object Float64Array]"] = typedArrayTags["[object Int8Array]"] = typedArrayTags["[object Int16Array]"] = typedArrayTags["[object Int32Array]"] = typedArrayTags["[object Uint8Array]"] = typedArrayTags["[object Uint8ClampedArray]"] = typedArrayTags["[object Uint16Array]"] = typedArrayTags["[object Uint32Array]"] = !0, typedArrayTags["[object Arguments]"] = typedArrayTags["[object Array]"] = typedArrayTags["[object ArrayBuffer]"] = typedArrayTags["[object Boolean]"] = typedArrayTags["[object DataView]"] = typedArrayTags["[object Date]"] = typedArrayTags["[object Error]"] = typedArrayTags["[object Function]"] = typedArrayTags["[object Map]"] = typedArrayTags["[object Number]"] = typedArrayTags["[object Object]"] = typedArrayTags["[object RegExp]"] = typedArrayTags["[object Set]"] = typedArrayTags["[object String]"] = typedArrayTags["[object WeakMap]"] = !1, module1.exports = /**
* 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(value) {
return isObjectLike(value) && isLength(value.length) && !!typedArrayTags[baseGetTag(value)];
};
/***/ },
/* 137 */ /***/ function(module1, exports1) {
module1.exports = /**
* 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(func) {
return function(value) {
return func(value);
};
};
/***/ },
/* 138 */ /***/ function(module1, exports1, __webpack_require__) {
/* WEBPACK VAR INJECTION */ (function(module1) {
var freeGlobal = __webpack_require__(45), freeExports = exports1 && !exports1.nodeType && exports1, freeModule = freeExports && "object" == typeof module1 && module1 && !module1.nodeType && module1, freeProcess = freeModule && freeModule.exports === freeExports && freeGlobal.process;
module1.exports = 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) {}
}();
/* WEBPACK VAR INJECTION */ }).call(this, __webpack_require__(38)(module1));
/***/ },
/* 139 */ /***/ function(module1, exports1, __webpack_require__) {
var copyObject = __webpack_require__(140), keysIn = __webpack_require__(56);
module1.exports = /**
* 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(value) {
return copyObject(value, keysIn(value));
};
/***/ },
/* 140 */ /***/ function(module1, exports1, __webpack_require__) {
var assignValue = __webpack_require__(55), baseAssignValue = __webpack_require__(37);
module1.exports = /**
* 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(source, props, object, customizer) {
var isNew = !object;
object || (object = {});
for(var index = -1, length = props.length; ++index < length;){
var key = props[index], newValue = customizer ? customizer(object[key], source[key], key, object, source) : void 0;
void 0 === newValue && (newValue = source[key]), isNew ? baseAssignValue(object, key, newValue) : assignValue(object, key, newValue);
}
return object;
};
/***/ },
/* 141 */ /***/ function(module1, exports1, __webpack_require__) {
var baseTimes = __webpack_require__(142), isArguments = __webpack_require__(30), isArray = __webpack_require__(15), isBuffer = __webpack_require__(52), isIndex = __webpack_require__(31), isTypedArray = __webpack_require__(53), hasOwnProperty = Object.prototype.hasOwnProperty;
module1.exports = /**
* 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(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)(inherited || hasOwnProperty.call(value, key)) && !(skipIndexes && // Safari 9 has enumerable `arguments.length` in strict mode.
("length" == key || isBuff && ("offset" == key || "parent" == key) || isType && ("buffer" == key || "byteLength" == key || "byteOffset" == key) || // Skip index properties.
isIndex(key, length))) && result.push(key);
return result;
};
/***/ },
/* 142 */ /***/ function(module1, exports1) {
module1.exports = /**
* 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(n, iteratee) {
for(var index = -1, result = Array(n); ++index < n;)result[index] = iteratee(index);
return result;
};
/***/ },
/* 143 */ /***/ function(module1, exports1, __webpack_require__) {
var isObject = __webpack_require__(14), isPrototype = __webpack_require__(51), nativeKeysIn = __webpack_require__(144), hasOwnProperty = Object.prototype.hasOwnProperty;
module1.exports = /**
* 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(object) {
if (!isObject(object)) return nativeKeysIn(object);
var isProto = isPrototype(object), result = [];
for(var key in object)"constructor" == key && (isProto || !hasOwnProperty.call(object, key)) || result.push(key);
return result;
};
/***/ },
/* 144 */ /***/ function(module1, exports1) {
module1.exports = /**
* 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(object) {
var result = [];
if (null != object) for(var key in Object(object))result.push(key);
return result;
};
/***/ },
/* 145 */ /***/ function(module1, exports1, __webpack_require__) {
var baseRest = __webpack_require__(146), isIterateeCall = __webpack_require__(151);
module1.exports = /**
* Creates a function like `_.assign`.
*
* @private
* @param {Function} assigner The function to assign values.
* @returns {Function} Returns the new assigner function.
*/ function(assigner) {
return baseRest(function(object, sources) {
var index = -1, length = sources.length, customizer = length > 1 ? sources[length - 1] : void 0, guard = length > 2 ? sources[2] : void 0;
for(customizer = assigner.length > 3 && "function" == typeof customizer ? (length--, customizer) : void 0, guard && isIterateeCall(sources[0], sources[1], guard) && (customizer = length < 3 ? void 0 : customizer, length = 1), object = Object(object); ++index < length;){
var source = sources[index];
source && assigner(object, source, index, customizer);
}
return object;
});
};
/***/ },
/* 146 */ /***/ function(module1, exports1, __webpack_require__) {
var identity = __webpack_require__(57), overRest = __webpack_require__(58), setToString = __webpack_require__(59);
module1.exports = /**
* 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(func, start) {
return setToString(overRest(func, start, identity), func + "");
};
/***/ },
/* 147 */ /***/ function(module1, exports1) {
module1.exports = /**
* 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(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);
};
/***/ },
/* 148 */ /***/ function(module1, exports1, __webpack_require__) {
var constant = __webpack_require__(149), defineProperty = __webpack_require__(49), identity = __webpack_require__(57);
module1.exports = defineProperty ? function(func, string) {
return defineProperty(func, "toString", {
configurable: !0,
enumerable: !1,
value: constant(string),
writable: !0
});
} : identity;
/***/ },
/* 149 */ /***/ function(module1, exports1) {
module1.exports = /**
* Creates a function that returns `value`.
*
* @static
* @memberOf _
* @since 2.4.0
* @category Util
* @param {*} value The value to return from the new function.
* @returns {Function} Returns the new constant function.
* @example
*
* var objects = _.times(2, _.constant({ 'a': 1 }));
*
* console.log(objects);
* // => [{ 'a': 1 }, { 'a': 1 }]
*
* console.log(objects[0] === objects[1]);
* // => true
*/ function(value) {
return function() {
return value;
};
};
/***/ },
/* 150 */ /***/ function(module1, exports1) {
/* Built-in method references for those with the same name as other `lodash` methods. */ var nativeNow = Date.now;
module1.exports = /**
* 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(func) {
var count = 0, lastCalled = 0;
return function() {
var stamp = nativeNow(), remaining = 16 - (stamp - lastCalled);
if (lastCalled = stamp, remaining > 0) {
if (++count >= 800) return arguments[0];
} else count = 0;
return func.apply(void 0, arguments);
};
};
/***/ },
/* 151 */ /***/ function(module1, exports1, __webpack_require__) {
var eq = __webpack_require__(26), isArrayLike = __webpack_require__(39), isIndex = __webpack_require__(31), isObject = __webpack_require__(14);
module1.exports = /**
* 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(value, index, object) {
if (!isObject(object)) return !1;
var type = typeof index;
return ("number" == type ? !!(isArrayLike(object) && isIndex(index, object.length)) : "string" == type && index in object) && eq(object[index], value);
};
/***/ },
/* 152 */ /***/ function(module1, exports1) {
"undefined" == typeof window || window.requestAnimationFrame || (window.requestAnimationFrame = window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame || function(/* function FrameRequestCallback */ callback) {
window.setTimeout(callback, 1000 / 60);
}), "function" != typeof Math.imul && /* eslint-disable no-bitwise */ (Math.imul = function(a, b) {
var al = 0xffff & a, bl = 0xffff & b;
// the final |0 converts the unsigned value into a signed value
return al * bl + ((a >>> 16 & 0xffff) * bl + al * (b >>> 16 & 0xffff) << 16 >>> 0) | 0;
}), "function" != typeof Object.assign && (Object.assign = function(target) {
// .length of function is 2
"use strict";
if (null === target) // TypeError if undefined or null
throw TypeError("Cannot convert undefined or null to object");
for(var to = Object(target), index = 1; index < arguments.length; index++){
// eslint-disable-next-line prefer-rest-params
var nextSource = arguments[index];
if (null !== nextSource) // Skip over if undefined or null
// eslint-disable-next-line no-restricted-syntax
for(var nextKey in nextSource)// Avoid bugs when hasOwnProperty is shadowed
Object.prototype.hasOwnProperty.call(nextSource, nextKey) && (to[nextKey] = nextSource[nextKey]);
}
return to;
});
/***/ },
/* 153 */ /***/ function(module1, exports1) {
module1.exports = function(arr) {
if (Array.isArray(arr)) return arr;
}, module1.exports.default = module1.exports, module1.exports.__esModule = !0;
/***/ },
/* 154 */ /***/ function(module1, exports1) {
module1.exports = function(arr, i) {
var _s, _e, _i = null == arr ? null : "undefined" != typeof Symbol && arr[Symbol.iterator] || arr["@@iterator"];
if (null != _i) {
var _arr = [], _n = !0, _d = !1;
try {
for(_i = _i.call(arr); !(_n = (_s = _i.next()).done) && (_arr.push(_s.value), !i || _arr.length !== i); _n = !0);
} catch (err) {
_d = !0, _e = err;
} finally{
try {
_n || null == _i.return || _i.return();
} finally{
if (_d) throw _e;
}
}
return _arr;
}
}, module1.exports.default = module1.exports, module1.exports.__esModule = !0;
/***/ },
/* 155 */ /***/ function(module1, exports1) {
module1.exports = function() {
throw TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}, module1.exports.default = module1.exports, module1.exports.__esModule = !0;
/***/ },
/* 156 */ /***/ function(module1, exports1) {
module1.exports = /**
* Creates a new vec2 initialized with values from an existing vector
*
* @param {vec2} a vector to clone
* @returns {vec2} a new 2D vector
*/ function(a) {
var out = new Float32Array(2);
return out[0] = a[0], out[1] = a[1], out;
};
/***/ },
/* 157 */ /***/ function(module1, exports1) {
module1.exports = /**
* Creates a new vec2 initialized with the given values
*
* @param {Number} x X component
* @param {Number} y Y component
* @returns {vec2} a new 2D vector
*/ function(x, y) {
var out = new Float32Array(2);
return out[0] = x, out[1] = y, out;
};
/***/ },
/* 158 */ /***/ function(module1, exports1) {
module1.exports = /**
* Copy the values from one vec2 to another
*
* @param {vec2} out the receiving vector
* @param {vec2} a the source vector
* @returns {vec2} out
*/ function(out, a) {
return out[0] = a[0], out[1] = a[1], out;
};
/***/ },
/* 159 */ /***/ function(module1, exports1) {
module1.exports = /**
* Set the components of a vec2 to the given values
*
* @param {vec2} out the receiving vector
* @param {Number} x X component
* @param {Number} y Y component
* @returns {vec2} out
*/ function(out, x, y) {
return out[0] = x, out[1] = y, out;
};
/***/ },
/* 160 */ /***/ function(module1, exports1, __webpack_require__) {
module1.exports = /**
* Returns whether or not the vectors have approximately the same elements in the same position.
*
* @param {vec2} a The first vector.
* @param {vec2} b The second vector.
* @returns {Boolean} True if the vectors are equal, false otherwise.
*/ function(a, b) {
var a0 = a[0], a1 = a[1], b0 = b[0], b1 = b[1];
return Math.abs(a0 - b0) <= EPSILON * Math.max(1.0, Math.abs(a0), Math.abs(b0)) && Math.abs(a1 - b1) <= EPSILON * Math.max(1.0, Math.abs(a1), Math.abs(b1));
};
var EPSILON = __webpack_require__(62);
/***/ },
/* 161 */ /***/ function(module1, exports1) {
module1.exports = /**
* Returns whether or not the vectors exactly have the same elements in the same position (when compared with ===)
*
* @param {vec2} a The first vector.
* @param {vec2} b The second vector.
* @returns {Boolean} True if the vectors are equal, false otherwise.
*/ function(a, b) {
return a[0] === b[0] && a[1] === b[1];
};
/***/ },
/* 162 */ /***/ function(module1, exports1) {
module1.exports = /**
* Adds two vec2's
*
* @param {vec2} out the receiving vector
* @param {vec2} a the first operand
* @param {vec2} b the second operand
* @returns {vec2} out
*/ function(out, a, b) {
return out[0] = a[0] + b[0], out[1] = a[1] + b[1], out;
};
/***/ },
/* 163 */ /***/ function(module1, exports1, __webpack_require__) {
module1.exports = __webpack_require__(64);
/***/ },
/* 164 */ /***/ function(module1, exports1, __webpack_require__) {
module1.exports = __webpack_require__(65);
/***/ },
/* 165 */ /***/ function(module1, exports1, __webpack_require__) {
module1.exports = __webpack_require__(66);
/***/ },
/* 166 */ /***/ function(module1, exports1) {
module1.exports = /**
* Returns the inverse of the components of a vec2
*
* @param {vec2} out the receiving vector
* @param {vec2} a vector to invert
* @returns {vec2} out
*/ function(out, a) {
return out[0] = 1.0 / a[0], out[1] = 1.0 / a[1], out;
};
/***/ },
/* 167 */ /***/ function(module1, exports1) {
module1.exports = /**
* Returns the minimum of two vec2's
*
* @param {vec2} out the receiving vector
* @param {vec2} a the first operand
* @param {vec2} b the second operand
* @returns {vec2} out
*/ function(out, a, b) {
return out[0] = Math.min(a[0], b[0]), out[1] = Math.min(a[1], b[1]), out;
};
/***/ },
/* 168 */ /***/ function(module1, exports1) {
module1.exports = /**
* Returns the maximum of two vec2's
*
* @param {vec2} out the receiving vector
* @param {vec2} a the first operand
* @param {vec2} b the second operand
* @returns {vec2} out
*/ function(out, a, b) {
return out[0] = Math.max(a[0], b[0]), out[1] = Math.max(a[1], b[1]), out;
};
/***/ },
/* 169 */ /***/ function(module1, exports1) {
module1.exports = /**
* Rotates a vec2 by an angle
*
* @param {vec2} out the receiving vector
* @param {vec2} a the vector to rotate
* @param {Number} angle the angle of rotation (in radians)
* @returns {vec2} out
*/ function(out, a, angle) {
var c = Math.cos(angle), s = Math.sin(angle), x = a[0], y = a[1];
return out[0] = x * c - y * s, out[1] = x * s + y * c, out;
};
/***/ },
/* 170 */ /***/ function(module1, exports1) {
module1.exports = /**
* Math.floor the components of a vec2
*
* @param {vec2} out the receiving vector
* @param {vec2} a vector to floor
* @returns {vec2} out
*/ function(out, a) {
return out[0] = Math.floor(a[0]), out[1] = Math.floor(a[1]), out;
};
/***/ },
/* 171 */ /***/ function(module1, exports1) {
module1.exports = /**
* Math.ceil the components of a vec2
*
* @param {vec2} out the receiving vector
* @param {vec2} a vector to ceil
* @returns {vec2} out
*/ function(out, a) {
return out[0] = Math.ceil(a[0]), out[1] = Math.ceil(a[1]), out;
};
/***/ },
/* 172 */ /***/ function(module1, exports1) {
module1.exports = /**
* Math.round the components of a vec2
*
* @param {vec2} out the receiving vector
* @param {vec2} a vector to round
* @returns {vec2} out
*/ function(out, a) {
return out[0] = Math.round(a[0]), out[1] = Math.round(a[1]), out;
};
/***/ },
/* 173 */ /***/ function(module1, exports1) {
module1.exports = /**
* Scales a vec2 by a scalar number
*
* @param {vec2} out the receiving vector
* @param {vec2} a the vector to scale
* @param {Number} b amount to scale the vector by
* @returns {vec2} out
*/ function(out, a, b) {
return out[0] = a[0] * b, out[1] = a[1] * b, out;
};
/***/ },
/* 174 */ /***/ function(module1, exports1) {
module1.exports = /**
* Adds two vec2's after scaling the second operand by a scalar value
*
* @param {vec2} out the receiving vector
* @param {vec2} a the first operand
* @param {vec2} b the second operand
* @param {Number} scale the amount to scale b by before adding
* @returns {vec2} out
*/ function(out, a, b, scale) {
return out[0] = a[0] + b[0] * scale, out[1] = a[1] + b[1] * scale, out;
};
/***/ },
/* 175 */ /***/ function(module1, exports1, __webpack_require__) {
module1.exports = __webpack_require__(67);
/***/ },
/* 176 */ /***/ function(module1, exports1, __webpack_require__) {
module1.exports = __webpack_require__(68);
/***/ },
/* 177 */ /***/ function(module1, exports1, __webpack_require__) {
module1.exports = __webpack_require__(69);
/***/ },
/* 178 */ /***/ function(module1, exports1, __webpack_require__) {
module1.exports = __webpack_require__(70);
/***/ },
/* 179 */ /***/ function(module1, exports1) {
module1.exports = /**
* Negates the components of a vec2
*
* @param {vec2} out the receiving vector
* @param {vec2} a vector to negate
* @returns {vec2} out
*/ function(out, a) {
return out[0] = -a[0], out[1] = -a[1], out;
};
/***/ },
/* 180 */ /***/ function(module1, exports1) {
module1.exports = /**
* Normalize a vec2
*
* @param {vec2} out the receiving vector
* @param {vec2} a vector to normalize
* @returns {vec2} out
*/ function(out, a) {
var x = a[0], y = a[1], len = x * x + y * y;
return len > 0 && (//TODO: evaluate use of glm_invsqrt here?
len = 1 / Math.sqrt(len), out[0] = a[0] * len, out[1] = a[1] * len), out;
};
/***/ },
/* 181 */ /***/ function(module1, exports1) {
module1.exports = /**
* Calculates the dot product of two vec2's
*
* @param {vec2} a the first operand
* @param {vec2} b the second operand
* @returns {Number} dot product of a and b
*/ function(a, b) {
return a[0] * b[0] + a[1] * b[1];
};
/***/ },
/* 182 */ /***/ function(module1, exports1) {
module1.exports = /**
* Computes the cross product of two vec2's
* Note that the cross product must by definition produce a 3D vector
*
* @param {vec3} out the receiving vector
* @param {vec2} a the first operand
* @param {vec2} b the second operand
* @returns {vec3} out
*/ function(out, a, b) {
var z = a[0] * b[1] - a[1] * b[0];
return out[0] = out[1] = 0, out[2] = z, out;
};
/***/ },
/* 183 */ /***/ function(module1, exports1) {
module1.exports = /**
* Performs a linear interpolation between two vec2's
*
* @param {vec2} out the receiving vector
* @param {vec2} a the first operand
* @param {vec2} b the second operand
* @param {Number} t interpolation amount between the two inputs
* @returns {vec2} out
*/ function(out, a, b, t) {
var ax = a[0], ay = a[1];
return out[0] = ax + t * (b[0] - ax), out[1] = ay + t * (b[1] - ay), out;
};
/***/ },
/* 184 */ /***/ function(module1, exports1) {
module1.exports = /**
* Generates a random vector with the given scale
*
* @param {vec2} out the receiving vector
* @param {Number} [scale] Length of the resulting vector. If ommitted, a unit vector will be returned
* @returns {vec2} out
*/ function(out, scale) {
scale = scale || 1.0;
var r = 2.0 * Math.random() * Math.PI;
return out[0] = Math.cos(r) * scale, out[1] = Math.sin(r) * scale, out;
};
/***/ },
/* 185 */ /***/ function(module1, exports1) {
module1.exports = /**
* Transforms the vec2 with a mat2
*
* @param {vec2} out the receiving vector
* @param {vec2} a the vector to transform
* @param {mat2} m matrix to transform with
* @returns {vec2} out
*/ function(out, a, m) {
var x = a[0], y = a[1];
return out[0] = m[0] * x + m[2] * y, out[1] = m[1] * x + m[3] * y, out;
};
/***/ },
/* 186 */ /***/ function(module1, exports1) {
module1.exports = /**
* Transforms the vec2 with a mat2d
*
* @param {vec2} out the receiving vector
* @param {vec2} a the vector to transform
* @param {mat2d} m matrix to transform with
* @returns {vec2} out
*/ function(out, a, m) {
var x = a[0], y = a[1];
return out[0] = m[0] * x + m[2] * y + m[4], out[1] = m[1] * x + m[3] * y + m[5], out;
};
/***/ },
/* 187 */ /***/ function(module1, exports1) {
module1.exports = /**
* Transforms the vec2 with a mat3
* 3rd vector component is implicitly '1'
*
* @param {vec2} out the receiving vector
* @param {vec2} a the vector to transform
* @param {mat3} m matrix to transform with
* @returns {vec2} out
*/ function(out, a, m) {
var x = a[0], y = a[1];
return out[0] = m[0] * x + m[3] * y + m[6], out[1] = m[1] * x + m[4] * y + m[7], out;
};
/***/ },
/* 188 */ /***/ function(module1, exports1) {
module1.exports = /**
* Transforms the vec2 with a mat4
* 3rd vector component is implicitly '0'
* 4th vector component is implicitly '1'
*
* @param {vec2} out the receiving vector
* @param {vec2} a the vector to transform
* @param {mat4} m matrix to transform with
* @returns {vec2} out
*/ function(out, a, m) {
var x = a[0], y = a[1];
return out[0] = m[0] * x + m[4] * y + m[12], out[1] = m[1] * x + m[5] * y + m[13], out;
};
/***/ },
/* 189 */ /***/ function(module1, exports1, __webpack_require__) {
module1.exports = /**
* Perform some operation over an array of vec2s.
*
* @param {Array} a the array of vectors to iterate over
* @param {Number} stride Number of elements between the start of each vec2. If 0 assumes tightly packed
* @param {Number} offset Number of elements to skip at the beginning of the array
* @param {Number} count Number of vec2s to iterate over. If 0 iterates over entire array
* @param {Function} fn Function to call for each vector in the array
* @param {Object} [arg] additional argument to pass to fn
* @returns {Array} a
* @function
*/ function(a, stride, offset, count, fn, arg) {
var i, l;
for(stride || (stride = 2), offset || (offset = 0), l = count ? Math.min(count * stride + offset, a.length) : a.length, i = offset; i < l; i += stride)vec[0] = a[i], vec[1] = a[i + 1], fn(vec, vec, arg), a[i] = vec[0], a[i + 1] = vec[1];
return a;
};
var vec = __webpack_require__(63)();
/***/ },
/* 190 */ /***/ function(module1, exports1) {
module1.exports = /**
* Limit the magnitude of this vector to the value used for the `max`
* parameter.
*
* @param {vec2} the vector to limit
* @param {Number} max the maximum magnitude for the vector
* @returns {vec2} out
*/ function(out, a, max) {
var mSq = a[0] * a[0] + a[1] * a[1];
if (mSq > max * max) {
var n = Math.sqrt(mSq);
out[0] = a[0] / n * max, out[1] = a[1] / n * max;
} else out[0] = a[0], out[1] = a[1];
return out;
};
/***/ },
/* 191 */ /***/ function(module1, exports1) {
module1.exports = /**
* Creates a new vec3 initialized with values from an existing vector
*
* @param {vec3} a vector to clone
* @returns {vec3} a new 3D vector
*/ function(a) {
var out = new Float32Array(3);
return out[0] = a[0], out[1] = a[1], out[2] = a[2], out;
};
/***/ },
/* 192 */ /***/ function(module1, exports1, __webpack_require__) {
module1.exports = /**
* Get the angle between two 3D vectors
* @param {vec3} a The first operand
* @param {vec3} b The second operand
* @returns {Number} The angle in radians
*/ function(a, b) {
var tempA = fromValues(a[0], a[1], a[2]), tempB = fromValues(b[0], b[1], b[2]);
normalize(tempA, tempA), normalize(tempB, tempB);
var cosine = dot(tempA, tempB);
return cosine > 1.0 ? 0 : Math.acos(cosine);
};
var fromValues = __webpack_require__(73), normalize = __webpack_require__(74), dot = __webpack_require__(75);
/***/ },
/* 193 */ /***/ function(module1, exports1) {
module1.exports = /**
* Copy the values from one vec3 to another
*
* @param {vec3} out the receiving vector
* @param {vec3} a the source vector
* @returns {vec3} out
*/ function(out, a) {
return out[0] = a[0], out[1] = a[1], out[2] = a[2], out;
};
/***/ },
/* 194 */ /***/ function(module1, exports1) {
module1.exports = /**
* Set the components of a vec3 to the given values
*
* @param {vec3} out the receiving vector
* @param {Number} x X component
* @param {Number} y Y component
* @param {Number} z Z component
* @returns {vec3} out
*/ function(out, x, y, z) {
return out[0] = x, out[1] = y, out[2] = z, out;
};
/***/ },
/* 195 */ /***/ function(module1, exports1, __webpack_require__) {
module1.exports = /**
* Returns whether or not the vectors have approximately the same elements in the same position.
*
* @param {vec3} a The first vector.
* @param {vec3} b The second vector.
* @returns {Boolean} True if the vectors are equal, false otherwise.
*/ function(a, b) {
var a0 = a[0], a1 = a[1], a2 = a[2], b0 = b[0], b1 = b[1], b2 = b[2];
return Math.abs(a0 - b0) <= EPSILON * Math.max(1.0, Math.abs(a0), Math.abs(b0)) && Math.abs(a1 - b1) <= EPSILON * Math.max(1.0, Math.abs(a1), Math.abs(b1)) && Math.abs(a2 - b2) <= EPSILON * Math.max(1.0, Math.abs(a2), Math.abs(b2));
};
var EPSILON = __webpack_require__(71);
/***/ },
/* 196 */ /***/ function(module1, exports1) {
module1.exports = /**
* Returns whether or not the vectors exactly have the same elements in the same position (when compared with ===)
*
* @param {vec3} a The first vector.
* @param {vec3} b The second vector.
* @returns {Boolean} True if the vectors are equal, false otherwise.
*/ function(a, b) {
return a[0] === b[0] && a[1] === b[1] && a[2] === b[2];
};
/***/ },
/* 197 */ /***/ function(module1, exports1) {
module1.exports = /**
* Adds two vec3's
*
* @param {vec3} out the receiving vector
* @param {vec3} a the first operand
* @param {vec3} b the second operand
* @returns {vec3} out
*/ function(out, a, b) {
return out[0] = a[0] + b[0], out[1] = a[1] + b[1], out[2] = a[2] + b[2], out;
};
/***/ },
/* 198 */ /***/ function(module1, exports1, __webpack_require__) {
module1.exports = __webpack_require__(76);
/***/ },
/* 199 */ /***/ function(module1, exports1, __webpack_require__) {
module1.exports = __webpack_require__(77);
/***/ },
/* 200 */ /***/ function(module1, exports1, __webpack_require__) {
module1.exports = __webpack_require__(78);
/***/ },
/* 201 */ /***/ function(module1, exports1) {
module1.exports = /**
* Returns the minimum of two vec3's
*
* @param {vec3} out the receiving vector
* @param {vec3} a the first operand
* @param {vec3} b the second operand
* @returns {vec3} out
*/ function(out, a, b) {
return out[0] = Math.min(a[0], b[0]), out[1] = Math.min(a[1], b[1]), out[2] = Math.min(a[2], b[2]), out;
};
/***/ },
/* 202 */ /***/ function(module1, exports1) {
module1.exports = /**
* Returns the maximum of two vec3's
*
* @param {vec3} out the receiving vector
* @param {vec3} a the first operand
* @param {vec3} b the second operand
* @returns {vec3} out
*/ function(out, a, b) {
return out[0] = Math.max(a[0], b[0]), out[1] = Math.max(a[1], b[1]), out[2] = Math.max(a[2], b[2]), out;
};
/***/ },
/* 203 */ /***/ function(module1, exports1) {
module1.exports = /**
* Math.floor the components of a vec3
*
* @param {vec3} out the receiving vector
* @param {vec3} a vector to floor
* @returns {vec3} out
*/ function(out, a) {
return out[0] = Math.floor(a[0]), out[1] = Math.floor(a[1]), out[2] = Math.floor(a[2]), out;
};
/***/ },
/* 204 */ /***/ function(module1, exports1) {
module1.exports = /**
* Math.ceil the components of a vec3
*
* @param {vec3} out the receiving vector
* @param {vec3} a vector to ceil
* @returns {vec3} out
*/ function(out, a) {
return out[0] = Math.ceil(a[0]), out[1] = Math.ceil(a[1]), out[2] = Math.ceil(a[2]), out;
};
/***/ },
/* 205 */ /***/ function(module1, exports1) {
module1.exports = /**
* Math.round the components of a vec3
*
* @param {vec3} out the receiving vector
* @param {vec3} a vector to round
* @returns {vec3} out
*/ function(out, a) {
return out[0] = Math.round(a[0]), out[1] = Math.round(a[1]), out[2] = Math.round(a[2]), out;
};
/***/ },
/* 206 */ /***/ function(module1, exports1) {
module1.exports = /**
* Scales a vec3 by a scalar number
*
* @param {vec3} out the receiving vector
* @param {vec3} a the vector to scale
* @param {Number} b amount to scale the vector by
* @returns {vec3} out
*/ function(out, a, b) {
return out[0] = a[0] * b, out[1] = a[1] * b, out[2] = a[2] * b, out;
};
/***/ },
/* 207 */ /***/ function(module1, exports1) {
module1.exports = /**
* Adds two vec3's after scaling the second operand by a scalar value
*
* @param {vec3} out the receiving vector
* @param {vec3} a the first operand
* @param {vec3} b the second operand
* @param {Number} scale the amount to scale b by before adding
* @returns {vec3} out
*/ function(out, a, b, scale) {
return out[0] = a[0] + b[0] * scale, out[1] = a[1] + b[1] * scale, out[2] = a[2] + b[2] * scale, out;
};
/***/ },
/* 208 */ /***/ function(module1, exports1, __webpack_require__) {
module1.exports = __webpack_require__(79);
/***/ },
/* 209 */ /***/ function(module1, exports1, __webpack_require__) {
module1.exports = __webpack_require__(80);
/***/ },
/* 210 */ /***/ function(module1, exports1, __webpack_require__) {
module1.exports = __webpack_require__(81);
/***/ },
/* 211 */ /***/ function(module1, exports1, __webpack_require__) {
module1.exports = __webpack_require__(82);
/***/ },
/* 212 */ /***/ function(module1, exports1) {
module1.exports = /**
* Negates the components of a vec3
*
* @param {vec3} out the receiving vector
* @param {vec3} a vector to negate
* @returns {vec3} out
*/ function(out, a) {
return out[0] = -a[0], out[1] = -a[1], out[2] = -a[2], out;
};
/***/ },
/* 213 */ /***/ function(module1, exports1) {
module1.exports = /**
* Returns the inverse of the components of a vec3
*
* @param {vec3} out the receiving vector
* @param {vec3} a vector to invert
* @returns {vec3} out
*/ function(out, a) {
return out[0] = 1.0 / a[0], out[1] = 1.0 / a[1], out[2] = 1.0 / a[2], out;
};
/***/ },
/* 214 */ /***/ function(module1, exports1) {
module1.exports = /**
* Computes the cross product of two vec3's
*
* @param {vec3} out the receiving vector
* @param {vec3} a the first operand
* @param {vec3} b the second operand
* @returns {vec3} out
*/ function(out, a, b) {
var ax = a[0], ay = a[1], az = a[2], bx = b[0], by = b[1], bz = b[2];
return out[0] = ay * bz - az * by, out[1] = az * bx - ax * bz, out[2] = ax * by - ay * bx, out;
};
/***/ },
/* 215 */ /***/ function(module1, exports1) {
module1.exports = /**
* Performs a linear interpolation between two vec3's
*
* @param {vec3} out the receiving vector
* @param {vec3} a the first operand
* @param {vec3} b the second operand
* @param {Number} t interpolation amount between the two inputs
* @returns {vec3} out
*/ function(out, a, b, t) {
var ax = a[0], ay = a[1], az = a[2];
return out[0] = ax + t * (b[0] - ax), out[1] = ay + t * (b[1] - ay), out[2] = az + t * (b[2] - az), out;
};
/***/ },
/* 216 */ /***/ function(module1, exports1) {
module1.exports = /**
* Generates a random vector with the given scale
*
* @param {vec3} out the receiving vector
* @param {Number} [scale] Length of the resulting vector. If ommitted, a unit vector will be returned
* @returns {vec3} out
*/ function(out, scale) {
var r = 2.0 * Math.random() * Math.PI, z = 2.0 * Math.random() - 1.0, zScale = Math.sqrt(1.0 - z * z) * (scale = scale || 1.0);
return out[0] = Math.cos(r) * zScale, out[1] = Math.sin(r) * zScale, out[2] = z * scale, out;
};
/***/ },
/* 217 */ /***/ function(module1, exports1) {
module1.exports = /**
* Transforms the vec3 with a mat4.
* 4th vector component is implicitly '1'
*
* @param {vec3} out the receiving vector
* @param {vec3} a the vector to transform
* @param {mat4} m matrix to transform with
* @returns {vec3} out
*/ function(out, a, m) {
var x = a[0], y = a[1], z = a[2], w = m[3] * x + m[7] * y + m[11] * z + m[15];
return w = w || 1.0, out[0] = (m[0] * x + m[4] * y + m[8] * z + m[12]) / w, out[1] = (m[1] * x + m[5] * y + m[9] * z + m[13]) / w, out[2] = (m[2] * x + m[6] * y + m[10] * z + m[14]) / w, out;
};
/***/ },
/* 218 */ /***/ function(module1, exports1) {
module1.exports = /**
* Transforms the vec3 with a mat3.
*
* @param {vec3} out the receiving vector
* @param {vec3} a the vector to transform
* @param {mat4} m the 3x3 matrix to transform with
* @returns {vec3} out
*/ function(out, a, m) {
var x = a[0], y = a[1], z = a[2];
return out[0] = x * m[0] + y * m[3] + z * m[6], out[1] = x * m[1] + y * m[4] + z * m[7], out[2] = x * m[2] + y * m[5] + z * m[8], out;
};
/***/ },
/* 219 */ /***/ function(module1, exports1) {
module1.exports = /**
* Transforms the vec3 with a quat
*
* @param {vec3} out the receiving vector
* @param {vec3} a the vector to transform
* @param {quat} q quaternion to transform with
* @returns {vec3} out
*/ function(out, a, q) {
// benchmarks: http://jsperf.com/quaternion-transform-vec3-implementations
var x = a[0], y = a[1], z = a[2], qx = q[0], qy = q[1], qz = q[2], qw = q[3], // calculate quat * vec
ix = qw * x + qy * z - qz * y, iy = qw * y + qz * x - qx * z, iz = qw * z + qx * y - qy * x, iw = -qx * x - qy * y - qz * z; // calculate result * inverse quat
return out[0] = ix * qw + -(iw * qx) + -(iy * qz) - -(iz * qy), out[1] = iy * qw + -(iw * qy) + -(iz * qx) - -(ix * qz), out[2] = iz * qw + -(iw * qz) + -(ix * qy) - -(iy * qx), out;
};
/***/ },
/* 220 */ /***/ function(module1, exports1) {
module1.exports = /**
* Rotate a 3D vector around the x-axis
* @param {vec3} out The receiving vec3
* @param {vec3} a The vec3 point to rotate
* @param {vec3} b The origin of the rotation
* @param {Number} c The angle of rotation
* @returns {vec3} out
*/ function(out, a, b, c) {
var by = b[1], bz = b[2], py = a[1] - by, pz = a[2] - bz, sc = Math.sin(c), cc = Math.cos(c);
return out[0] = a[0], out[1] = by + py * cc - pz * sc, out[2] = bz + py * sc + pz * cc, out;
};
/***/ },
/* 221 */ /***/ function(module1, exports1) {
module1.exports = /**
* Rotate a 3D vector around the y-axis
* @param {vec3} out The receiving vec3
* @param {vec3} a The vec3 point to rotate
* @param {vec3} b The origin of the rotation
* @param {Number} c The angle of rotation
* @returns {vec3} out
*/ function(out, a, b, c) {
var bx = b[0], bz = b[2], px = a[0] - bx, pz = a[2] - bz, sc = Math.sin(c), cc = Math.cos(c);
return out[0] = bx + pz * sc + px * cc, out[1] = a[1], out[2] = bz + pz * cc - px * sc, out;
};
/***/ },
/* 222 */ /***/ function(module1, exports1) {
module1.exports = /**
* Rotate a 3D vector around the z-axis
* @param {vec3} out The receiving vec3
* @param {vec3} a The vec3 point to rotate
* @param {vec3} b The origin of the rotation
* @param {Number} c The angle of rotation
* @returns {vec3} out
*/ function(out, a, b, c) {
var bx = b[0], by = b[1], px = a[0] - bx, py = a[1] - by, sc = Math.sin(c), cc = Math.cos(c);
return out[0] = bx + px * cc - py * sc, out[1] = by + px * sc + py * cc, out[2] = a[2], out;
};
/***/ },
/* 223 */ /***/ function(module1, exports1, __webpack_require__) {
module1.exports = /**
* Perform some operation over an array of vec3s.
*
* @param {Array} a the array of vectors to iterate over
* @param {Number} stride Number of elements between the start of each vec3. If 0 assumes tightly packed
* @param {Number} offset Number of elements to skip at the beginning of the array
* @param {Number} count Number of vec3s to iterate over. If 0 iterates over entire array
* @param {Function} fn Function to call for each vector in the array
* @param {Object} [arg] additional argument to pass to fn
* @returns {Array} a
* @function
*/ function(a, stride, offset, count, fn, arg) {
var i, l;
for(stride || (stride = 3), offset || (offset = 0), l = count ? Math.min(count * stride + offset, a.length) : a.length, i = offset; i < l; i += stride)vec[0] = a[i], vec[1] = a[i + 1], vec[2] = a[i + 2], fn(vec, vec, arg), a[i] = vec[0], a[i + 1] = vec[1], a[i + 2] = vec[2];
return a;
};
var vec = __webpack_require__(72)();
/***/ },
/* 224 */ /***/ function(module1, exports1, __webpack_require__) {
var arrayLikeToArray = __webpack_require__(61);
module1.exports = function(arr) {
if (Array.isArray(arr)) return arrayLikeToArray(arr);
}, module1.exports.default = module1.exports, module1.exports.__esModule = !0;
/***/ },
/* 225 */ /***/ function(module1, exports1) {
module1.exports = function(iter) {
if ("undefined" != typeof Symbol && null != iter[Symbol.iterator] || null != iter["@@iterator"]) return Array.from(iter);
}, module1.exports.default = module1.exports, module1.exports.__esModule = !0;
/***/ },
/* 226 */ /***/ function(module1, exports1) {
module1.exports = function() {
throw TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}, module1.exports.default = module1.exports, module1.exports.__esModule = !0;
/***/ },
/* 227 */ /***/ function(module1, exports1, __webpack_require__) {
var getPrototypeOf = __webpack_require__(2);
module1.exports = function(object, property) {
for(; !Object.prototype.hasOwnProperty.call(object, property) && null !== (object = getPrototypeOf(object)););
return object;
}, module1.exports.default = module1.exports, module1.exports.__esModule = !0;
/***/ },
/* 228 */ /***/ function(module1, exports1, __webpack_require__) {
/**
* Copyright (c) 2014-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/ var runtime = function(exports1) {
"use strict";
var undefined, Op = Object.prototype, hasOwn = Op.hasOwnProperty, $Symbol = "function" == typeof Symbol ? Symbol : {}, iteratorSymbol = $Symbol.iterator || "@@iterator", asyncIteratorSymbol = $Symbol.asyncIterator || "@@asyncIterator", toStringTagSymbol = $Symbol.toStringTag || "@@toStringTag";
function wrap(innerFn, outerFn, self1, tryLocsList) {
var context, state, generator = Object.create((outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator).prototype);
return context = new Context(tryLocsList || []), state = GenStateSuspendedStart, // .throw, and .return methods.
generator._invoke = function(method, arg) {
if (state === GenStateExecuting) throw Error("Generator is already running");
if (state === GenStateCompleted) {
if ("throw" === method) throw arg;
// Be forgiving, per 25.3.3.3.3 of the spec:
// https://people.mozilla.org/~jorendorff/es6-draft.html#sec-generatorresume
return doneResult();
}
for(context.method = method, context.arg = arg;;){
var delegate = context.delegate;
if (delegate) {
var delegateResult = // result, either by returning a { value, done } result from the
// delegate iterator, or by modifying context.method and context.arg,
// setting context.delegate to null, and returning the ContinueSentinel.
function maybeInvokeDelegate(delegate, context) {
var method = delegate.iterator[context.method];
if (undefined === method) {
if (// A .throw or .return when the delegate iterator has no .throw
// method always terminates the yield* loop.
context.delegate = null, "throw" === context.method) {
// Note: ["return"] must be used for ES3 parsing compatibility.
if (delegate.iterator.return && (// If the delegate iterator has a return method, give it a
// chance to clean up.
context.method = "return", context.arg = undefined, maybeInvokeDelegate(delegate, context), "throw" === context.method)) // If maybeInvokeDelegate(context) changed context.method from
// "return" to "throw", let that override the TypeError below.
return ContinueSentinel;
context.method = "throw", context.arg = TypeError("The iterator does not provide a 'throw' method");
}
return ContinueSentinel;
}
var record = tryCatch(method, delegate.iterator, context.arg);
if ("throw" === record.type) return context.method = "throw", context.arg = record.arg, context.delegate = null, ContinueSentinel;
var info = record.arg;
return info ? info.done ? (// Assign the result of the finished delegate to the temporary
// variable specified by delegate.resultName (see delegateYield).
context[delegate.resultName] = info.value, context.next = delegate.nextLoc, "return" !== context.method && (context.method = "next", context.arg = undefined), // the outer generator.
context.delegate = null, ContinueSentinel) : info : (context.method = "throw", context.arg = TypeError("iterator result is not an object"), context.delegate = null, ContinueSentinel);
} // Define Generator.prototype.{next,throw,return} in terms of the
(delegate, context);
if (delegateResult) {
if (delegateResult === ContinueSentinel) continue;
return delegateResult;
}
}
if ("next" === context.method) // Setting context._sent for legacy support of Babel's
// function.sent implementation.
context.sent = context._sent = context.arg;
else if ("throw" === context.method) {
if (state === GenStateSuspendedStart) throw state = GenStateCompleted, context.arg;
context.dispatchException(context.arg);
} else "return" === context.method && context.abrupt("return", context.arg);
state = GenStateExecuting;
var record = tryCatch(innerFn, self1, context);
if ("normal" === record.type) {
if (// If an exception is thrown from innerFn, we leave state ===
// GenStateExecuting and loop back for another invocation.
state = context.done ? GenStateCompleted : "suspendedYield", record.arg === ContinueSentinel) continue;
return {
value: record.arg,
done: context.done
};
}
"throw" === record.type && (state = GenStateCompleted, // context.dispatchException(context.arg) call above.
context.method = "throw", context.arg = record.arg);
}
}, generator;
}
// record like context.tryEntries[i].completion. This interface could
// have been (and was previously) designed to take a closure to be
// invoked without arguments, but in all the cases we care about we
// already have an existing method we want to call, so there's no need
// to create a new function object. We can even get away with assuming
// the method takes exactly one argument, since that happens to be true
// in every case, so we don't have to touch the arguments object. The
// only additional allocation required is the completion record, which
// has a stable shape and so hopefully should be cheap to allocate.
function tryCatch(fn, obj, arg) {
try {
return {
type: "normal",
arg: fn.call(obj, arg)
};
} catch (err) {
return {
type: "throw",
arg: err
};
}
}
exports1.wrap = wrap;
var GenStateSuspendedStart = "suspendedStart", GenStateExecuting = "executing", GenStateCompleted = "completed", ContinueSentinel = {};
// .constructor.prototype properties for functions that return Generator
// objects. For full spec compliance, you may wish to configure your
// minifier not to mangle the names of these two functions.
function Generator() {}
function GeneratorFunction() {}
function GeneratorFunctionPrototype() {} // This is a polyfill for %IteratorPrototype% for environments that
// don't natively support it.
var IteratorPrototype = {};
IteratorPrototype[iteratorSymbol] = function() {
return this;
};
var getProto = Object.getPrototypeOf, NativeIteratorPrototype = getProto && getProto(getProto(values([])));
NativeIteratorPrototype && NativeIteratorPrototype !== Op && hasOwn.call(NativeIteratorPrototype, iteratorSymbol) && // This environment has a native %IteratorPrototype%; use it instead
// of the polyfill.
(IteratorPrototype = NativeIteratorPrototype);
var Gp = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(IteratorPrototype);
// Iterator interface in terms of a single ._invoke method.
function defineIteratorMethods(prototype) {
[
"next",
"throw",
"return"
].forEach(function(method) {
prototype[method] = function(arg) {
return this._invoke(method, arg);
};
});
}
function AsyncIterator(generator, PromiseImpl) {
var previousPromise;
// .throw, and .return (see defineIteratorMethods).
this._invoke = function(method, arg) {
function callInvokeWithMethodAndArg() {
return new PromiseImpl(function(resolve, reject) {
!function invoke(method, arg, resolve, reject) {
var record = tryCatch(generator[method], generator, arg);
if ("throw" === record.type) reject(record.arg);
else {
var result = record.arg, value = result.value;
return value && "object" == typeof value && hasOwn.call(value, "__await") ? PromiseImpl.resolve(value.__await).then(function(value) {
invoke("next", value, resolve, reject);
}, function(err) {
invoke("throw", err, resolve, reject);
}) : PromiseImpl.resolve(value).then(function(unwrapped) {
// When a yielded Promise is resolved, its final value becomes
// the .value of the Promise<{value,done}> result for the
// current iteration.
result.value = unwrapped, resolve(result);
}, function(error) {
// If a rejected Promise was yielded, throw the rejection back
// into the async generator function so it can be handled there.
return invoke("throw", error, resolve, reject);
});
}
}(method, arg, resolve, reject);
});
}
return previousPromise = // all previous Promises have been resolved before calling invoke,
// so that results are always delivered in the correct order. If
// enqueue has not been called before, then it is important to
// call invoke immediately, without waiting on a callback to fire,
// so that the async generator function has the opportunity to do
// any necessary setup in a predictable way. This predictability
// is why the Promise constructor synchronously invokes its
// executor callback, and why async functions synchronously
// execute code before the first await. Since we implement simple
// async functions in terms of async generators, it is especially
// important to get this right, even though it requires care.
previousPromise ? previousPromise.then(callInvokeWithMethodAndArg, // invocations of the iterator.
callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg();
} // Define the unified helper method that is used to implement .next,
;
}
function pushTryEntry(locs) {
var entry = {
tryLoc: locs[0]
};
1 in locs && (entry.catchLoc = locs[1]), 2 in locs && (entry.finallyLoc = locs[2], entry.afterLoc = locs[3]), this.tryEntries.push(entry);
}
function resetTryEntry(entry) {
var record = entry.completion || {};
record.type = "normal", delete record.arg, entry.completion = record;
}
function Context(tryLocsList) {
// The root entry object (effectively a try statement without a catch
// or a finally block) gives us a place to store values thrown from
// locations where there is no enclosing try statement.
this.tryEntries = [
{
tryLoc: "root"
}
], tryLocsList.forEach(pushTryEntry, this), this.reset(!0);
}
function values(iterable) {
if (iterable) {
var iteratorMethod = iterable[iteratorSymbol];
if (iteratorMethod) return iteratorMethod.call(iterable);
if ("function" == typeof iterable.next) return iterable;
if (!isNaN(iterable.length)) {
var i = -1, next = function next() {
for(; ++i < iterable.length;)if (hasOwn.call(iterable, i)) return next.value = iterable[i], next.done = !1, next;
return next.value = undefined, next.done = !0, next;
};
return next.next = next;
}
} // Return an iterator with no values.
return {
next: doneResult
};
}
function doneResult() {
return {
value: undefined,
done: !0
};
}
// or not, return the runtime object so that we can declare the variable
// regeneratorRuntime in the outer scope, which allows this module to be
// injected easily by `bin/regenerator --include-runtime script.js`.
return GeneratorFunction.prototype = Gp.constructor = GeneratorFunctionPrototype, GeneratorFunctionPrototype.constructor = GeneratorFunction, GeneratorFunctionPrototype[toStringTagSymbol] = GeneratorFunction.displayName = "GeneratorFunction", exports1.isGeneratorFunction = function(genFun) {
var ctor = "function" == typeof genFun && genFun.constructor;
return !!ctor && (ctor === GeneratorFunction || "GeneratorFunction" === // For the native GeneratorFunction constructor, the best we can
// do is to check its .name property.
(ctor.displayName || ctor.name));
}, exports1.mark = function(genFun) {
return Object.setPrototypeOf ? Object.setPrototypeOf(genFun, GeneratorFunctionPrototype) : (genFun.__proto__ = GeneratorFunctionPrototype, toStringTagSymbol in genFun || (genFun[toStringTagSymbol] = "GeneratorFunction")), genFun.prototype = Object.create(Gp), genFun;
}, // `yield regeneratorRuntime.awrap(x)`, so that the runtime can test
// `hasOwn.call(value, "__await")` to determine if the yielded value is
// meant to be awaited.
exports1.awrap = function(arg) {
return {
__await: arg
};
}, defineIteratorMethods(AsyncIterator.prototype), AsyncIterator.prototype[asyncIteratorSymbol] = function() {
return this;
}, exports1.AsyncIterator = AsyncIterator, // AsyncIterator objects; they just return a Promise for the value of
// the final result produced by the iterator.
exports1.async = function(innerFn, outerFn, self1, tryLocsList, PromiseImpl) {
void 0 === PromiseImpl && (PromiseImpl = Promise);
var iter = new AsyncIterator(wrap(innerFn, outerFn, self1, tryLocsList), PromiseImpl);
return exports1.isGeneratorFunction(outerFn) ? iter // If outerFn is a generator, return the full iterator.
: iter.next().then(function(result) {
return result.done ? result.value : iter.next();
});
}, // unified ._invoke helper method.
defineIteratorMethods(Gp), Gp[toStringTagSymbol] = "Generator", // @@iterator function is called on it. Some browsers' implementations of the
// iterator prototype chain incorrectly implement this, causing the Generator
// object to not be returned from this call. This ensures that doesn't happen.
// See https://github.com/facebook/regenerator/issues/274 for more details.
Gp[iteratorSymbol] = function() {
return this;
}, Gp.toString = function() {
return "[object Generator]";
}, exports1.keys = function(object) {
var keys = [];
for(var key in object)keys.push(key);
// things simple and return the next function itself.
return keys.reverse(), function next() {
for(; keys.length;){
var key = keys.pop();
if (key in object) return next.value = key, next.done = !1, next;
} // To avoid creating an additional object, we just hang the .value
return(// and .done properties off the next function object itself. This
// also ensures that the minifier will not anonymize the function.
next.done = !0, next);
};
}, exports1.values = values, Context.prototype = {
constructor: Context,
reset: function(skipTempReset) {
if (this.prev = 0, this.next = 0, // function.sent implementation.
this.sent = this._sent = undefined, this.done = !1, this.delegate = null, this.method = "next", this.arg = undefined, this.tryEntries.forEach(resetTryEntry), !skipTempReset) for(var name in this)// Not sure about the optimal order of these conditions:
"t" === name.charAt(0) && hasOwn.call(this, name) && !isNaN(+name.slice(1)) && (this[name] = undefined);
},
stop: function() {
this.done = !0;
var rootRecord = this.tryEntries[0].completion;
if ("throw" === rootRecord.type) throw rootRecord.arg;
return this.rval;
},
dispatchException: function(exception) {
if (this.done) throw exception;
var context = this;
function handle(loc, caught) {
return record.type = "throw", record.arg = exception, context.next = loc, caught && (// If the dispatched exception was caught by a catch block,
// then let that catch block handle the exception normally.
context.method = "next", context.arg = undefined), !!caught;
}
for(var i = this.tryEntries.length - 1; i >= 0; --i){
var entry = this.tryEntries[i], record = entry.completion;
if ("root" === entry.tryLoc) // Exception thrown outside of any try block that could handle
// it, so set the completion value of the entire function to
// throw the exception.
return handle("end");
if (entry.tryLoc <= this.prev) {
var hasCatch = hasOwn.call(entry, "catchLoc"), hasFinally = hasOwn.call(entry, "finallyLoc");
if (hasCatch && hasFinally) {
if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0);
if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc);
} else if (hasCatch) {
if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0);
} else if (hasFinally) {
if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc);
} else throw Error("try statement without catch or finally");
}
}
},
abrupt: function(type, arg) {
for(var i = this.tryEntries.length - 1; i >= 0; --i){
var entry = this.tryEntries[i];
if (entry.tryLoc <= this.prev && hasOwn.call(entry, "finallyLoc") && this.prev < entry.finallyLoc) {
var finallyEntry = entry;
break;
}
}
finallyEntry && ("break" === type || "continue" === type) && finallyEntry.tryLoc <= arg && arg <= finallyEntry.finallyLoc && // Ignore the finally entry if control is not jumping to a
// location outside the try/catch block.
(finallyEntry = null);
var record = finallyEntry ? finallyEntry.completion : {};
return (record.type = type, record.arg = arg, finallyEntry) ? (this.method = "next", this.next = finallyEntry.finallyLoc, ContinueSentinel) : this.complete(record);
},
complete: function(record, afterLoc) {
if ("throw" === record.type) throw record.arg;
return "break" === record.type || "continue" === record.type ? this.next = record.arg : "return" === record.type ? (this.rval = this.arg = record.arg, this.method = "return", this.next = "end") : "normal" === record.type && afterLoc && (this.next = afterLoc), ContinueSentinel;
},
finish: function(finallyLoc) {
for(var i = this.tryEntries.length - 1; i >= 0; --i){
var entry = this.tryEntries[i];
if (entry.finallyLoc === finallyLoc) return this.complete(entry.completion, entry.afterLoc), resetTryEntry(entry), ContinueSentinel;
}
},
catch: function(tryLoc) {
for(var i = this.tryEntries.length - 1; i >= 0; --i){
var entry = this.tryEntries[i];
if (entry.tryLoc === tryLoc) {
var record = entry.completion;
if ("throw" === record.type) {
var thrown = record.arg;
resetTryEntry(entry);
}
return thrown;
}
} // The context.catch method must only be called with a location
// argument that corresponds to a known catch block.
throw Error("illegal catch attempt");
},
delegateYield: function(iterable, resultName, nextLoc) {
return this.delegate = {
iterator: values(iterable),
resultName: resultName,
nextLoc: nextLoc
}, "next" === this.method && // Deliberately forget the last sent value so that we don't
// accidentally pass it on to the delegate.
(this.arg = undefined), ContinueSentinel;
}
}, exports1;
}(// If this script is executing as a CommonJS module, use module.exports
// as the regeneratorRuntime namespace. Otherwise create a new empty
// object. Either way, the resulting object will be used to initialize
// the regeneratorRuntime variable at the top of this file.
module1.exports);
try {
regeneratorRuntime = runtime;
} catch (accidentalStrictMode) {
// This module should not be running in strict mode, so the above
// assignment should always work unless something is misconfigured. Just
// in case runtime.js accidentally runs in strict mode, we can escape
// strict mode using a global Function call. This could conceivably fail
// if a Content Security Policy forbids using Function, but in that case
// the proper solution is to fix the accidental strict mode problem. If
// you've misconfigured your bundler to force strict mode and applied a
// CSP to forbid Function, and you're not willing to fix either of those
// problems, please detail your unique predicament in a GitHub issue.
Function("r", "regeneratorRuntime = r")(runtime);
}
/***/ },
/* 229 */ /***/ function(module1, exports1, __webpack_require__) {
var basePickBy = __webpack_require__(230), hasIn = __webpack_require__(240);
module1.exports = /**
* 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(object, paths) {
return basePickBy(object, paths, function(value, path) {
return hasIn(object, path);
});
};
/***/ },
/* 230 */ /***/ function(module1, exports1, __webpack_require__) {
var baseGet = __webpack_require__(231), baseSet = __webpack_require__(239), castPath = __webpack_require__(32);
module1.exports = /**
* 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(object, paths, predicate) {
for(var index = -1, length = paths.length, result = {}; ++index < length;){
var path = paths[index], value = baseGet(object, path);
predicate(value, path) && baseSet(result, castPath(path, object), value);
}
return result;
};
/***/ },
/* 231 */ /***/ function(module1, exports1, __webpack_require__) {
var castPath = __webpack_require__(32), toKey = __webpack_require__(43);
module1.exports = /**
* 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(object, path) {
path = castPath(path, object);
for(var index = 0, length = path.length; null != object && index < length;)object = object[toKey(path[index++])];
return index && index == length ? object : void 0;
};
/***/ },
/* 232 */ /***/ function(module1, exports1, __webpack_require__) {
var isArray = __webpack_require__(15), isSymbol = __webpack_require__(42), reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/, reIsPlainProp = /^\w*$/;
module1.exports = /**
* 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(value, object) {
if (isArray(value)) return !1;
var type = typeof value;
return !!("number" == type || "symbol" == type || "boolean" == type || null == value || isSymbol(value)) || reIsPlainProp.test(value) || !reIsDeepProp.test(value) || null != object && value in Object(object);
};
/***/ },
/* 233 */ /***/ function(module1, exports1, __webpack_require__) {
var memoizeCapped = __webpack_require__(234), rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g, reEscapeChar = /\\(\\)?/g;
module1.exports = memoizeCapped(function(string) {
var result = [];
return 46 === string.charCodeAt(0) && result.push(""), string.replace(rePropName, function(match, number, quote, subString) {
result.push(quote ? subString.replace(reEscapeChar, "$1") : number || match);
}), result;
});
/***/ },
/* 234 */ /***/ function(module1, exports1, __webpack_require__) {
var memoize = __webpack_require__(235);
module1.exports = /**
* 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(func) {
var result = memoize(func, function(key) {
return 500 === cache.size && cache.clear(), key;
}), cache = result.cache;
return result;
};
/***/ },
/* 235 */ /***/ function(module1, exports1, __webpack_require__) {
var MapCache = __webpack_require__(47);
/**
* 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 ("function" != typeof func || null != resolver && "function" != typeof resolver) throw TypeError("Expected a function");
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);
return memoized.cache = cache.set(key, result) || cache, result;
};
return memoized.cache = new (memoize.Cache || MapCache)(), memoized;
} // Expose `MapCache`.
memoize.Cache = MapCache, module1.exports = memoize;
/***/ },
/* 236 */ /***/ function(module1, exports1, __webpack_require__) {
var baseToString = __webpack_require__(237);
module1.exports = /**
* 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(value) {
return null == value ? "" : baseToString(value);
};
/***/ },
/* 237 */ /***/ function(module1, exports1, __webpack_require__) {
var Symbol1 = __webpack_require__(27), arrayMap = __webpack_require__(238), isArray = __webpack_require__(15), isSymbol = __webpack_require__(42), INFINITY = 1 / 0, symbolProto = Symbol1 ? Symbol1.prototype : void 0, symbolToString = symbolProto ? symbolProto.toString : void 0;
module1.exports = /**
* 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 ("string" == typeof value) 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 "0" == result && 1 / value == -INFINITY ? "-0" : result;
};
/***/ },
/* 238 */ /***/ function(module1, exports1) {
module1.exports = /**
* 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(array, iteratee) {
for(var index = -1, length = null == array ? 0 : array.length, result = Array(length); ++index < length;)result[index] = iteratee(array[index], index, array);
return result;
};
/***/ },
/* 239 */ /***/ function(module1, exports1, __webpack_require__) {
var assignValue = __webpack_require__(55), castPath = __webpack_require__(32), isIndex = __webpack_require__(31), isObject = __webpack_require__(14), toKey = __webpack_require__(43);
module1.exports = /**
* 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(object, path, value, customizer) {
if (!isObject(object)) return object;
path = castPath(path, object);
for(var index = -1, length = path.length, lastIndex = length - 1, nested = object; null != nested && ++index < length;){
var key = toKey(path[index]), newValue = value;
if ("__proto__" === key || "constructor" === key || "prototype" === key) break;
if (index != lastIndex) {
var objValue = nested[key];
void 0 === (newValue = customizer ? customizer(objValue, key, nested) : void 0) && (newValue = isObject(objValue) ? objValue : isIndex(path[index + 1]) ? [] : {});
}
assignValue(nested, key, newValue), nested = nested[key];
}
return object;
};
/***/ },
/* 240 */ /***/ function(module1, exports1, __webpack_require__) {
var baseHasIn = __webpack_require__(241), hasPath = __webpack_require__(242);
module1.exports = /**
* 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(object, path) {
return null != object && hasPath(object, path, baseHasIn);
};
/***/ },
/* 241 */ /***/ function(module1, exports1) {
module1.exports = /**
* 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(object, key) {
return null != object && key in Object(object);
};
/***/ },
/* 242 */ /***/ function(module1, exports1, __webpack_require__) {
var castPath = __webpack_require__(32), isArguments = __webpack_require__(30), isArray = __webpack_require__(15), isIndex = __webpack_require__(31), isLength = __webpack_require__(40), toKey = __webpack_require__(43);
module1.exports = /**
* 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(object, path, hasFunc) {
path = castPath(path, object);
for(var index = -1, length = path.length, result = !1; ++index < length;){
var key = toKey(path[index]);
if (!(result = null != object && hasFunc(object, key))) break;
object = object[key];
}
return result || ++index != length ? result : !!(length = null == object ? 0 : object.length) && isLength(length) && isIndex(key, length) && (isArray(object) || isArguments(object));
};
/***/ },
/* 243 */ /***/ function(module1, exports1, __webpack_require__) {
var flatten = __webpack_require__(244), overRest = __webpack_require__(58), setToString = __webpack_require__(59);
module1.exports = /**
* 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(func) {
return setToString(overRest(func, void 0, flatten), func + "");
};
/***/ },
/* 244 */ /***/ function(module1, exports1, __webpack_require__) {
var baseFlatten = __webpack_require__(245);
module1.exports = /**
* 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(array) {
return (null == array ? 0 : array.length) ? baseFlatten(array, 1) : [];
};
/***/ },
/* 245 */ /***/ function(module1, exports1, __webpack_require__) {
var arrayPush = __webpack_require__(246), isFlattenable = __webpack_require__(247);
module1.exports = /**
* 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;
for(predicate || (predicate = isFlattenable), result || (result = []); ++index < length;){
var value = array[index];
depth > 0 && predicate(value) ? depth > 1 ? // Recursively flatten arrays (susceptible to call stack limits).
baseFlatten(value, depth - 1, predicate, isStrict, result) : arrayPush(result, value) : isStrict || (result[result.length] = value);
}
return result;
};
/***/ },
/* 246 */ /***/ function(module1, exports1) {
module1.exports = /**
* 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(array, values) {
for(var index = -1, length = values.length, offset = array.length; ++index < length;)array[offset + index] = values[index];
return array;
};
/***/ },
/* 247 */ /***/ function(module1, exports1, __webpack_require__) {
var Symbol1 = __webpack_require__(27), isArguments = __webpack_require__(30), isArray = __webpack_require__(15), spreadableSymbol = Symbol1 ? Symbol1.isConcatSpreadable : void 0;
module1.exports = /**
* 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(value) {
return isArray(value) || isArguments(value) || !!(spreadableSymbol && value && value[spreadableSymbol]);
};
/***/ },
/* 248 */ /***/ function(module1, exports1) {
module1.exports = function(fn) {
return -1 !== Function.toString.call(fn).indexOf("[native code]");
}, module1.exports.default = module1.exports, module1.exports.__esModule = !0;
/***/ },
/* 249 */ /***/ function(module1, exports1, __webpack_require__) {
var setPrototypeOf = __webpack_require__(41), isNativeReflectConstruct = __webpack_require__(250);
function _construct(Parent, args, Class) {
return isNativeReflectConstruct() ? module1.exports = _construct = Reflect.construct : module1.exports = _construct = function(Parent, args, Class) {
var a = [
null
];
a.push.apply(a, args);
var instance = new (Function.bind.apply(Parent, a))();
return Class && setPrototypeOf(instance, Class.prototype), instance;
}, module1.exports.default = module1.exports, module1.exports.__esModule = !0, _construct.apply(null, arguments);
}
module1.exports = _construct, module1.exports.default = module1.exports, module1.exports.__esModule = !0;
/***/ },
/* 250 */ /***/ function(module1, exports1) {
module1.exports = function() {
if ("undefined" == typeof Reflect || !Reflect.construct || Reflect.construct.sham) return !1;
if ("function" == typeof Proxy) return !0;
try {
return Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function() {})), !0;
} catch (e) {
return !1;
}
}, module1.exports.default = module1.exports, module1.exports.__esModule = !0;
/***/ },
/* 251 */ /***/ function(module1, exports1) {
module1.exports = /**
* Calculates the determinant of a mat2
*
* @alias mat2.determinant
* @param {mat2} a the source matrix
* @returns {Number} determinant of a
*/ function(a) {
return a[0] * a[3] - a[2] * a[1];
};
/***/ },
/* 252 */ /***/ function(module1, exports1) {
module1.exports = /**
* Transpose the values of a mat2
*
* @alias mat2.transpose
* @param {mat2} out the receiving matrix
* @param {mat2} a the source matrix
* @returns {mat2} out
*/ function(out, a) {
// If we are transposing ourselves we can skip a few steps but have to cache some values
if (out === a) {
var a1 = a[1];
out[1] = a[2], out[2] = a1;
} else out[0] = a[0], out[1] = a[2], out[2] = a[1], out[3] = a[3];
return out;
};
/***/ },
/* 253 */ /***/ function(module1, exports1) {
module1.exports = /**
* Multiplies two mat2's
*
* @alias mat2.multiply
* @param {mat2} out the receiving matrix
* @param {mat2} a the first operand
* @param {mat2} b the second operand
* @returns {mat2} out
*/ function(out, a, b) {
var a0 = a[0], a1 = a[1], a2 = a[2], a3 = a[3], b0 = b[0], b1 = b[1], b2 = b[2], b3 = b[3];
return out[0] = a0 * b0 + a2 * b1, out[1] = a1 * b0 + a3 * b1, out[2] = a0 * b2 + a2 * b3, out[3] = a1 * b2 + a3 * b3, out;
};
/***/ },
/* 254 */ /***/ function(module1, exports1) {
module1.exports = /**
* Set a mat2 to the identity matrix
*
* @alias mat2.identity
* @param {mat2} out the receiving matrix
* @returns {mat2} out
*/ function(out) {
return out[0] = 1, out[1] = 0, out[2] = 0, out[3] = 1, out;
};
/***/ },
/* 255 */ /***/ function(module1, exports1) {
module1.exports = /**
* Calculates the adjugate of a mat2
*
* @alias mat2.adjoint
* @param {mat2} out the receiving matrix
* @param {mat2} a the source matrix
* @returns {mat2} out
*/ function(out, a) {
// Caching this value is nessecary if out == a
var a0 = a[0];
return out[0] = a[3], out[1] = -a[1], out[2] = -a[2], out[3] = a0, out;
};
/***/ },
/* 256 */ /***/ function(module1, exports1) {
module1.exports = /**
* Rotates a mat2 by the given angle
*
* @alias mat2.rotate
* @param {mat2} out the receiving matrix
* @param {mat2} a the matrix to rotate
* @param {Number} rad the angle to rotate the matrix by
* @returns {mat2} out
*/ function(out, a, rad) {
var a0 = a[0], a1 = a[1], a2 = a[2], a3 = a[3], s = Math.sin(rad), c = Math.cos(rad);
return out[0] = a0 * c + a2 * s, out[1] = a1 * c + a3 * s, out[2] = -(a0 * s) + a2 * c, out[3] = -(a1 * s) + a3 * c, out;
};
/***/ },
/* 257 */ /***/ function(module1, exports1) {
module1.exports = /**
* Inverts a mat2
*
* @alias mat2.invert
* @param {mat2} out the receiving matrix
* @param {mat2} a the source matrix
* @returns {mat2} out
*/ function(out, a) {
var a0 = a[0], a1 = a[1], a2 = a[2], a3 = a[3], det = a0 * a3 - a2 * a1;
return det ? (det = 1.0 / det, out[0] = a3 * det, out[1] = -a1 * det, out[2] = -a2 * det, out[3] = a0 * det, out) : null;
};
/***/ },
/* 258 */ /***/ function(module1, exports1) {
module1.exports = /**
* Creates a new identity mat2
*
* @alias mat2.create
* @returns {mat2} a new 2x2 matrix
*/ function() {
var out = new Float32Array(4);
return out[0] = 1, out[1] = 0, out[2] = 0, out[3] = 1, out;
};
/***/ },
/* 259 */ /***/ function(module1, exports1) {
module1.exports = /**
* Scales the mat2 by the dimensions in the given vec2
*
* @alias mat2.scale
* @param {mat2} out the receiving matrix
* @param {mat2} a the matrix to rotate
* @param {vec2} v the vec2 to scale the matrix by
* @returns {mat2} out
**/ function(out, a, v) {
var a0 = a[0], a1 = a[1], a2 = a[2], a3 = a[3], v0 = v[0], v1 = v[1];
return out[0] = a0 * v0, out[1] = a1 * v0, out[2] = a2 * v1, out[3] = a3 * v1, out;
};
/***/ },
/* 260 */ /***/ function(module1, exports1) {
module1.exports = /**
* Copy the values from one mat2 to another
*
* @alias mat2.copy
* @param {mat2} out the receiving matrix
* @param {mat2} a the source matrix
* @returns {mat2} out
*/ function(out, a) {
return out[0] = a[0], out[1] = a[1], out[2] = a[2], out[3] = a[3], out;
};
/***/ },
/* 261 */ /***/ function(module1, exports1) {
module1.exports = /**
* Returns Frobenius norm of a mat2
*
* @alias mat2.frob
* @param {mat2} a the matrix to calculate Frobenius norm of
* @returns {Number} Frobenius norm
*/ function(a) {
return Math.sqrt(Math.pow(a[0], 2) + Math.pow(a[1], 2) + Math.pow(a[2], 2) + Math.pow(a[3], 2));
};
/***/ },
/* 262 */ /***/ function(module1, exports1) {
module1.exports = /**
* Returns L, D and U matrices (Lower triangular, Diagonal and Upper triangular) by factorizing the input matrix
*
* @alias mat2.ldu
* @param {mat2} L the lower triangular matrix
* @param {mat2} D the diagonal matrix
* @param {mat2} U the upper triangular matrix
* @param {mat2} a the input matrix to factorize
*/ function(L, D, U, a) {
return L[2] = a[2] / a[0], U[0] = a[0], U[1] = a[1], U[3] = a[3] - L[2] * U[1], [
L,
D,
U
];
};
/***/ },
/* 263 */ /***/ function(module1, __webpack_exports__, __webpack_require__) {
"use strict";
// ESM COMPAT FLAG
__webpack_require__.r(__webpack_exports__), // EXPORTS
__webpack_require__.d(__webpack_exports__, "BarcodeDecoder", function() {
return /* reexport */ barcode_decoder;
}), __webpack_require__.d(__webpack_exports__, "Readers", function() {
return /* reexport */ reader_namespaceObject;
}), __webpack_require__.d(__webpack_exports__, "CameraAccess", function() {
return /* reexport */ camera_access;
}), __webpack_require__.d(__webpack_exports__, "ImageDebug", function() {
return /* reexport */ image_debug.a;
}), __webpack_require__.d(__webpack_exports__, "ImageWrapper", function() {
return /* reexport */ image_wrapper.a;
}), __webpack_require__.d(__webpack_exports__, "ResultCollector", function() {
return /* reexport */ result_collector;
});
// NAMESPACE OBJECT: ./src/reader/index.ts
var BarcodeDirection, BarcodeDirection1, streamRef, reader_namespaceObject = {};
__webpack_require__.r(reader_namespaceObject), __webpack_require__.d(reader_namespaceObject, "BarcodeReader", function() {
return barcode_reader;
}), __webpack_require__.d(reader_namespaceObject, "TwoOfFiveReader", function() {
return _2of5_reader;
}), __webpack_require__.d(reader_namespaceObject, "NewCodabarReader", function() {
return codabar_reader;
}), __webpack_require__.d(reader_namespaceObject, "Code128Reader", function() {
return code_128_reader;
}), __webpack_require__.d(reader_namespaceObject, "Code32Reader", function() {
return code_32_reader;
}), __webpack_require__.d(reader_namespaceObject, "Code39Reader", function() {
return code_39_reader;
}), __webpack_require__.d(reader_namespaceObject, "Code39VINReader", function() {
return code_39_vin_reader;
}), __webpack_require__.d(reader_namespaceObject, "Code93Reader", function() {
return code_93_reader;
}), __webpack_require__.d(reader_namespaceObject, "EAN2Reader", function() {
return ean_2_reader;
}), __webpack_require__.d(reader_namespaceObject, "EAN5Reader", function() {
return ean_5_reader;
}), __webpack_require__.d(reader_namespaceObject, "EAN8Reader", function() {
return ean_8_reader;
}), __webpack_require__.d(reader_namespaceObject, "EANReader", function() {
return ean_reader;
}), __webpack_require__.d(reader_namespaceObject, "I2of5Reader", function() {
return i2of5_reader;
}), __webpack_require__.d(reader_namespaceObject, "UPCEReader", function() {
return upc_e_reader;
}), __webpack_require__.d(reader_namespaceObject, "UPCReader", function() {
return upc_reader;
});
// EXTERNAL MODULE: ./node_modules/@babel/runtime/helpers/typeof.js
var helpers_typeof = __webpack_require__(19), typeof_default = /*#__PURE__*/ __webpack_require__.n(helpers_typeof), merge = __webpack_require__(16), merge_default = /*#__PURE__*/ __webpack_require__.n(merge);
__webpack_require__(152);
// EXTERNAL MODULE: ./src/common/image_wrapper.ts
var image_wrapper = __webpack_require__(11), Bresenham = {}, Slope = {
DIR: {
UP: 1,
DOWN: -1
}
};
/**
* Scans a line of the given image from point p1 to p2 and returns a result object containing
* gray-scale values (0-255) of the underlying pixels in addition to the min
* and max values.
* @param {Object} imageWrapper
* @param {Object} p1 The start point {x,y}
* @param {Object} p2 The end point {x,y}
* @returns {line, min, max}
*/ Bresenham.getBarcodeLine = function(imageWrapper, p1, p2) {
/* eslint-disable no-bitwise */ var error, y, tmp, x, val, x0 = 0 | p1.x, y0 = 0 | p1.y, x1 = 0 | p2.x, y1 = 0 | p2.y, steep = Math.abs(y1 - y0) > Math.abs(x1 - x0), line = [], imageData = imageWrapper.data, width = imageWrapper.size.x, min = 255, max = 0;
function read(a, b) {
min = (val = imageData[b * width + a]) < min ? val : min, max = val > max ? val : max, line.push(val);
}
steep && (tmp = x0, x0 = y0, y0 = tmp, tmp = x1, x1 = y1, y1 = tmp), x0 > x1 && (tmp = x0, x0 = x1, x1 = tmp, tmp = y0, y0 = y1, y1 = tmp);
var deltaX = x1 - x0, deltaY = Math.abs(y1 - y0);
error = deltaX / 2 | 0, y = y0;
var yStep = y0 < y1 ? 1 : -1;
for(x = x0; x < x1; x++)steep ? read(y, x) : read(x, y), (error -= deltaY) < 0 && (y += yStep, error += deltaX);
return {
line: line,
min: min,
max: max
};
}, /**
* Converts the result from getBarcodeLine into a binary representation
* also considering the frequency and slope of the signal for more robust results
* @param {Object} result {line, min, max}
*/ Bresenham.toBinaryLine = function(result) {
var slope, slope2, currentDir, dir, i, j, min = result.min, max = result.max, line = result.line, center = min + (max - min) / 2, extrema = [], threshold = (max - min) / 12, rThreshold = -threshold;
for(currentDir = line[0] > center ? Slope.DIR.UP : Slope.DIR.DOWN, extrema.push({
pos: 0,
val: line[0]
}), i = 0; i < line.length - 2; i++)dir = (slope = line[i + 1] - line[i]) + (slope2 = line[i + 2] - line[i + 1]) < rThreshold && line[i + 1] < 1.5 * center ? Slope.DIR.DOWN : slope + slope2 > threshold && line[i + 1] > 0.5 * center ? Slope.DIR.UP : currentDir, currentDir !== dir && (extrema.push({
pos: i,
val: line[i]
}), currentDir = dir);
for(extrema.push({
pos: line.length,
val: line[line.length - 1]
}), j = extrema[0].pos; j < extrema[1].pos; j++)line[j] = line[j] > center ? 0 : 1;
// iterate over extrema and convert to binary based on avg between minmax
for(i = 1; i < extrema.length - 1; i++)for(threshold = extrema[i + 1].val > extrema[i].val ? extrema[i].val + (extrema[i + 1].val - extrema[i].val) / 3 * 2 | 0 : extrema[i + 1].val + (extrema[i].val - extrema[i + 1].val) / 3 | 0, j = extrema[i].pos; j < extrema[i + 1].pos; j++)line[j] = line[j] > threshold ? 0 : 1;
return {
line: line,
threshold: threshold
};
}, /**
* Used for development only
*/ Bresenham.debug = {
printFrequency: function(line, canvas) {
var i, ctx = canvas.getContext("2d"); // eslint-disable-next-line no-param-reassign
for(canvas.width = line.length, canvas.height = 256, ctx.beginPath(), ctx.strokeStyle = "blue", i = 0; i < line.length; i++)ctx.moveTo(i, 255), ctx.lineTo(i, 255 - line[i]);
ctx.stroke(), ctx.closePath();
},
printPattern: function(line, canvas) {
var i, ctx = canvas.getContext("2d");
for(i = 0, canvas.width = line.length, ctx.fillColor = "black"; i < line.length; i++)1 === line[i] && ctx.fillRect(i, 0, 1, 100);
}
};
// EXTERNAL MODULE: ./src/common/image_debug.ts
var image_debug = __webpack_require__(9), classCallCheck = __webpack_require__(3), classCallCheck_default = /*#__PURE__*/ __webpack_require__.n(classCallCheck), createClass = __webpack_require__(4), createClass_default = /*#__PURE__*/ __webpack_require__.n(createClass), assertThisInitialized = __webpack_require__(1), assertThisInitialized_default = /*#__PURE__*/ __webpack_require__.n(assertThisInitialized), inherits = __webpack_require__(6), inherits_default = /*#__PURE__*/ __webpack_require__.n(inherits), possibleConstructorReturn = __webpack_require__(5), possibleConstructorReturn_default = /*#__PURE__*/ __webpack_require__.n(possibleConstructorReturn), getPrototypeOf = __webpack_require__(2), getPrototypeOf_default = /*#__PURE__*/ __webpack_require__.n(getPrototypeOf), defineProperty = __webpack_require__(0), defineProperty_default = /*#__PURE__*/ __webpack_require__.n(defineProperty), array_helper = __webpack_require__(10);
(BarcodeDirection = BarcodeDirection1 || (BarcodeDirection1 = {}))[BarcodeDirection.Forward = 1] = "Forward", BarcodeDirection[BarcodeDirection.Reverse = -1] = "Reverse";
/* harmony default export */ var barcode_reader = /*#__PURE__*/ function() {
function BarcodeReader(config, supplements) {
return classCallCheck_default()(this, BarcodeReader), defineProperty_default()(this, "_row", []), defineProperty_default()(this, "config", {}), defineProperty_default()(this, "supplements", []), defineProperty_default()(this, "SINGLE_CODE_ERROR", 0), defineProperty_default()(this, "FORMAT", "unknown"), defineProperty_default()(this, "CONFIG_KEYS", {}), this._row = [], this.config = config || {}, supplements && (this.supplements = supplements), this;
}
return createClass_default()(BarcodeReader, [
{
key: "_nextUnset",
value: function(line) {
for(var start = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : 0, i = start; i < line.length; i++)if (!line[i]) return i;
return line.length;
}
},
{
key: "_matchPattern",
value: function(counter, code, maxSingleError) {
var error = 0, singleError = 0, sum = 0, modulo = 0, barWidth = 0, scaled = 0;
maxSingleError = maxSingleError || this.SINGLE_CODE_ERROR || 1;
for(var i = 0; i < counter.length; i++)sum += counter[i], modulo += code[i];
if (sum < modulo) return Number.MAX_VALUE;
maxSingleError *= barWidth = sum / modulo;
for(var _i = 0; _i < counter.length; _i++){
if ((singleError = Math.abs(counter[_i] - (scaled = code[_i] * barWidth)) / scaled) > maxSingleError) return Number.MAX_VALUE;
error += singleError;
}
return error / modulo;
}
},
{
key: "_nextSet",
value: function(line) {
for(var offset = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : 0, i = offset; i < line.length; i++)if (line[i]) return i;
return line.length;
}
},
{
key: "_correctBars",
value: function(counter, correction, indices) {
for(var length = indices.length, tmp = 0; length--;)(tmp = counter[indices[length]] * (1 - (1 - correction) / 2)) > 1 && (counter[indices[length]] = tmp);
}
},
{
key: "decodePattern",
value: function(pattern) {
// console.warn('* decodePattern', pattern);
this._row = pattern;
var result = this.decode(); // console.warn('* first result=', result);
return null === result ? (this._row.reverse(), (result = this.decode()) && (result.direction = BarcodeDirection1.Reverse, result.start = this._row.length - result.start, result.end = this._row.length - result.end)) : result.direction = BarcodeDirection1.Forward, result && (result.format = this.FORMAT), result;
}
},
{
key: "_matchRange",
value: function(start, end, value) {
var i;
for(i = start = start < 0 ? 0 : start; i < end; i++)if (this._row[i] !== value) return !1;
return !0;
}
},
{
key: "_fillCounters",
value: function() {
var offset = arguments.length > 0 && void 0 !== arguments[0] ? arguments[0] : this._nextUnset(this._row), end = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : this._row.length, isWhite = !(arguments.length > 2) || void 0 === arguments[2] || arguments[2], counters = [], counterPos = 0;
counters[0] = 0;
for(var i = offset; i < end; i++)this._row[i] ^ +!!isWhite ? counters[counterPos]++ : (counters[++counterPos] = 1, isWhite = !isWhite);
return counters;
}
},
{
key: "_toCounters",
value: function(start, counters) {
var numCounters = counters.length, end = this._row.length, isWhite = !this._row[start], counterPos = 0;
array_helper.a.init(counters, 0);
for(var i = start; i < end; i++)if (this._row[i] ^ +!!isWhite) counters[counterPos]++;
else {
if (++counterPos === numCounters) break;
counters[counterPos] = 1, isWhite = !isWhite;
}
return counters;
}
}
], [
{
key: "Exception",
get: function() {
return {
StartNotFoundException: "Start-Info was not found!",
CodeNotFoundException: "Code could not be found!",
PatternNotFoundException: "Pattern could not be found!"
};
}
}
]), BarcodeReader;
}(), code_128_reader = /*#__PURE__*/ function(_BarcodeReader) {
inherits_default()(Code128Reader, _BarcodeReader);
var hasNativeReflectConstruct, _super = (hasNativeReflectConstruct = function() {
if ("undefined" == typeof Reflect || !Reflect.construct || Reflect.construct.sham) return !1;
if ("function" == typeof Proxy) return !0;
try {
return Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function() {})), !0;
} catch (e) {
return !1;
}
}(), function() {
var result, Super = getPrototypeOf_default()(Code128Reader);
return result = hasNativeReflectConstruct ? Reflect.construct(Super, arguments, getPrototypeOf_default()(this).constructor) : Super.apply(this, arguments), possibleConstructorReturn_default()(this, result);
});
function Code128Reader() {
var _this;
classCallCheck_default()(this, Code128Reader);
for(var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++)args[_key] = arguments[_key];
return _this = _super.call.apply(_super, [
this
].concat(args)), defineProperty_default()(assertThisInitialized_default()(_this), "CODE_SHIFT", 98), defineProperty_default()(assertThisInitialized_default()(_this), "CODE_C", 99), defineProperty_default()(assertThisInitialized_default()(_this), "CODE_B", 100), defineProperty_default()(assertThisInitialized_default()(_this), "CODE_A", 101), defineProperty_default()(assertThisInitialized_default()(_this), "START_CODE_A", 103), defineProperty_default()(assertThisInitialized_default()(_this), "START_CODE_B", 104), defineProperty_default()(assertThisInitialized_default()(_this), "START_CODE_C", 105), defineProperty_default()(assertThisInitialized_default()(_this), "STOP_CODE", 106), defineProperty_default()(assertThisInitialized_default()(_this), "CODE_PATTERN", [
[
2,
1,
2,
2,
2,
2
],
[
2,
2,
2,
1,
2,
2
],
[
2,
2,
2,
2,
2,
1
],
[
1,
2,
1,
2,
2,
3
],
[
1,
2,
1,
3,
2,
2
],
[
1,
3,
1,
2,
2,
2
],
[
1,
2,
2,
2,
1,
3
],
[
1,
2,
2,
3,
1,
2
],
[
1,
3,
2,
2,
1,
2
],
[
2,
2,
1,
2,
1,
3
],
[
2,
2,
1,
3,
1,
2
],
[
2,
3,
1,
2,
1,
2
],
[
1,
1,
2,
2,
3,
2
],
[
1,
2,
2,
1,
3,
2
],
[
1,
2,
2,
2,
3,
1
],
[
1,
1,
3,
2,
2,
2
],
[
1,
2,
3,
1,
2,
2
],
[
1,
2,
3,
2,
2,
1
],
[
2,
2,
3,
2,
1,
1
],
[
2,
2,
1,
1,
3,
2
],
[
2,
2,
1,
2,
3,
1
],
[
2,
1,
3,
2,
1,
2
],
[
2,
2,
3,
1,
1,
2
],
[
3,
1,
2,
1,
3,
1
],
[
3,
1,
1,
2,
2,
2
],
[
3,
2,
1,
1,
2,
2
],
[
3,
2,
1,
2,
2,
1
],
[
3,
1,
2,
2,
1,
2
],
[
3,
2,
2,
1,
1,
2
],
[
3,
2,
2,
2,
1,
1
],
[
2,
1,
2,
1,
2,
3
],
[
2,
1,
2,
3,
2,
1
],
[
2,
3,
2,
1,
2,
1
],
[
1,
1,
1,
3,
2,
3
],
[
1,
3,
1,
1,
2,
3
],
[
1,
3,
1,
3,
2,
1
],
[
1,
1,
2,
3,
1,
3
],
[
1,
3,
2,
1,
1,
3
],
[
1,
3,
2,
3,
1,
1
],
[
2,
1,
1,
3,
1,
3
],
[
2,
3,
1,
1,
1,
3
],
[
2,
3,
1,
3,
1,
1
],
[
1,
1,
2,
1,
3,
3
],
[
1,
1,
2,
3,
3,
1
],
[
1,
3,
2,
1,
3,
1
],
[
1,
1,
3,
1,
2,
3
],
[
1,
1,
3,
3,
2,
1
],
[
1,
3,
3,
1,
2,
1
],
[
3,
1,
3,
1,
2,
1
],
[
2,
1,
1,
3,
3,
1
],
[
2,
3,
1,
1,
3,
1
],
[
2,
1,
3,
1,
1,
3
],
[
2,
1,
3,
3,
1,
1
],
[
2,
1,
3,
1,
3,
1
],
[
3,
1,
1,
1,
2,
3
],
[
3,
1,
1,
3,
2,
1
],
[
3,
3,
1,
1,
2,
1
],
[
3,
1,
2,
1,
1,
3
],
[
3,
1,
2,
3,
1,
1
],
[
3,
3,
2,
1,
1,
1
],
[
3,
1,
4,
1,
1,
1
],
[
2,
2,
1,
4,
1,
1
],
[
4,
3,
1,
1,
1,
1
],
[
1,
1,
1,
2,
2,
4
],
[
1,
1,
1,
4,
2,
2
],
[
1,
2,
1,
1,
2,
4
],
[
1,
2,
1,
4,
2,
1
],
[
1,
4,
1,
1,
2,
2
],
[
1,
4,
1,
2,
2,
1
],
[
1,
1,
2,
2,
1,
4
],
[
1,
1,
2,
4,
1,
2
],
[
1,
2,
2,
1,
1,
4
],
[
1,
2,
2,
4,
1,
1
],
[
1,
4,
2,
1,
1,
2
],
[
1,
4,
2,
2,
1,
1
],
[
2,
4,
1,
2,
1,
1
],
[
2,
2,
1,
1,
1,
4
],
[
4,
1,
3,
1,
1,
1
],
[
2,
4,
1,
1,
1,
2
],
[
1,
3,
4,
1,
1,
1
],
[
1,
1,
1,
2,
4,
2
],
[
1,
2,
1,
1,
4,
2
],
[
1,
2,
1,
2,
4,
1
],
[
1,
1,
4,
2,
1,
2
],
[
1,
2,
4,
1,
1,
2
],
[
1,
2,
4,
2,
1,
1
],
[
4,
1,
1,
2,
1,
2
],
[
4,
2,
1,
1,
1,
2
],
[
4,
2,
1,
2,
1,
1
],
[
2,
1,
2,
1,
4,
1
],
[
2,
1,
4,
1,
2,
1
],
[
4,
1,
2,
1,
2,
1
],
[
1,
1,
1,
1,
4,
3
],
[
1,
1,
1,
3,
4,
1
],
[
1,
3,
1,
1,
4,
1
],
[
1,
1,
4,
1,
1,
3
],
[
1,
1,
4,
3,
1,
1
],
[
4,
1,
1,
1,
1,
3
],
[
4,
1,
1,
3,
1,
1
],
[
1,
1,
3,
1,
4,
1
],
[
1,
1,
4,
1,
3,
1
],
[
3,
1,
1,
1,
4,
1
],
[
4,
1,
1,
1,
3,
1
],
[
2,
1,
1,
4,
1,
2
],
[
2,
1,
1,
2,
1,
4
],
[
2,
1,
1,
2,
3,
2
],
[
2,
3,
3,
1,
1,
1,
2
]
]), defineProperty_default()(assertThisInitialized_default()(_this), "SINGLE_CODE_ERROR", 0.64), defineProperty_default()(assertThisInitialized_default()(_this), "AVG_CODE_ERROR", 0.3), defineProperty_default()(assertThisInitialized_default()(_this), "FORMAT", "code_128"), defineProperty_default()(assertThisInitialized_default()(_this), "MODULE_INDICES", {
bar: [
0,
2,
4
],
space: [
1,
3,
5
]
}), _this;
}
return createClass_default()(Code128Reader, [
{
key: "_decodeCode",
value: function(start, correction) {
for(var bestMatch = {
error: Number.MAX_VALUE,
code: -1,
start: start,
end: start,
correction: {
bar: 1,
space: 1
}
}, counter = [
0,
0,
0,
0,
0,
0
], isWhite = !this._row[start], counterPos = 0, i = start; i < this._row.length; i++)if (this._row[i] ^ +!!isWhite) counter[counterPos]++;
else {
if (counterPos === counter.length - 1) {
correction && this._correct(counter, correction);
for(var code = 0; code < this.CODE_PATTERN.length; code++){
var error = this._matchPattern(counter, this.CODE_PATTERN[code]);
error < bestMatch.error && (bestMatch.code = code, bestMatch.error = error);
}
if (bestMatch.end = i, -1 === bestMatch.code || bestMatch.error > this.AVG_CODE_ERROR) return null;
return this.CODE_PATTERN[bestMatch.code] && (bestMatch.correction.bar = this.calculateCorrection(this.CODE_PATTERN[bestMatch.code], counter, this.MODULE_INDICES.bar), bestMatch.correction.space = this.calculateCorrection(this.CODE_PATTERN[bestMatch.code], counter, this.MODULE_INDICES.space)), bestMatch;
}
counter[++counterPos] = 1, isWhite = !isWhite;
}
return null;
}
},
{
key: "_correct",
value: function(counter, correction) {
this._correctBars(counter, correction.bar, this.MODULE_INDICES.bar), this._correctBars(counter, correction.space, this.MODULE_INDICES.space);
}
},
{
key: "_findStart",
// TODO: _findStart and decodeCode share similar code, can we re-use some?
value: function() {
for(var counter = [
0,
0,
0,
0,
0,
0
], offset = this._nextSet(this._row), bestMatch = {
error: Number.MAX_VALUE,
code: -1,
start: 0,
end: 0,
correction: {
bar: 1,
space: 1
}
}, isWhite = !1, counterPos = 0, i = offset; i < this._row.length; i++)if (this._row[i] ^ +!!isWhite) counter[counterPos]++;
else {
if (counterPos === counter.length - 1) {
for(var sum = counter.reduce(function(prev, next) {
return prev + next;
}, 0), code = this.START_CODE_A; code <= this.START_CODE_C; code++){
var error = this._matchPattern(counter, this.CODE_PATTERN[code]);
error < bestMatch.error && (bestMatch.code = code, bestMatch.error = error);
}
if (bestMatch.error < this.AVG_CODE_ERROR) return bestMatch.start = i - sum, bestMatch.end = i, bestMatch.correction.bar = this.calculateCorrection(this.CODE_PATTERN[bestMatch.code], counter, this.MODULE_INDICES.bar), bestMatch.correction.space = this.calculateCorrection(this.CODE_PATTERN[bestMatch.code], counter, this.MODULE_INDICES.space), bestMatch;
for(var j = 0; j < 4; j++)counter[j] = counter[j + 2];
counter[4] = 0, counter[5] = 0, counterPos--;
} else counterPos++;
counter[counterPos] = 1, isWhite = !isWhite;
}
return null;
}
},
{
key: "decode",
value: function(row, start) {
var _this2 = this, startInfo = this._findStart();
if (null === startInfo) return null;
// var self = this,
// done = false,
// result = [],
// multiplier = 0,
// checksum = 0,
// codeset,
// rawResult = [],
// decodedCodes = [],
// shiftNext = false,
// unshift,
// removeLastCharacter = true;
var code = {
code: startInfo.code,
start: startInfo.start,
end: startInfo.end,
correction: {
bar: startInfo.correction.bar,
space: startInfo.correction.space
}
}, decodedCodes = [];
decodedCodes.push(code);
for(var checksum = code.code, codeset = function(c) {
switch(c){
case _this2.START_CODE_A:
return _this2.CODE_A;
case _this2.START_CODE_B:
return _this2.CODE_B;
case _this2.START_CODE_C:
return _this2.CODE_C;
default:
return null;
}
}(code.code), done = !1, shiftNext = !1, unshift = !1, removeLastCharacter = !0, multiplier = 0, rawResult = [], result = []; !done;){
if (unshift = shiftNext, shiftNext = !1, null !== (code = this._decodeCode(code.end, code.correction))) switch(code.code !== this.STOP_CODE && (removeLastCharacter = !0), code.code !== this.STOP_CODE && (rawResult.push(code.code), checksum += ++multiplier * code.code), decodedCodes.push(code), codeset){
case this.CODE_A:
if (code.code < 64) result.push(String.fromCharCode(32 + code.code));
else if (code.code < 96) result.push(String.fromCharCode(code.code - 64));
else switch(code.code !== this.STOP_CODE && (removeLastCharacter = !1), code.code){
case this.CODE_SHIFT:
shiftNext = !0, codeset = this.CODE_B;
break;
case this.CODE_B:
codeset = this.CODE_B;
break;
case this.CODE_C:
codeset = this.CODE_C;
break;
case this.STOP_CODE:
done = !0;
}
break;
case this.CODE_B:
if (code.code < 96) result.push(String.fromCharCode(32 + code.code));
else switch(code.code !== this.STOP_CODE && (removeLastCharacter = !1), code.code){
case this.CODE_SHIFT:
shiftNext = !0, codeset = this.CODE_A;
break;
case this.CODE_A:
codeset = this.CODE_A;
break;
case this.CODE_C:
codeset = this.CODE_C;
break;
case this.STOP_CODE:
done = !0;
}
break;
case this.CODE_C:
if (code.code < 100) result.push(code.code < 10 ? "0" + code.code : code.code);
else switch(code.code !== this.STOP_CODE && (removeLastCharacter = !1), code.code){
case this.CODE_A:
codeset = this.CODE_A;
break;
case this.CODE_B:
codeset = this.CODE_B;
break;
case this.STOP_CODE:
done = !0;
}
}
else done = !0;
unshift && (codeset = codeset === this.CODE_A ? this.CODE_B : this.CODE_A);
}
return null === code ? null : (code.end = this._nextUnset(this._row, code.end), this._verifyTrailingWhitespace(code) && (checksum -= multiplier * rawResult[rawResult.length - 1]) % 103 === rawResult[rawResult.length - 1] && result.length) ? (removeLastCharacter && result.splice(result.length - 1, 1), {
code: result.join(""),
start: startInfo.start,
end: code.end,
codeset: codeset,
startInfo: startInfo,
decodedCodes: decodedCodes,
endInfo: code,
format: this.FORMAT
}) : null;
}
},
{
key: "_verifyTrailingWhitespace",
value: function(endInfo) {
var trailingWhitespaceEnd;
return (trailingWhitespaceEnd = endInfo.end + (endInfo.end - endInfo.start) / 2) < this._row.length && this._matchRange(endInfo.end, trailingWhitespaceEnd, 0) ? endInfo : null;
}
},
{
key: "calculateCorrection",
value: function(expected, normalized, indices) {
for(var length = indices.length, sumNormalized = 0, sumExpected = 0; length--;)sumExpected += expected[indices[length]], sumNormalized += normalized[indices[length]];
return sumExpected / sumNormalized;
}
}
]), Code128Reader;
}(barcode_reader);
// CONCATENATED MODULE: ./src/reader/ean_reader.ts
function ownKeys(object, enumerableOnly) {
var keys = Object.keys(object);
if (Object.getOwnPropertySymbols) {
var symbols = Object.getOwnPropertySymbols(object);
enumerableOnly && (symbols = symbols.filter(function(sym) {
return Object.getOwnPropertyDescriptor(object, sym).enumerable;
})), keys.push.apply(keys, symbols);
}
return keys;
}
function _objectSpread(target) {
for(var i = 1; i < arguments.length; i++){
var source = null != arguments[i] ? arguments[i] : {};
i % 2 ? ownKeys(Object(source), !0).forEach(function(key) {
defineProperty_default()(target, key, source[key]);
}) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function(key) {
Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
});
}
return target;
}
var START_PATTERN = [
1,
1,
1
], MIDDLE_PATTERN = [
1,
1,
1,
1,
1
], EXTENSION_START_PATTERN = [
1,
1,
2
], CODE_PATTERN = [
[
3,
2,
1,
1
],
[
2,
2,
2,
1
],
[
2,
1,
2,
2
],
[
1,
4,
1,
1
],
[
1,
1,
3,
2
],
[
1,
2,
3,
1
],
[
1,
1,
1,
4
],
[
1,
3,
1,
2
],
[
1,
2,
1,
3
],
[
3,
1,
1,
2
],
[
1,
1,
2,
3
],
[
1,
2,
2,
2
],
[
2,
2,
1,
2
],
[
1,
1,
4,
1
],
[
2,
3,
1,
1
],
[
1,
3,
2,
1
],
[
4,
1,
1,
1
],
[
2,
1,
3,
1
],
[
3,
1,
2,
1
],
[
2,
1,
1,
3
]
], CODE_FREQUENCY = [
0,
11,
13,
14,
19,
25,
28,
21,
22,
26
], ean_reader = /*#__PURE__*/ function(_BarcodeReader) {
inherits_default()(EANReader, _BarcodeReader);
var hasNativeReflectConstruct, _super = (hasNativeReflectConstruct = function() {
if ("undefined" == typeof Reflect || !Reflect.construct || Reflect.construct.sham) return !1;
if ("function" == typeof Proxy) return !0;
try {
return Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function() {})), !0;
} catch (e) {
return !1;
}
}(), function() {
var result, Super = getPrototypeOf_default()(EANReader);
return result = hasNativeReflectConstruct ? Reflect.construct(Super, arguments, getPrototypeOf_default()(this).constructor) : Super.apply(this, arguments), possibleConstructorReturn_default()(this, result);
});
// TODO: does this need to be in the class?
function EANReader(config, supplements) {
var _this;
return classCallCheck_default()(this, EANReader), _this = _super.call(this, merge_default()({
supplements: []
}, config), supplements), defineProperty_default()(assertThisInitialized_default()(_this), "FORMAT", "ean_13"), defineProperty_default()(assertThisInitialized_default()(_this), "SINGLE_CODE_ERROR", 0.7), defineProperty_default()(assertThisInitialized_default()(_this), "STOP_PATTERN", [
1,
1,
1
]), _this;
}
return createClass_default()(EANReader, [
{
key: "_findPattern",
value: function(pattern, offset, isWhite, tryHarder) {
var counter = Array(pattern.length).fill(0), bestMatch = {
error: Number.MAX_VALUE,
start: 0,
end: 0
}, counterPos = 0;
offset || (offset = this._nextSet(this._row));
for(var found = !1, i = offset; i < this._row.length; i++)// console.warn(`* loop i=${offset} len=${this._row.length} isWhite=${isWhite} counterPos=${counterPos}`);
if (this._row[i] ^ +!!isWhite) counter[counterPos] += 1;
else {
if (counterPos === counter.length - 1) {
var error = this._matchPattern(counter, pattern); // console.warn('* matchPattern', error, counter, pattern);
if (error < 0.48 && bestMatch.error && error < bestMatch.error) return found = !0, bestMatch.error = error, bestMatch.start = i - counter.reduce(function(sum, value) {
return sum + value;
}, 0), bestMatch.end = i, bestMatch;
if (tryHarder) {
for(var j = 0; j < counter.length - 2; j++)counter[j] = counter[j + 2];
counter[counter.length - 2] = 0, counter[counter.length - 1] = 0, counterPos--;
}
} else counterPos++;
counter[counterPos] = 1, isWhite = !isWhite;
}
return found ? bestMatch : null;
}
},
{
key: "_decodeCode",
value: function(start, coderange) {
// console.warn('* decodeCode', start, coderange);
var counter = [
0,
0,
0,
0
], bestMatch = {
error: Number.MAX_VALUE,
code: -1,
start: start,
end: start
}, isWhite = !this._row[start], counterPos = 0;
coderange || // console.warn('* decodeCode before length');
(coderange = CODE_PATTERN.length);
for(var i = start; i < this._row.length; i++)if (this._row[i] ^ +!!isWhite) counter[counterPos]++;
else {
if (counterPos === counter.length - 1) {
for(var code = 0; code < coderange; code++){
var error = this._matchPattern(counter, CODE_PATTERN[code]);
bestMatch.end = i, error < bestMatch.error && (bestMatch.code = code, bestMatch.error = error);
}
if (bestMatch.error > 0.48) // console.warn('* return null');
return null;
// console.warn('* return bestMatch', JSON.stringify(bestMatch));
return bestMatch;
}
counter[++counterPos] = 1, isWhite = !isWhite;
}
return null;
}
},
{
key: "_findStart",
value: function() {
for(// console.warn('* findStart');
var offset = this._nextSet(this._row), startInfo = null; !startInfo && (startInfo = this._findPattern(START_PATTERN, offset, !1, !0));){
var leadingWhitespaceStart = startInfo.start - (startInfo.end - startInfo.start);
if (leadingWhitespaceStart >= 0 && this._matchRange(leadingWhitespaceStart, startInfo.start, 0)) // console.warn('* returning startInfo');
return startInfo;
offset = startInfo.end, startInfo = null;
} // console.warn('* returning null');
return null;
}
},
{
key: "_calculateFirstDigit",
value: function(codeFrequency) {
// console.warn('* calculateFirstDigit', codeFrequency);
for(var i = 0; i < CODE_FREQUENCY.length; i++)if (codeFrequency === CODE_FREQUENCY[i]) // console.warn('* returning', i);
return i;
// console.warn('* return null');
return null;
}
},
{
key: "_decodePayload",
value: function(inCode, result, decodedCodes) {
for(var outCode = _objectSpread({}, inCode), codeFrequency = 0x0, i = 0; i < 6; i++){
if (!(outCode = this._decodeCode(outCode.end))) // console.warn('* return null');
return null;
outCode.code >= 10 ? (outCode.code -= 10, codeFrequency |= 1 << 5 - i) : codeFrequency |= 0 << 5 - i, result.push(outCode.code), decodedCodes.push(outCode);
}
// console.warn('* decodePayload', inCode, result, decodedCodes);
var firstDigit = this._calculateFirstDigit(codeFrequency);
if (null === firstDigit) // console.warn('* return null');
return null;
result.unshift(firstDigit);
var middlePattern = this._findPattern(MIDDLE_PATTERN, outCode.end, !0, !1); // console.warn('* findPattern=', JSON.stringify(middlePattern));
if (null === middlePattern || !middlePattern.end) // console.warn('* return null');
return null;
decodedCodes.push(middlePattern);
for(var _i = 0; _i < 6; _i++){
if (!(middlePattern = this._decodeCode(middlePattern.end, 10))) // console.warn('* return null');
return null;
decodedCodes.push(middlePattern), result.push(middlePattern.code);
} // console.warn('* end code=', JSON.stringify(middlePattern));
// console.warn('* end result=', JSON.stringify(result));
// console.warn('* end decodedCodes=', decodedCodes);
return middlePattern;
}
},
{
key: "_verifyTrailingWhitespace",
value: function(endInfo) {
// console.warn('* verifyTrailingWhitespace', JSON.stringify(endInfo));
var trailingWhitespaceEnd = endInfo.end + (endInfo.end - endInfo.start);
return trailingWhitespaceEnd < this._row.length && this._matchRange(endInfo.end, trailingWhitespaceEnd, 0) ? endInfo : null // console.warn('* return null');
;
}
},
{
key: "_findEnd",
value: function(offset, isWhite) {
// console.warn('* findEnd', offset, isWhite);
var endInfo = this._findPattern(this.STOP_PATTERN, offset, isWhite, !1);
return null !== endInfo ? this._verifyTrailingWhitespace(endInfo) : null;
}
},
{
key: "_checksum",
value: function(result) {
for(var sum = 0, i = result.length - 2; i >= 0; i -= 2)sum += result[i];
sum *= 3;
for(var _i2 = result.length - 1; _i2 >= 0; _i2 -= 2)sum += result[_i2];
// console.warn('* end checksum', sum % 10 === 0);
return sum % 10 == 0;
}
},
{
key: "_decodeExtensions",
value: function(offset) {
var start = this._nextSet(this._row, offset), startInfo = this._findPattern(EXTENSION_START_PATTERN, start, !1, !1);
if (null === startInfo) return null;
// console.warn('* decodeExtensions', this.supplements);
// console.warn('* there are ', this.supplements.length, ' supplements');
for(var i = 0; i < this.supplements.length; i++)// console.warn('* extensions loop', i, this.supplements[i], this.supplements[i]._decode);
try {
var result = this.supplements[i].decode(this._row, startInfo.end); // console.warn('* decode result=', result);
if (null !== result) return {
code: result.code,
start: start,
startInfo: startInfo,
end: result.end,
decodedCodes: result.decodedCodes,
format: this.supplements[i].FORMAT
};
} catch (err) {
console.error("* decodeExtensions error in ", this.supplements[i], ": ", err);
}
// console.warn('* end decodeExtensions');
return null;
}
},
{
key: "decode",
value: function(row, start) {
// console.warn('* decode', row);
// console.warn('* decode', start);
var result = [], decodedCodes = [], resultInfo = {}, startInfo = this._findStart();
if (!startInfo) return null;
var code = {
start: startInfo.start,
end: startInfo.end
};
if (decodedCodes.push(code), !(code = this._decodePayload(code, result, decodedCodes)) || !(code = this._findEnd(code.end, !1)) || (decodedCodes.push(code), !this._checksum(result))) return null;
if (this.supplements.length > 0) {
var supplement = this._decodeExtensions(code.end); // console.warn('* decodeExtensions returns', supplement);
if (!supplement || !supplement.decodedCodes) return null;
var lastCode = supplement.decodedCodes[supplement.decodedCodes.length - 1], endInfo = {
start: lastCode.start + ((lastCode.end - lastCode.start) / 2 | 0),
end: lastCode.end
};
if (!this._verifyTrailingWhitespace(endInfo)) return null;
resultInfo = {
supplement: supplement,
code: result.join("") + supplement.code
};
}
return _objectSpread(_objectSpread({
code: result.join(""),
start: startInfo.start,
end: code.end,
startInfo: startInfo,
decodedCodes: decodedCodes
}, resultInfo), {}, {
format: this.FORMAT
});
}
}
]), EANReader;
}(barcode_reader), toConsumableArray = __webpack_require__(33), toConsumableArray_default = /*#__PURE__*/ __webpack_require__.n(toConsumableArray), ALPHABET = new Uint16Array(toConsumableArray_default()("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ-. *$/+%").map(function(_char) {
return _char.charCodeAt(0);
})), CHARACTER_ENCODINGS = new Uint16Array([
0x034,
0x121,
0x061,
0x160,
0x031,
0x130,
0x070,
0x025,
0x124,
0x064,
0x109,
0x049,
0x148,
0x019,
0x118,
0x058,
0x00d,
0x10c,
0x04c,
0x01c,
0x103,
0x043,
0x142,
0x013,
0x112,
0x052,
0x007,
0x106,
0x046,
0x016,
0x181,
0x0c1,
0x1c0,
0x091,
0x190,
0x0d0,
0x085,
0x184,
0x0c4,
0x094,
0x0a8,
0x0a2,
0x08a,
0x02a
]), code_39_reader = /*#__PURE__*/ function(_BarcodeReader) {
inherits_default()(Code39Reader, _BarcodeReader);
var hasNativeReflectConstruct, _super = (hasNativeReflectConstruct = function() {
if ("undefined" == typeof Reflect || !Reflect.construct || Reflect.construct.sham) return !1;
if ("function" == typeof Proxy) return !0;
try {
return Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function() {})), !0;
} catch (e) {
return !1;
}
}(), function() {
var result, Super = getPrototypeOf_default()(Code39Reader);
return result = hasNativeReflectConstruct ? Reflect.construct(Super, arguments, getPrototypeOf_default()(this).constructor) : Super.apply(this, arguments), possibleConstructorReturn_default()(this, result);
});
function Code39Reader() {
var _this;
classCallCheck_default()(this, Code39Reader);
for(var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++)args[_key] = arguments[_key];
return _this = _super.call.apply(_super, [
this
].concat(args)), defineProperty_default()(assertThisInitialized_default()(_this), "FORMAT", "code_39"), _this;
}
return createClass_default()(Code39Reader, [
{
key: "_findStart",
value: function() {
for(var offset = this._nextSet(this._row), patternStart = offset, counter = new Uint16Array([
0,
0,
0,
0,
0,
0,
0,
0,
0
]), counterPos = 0, isWhite = !1, i = offset; i < this._row.length; i++)if (this._row[i] ^ +!!isWhite) counter[counterPos]++;
else {
if (counterPos === counter.length - 1) {
// find start pattern
if (0x094 === this._toPattern(counter)) {
var whiteSpaceMustStart = Math.floor(Math.max(0, patternStart - (i - patternStart) / 4));
if (this._matchRange(whiteSpaceMustStart, patternStart, 0)) return {
start: patternStart,
end: i
};
}
patternStart += counter[0] + counter[1];
for(var j = 0; j < 7; j++)counter[j] = counter[j + 2];
counter[7] = 0, counter[8] = 0, counterPos--;
} else counterPos++;
counter[counterPos] = 1, isWhite = !isWhite;
}
return null;
}
},
{
key: "_toPattern",
value: function(counters) {
for(var numCounters = counters.length, maxNarrowWidth = 0, numWideBars = numCounters, wideBarWidth = 0; numWideBars > 3;){
maxNarrowWidth = this._findNextWidth(counters, maxNarrowWidth), numWideBars = 0;
for(var pattern = 0, i = 0; i < numCounters; i++)counters[i] > maxNarrowWidth && (pattern |= 1 << numCounters - 1 - i, numWideBars++, wideBarWidth += counters[i]);
if (3 === numWideBars) {
for(var _i = 0; _i < numCounters && numWideBars > 0; _i++)if (counters[_i] > maxNarrowWidth && (numWideBars--, 2 * counters[_i] >= wideBarWidth)) return -1;
return pattern;
}
}
return -1;
}
},
{
key: "_findNextWidth",
value: function(counters, current) {
for(var minWidth = Number.MAX_VALUE, i = 0; i < counters.length; i++)counters[i] < minWidth && counters[i] > current && (minWidth = counters[i]);
return minWidth;
}
},
{
key: "_patternToChar",
value: function(pattern) {
for(var i = 0; i < CHARACTER_ENCODINGS.length; i++)if (CHARACTER_ENCODINGS[i] === pattern) return String.fromCharCode(ALPHABET[i]);
return null;
}
},
{
key: "_verifyTrailingWhitespace",
value: function(lastStart, nextStart, counters) {
var patternSize = array_helper.a.sum(counters);
return 3 * (nextStart - lastStart - patternSize) >= patternSize;
}
},
{
key: "decode",
value: function(row, start) {
var decodedChar, lastStart, counters = new Uint16Array([
0,
0,
0,
0,
0,
0,
0,
0,
0
]), result = [];
if (!(start = this._findStart())) return null;
var nextStart = this._nextSet(this._row, start.end);
do {
counters = this._toCounters(nextStart, counters);
var pattern = this._toPattern(counters);
if (pattern < 0 || null === (decodedChar = this._patternToChar(pattern))) return null;
result.push(decodedChar), lastStart = nextStart, nextStart += array_helper.a.sum(counters), nextStart = this._nextSet(this._row, nextStart);
}while ("*" !== decodedChar)
return (result.pop(), result.length && this._verifyTrailingWhitespace(lastStart, nextStart, counters)) ? {
code: result.join(""),
start: start.start,
end: nextStart,
startInfo: start,
decodedCodes: result,
format: this.FORMAT
} : null;
}
}
]), Code39Reader;
}(barcode_reader), get = __webpack_require__(13), get_default = /*#__PURE__*/ __webpack_require__.n(get), patterns_IOQ = /[IOQ]/g, patterns_AZ09 = /[A-Z0-9]{17}/, code_39_vin_reader = /*#__PURE__*/ function(_Code39Reader) {
inherits_default()(Code39VINReader, _Code39Reader);
var hasNativeReflectConstruct, _super = (hasNativeReflectConstruct = function() {
if ("undefined" == typeof Reflect || !Reflect.construct || Reflect.construct.sham) return !1;
if ("function" == typeof Proxy) return !0;
try {
return Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function() {})), !0;
} catch (e) {
return !1;
}
}(), function() {
var result, Super = getPrototypeOf_default()(Code39VINReader);
return result = hasNativeReflectConstruct ? Reflect.construct(Super, arguments, getPrototypeOf_default()(this).constructor) : Super.apply(this, arguments), possibleConstructorReturn_default()(this, result);
});
function Code39VINReader() {
var _this;
classCallCheck_default()(this, Code39VINReader);
for(var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++)args[_key] = arguments[_key];
return _this = _super.call.apply(_super, [
this
].concat(args)), defineProperty_default()(assertThisInitialized_default()(_this), "FORMAT", "code_39_vin"), _this;
}
return createClass_default()(Code39VINReader, [
{
key: "_checkChecksum",
// TODO (this was todo in original repo, no text was there. sorry.)
value: function(code) {
return !!code;
}
},
{
key: "decode",
value: function(row, start) {
var result = get_default()(getPrototypeOf_default()(Code39VINReader.prototype), "decode", this).call(this, row, start);
if (!result) return null;
var code = result.code;
return code ? (code = code.replace(patterns_IOQ, "")).match(patterns_AZ09) ? this._checkChecksum(code) ? (result.code = code, result) : null : (console.log("Failed AZ09 pattern code:", code), null) : null;
}
}
]), Code39VINReader;
}(code_39_reader), codabar_reader_ALPHABET = [
48,
49,
50,
51,
52,
53,
54,
55,
56,
57,
45,
36,
58,
47,
46,
43,
65,
66,
67,
68
], codabar_reader_CHARACTER_ENCODINGS = [
0x003,
0x006,
0x009,
0x060,
0x012,
0x042,
0x021,
0x024,
0x030,
0x048,
0x00c,
0x018,
0x045,
0x051,
0x054,
0x015,
0x01a,
0x029,
0x00b,
0x00e
], START_END = [
0x01a,
0x029,
0x00b,
0x00e
], codabar_reader = /*#__PURE__*/ function(_BarcodeReader) {
inherits_default()(NewCodabarReader, _BarcodeReader);
var hasNativeReflectConstruct, _super = (hasNativeReflectConstruct = function() {
if ("undefined" == typeof Reflect || !Reflect.construct || Reflect.construct.sham) return !1;
if ("function" == typeof Proxy) return !0;
try {
return Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function() {})), !0;
} catch (e) {
return !1;
}
}(), function() {
var result, Super = getPrototypeOf_default()(NewCodabarReader);
return result = hasNativeReflectConstruct ? Reflect.construct(Super, arguments, getPrototypeOf_default()(this).constructor) : Super.apply(this, arguments), possibleConstructorReturn_default()(this, result);
});
function NewCodabarReader() {
var _this;
classCallCheck_default()(this, NewCodabarReader);
for(var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++)args[_key] = arguments[_key];
return _this = _super.call.apply(_super, [
this
].concat(args)), defineProperty_default()(assertThisInitialized_default()(_this), "_counters", []), defineProperty_default()(assertThisInitialized_default()(_this), "FORMAT", "codabar"), _this;
}
return createClass_default()(NewCodabarReader, [
{
key: "_computeAlternatingThreshold",
value: function(offset, end) {
for(var min = Number.MAX_VALUE, max = 0, counter = 0, i = offset; i < end; i += 2)(counter = this._counters[i]) > max && (max = counter), counter < min && (min = counter);
return (min + max) / 2.0 | 0;
}
},
{
key: "_toPattern",
value: function(offset) {
var end = offset + 7;
if (end > this._counters.length) return -1;
for(var barThreshold = this._computeAlternatingThreshold(offset, end), spaceThreshold = this._computeAlternatingThreshold(offset + 1, end), bitmask = 64, threshold = 0, pattern = 0, i = 0; i < 7; i++)threshold = (1 & i) == 0 ? barThreshold : spaceThreshold, this._counters[offset + i] > threshold && (pattern |= bitmask), bitmask >>= 1;
return pattern;
}
},
{
key: "_isStartEnd",
value: function(pattern) {
for(var i = 0; i < START_END.length; i++)if (START_END[i] === pattern) return !0;
return !1;
}
},
{
key: "_sumCounters",
value: function(start, end) {
for(var sum = 0, i = start; i < end; i++)sum += this._counters[i];
return sum;
}
},
{
key: "_findStart",
value: function() {
for(var start = this._nextUnset(this._row), end = start, i = 1; i < this._counters.length; i++){
var pattern = this._toPattern(i);
if (-1 !== pattern && this._isStartEnd(pattern)) return(// TODO: Look for whitespace ahead
start += this._sumCounters(0, i), end = start + this._sumCounters(i, i + 8), {
start: start,
end: end,
startCounter: i,
endCounter: i + 8
});
}
return null;
}
},
{
key: "_patternToChar",
value: function(pattern) {
for(var i = 0; i < codabar_reader_CHARACTER_ENCODINGS.length; i++)if (codabar_reader_CHARACTER_ENCODINGS[i] === pattern) return String.fromCharCode(codabar_reader_ALPHABET[i]);
return null;
}
},
{
key: "_calculatePatternLength",
value: function(offset) {
for(var sum = 0, i = offset; i < offset + 7; i++)sum += this._counters[i];
return sum;
}
},
{
key: "_verifyWhitespace",
value: function(startCounter, endCounter) {
return !!((startCounter - 1 <= 0 || this._counters[startCounter - 1] >= this._calculatePatternLength(startCounter) / 2.0) && (endCounter + 8 >= this._counters.length || this._counters[endCounter + 7] >= this._calculatePatternLength(endCounter) / 2.0));
}
},
{
key: "_charToPattern",
value: function(_char) {
for(var charCode = _char.charCodeAt(0), i = 0; i < codabar_reader_ALPHABET.length; i++)if (codabar_reader_ALPHABET[i] === charCode) return codabar_reader_CHARACTER_ENCODINGS[i];
return 0x0;
}
},
{
key: "_thresholdResultPattern",
value: function(result, startCounter) {
for(var pattern, categorization = {
space: {
narrow: {
size: 0,
counts: 0,
min: 0,
max: Number.MAX_VALUE
},
wide: {
size: 0,
counts: 0,
min: 0,
max: Number.MAX_VALUE
}
},
bar: {
narrow: {
size: 0,
counts: 0,
min: 0,
max: Number.MAX_VALUE
},
wide: {
size: 0,
counts: 0,
min: 0,
max: Number.MAX_VALUE
}
}
}, pos = startCounter, i = 0; i < result.length; i++){
pattern = this._charToPattern(result[i]);
for(var j = 6; j >= 0; j--){
var kind = (1 & j) == 2 ? categorization.bar : categorization.space, cat = (1 & pattern) == 1 ? kind.wide : kind.narrow;
cat.size += this._counters[pos + j], cat.counts++, pattern >>= 1;
}
pos += 8;
}
return [
"space",
"bar"
].forEach(function(key) {
var newkind = categorization[key];
newkind.wide.min = Math.floor((newkind.narrow.size / newkind.narrow.counts + newkind.wide.size / newkind.wide.counts) / 2), newkind.narrow.max = Math.ceil(newkind.wide.min), newkind.wide.max = Math.ceil((2.0 * newkind.wide.size + 1.5) / newkind.wide.counts);
}), categorization;
}
},
{
key: "_validateResult",
value: function(result, startCounter) {
for(var pattern, thresholds = this._thresholdResultPattern(result, startCounter), pos = startCounter, i = 0; i < result.length; i++){
pattern = this._charToPattern(result[i]);
for(var j = 6; j >= 0; j--){
var kind = (1 & j) == 0 ? thresholds.bar : thresholds.space, cat = (1 & pattern) == 1 ? kind.wide : kind.narrow, size = this._counters[pos + j];
if (size < cat.min || size > cat.max) return !1;
pattern >>= 1;
}
pos += 8;
}
return !0;
}
},
{
key: "decode",
value: function(row, start) {
if (this._counters = this._fillCounters(), !(start = this._findStart())) return null;
var pattern, nextStart = start.startCounter, result = [];
do {
if ((pattern = this._toPattern(nextStart)) < 0) return null;
var decodedChar = this._patternToChar(pattern);
if (null === decodedChar) return null;
if (result.push(decodedChar), nextStart += 8, result.length > 1 && this._isStartEnd(pattern)) break;
}while (nextStart < this._counters.length) // verify end
if (result.length - 2 < 4 || !this._isStartEnd(pattern) || !this._verifyWhitespace(start.startCounter, nextStart - 8) || !this._validateResult(result, start.startCounter)) return null;
// verify end white space
nextStart = nextStart > this._counters.length ? this._counters.length : nextStart;
var end = start.start + this._sumCounters(start.startCounter, nextStart - 8);
return {
code: result.join(""),
start: start.start,
end: end,
startInfo: start,
decodedCodes: result,
format: this.FORMAT
};
}
}
]), NewCodabarReader;
}(barcode_reader), upc_reader = /*#__PURE__*/ function(_EANReader) {
inherits_default()(UPCReader, _EANReader);
var hasNativeReflectConstruct, _super = (hasNativeReflectConstruct = function() {
if ("undefined" == typeof Reflect || !Reflect.construct || Reflect.construct.sham) return !1;
if ("function" == typeof Proxy) return !0;
try {
return Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function() {})), !0;
} catch (e) {
return !1;
}
}(), function() {
var result, Super = getPrototypeOf_default()(UPCReader);
return result = hasNativeReflectConstruct ? Reflect.construct(Super, arguments, getPrototypeOf_default()(this).constructor) : Super.apply(this, arguments), possibleConstructorReturn_default()(this, result);
});
function UPCReader() {
var _this;
classCallCheck_default()(this, UPCReader);
for(var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++)args[_key] = arguments[_key];
return _this = _super.call.apply(_super, [
this
].concat(args)), defineProperty_default()(assertThisInitialized_default()(_this), "FORMAT", "upc_a"), _this;
}
return createClass_default()(UPCReader, [
{
key: "decode",
value: function(row, start) {
var result = ean_reader.prototype.decode.call(this);
return result && result.code && 13 === result.code.length && "0" === result.code.charAt(0) ? (result.code = result.code.substring(1), result) : null;
}
}
]), UPCReader;
}(ean_reader), ean_8_reader = /*#__PURE__*/ function(_EANReader) {
inherits_default()(EAN8Reader, _EANReader);
var hasNativeReflectConstruct, _super = (hasNativeReflectConstruct = function() {
if ("undefined" == typeof Reflect || !Reflect.construct || Reflect.construct.sham) return !1;
if ("function" == typeof Proxy) return !0;
try {
return Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function() {})), !0;
} catch (e) {
return !1;
}
}(), function() {
var result, Super = getPrototypeOf_default()(EAN8Reader);
return result = hasNativeReflectConstruct ? Reflect.construct(Super, arguments, getPrototypeOf_default()(this).constructor) : Super.apply(this, arguments), possibleConstructorReturn_default()(this, result);
});
function EAN8Reader() {
var _this;
classCallCheck_default()(this, EAN8Reader);
for(var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++)args[_key] = arguments[_key];
return _this = _super.call.apply(_super, [
this
].concat(args)), defineProperty_default()(assertThisInitialized_default()(_this), "FORMAT", "ean_8"), _this;
}
return createClass_default()(EAN8Reader, [
{
key: "_decodePayload",
value: function(inCode, result, decodedCodes) {
for(var code = inCode, i = 0; i < 4; i++){
if (!(code = this._decodeCode(code.end, 10))) return null;
result.push(code.code), decodedCodes.push(code);
}
if (null === (code = this._findPattern(MIDDLE_PATTERN, code.end, !0, !1))) return null;
decodedCodes.push(code);
for(var _i = 0; _i < 4; _i++){
if (!(code = this._decodeCode(code.end, 10))) return null;
decodedCodes.push(code), result.push(code.code);
}
return code;
}
}
]), EAN8Reader;
}(ean_reader), ean_2_reader = /*#__PURE__*/ function(_EANReader) {
inherits_default()(EAN2Reader, _EANReader);
var hasNativeReflectConstruct, _super = (hasNativeReflectConstruct = function() {
if ("undefined" == typeof Reflect || !Reflect.construct || Reflect.construct.sham) return !1;
if ("function" == typeof Proxy) return !0;
try {
return Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function() {})), !0;
} catch (e) {
return !1;
}
}(), function() {
var result, Super = getPrototypeOf_default()(EAN2Reader);
return result = hasNativeReflectConstruct ? Reflect.construct(Super, arguments, getPrototypeOf_default()(this).constructor) : Super.apply(this, arguments), possibleConstructorReturn_default()(this, result);
});
function EAN2Reader() {
var _this;
classCallCheck_default()(this, EAN2Reader);
for(var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++)args[_key] = arguments[_key];
return _this = _super.call.apply(_super, [
this
].concat(args)), defineProperty_default()(assertThisInitialized_default()(_this), "FORMAT", "ean_2"), _this;
}
return createClass_default()(EAN2Reader, [
{
key: "decode",
value: function(row, start) {
row && (this._row = row);
var codeFrequency = 0, offset = start, end = this._row.length, result = [], decodedCodes = [], code = null;
if (void 0 === offset) return null;
for(var i = 0; i < 2 && offset < end; i++){
if (!(code = this._decodeCode(offset))) return null;
decodedCodes.push(code), result.push(code.code % 10), code.code >= 10 && (codeFrequency |= 1 << 1 - i), 1 !== i && (offset = this._nextSet(this._row, code.end), offset = this._nextUnset(this._row, offset));
}
if (2 !== result.length || parseInt(result.join("")) % 4 !== codeFrequency) return null;
var startInfo = this._findStart();
return {
code: result.join(""),
decodedCodes: decodedCodes,
end: code.end,
format: this.FORMAT,
startInfo: startInfo,
start: startInfo.start
};
}
}
]), EAN2Reader;
}(ean_reader), CHECK_DIGIT_ENCODINGS = [
24,
20,
18,
17,
12,
6,
3,
10,
9,
5
], ean_5_reader = /*#__PURE__*/ function(_EANReader) {
inherits_default()(EAN5Reader, _EANReader);
var hasNativeReflectConstruct, _super = (hasNativeReflectConstruct = function() {
if ("undefined" == typeof Reflect || !Reflect.construct || Reflect.construct.sham) return !1;
if ("function" == typeof Proxy) return !0;
try {
return Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function() {})), !0;
} catch (e) {
return !1;
}
}(), function() {
var result, Super = getPrototypeOf_default()(EAN5Reader);
return result = hasNativeReflectConstruct ? Reflect.construct(Super, arguments, getPrototypeOf_default()(this).constructor) : Super.apply(this, arguments), possibleConstructorReturn_default()(this, result);
});
function EAN5Reader() {
var _this;
classCallCheck_default()(this, EAN5Reader);
for(var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++)args[_key] = arguments[_key];
return _this = _super.call.apply(_super, [
this
].concat(args)), defineProperty_default()(assertThisInitialized_default()(_this), "FORMAT", "ean_5"), _this;
}
return createClass_default()(EAN5Reader, [
{
key: "decode",
value: function(row, start) {
if (void 0 === start) return null;
row && (this._row = row);
for(var codeFrequency = 0, offset = start, end = this._row.length, code = null, result = [], decodedCodes = [], i = 0; i < 5 && offset < end; i++){
if (!(code = this._decodeCode(offset))) return null;
decodedCodes.push(code), result.push(code.code % 10), code.code >= 10 && (codeFrequency |= 1 << 4 - i), 4 !== i && (offset = this._nextSet(this._row, code.end), offset = this._nextUnset(this._row, offset));
}
if (5 !== result.length || function(result) {
for(var length = result.length, sum = 0, i = length - 2; i >= 0; i -= 2)sum += result[i];
sum *= 3;
for(var _i = length - 1; _i >= 0; _i -= 2)sum += result[_i];
return (sum *= 3) % 10;
}(result) !== function(codeFrequency) {
for(var i = 0; i < 10; i++)if (codeFrequency === CHECK_DIGIT_ENCODINGS[i]) return i;
return null;
}(codeFrequency)) return null;
var startInfo = this._findStart();
return {
code: result.join(""),
decodedCodes: decodedCodes,
end: code.end,
format: this.FORMAT,
startInfo: startInfo,
start: startInfo.start
};
}
}
]), EAN5Reader;
}(ean_reader);
// CONCATENATED MODULE: ./src/reader/upc_e_reader.ts
function upc_e_reader_ownKeys(object, enumerableOnly) {
var keys = Object.keys(object);
if (Object.getOwnPropertySymbols) {
var symbols = Object.getOwnPropertySymbols(object);
enumerableOnly && (symbols = symbols.filter(function(sym) {
return Object.getOwnPropertyDescriptor(object, sym).enumerable;
})), keys.push.apply(keys, symbols);
}
return keys;
}
/* harmony default export */ var upc_e_reader = /*#__PURE__*/ function(_EANReader) {
inherits_default()(UPCEReader, _EANReader);
var hasNativeReflectConstruct, _super = (hasNativeReflectConstruct = function() {
if ("undefined" == typeof Reflect || !Reflect.construct || Reflect.construct.sham) return !1;
if ("function" == typeof Proxy) return !0;
try {
return Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function() {})), !0;
} catch (e) {
return !1;
}
}(), function() {
var result, Super = getPrototypeOf_default()(UPCEReader);
return result = hasNativeReflectConstruct ? Reflect.construct(Super, arguments, getPrototypeOf_default()(this).constructor) : Super.apply(this, arguments), possibleConstructorReturn_default()(this, result);
});
function UPCEReader() {
var _this;
classCallCheck_default()(this, UPCEReader);
for(var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++)args[_key] = arguments[_key];
return _this = _super.call.apply(_super, [
this
].concat(args)), defineProperty_default()(assertThisInitialized_default()(_this), "CODE_FREQUENCY", [
[
56,
52,
50,
49,
44,
38,
35,
42,
41,
37
],
[
7,
11,
13,
14,
19,
25,
28,
21,
22,
26
]
]), defineProperty_default()(assertThisInitialized_default()(_this), "STOP_PATTERN", [
1 / 6 * 7,
1 / 6 * 7,
1 / 6 * 7,
1 / 6 * 7,
1 / 6 * 7,
1 / 6 * 7
]), defineProperty_default()(assertThisInitialized_default()(_this), "FORMAT", "upc_e"), _this;
}
return createClass_default()(UPCEReader, [
{
key: "_decodePayload",
value: function(inCode, result, decodedCodes) {
for(var outCode = function(target) {
for(var i = 1; i < arguments.length; i++){
var source = null != arguments[i] ? arguments[i] : {};
i % 2 ? upc_e_reader_ownKeys(Object(source), !0).forEach(function(key) {
defineProperty_default()(target, key, source[key]);
}) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : upc_e_reader_ownKeys(Object(source)).forEach(function(key) {
Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
});
}
return target;
}({}, inCode), codeFrequency = 0x0, i = 0; i < 6; i++){
if (!(outCode = this._decodeCode(outCode.end))) return null;
outCode.code >= 10 && (outCode.code = outCode.code - 10, codeFrequency |= 1 << 5 - i), result.push(outCode.code), decodedCodes.push(outCode);
}
return this._determineParity(codeFrequency, result) ? outCode : null;
}
},
{
key: "_determineParity",
value: function(codeFrequency, result) {
for(var nrSystem = 0; nrSystem < this.CODE_FREQUENCY.length; nrSystem++)for(var i = 0; i < this.CODE_FREQUENCY[nrSystem].length; i++)if (codeFrequency === this.CODE_FREQUENCY[nrSystem][i]) return result.unshift(nrSystem), result.push(i), !0;
return !1;
}
},
{
key: "_convertToUPCA",
value: function(result) {
var upca = [
result[0]
], lastDigit = result[result.length - 2];
return (upca = lastDigit <= 2 ? upca.concat(result.slice(1, 3)).concat([
lastDigit,
0,
0,
0,
0
]).concat(result.slice(3, 6)) : 3 === lastDigit ? upca.concat(result.slice(1, 4)).concat([
0,
0,
0,
0,
0
]).concat(result.slice(4, 6)) : 4 === lastDigit ? upca.concat(result.slice(1, 5)).concat([
0,
0,
0,
0,
0,
result[5]
]) : upca.concat(result.slice(1, 6)).concat([
0,
0,
0,
0,
lastDigit
])).push(result[result.length - 1]), upca;
}
},
{
key: "_checksum",
value: function(result) {
return get_default()(getPrototypeOf_default()(UPCEReader.prototype), "_checksum", this).call(this, this._convertToUPCA(result));
}
},
{
key: "_findEnd",
value: function(offset, isWhite) {
return get_default()(getPrototypeOf_default()(UPCEReader.prototype), "_findEnd", this).call(this, offset, !0);
}
},
{
key: "_verifyTrailingWhitespace",
value: function(endInfo) {
var trailingWhitespaceEnd = endInfo.end + (endInfo.end - endInfo.start) / 2;
return trailingWhitespaceEnd < this._row.length && this._matchRange(endInfo.end, trailingWhitespaceEnd, 0) ? endInfo : null;
}
}
]), UPCEReader;
}(ean_reader), i2of5_reader = /*#__PURE__*/ function(_BarcodeReader) {
inherits_default()(I2of5Reader, _BarcodeReader);
var hasNativeReflectConstruct, _super = (hasNativeReflectConstruct = function() {
if ("undefined" == typeof Reflect || !Reflect.construct || Reflect.construct.sham) return !1;
if ("function" == typeof Proxy) return !0;
try {
return Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function() {})), !0;
} catch (e) {
return !1;
}
}(), function() {
var result, Super = getPrototypeOf_default()(I2of5Reader);
return result = hasNativeReflectConstruct ? Reflect.construct(Super, arguments, getPrototypeOf_default()(this).constructor) : Super.apply(this, arguments), possibleConstructorReturn_default()(this, result);
});
function I2of5Reader(opts) {
var _this;
return classCallCheck_default()(this, I2of5Reader), _this = _super.call(this, merge_default()({
normalizeBarSpaceWidth: !1
}, opts)), defineProperty_default()(assertThisInitialized_default()(_this), "barSpaceRatio", [
1,
1
]), defineProperty_default()(assertThisInitialized_default()(_this), "SINGLE_CODE_ERROR", 0.78), defineProperty_default()(assertThisInitialized_default()(_this), "AVG_CODE_ERROR", 0.38), defineProperty_default()(assertThisInitialized_default()(_this), "START_PATTERN", [
1,
1,
1,
1
]), defineProperty_default()(assertThisInitialized_default()(_this), "STOP_PATTERN", [
1,
1,
3
]), defineProperty_default()(assertThisInitialized_default()(_this), "CODE_PATTERN", [
[
1,
1,
3,
3,
1
],
[
3,
1,
1,
1,
3
],
[
1,
3,
1,
1,
3
],
[
3,
3,
1,
1,
1
],
[
1,
1,
3,
1,
3
],
[
3,
1,
3,
1,
1
],
[
1,
3,
3,
1,
1
],
[
1,
1,
1,
3,
3
],
[
3,
1,
1,
3,
1
],
[
1,
3,
1,
3,
1
]
]), defineProperty_default()(assertThisInitialized_default()(_this), "MAX_CORRECTION_FACTOR", 5), defineProperty_default()(assertThisInitialized_default()(_this), "FORMAT", "i2of5"), opts.normalizeBarSpaceWidth && (_this.SINGLE_CODE_ERROR = 0.38, _this.AVG_CODE_ERROR = 0.09), _this.config = opts, possibleConstructorReturn_default()(_this, assertThisInitialized_default()(_this));
}
return createClass_default()(I2of5Reader, [
{
key: "_matchPattern",
value: function(counter, code) {
if (this.config.normalizeBarSpaceWidth) {
for(var counterSum = [
0,
0
], codeSum = [
0,
0
], correction = [
0,
0
], correctionRatio = this.MAX_CORRECTION_FACTOR, correctionRatioInverse = 1 / correctionRatio, i = 0; i < counter.length; i++)counterSum[i % 2] += counter[i], codeSum[i % 2] += code[i];
correction[0] = codeSum[0] / counterSum[0], correction[1] = codeSum[1] / counterSum[1], correction[0] = Math.max(Math.min(correction[0], correctionRatio), correctionRatioInverse), correction[1] = Math.max(Math.min(correction[1], correctionRatio), correctionRatioInverse), this.barSpaceRatio = correction;
for(var _i = 0; _i < counter.length; _i++)counter[_i] *= this.barSpaceRatio[_i % 2];
}
return get_default()(getPrototypeOf_default()(I2of5Reader.prototype), "_matchPattern", this).call(this, counter, code);
}
},
{
key: "_findPattern",
value: function(pattern, offset) {
var isWhite = arguments.length > 2 && void 0 !== arguments[2] && arguments[2], tryHarder = arguments.length > 3 && void 0 !== arguments[3] && arguments[3], counter = Array(pattern.length).fill(0), counterPos = 0, bestMatch = {
error: Number.MAX_VALUE,
start: 0,
end: 0
}, epsilon = this.AVG_CODE_ERROR;
isWhite = isWhite || !1, tryHarder = tryHarder || !1, offset || (offset = this._nextSet(this._row));
for(var i = offset; i < this._row.length; i++)if (this._row[i] ^ +!!isWhite) counter[counterPos]++;
else {
if (counterPos === counter.length - 1) {
var sum = counter.reduce(function(prev, next) {
return prev + next;
}, 0), error = this._matchPattern(counter, pattern);
if (error < epsilon) return bestMatch.error = error, bestMatch.start = i - sum, bestMatch.end = i, bestMatch;
if (!tryHarder) return null;
for(var j = 0; j < counter.length - 2; j++)counter[j] = counter[j + 2];
counter[counter.length - 2] = 0, counter[counter.length - 1] = 0, counterPos--;
} else counterPos++;
counter[counterPos] = 1, isWhite = !isWhite;
}
return null;
}
},
{
key: "_findStart",
value: function() {
for(var leadingWhitespaceStart = 0, offset = this._nextSet(this._row), startInfo = null, narrowBarWidth = 1; !startInfo && (startInfo = this._findPattern(this.START_PATTERN, offset, !1, !0));){
if (narrowBarWidth = Math.floor((startInfo.end - startInfo.start) / 4), (leadingWhitespaceStart = startInfo.start - 10 * narrowBarWidth) >= 0 && this._matchRange(leadingWhitespaceStart, startInfo.start, 0)) return startInfo;
offset = startInfo.end, startInfo = null;
}
return null;
}
},
{
key: "_verifyTrailingWhitespace",
value: function(endInfo) {
var trailingWhitespaceEnd = endInfo.end + (endInfo.end - endInfo.start) / 2;
return trailingWhitespaceEnd < this._row.length && this._matchRange(endInfo.end, trailingWhitespaceEnd, 0) ? endInfo : null;
}
},
{
key: "_findEnd",
value: function() {
this._row.reverse();
var endInfo = this._findPattern(this.STOP_PATTERN);
if (this._row.reverse(), null === endInfo) return null;
// reverse numbers
var tmp = endInfo.start;
return endInfo.start = this._row.length - endInfo.end, endInfo.end = this._row.length - tmp, null !== endInfo ? this._verifyTrailingWhitespace(endInfo) : null;
}
},
{
key: "_decodePair",
value: function(counterPair) {
for(var codes = [], i = 0; i < counterPair.length; i++){
var code = this._decodeCode(counterPair[i]);
if (!code) return null;
codes.push(code);
}
return codes;
}
},
{
key: "_decodeCode",
value: function(counter) {
for(var epsilon = this.AVG_CODE_ERROR, bestMatch = {
error: Number.MAX_VALUE,
code: -1,
start: 0,
end: 0
}, code = 0; code < this.CODE_PATTERN.length; code++){
var error = this._matchPattern(counter, this.CODE_PATTERN[code]);
error < bestMatch.error && (bestMatch.code = code, bestMatch.error = error);
}
return bestMatch.error < epsilon ? bestMatch : null;
}
},
{
key: "_decodePayload",
value: function(counters, result, decodedCodes) {
for(var pos = 0, counterLength = counters.length, counterPair = [
[
0,
0,
0,
0,
0
],
[
0,
0,
0,
0,
0
]
], codes = null; pos < counterLength;){
for(var i = 0; i < 5; i++)counterPair[0][i] = counters[pos] * this.barSpaceRatio[0], counterPair[1][i] = counters[pos + 1] * this.barSpaceRatio[1], pos += 2;
if (!(codes = this._decodePair(counterPair))) return null;
for(var _i2 = 0; _i2 < codes.length; _i2++)result.push(codes[_i2].code + ""), decodedCodes.push(codes[_i2]);
}
return codes;
}
},
{
key: "_verifyCounterLength",
value: function(counters) {
return counters.length % 10 == 0;
}
},
{
key: "decode",
value: function(row, start) {
var result = [], decodedCodes = [], startInfo = this._findStart();
if (!startInfo) return null;
decodedCodes.push(startInfo);
var endInfo = this._findEnd();
if (!endInfo) return null;
var counters = this._fillCounters(startInfo.end, endInfo.start, !1);
return this._verifyCounterLength(counters) && this._decodePayload(counters, result, decodedCodes) && result.length % 2 == 0 && !(result.length < 6) ? (decodedCodes.push(endInfo), {
code: result.join(""),
start: startInfo.start,
end: endInfo.end,
startInfo: startInfo,
decodedCodes: decodedCodes,
format: this.FORMAT
}) : null;
}
}
]), I2of5Reader;
}(barcode_reader), _2of5_reader_START_PATTERN = [
3,
1,
3,
1,
1,
1
], STOP_PATTERN = [
3,
1,
1,
1,
3
], _2of5_reader_CODE_PATTERN = [
[
1,
1,
3,
3,
1
],
[
3,
1,
1,
1,
3
],
[
1,
3,
1,
1,
3
],
[
3,
3,
1,
1,
1
],
[
1,
1,
3,
1,
3
],
[
3,
1,
3,
1,
1
],
[
1,
3,
3,
1,
1
],
[
1,
1,
1,
3,
3
],
[
3,
1,
1,
3,
1
],
[
1,
3,
1,
3,
1
]
], START_PATTERN_LENGTH = _2of5_reader_START_PATTERN.reduce(function(sum, val) {
return sum + val;
}, 0), _2of5_reader = /*#__PURE__*/ function(_BarcodeReader) {
inherits_default()(TwoOfFiveReader, _BarcodeReader);
var hasNativeReflectConstruct, _super = (hasNativeReflectConstruct = function() {
if ("undefined" == typeof Reflect || !Reflect.construct || Reflect.construct.sham) return !1;
if ("function" == typeof Proxy) return !0;
try {
return Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function() {})), !0;
} catch (e) {
return !1;
}
}(), function() {
var result, Super = getPrototypeOf_default()(TwoOfFiveReader);
return result = hasNativeReflectConstruct ? Reflect.construct(Super, arguments, getPrototypeOf_default()(this).constructor) : Super.apply(this, arguments), possibleConstructorReturn_default()(this, result);
});
function TwoOfFiveReader() {
var _this;
classCallCheck_default()(this, TwoOfFiveReader);
for(var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++)args[_key] = arguments[_key];
return _this = _super.call.apply(_super, [
this
].concat(args)), defineProperty_default()(assertThisInitialized_default()(_this), "barSpaceRatio", [
1,
1
]), defineProperty_default()(assertThisInitialized_default()(_this), "FORMAT", "2of5"), defineProperty_default()(assertThisInitialized_default()(_this), "SINGLE_CODE_ERROR", 0.78), defineProperty_default()(assertThisInitialized_default()(_this), "AVG_CODE_ERROR", 0.3), _this;
}
return createClass_default()(TwoOfFiveReader, [
{
key: "_findPattern",
value: function(pattern, offset) {
var isWhite = arguments.length > 2 && void 0 !== arguments[2] && arguments[2], tryHarder = arguments.length > 3 && void 0 !== arguments[3] && arguments[3], counter = [], counterPos = 0, bestMatch = {
error: Number.MAX_VALUE,
code: -1,
start: 0,
end: 0
}, sum = 0, error = 0, epsilon = this.AVG_CODE_ERROR;
offset || (offset = this._nextSet(this._row));
for(var i = 0; i < pattern.length; i++)counter[i] = 0;
for(var _i = offset; _i < this._row.length; _i++)if (this._row[_i] ^ +!!isWhite) counter[counterPos]++;
else {
if (counterPos === counter.length - 1) {
sum = 0;
for(var j = 0; j < counter.length; j++)sum += counter[j];
if ((error = this._matchPattern(counter, pattern)) < epsilon) return bestMatch.error = error, bestMatch.start = _i - sum, bestMatch.end = _i, bestMatch;
if (!tryHarder) return null;
for(var _j = 0; _j < counter.length - 2; _j++)counter[_j] = counter[_j + 2];
counter[counter.length - 2] = 0, counter[counter.length - 1] = 0, counterPos--;
} else counterPos++;
counter[counterPos] = 1, isWhite = !isWhite;
}
return null;
}
},
{
key: "_findStart",
value: function() {
for(var startInfo = null, offset = this._nextSet(this._row), narrowBarWidth = 1, leadingWhitespaceStart = 0; !startInfo;){
if (!(startInfo = this._findPattern(_2of5_reader_START_PATTERN, offset, !1, !0))) return null;
if (narrowBarWidth = Math.floor((startInfo.end - startInfo.start) / START_PATTERN_LENGTH), (leadingWhitespaceStart = startInfo.start - 5 * narrowBarWidth) >= 0 && this._matchRange(leadingWhitespaceStart, startInfo.start, 0)) break;
offset = startInfo.end, startInfo = null;
}
return startInfo;
}
},
{
key: "_verifyTrailingWhitespace",
value: function(endInfo) {
var trailingWhitespaceEnd = endInfo.end + (endInfo.end - endInfo.start) / 2;
return trailingWhitespaceEnd < this._row.length && this._matchRange(endInfo.end, trailingWhitespaceEnd, 0) ? endInfo : null;
}
},
{
key: "_findEnd",
value: function() {
// TODO: reverse, followed by some calcs, followed by another reverse? really?
this._row.reverse();
var offset = this._nextSet(this._row), endInfo = this._findPattern(STOP_PATTERN, offset, !1, !0);
if (this._row.reverse(), null === endInfo) return null;
// reverse numbers
var tmp = endInfo.start;
return endInfo.start = this._row.length - endInfo.end, endInfo.end = this._row.length - tmp, null !== endInfo ? this._verifyTrailingWhitespace(endInfo) : null;
}
},
{
key: "_verifyCounterLength",
value: function(counters) {
return counters.length % 10 == 0;
}
},
{
key: "_decodeCode",
value: function(counter) {
for(var epsilon = this.AVG_CODE_ERROR, bestMatch = {
error: Number.MAX_VALUE,
code: -1,
start: 0,
end: 0
}, code = 0; code < _2of5_reader_CODE_PATTERN.length; code++){
var error = this._matchPattern(counter, _2of5_reader_CODE_PATTERN[code]);
error < bestMatch.error && (bestMatch.code = code, bestMatch.error = error);
}
return bestMatch.error < epsilon ? bestMatch : null;
}
},
{
key: "_decodePayload",
value: function(counters, result, decodedCodes) {
for(var pos = 0, counterLength = counters.length, counter = [
0,
0,
0,
0,
0
], code = null; pos < counterLength;){
for(var i = 0; i < 5; i++)counter[i] = counters[pos] * this.barSpaceRatio[0], pos += 2;
if (!(code = this._decodeCode(counter))) return null;
result.push("".concat(code.code)), decodedCodes.push(code);
}
return code;
}
},
{
key: "decode",
value: function(row, start) {
var startInfo = this._findStart();
if (!startInfo) return null;
var endInfo = this._findEnd();
if (!endInfo) return null;
var counters = this._fillCounters(startInfo.end, endInfo.start, !1);
if (!this._verifyCounterLength(counters)) return null;
var decodedCodes = [];
decodedCodes.push(startInfo);
var result = [];
return !this._decodePayload(counters, result, decodedCodes) || result.length < 5 ? null : (decodedCodes.push(endInfo), {
code: result.join(""),
start: startInfo.start,
end: endInfo.end,
startInfo: startInfo,
decodedCodes: decodedCodes,
format: this.FORMAT
});
}
}
]), TwoOfFiveReader;
}(barcode_reader), code_93_reader_ALPHABET = new Uint16Array(toConsumableArray_default()("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ-. $/+%abcd*").map(function(_char) {
return _char.charCodeAt(0);
})), code_93_reader_CHARACTER_ENCODINGS = new Uint16Array([
0x114,
0x148,
0x144,
0x142,
0x128,
0x124,
0x122,
0x150,
0x112,
0x10a,
0x1a8,
0x1a4,
0x1a2,
0x194,
0x192,
0x18a,
0x168,
0x164,
0x162,
0x134,
0x11a,
0x158,
0x14c,
0x146,
0x12c,
0x116,
0x1b4,
0x1b2,
0x1ac,
0x1a6,
0x196,
0x19a,
0x16c,
0x166,
0x136,
0x13a,
0x12e,
0x1d4,
0x1d2,
0x1ca,
0x16e,
0x176,
0x1ae,
0x126,
0x1da,
0x1d6,
0x132,
0x15e
]), code_93_reader = /*#__PURE__*/ function(_BarcodeReader) {
inherits_default()(Code93Reader, _BarcodeReader);
var hasNativeReflectConstruct, _super = (hasNativeReflectConstruct = function() {
if ("undefined" == typeof Reflect || !Reflect.construct || Reflect.construct.sham) return !1;
if ("function" == typeof Proxy) return !0;
try {
return Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function() {})), !0;
} catch (e) {
return !1;
}
}(), function() {
var result, Super = getPrototypeOf_default()(Code93Reader);
return result = hasNativeReflectConstruct ? Reflect.construct(Super, arguments, getPrototypeOf_default()(this).constructor) : Super.apply(this, arguments), possibleConstructorReturn_default()(this, result);
});
function Code93Reader() {
var _this;
classCallCheck_default()(this, Code93Reader);
for(var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++)args[_key] = arguments[_key];
return _this = _super.call.apply(_super, [
this
].concat(args)), defineProperty_default()(assertThisInitialized_default()(_this), "FORMAT", "code_93"), _this;
}
return createClass_default()(Code93Reader, [
{
key: "_patternToChar",
value: function(pattern) {
for(var i = 0; i < code_93_reader_CHARACTER_ENCODINGS.length; i++)if (code_93_reader_CHARACTER_ENCODINGS[i] === pattern) return String.fromCharCode(code_93_reader_ALPHABET[i]);
return null;
}
},
{
key: "_toPattern",
value: function(counters) {
for(var numCounters = counters.length, sum = counters.reduce(function(prev, next) {
return prev + next;
}, 0), pattern = 0, i = 0; i < numCounters; i++){
var normalized = Math.round(9 * counters[i] / sum);
if (normalized < 1 || normalized > 4) return -1;
if ((1 & i) == 0) for(var j = 0; j < normalized; j++)pattern = pattern << 1 | 1;
else pattern <<= normalized;
}
return pattern;
}
},
{
key: "_findStart",
value: function() {
for(var offset = this._nextSet(this._row), patternStart = offset, counter = new Uint16Array([
0,
0,
0,
0,
0,
0
]), counterPos = 0, isWhite = !1, i = offset; i < this._row.length; i++)if (this._row[i] ^ +!!isWhite) counter[counterPos]++;
else {
if (counterPos === counter.length - 1) {
// find start pattern
if (0x15e === this._toPattern(counter)) {
var whiteSpaceMustStart = Math.floor(Math.max(0, patternStart - (i - patternStart) / 4));
if (this._matchRange(whiteSpaceMustStart, patternStart, 0)) return {
start: patternStart,
end: i
};
}
patternStart += counter[0] + counter[1];
for(var j = 0; j < 4; j++)counter[j] = counter[j + 2];
counter[4] = 0, counter[5] = 0, counterPos--;
} else counterPos++;
counter[counterPos] = 1, isWhite = !isWhite;
}
return null;
}
},
{
key: "_verifyEnd",
value: function(lastStart, nextStart) {
return lastStart !== nextStart && !!this._row[nextStart];
}
},
{
key: "_decodeExtended",
value: function(charArray) {
for(var length = charArray.length, result = [], i = 0; i < length; i++){
var _char2 = charArray[i];
if (_char2 >= "a" && _char2 <= "d") {
if (i > length - 2) return null;
var nextChar = charArray[++i], nextCharCode = nextChar.charCodeAt(0), decodedChar = void 0;
switch(_char2){
case "a":
if (!(nextChar >= "A") || !(nextChar <= "Z")) return null;
decodedChar = String.fromCharCode(nextCharCode - 64);
break;
case "b":
if (nextChar >= "A" && nextChar <= "E") decodedChar = String.fromCharCode(nextCharCode - 38);
else if (nextChar >= "F" && nextChar <= "J") decodedChar = String.fromCharCode(nextCharCode - 11);
else if (nextChar >= "K" && nextChar <= "O") decodedChar = String.fromCharCode(nextCharCode + 16);
else if (nextChar >= "P" && nextChar <= "S") decodedChar = String.fromCharCode(nextCharCode + 43);
else {
if (!(nextChar >= "T") || !(nextChar <= "Z")) return null;
decodedChar = "";
}
break;
case "c":
if (nextChar >= "A" && nextChar <= "O") decodedChar = String.fromCharCode(nextCharCode - 32);
else {
if ("Z" !== nextChar) return null;
decodedChar = ":";
}
break;
case "d":
if (!(nextChar >= "A") || !(nextChar <= "Z")) return null;
decodedChar = String.fromCharCode(nextCharCode + 32);
break;
default:
return console.warn("* code_93_reader _decodeExtended hit default case, this may be an error", decodedChar), null;
}
result.push(decodedChar);
} else result.push(_char2);
}
return result;
}
},
{
key: "_matchCheckChar",
value: function(charArray, index, maxWeight) {
var arrayToCheck = charArray.slice(0, index), length = arrayToCheck.length;
return code_93_reader_ALPHABET[arrayToCheck.reduce(function(sum, _char3, i) {
return sum + ((-1 * i + (length - 1)) % maxWeight + 1) * code_93_reader_ALPHABET.indexOf(_char3.charCodeAt(0));
}, 0) % 47] === charArray[index].charCodeAt(0);
}
},
{
key: "_verifyChecksums",
value: function(charArray) {
return this._matchCheckChar(charArray, charArray.length - 2, 20) && this._matchCheckChar(charArray, charArray.length - 1, 15);
}
},
{
key: "decode",
value: function(row, start) {
if (!(start = this._findStart())) return null;
var lastStart, decodedChar, counters = new Uint16Array([
0,
0,
0,
0,
0,
0
]), result = [], nextStart = this._nextSet(this._row, start.end);
do {
counters = this._toCounters(nextStart, counters);
var pattern = this._toPattern(counters);
if (pattern < 0 || null === (decodedChar = this._patternToChar(pattern))) return null;
result.push(decodedChar), lastStart = nextStart, nextStart += array_helper.a.sum(counters), nextStart = this._nextSet(this._row, nextStart);
}while ("*" !== decodedChar)
return (result.pop(), result.length && this._verifyEnd(lastStart, nextStart) && this._verifyChecksums(result)) ? (result = result.slice(0, result.length - 2), null === (result = this._decodeExtended(result))) ? null : {
code: result.join(""),
start: start.start,
end: nextStart,
startInfo: start,
decodedCodes: result,
format: this.FORMAT
} : null;
}
}
]), Code93Reader;
}(barcode_reader), code_32_reader_patterns_AEIO = /[AEIO]/g, code_32_reader = /*#__PURE__*/ function(_Code39Reader) {
inherits_default()(Code32Reader, _Code39Reader);
var hasNativeReflectConstruct, _super = (hasNativeReflectConstruct = function() {
if ("undefined" == typeof Reflect || !Reflect.construct || Reflect.construct.sham) return !1;
if ("function" == typeof Proxy) return !0;
try {
return Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function() {})), !0;
} catch (e) {
return !1;
}
}(), function() {
var result, Super = getPrototypeOf_default()(Code32Reader);
return result = hasNativeReflectConstruct ? Reflect.construct(Super, arguments, getPrototypeOf_default()(this).constructor) : Super.apply(this, arguments), possibleConstructorReturn_default()(this, result);
});
function Code32Reader() {
var _this;
classCallCheck_default()(this, Code32Reader);
for(var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++)args[_key] = arguments[_key];
return _this = _super.call.apply(_super, [
this
].concat(args)), defineProperty_default()(assertThisInitialized_default()(_this), "FORMAT", "code_32_reader"), _this;
}
return createClass_default()(Code32Reader, [
{
key: "_decodeCode32",
value: function(code) {
if (/[^0-9BCDFGHJKLMNPQRSTUVWXYZ]/.test(code)) return null;
for(var res = 0, i = 0; i < code.length; i++)res = 32 * res + "0123456789BCDFGHJKLMNPQRSTUVWXYZ".indexOf(code[i]);
var code32 = "" + res;
return code32.length < 9 && (code32 = ("000000000" + code32).slice(-9)), "A" + code32;
}
},
{
key: "_checkChecksum",
value: function(code) {
return !!code;
}
},
{
key: "decode",
value: function(row, start) {
var result = get_default()(getPrototypeOf_default()(Code32Reader.prototype), "decode", this).call(this, row, start);
if (!result) return null;
var code = result.code;
if (!code || (code = code.replace(code_32_reader_patterns_AEIO, ""), !this._checkChecksum(code))) return null;
var code32 = this._decodeCode32(code);
return code32 ? (result.code = code32, result) : null;
}
}
]), Code32Reader;
}(code_39_reader), READERS = {
code_128_reader: code_128_reader,
ean_reader: ean_reader,
ean_5_reader: ean_5_reader,
ean_2_reader: ean_2_reader,
ean_8_reader: ean_8_reader,
code_39_reader: code_39_reader,
code_39_vin_reader: code_39_vin_reader,
codabar_reader: codabar_reader,
upc_reader: upc_reader,
upc_e_reader: upc_e_reader,
i2of5_reader: i2of5_reader,
"2of5_reader": _2of5_reader,
code_93_reader: code_93_reader,
code_32_reader: code_32_reader
}, barcode_decoder = {
registerReader: function(name, reader) {
READERS[name] = reader;
},
create: function(config, inputImageWrapper) {
var _canvas = {
ctx: {
frequency: null,
pattern: null,
overlay: null
},
dom: {
frequency: null,
pattern: null,
overlay: null
}
}, _barcodeReaders = [];
function initReaders() {
config.readers.forEach(function(readerConfig) {
var reader, configuration = {}, supplements = [];
"object" === typeof_default()(readerConfig) ? (reader = readerConfig.format, configuration = readerConfig.config) : "string" == typeof readerConfig && (reader = readerConfig), console.log("Before registering reader: ", reader), configuration.supplements && (supplements = configuration.supplements.map(function(supplement) {
return new READERS[supplement]();
}));
try {
var readerObj = new READERS[reader](configuration, supplements);
_barcodeReaders.push(readerObj);
} catch (err) {
throw console.error("* Error constructing reader ", reader, err), err;
}
}), console.log("Registered Readers: ".concat(_barcodeReaders.map(function(reader) {
return JSON.stringify({
format: reader.FORMAT,
config: reader.config
});
}).join(", ")));
}
function tryDecode(line) {
var i, result = null, barcodeLine = Bresenham.getBarcodeLine(inputImageWrapper, line[0], line[1]);
for(config.debug.showFrequency && (image_debug.a.drawPath(line, {
x: "x",
y: "y"
}, _canvas.ctx.overlay, {
color: "red",
lineWidth: 3
}), Bresenham.debug.printFrequency(barcodeLine.line, _canvas.dom.frequency)), Bresenham.toBinaryLine(barcodeLine), config.debug.showPattern && Bresenham.debug.printPattern(barcodeLine.line, _canvas.dom.pattern), i = 0; i < _barcodeReaders.length && null === result; i++)result = _barcodeReaders[i].decodePattern(barcodeLine.line);
return null === result ? null : {
codeResult: result,
barcodeLine: barcodeLine
};
}
/**
* With the help of the configured readers (Code128 or EAN) this function tries to detect a
* valid barcode pattern within the given area.
* @param {Object} box The area to search in
* @returns {Object} the result {codeResult, line, angle, pattern, threshold}
*/ function _decodeFromBoundingBox(box) {
var line, line1, result, ctx = _canvas.ctx.overlay;
config.debug.drawBoundingBox && ctx && image_debug.a.drawPath(box, {
x: 0,
y: 1
}, ctx, {
color: "blue",
lineWidth: 2
});
var lineLength = Math.sqrt(Math.pow(Math.abs((line = line1 = [
{
x: (box[1][0] - box[0][0]) / 2 + box[0][0],
y: (box[1][1] - box[0][1]) / 2 + box[0][1]
},
{
x: (box[3][0] - box[2][0]) / 2 + box[2][0],
y: (box[3][1] - box[2][1]) / 2 + box[2][1]
}
])[1].y - line[0].y), 2) + Math.pow(Math.abs(line[1].x - line[0].x), 2)), lineAngle = Math.atan2(line1[1].y - line1[0].y, line1[1].x - line1[0].x);
return null === (line1 = /**
* extend the line on both ends
* @param {Array} line
* @param {Number} angle
*/ function(line, angle, ext) {
function extendLine(amount) {
var extension = {
y: amount * Math.sin(angle),
x: amount * Math.cos(angle)
};
/* eslint-disable no-param-reassign */ line[0].y -= extension.y, line[0].x -= extension.x, line[1].y += extension.y, line[1].x += extension.x;
/* eslint-enable no-param-reassign */ } // check if inside image
for(extendLine(ext); ext > 1 && (!inputImageWrapper.inImageWithBorder(line[0]) || !inputImageWrapper.inImageWithBorder(line[1]));)extendLine(-// eslint-disable-next-line no-param-reassign
(ext -= Math.ceil(ext / 2)));
return line;
}(line1, lineAngle, Math.floor(0.1 * lineLength))) ? null : (null === (result = tryDecode(line1)) && (result = /**
* This method slices the given area apart and tries to detect a barcode-pattern
* for each slice. It returns the decoded barcode, or null if nothing was found
* @param {Array} box
* @param {Array} line
* @param {Number} lineAngle
*/ function(box, line, lineAngle) {
var i, dir, extension, sideLength = Math.sqrt(Math.pow(box[1][0] - box[0][0], 2) + Math.pow(box[1][1] - box[0][1], 2)), result = null, xdir = Math.sin(lineAngle), ydir = Math.cos(lineAngle);
for(i = 1; i < 16 && null === result; i++)extension = {
y: // move line perpendicular to angle
// eslint-disable-next-line no-mixed-operators
(dir = sideLength / 16 * i * (i % 2 == 0 ? -1 : 1)) * xdir,
x: dir * ydir
}, /* eslint-disable no-param-reassign */ line[0].y += extension.x, line[0].x -= extension.y, line[1].y += extension.x, line[1].x -= extension.y, /* eslint-enable no-param-reassign */ result = tryDecode(line);
return result;
}(box, line1, lineAngle)), null === result) ? null : (result && config.debug.drawScanline && ctx && image_debug.a.drawPath(line1, {
x: "x",
y: "y"
}, ctx, {
color: "red",
lineWidth: 3
}), {
codeResult: result.codeResult,
line: line1,
angle: lineAngle,
pattern: result.barcodeLine.line,
threshold: result.barcodeLine.threshold
});
}
return function() {
if ("undefined" != typeof document) {
var $debug = document.querySelector("#debug.detection");
_canvas.dom.frequency = document.querySelector("canvas.frequency"), !_canvas.dom.frequency && (_canvas.dom.frequency = document.createElement("canvas"), _canvas.dom.frequency.className = "frequency", $debug && $debug.appendChild(_canvas.dom.frequency)), _canvas.ctx.frequency = _canvas.dom.frequency.getContext("2d"), _canvas.dom.pattern = document.querySelector("canvas.patternBuffer"), !_canvas.dom.pattern && (_canvas.dom.pattern = document.createElement("canvas"), _canvas.dom.pattern.className = "patternBuffer", $debug && $debug.appendChild(_canvas.dom.pattern)), _canvas.ctx.pattern = _canvas.dom.pattern.getContext("2d"), _canvas.dom.overlay = document.querySelector("canvas.drawingBuffer"), _canvas.dom.overlay && (_canvas.ctx.overlay = _canvas.dom.overlay.getContext("2d"));
}
}(), initReaders(), function() {
if ("undefined" != typeof document) {
var i, vis = [
{
node: _canvas.dom.frequency,
prop: config.debug.showFrequency
},
{
node: _canvas.dom.pattern,
prop: config.debug.showPattern
}
];
for(i = 0; i < vis.length; i++)!0 === vis[i].prop ? vis[i].node.style.display = "block" : vis[i].node.style.display = "none";
}
}(), {
decodeFromBoundingBox: function(box) {
return _decodeFromBoundingBox(box);
},
decodeFromBoundingBoxes: function(boxes) {
var i, result, barcodes = [], multiple = config.multiple;
for(i = 0; i < boxes.length; i++){
var box = boxes[i];
if ((result = _decodeFromBoundingBox(box) || {}).box = box, multiple) barcodes.push(result);
else if (result.codeResult) return result;
}
if (multiple) return {
barcodes: barcodes
};
},
decodeFromImage: function(inputImageWrapper) {
return function(imageWrapper) {
for(var result = null, i = 0; i < _barcodeReaders.length && null === result; i++)result = _barcodeReaders[i].decodeImage ? _barcodeReaders[i].decodeImage(imageWrapper) : null;
return result;
}(inputImageWrapper);
},
registerReader: function(name, reader) {
if (READERS[name]) throw Error("cannot register existing reader", name);
READERS[name] = reader;
},
setReaders: function(readers) {
// eslint-disable-next-line no-param-reassign
config.readers = readers, _barcodeReaders.length = 0, initReaders();
}
};
}
}, events = function() {
var events = {};
function getEvent(eventName) {
return events[eventName] || (events[eventName] = {
subscribers: []
}), events[eventName];
}
function publishSubscription(subscription, data) {
subscription.async ? setTimeout(function() {
subscription.callback(data);
}, 4) : subscription.callback(data);
}
function _subscribe(event, callback, async) {
var subscription;
if ("function" == typeof callback) subscription = {
callback: callback,
async: async
};
else if (!(subscription = callback).callback) throw Error("Callback was not specified on options");
getEvent(event).subscribers.push(subscription);
}
return {
subscribe: function(event, callback, async) {
return _subscribe(event, callback, async);
},
publish: function(eventName, data) {
var event = getEvent(eventName), subscribers = event.subscribers;
subscribers.filter(function(subscriber) {
return !!subscriber.once;
}).forEach(function(subscriber) {
publishSubscription(subscriber, data);
}), event.subscribers = subscribers.filter(function(subscriber) {
return !subscriber.once;
}), event.subscribers.forEach(function(subscriber) {
publishSubscription(subscriber, data);
});
},
once: function(event, callback) {
var async = arguments.length > 2 && void 0 !== arguments[2] && arguments[2];
_subscribe(event, {
callback: callback,
async: async,
once: !0
});
},
unsubscribe: function(eventName, callback) {
if (eventName) {
var _event = getEvent(eventName);
_event && callback ? _event.subscribers = _event.subscribers.filter(function(subscriber) {
return subscriber.callback !== callback;
}) : _event.subscribers = [];
} else events = {};
}
};
}(), asyncToGenerator = __webpack_require__(20), asyncToGenerator_default = /*#__PURE__*/ __webpack_require__.n(asyncToGenerator), regenerator = __webpack_require__(12), regenerator_default = /*#__PURE__*/ __webpack_require__.n(regenerator), pick = __webpack_require__(85), pick_default = /*#__PURE__*/ __webpack_require__.n(pick), wrapNativeSuper = __webpack_require__(86), Exception_Exception = /*#__PURE__*/ function(_Error) {
inherits_default()(Exception, _Error);
var hasNativeReflectConstruct, _super = (hasNativeReflectConstruct = function() {
if ("undefined" == typeof Reflect || !Reflect.construct || Reflect.construct.sham) return !1;
if ("function" == typeof Proxy) return !0;
try {
return Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function() {})), !0;
} catch (e) {
return !1;
}
}(), function() {
var result, Super = getPrototypeOf_default()(Exception);
return result = hasNativeReflectConstruct ? Reflect.construct(Super, arguments, getPrototypeOf_default()(this).constructor) : Super.apply(this, arguments), possibleConstructorReturn_default()(this, result);
});
function Exception(m, code) {
var _this;
return classCallCheck_default()(this, Exception), _this = _super.call(this, m), defineProperty_default()(assertThisInitialized_default()(_this), "code", void 0), _this.code = code, Object.setPrototypeOf(assertThisInitialized_default()(_this), Exception.prototype), _this;
}
return Exception;
}(/*#__PURE__*/ /*#__PURE__*/ __webpack_require__.n(wrapNativeSuper)()(Error)), ERROR_DESC = "This may mean that the user has declined camera access, or the browser does not support media APIs. If you are running in iOS, you must use Safari.";
function _initCamera() {
return (_initCamera = asyncToGenerator_default()(/*#__PURE__*/ regenerator_default.a.mark(function _callee2(video, constraints) {
var stream;
return regenerator_default.a.wrap(function(_context2) {
for(;;)switch(_context2.prev = _context2.next){
case 0:
return _context2.next = 2, function(constraints) {
try {
return navigator.mediaDevices.getUserMedia(constraints);
} catch (err) {
return Promise.reject(new Exception_Exception("getUserMedia is not defined. ".concat(ERROR_DESC), -1));
}
}(constraints);
case 2:
if (streamRef = stream = _context2.sent, !video) {
_context2.next = 11;
break;
}
return video.setAttribute("autoplay", "true"), video.setAttribute("muted", "true"), video.setAttribute("playsinline", "true"), // eslint-disable-next-line no-param-reassign
video.srcObject = stream, video.addEventListener("loadedmetadata", function() {
video.play();
}), _context2.abrupt("return", function(video) {
return new Promise(function(resolve, reject) {
var attempts = 10;
!function checkVideo() {
attempts > 0 ? video.videoWidth > 10 && video.videoHeight > 10 ? (console.log("* dev: checkVideo found ".concat(video.videoWidth, "px x ").concat(video.videoHeight, "px")), resolve()) : window.setTimeout(checkVideo, 500) : reject(new Exception_Exception("Unable to play video stream. Is webcam working?", -1)), attempts--;
}();
});
}(video));
case 11:
return _context2.abrupt("return", Promise.resolve());
case 12:
case "end":
return _context2.stop();
}
}, _callee2);
}))).apply(this, arguments);
}
function _enumerateVideoDevices() {
return (_enumerateVideoDevices = asyncToGenerator_default()(/*#__PURE__*/ regenerator_default.a.mark(function _callee3() {
var devices;
return regenerator_default.a.wrap(function(_context3) {
for(;;)switch(_context3.prev = _context3.next){
case 0:
return _context3.next = 2, function() {
try {
return navigator.mediaDevices.enumerateDevices();
} catch (err) {
return Promise.reject(new Exception_Exception("enumerateDevices is not defined. ".concat(ERROR_DESC), -1));
}
}();
case 2:
return devices = _context3.sent, _context3.abrupt("return", devices.filter(function(device) {
return "videoinput" === device.kind;
}));
case 4:
case "end":
return _context3.stop();
}
}, _callee3);
}))).apply(this, arguments);
}
function getActiveTrack() {
if (!streamRef) return null;
var tracks = streamRef.getVideoTracks();
return tracks && null != tracks && tracks.length ? tracks[0] : null;
}
/**
* Used for accessing information about the active stream track and available video devices.
*/ var QuaggaJSCameraAccess = {
requestedVideoElement: null,
request: function(video, videoConstraints) {
return asyncToGenerator_default()(/*#__PURE__*/ regenerator_default.a.mark(function _callee() {
var newConstraints;
return regenerator_default.a.wrap(function(_context) {
for(;;)switch(_context.prev = _context.next){
case 0:
return QuaggaJSCameraAccess.requestedVideoElement = video, _context.next = 3, // I think it was just that way so it could be chained to other functions that did return a Promise.
// That's not necessary with async functions being a thing, so that should be fixed.
function() {
var normalized, videoConstraints = arguments.length > 0 && void 0 !== arguments[0] ? arguments[0] : {}, video = (normalized = pick_default()(videoConstraints, [
"width",
"height",
"facingMode",
"aspectRatio",
"deviceId"
]), void 0 !== videoConstraints.minAspectRatio && videoConstraints.minAspectRatio > 0 && (normalized.aspectRatio = videoConstraints.minAspectRatio, console.log("WARNING: Constraint 'minAspectRatio' is deprecated; Use 'aspectRatio' instead")), void 0 !== videoConstraints.facing && (normalized.facingMode = videoConstraints.facing, console.log("WARNING: Constraint 'facing' is deprecated. Use 'facingMode' instead'")), normalized);
return video && video.deviceId && video.facingMode && delete video.facingMode, Promise.resolve({
audio: !1,
video: video
});
}(videoConstraints);
case 3:
return newConstraints = _context.sent, _context.abrupt("return", /**
* Tries to attach the camera-stream to a given video-element
* and calls the callback function when the content is ready
* @param {Object} constraints
* @param {Object} video
*/ function(_x, _x2) {
return _initCamera.apply(this, arguments);
}(video, newConstraints));
case 5:
case "end":
return _context.stop();
}
}, _callee);
}))();
},
release: function() {
var tracks = streamRef && streamRef.getVideoTracks();
return null !== QuaggaJSCameraAccess.requestedVideoElement && QuaggaJSCameraAccess.requestedVideoElement.pause(), new Promise(function(resolve) {
setTimeout(function() {
tracks && tracks.length && tracks[0].stop(), streamRef = null, QuaggaJSCameraAccess.requestedVideoElement = null, resolve();
}, 0);
});
},
enumerateVideoDevices: function() {
return _enumerateVideoDevices.apply(this, arguments);
},
getActiveStreamLabel: function() {
var track = getActiveTrack();
return track ? track.label : "";
},
getActiveTrack: getActiveTrack
}, camera_access = QuaggaJSCameraAccess, result_collector = {
create: function(config) {
var _config$capacity, canvas = document.createElement("canvas"), ctx = canvas.getContext("2d"), results = [], capacity = null !== (_config$capacity = config.capacity) && void 0 !== _config$capacity ? _config$capacity : 20, capture = !0 === config.capture;
return {
addResult: function(data, imageSize, codeResult) {
var list, filter, result = {}; // this is 'any' to avoid having to construct a whole QuaggaJSCodeResult :|
capacity && codeResult && !((list = config.blacklist) && list.some(function(item) {
return Object.keys(item).every(function(key) {
return item[key] === codeResult[key];
});
})) && ("function" != typeof (filter = config.filter) || filter(codeResult)) && (capacity--, result.codeResult = codeResult, capture && (canvas.width = imageSize.x, canvas.height = imageSize.y, image_debug.a.drawImage(data, imageSize, ctx), result.frame = canvas.toDataURL()), results.push(result));
},
getResults: function() {
return results;
}
};
}
}, config_config = {
inputStream: {
name: "Live",
type: "LiveStream",
constraints: {
width: 640,
height: 480,
// aspectRatio: 640/480, // optional
facingMode: "environment"
},
area: {
top: "0%",
right: "0%",
left: "0%",
bottom: "0%"
},
singleChannel: !1
},
locate: !0,
numOfWorkers: 0,
decoder: {
readers: [
"code_128_reader"
],
debug: {
drawBoundingBox: !1,
showFrequency: !1,
drawScanline: !1,
showPattern: !1
}
},
locator: {
halfSample: !0,
patchSize: "medium",
// x-small, small, medium, large, x-large
debug: {
showCanvas: !1,
showPatches: !1,
showFoundPatches: !1,
showSkeleton: !1,
showLabels: !1,
showPatchLabels: !1,
showRemainingPatchLabels: !1,
boxFromPatches: {
showTransformed: !1,
showTransformedBox: !1,
showBB: !1
}
}
}
}, gl_vec2 = __webpack_require__(7), QuaggaContext_QuaggaContext = function QuaggaContext() {
classCallCheck_default()(this, QuaggaContext), defineProperty_default()(this, "config", void 0), defineProperty_default()(this, "inputStream", void 0), defineProperty_default()(this, "framegrabber", void 0), defineProperty_default()(this, "inputImageWrapper", void 0), defineProperty_default()(this, "stopped", !1), defineProperty_default()(this, "boxSize", void 0), defineProperty_default()(this, "resultCollector", void 0), defineProperty_default()(this, "decoder", void 0), defineProperty_default()(this, "workerPool", []), defineProperty_default()(this, "onUIThread", !0), defineProperty_default()(this, "canvasContainer", new QuaggaContext_CanvasContainer());
}, QuaggaContext_CanvasInfo = function CanvasInfo() {
classCallCheck_default()(this, CanvasInfo), defineProperty_default()(this, "image", void 0), defineProperty_default()(this, "overlay", void 0);
}, QuaggaContext_CanvasContainer = function CanvasContainer() {
classCallCheck_default()(this, CanvasContainer), defineProperty_default()(this, "ctx", void 0), defineProperty_default()(this, "dom", void 0), this.ctx = new QuaggaContext_CanvasInfo(), this.dom = new QuaggaContext_CanvasInfo();
}, barcode_locator = __webpack_require__(23);
// CONCATENATED MODULE: ./src/quagga/getViewPort.ts
function getViewPort_getViewPort(target) {
if ("undefined" == typeof document) return null;
// Check if target is already a DOM element
if (target instanceof HTMLElement && target.nodeName && 1 === target.nodeType) return target;
// Use '#interactive.viewport' as a fallback selector (backwards compatibility)
var selector = "string" == typeof target ? target : "#interactive.viewport";
return document.querySelector(selector);
}
function getCanvasAndContext(selector, className) {
var canvas, canvas1 = ((canvas = document.querySelector(selector)) || ((canvas = document.createElement("canvas")).className = className), canvas), context = canvas1.getContext("2d");
return {
canvas: canvas1,
context: context
};
}
// CONCATENATED MODULE: ./src/input/exif_helper.js
// NOTE: (SOME OF) THIS IS BROWSER ONLY CODE. Node does not have 'atob' built in, nor XMLHttpRequest.
// How exactly is this set of functions used in Quagga? Do we need the browser specific code? Do we
// need to port any part of this that doesn't work in Node to node?
// Tags scraped from https://github.com/exif-js/exif-js
var ExifTags = {
0x0112: "orientation"
}, AvailableTags = Object.keys(ExifTags).map(function(key) {
return ExifTags[key];
});
function readToBuffer(blob) {
return new Promise(function(resolve) {
var fileReader = new FileReader();
fileReader.onload = function(e) {
return resolve(e.target.result);
}, fileReader.readAsArrayBuffer(blob);
});
}
// CONCATENATED MODULE: ./src/input/image_loader.js
var ImageLoader = {};
ImageLoader.load = function(directory, callback, offset, size, sequence) {
var i, img, num, htmlImagesSrcArray = Array(size), htmlImagesArray = Array(htmlImagesSrcArray.length);
if (!1 === sequence) htmlImagesSrcArray[0] = directory;
else for(i = 0; i < htmlImagesSrcArray.length; i++)num = offset + i, htmlImagesSrcArray[i] = "".concat(directory, "image-").concat("00".concat(num).slice(-3), ".jpg");
for(i = 0, htmlImagesArray.notLoaded = [], htmlImagesArray.addImage = function(image) {
htmlImagesArray.notLoaded.push(image);
}, htmlImagesArray.loaded = function(loadedImg) {
for(var notloadedImgs = htmlImagesArray.notLoaded, x = 0; x < notloadedImgs.length; x++)if (notloadedImgs[x] === loadedImg) {
notloadedImgs.splice(x, 1);
for(var y = 0; y < htmlImagesSrcArray.length; y++){
var imgName = htmlImagesSrcArray[y].substr(htmlImagesSrcArray[y].lastIndexOf("/"));
if (-1 !== loadedImg.src.lastIndexOf(imgName)) {
htmlImagesArray[y] = {
img: loadedImg
};
break;
}
}
break;
}
0 === notloadedImgs.length && (console.log("Images loaded"), !1 === sequence ? (function(src) {
var tags = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : AvailableTags;
return /^blob:/i.test(src) ? new Promise(function(resolve, reject) {
var http = new XMLHttpRequest();
http.open("GET", src, !0), http.responseType = "blob", http.onreadystatechange = function() {
http.readyState === XMLHttpRequest.DONE && (200 === http.status || 0 === http.status) && resolve(this.response);
}, http.onerror = reject, http.send();
}).then(readToBuffer).then(function(buffer) {
return function(file) {
var selectedTags = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : AvailableTags, dataView = new DataView(file), length = file.byteLength, exifTags = selectedTags.reduce(function(result, selectedTag) {
var exifTag = Object.keys(ExifTags).filter(function(tag) {
return ExifTags[tag] === selectedTag;
})[0];
return exifTag && (result[exifTag] = selectedTag), result;
}, {}), offset = 2;
if (0xff !== dataView.getUint8(0) || 0xd8 !== dataView.getUint8(1)) return !1;
for(; offset < length && 0xff === dataView.getUint8(offset);){
if (0xe1 === dataView.getUint8(offset + 1)) return function(file, start, exifTags) {
if ("Exif" !== function(buffer, start, length) {
for(var outstr = "", n = start; n < start + 4; n++)outstr += String.fromCharCode(buffer.getUint8(n));
return outstr;
}(file, start, 0)) return !1;
var bigEnd, tiffOffset = start + 6;
if (0x4949 === file.getUint16(tiffOffset)) bigEnd = !1;
else {
if (0x4d4d !== file.getUint16(tiffOffset)) return !1;
bigEnd = !0;
}
if (0x002a !== file.getUint16(tiffOffset + 2, !bigEnd)) return !1;
var firstIFDOffset = file.getUint32(tiffOffset + 4, !bigEnd);
return !(firstIFDOffset < 0x00000008) && function(file, tiffStart, dirStart, strings, bigEnd) {
for(var entries = file.getUint16(dirStart, !bigEnd), tags = {}, i = 0; i < entries; i++){
var entryOffset = dirStart + 12 * i + 2, tag = strings[file.getUint16(entryOffset, !bigEnd)];
tag && (tags[tag] = function(file, entryOffset, tiffStart, dirStart, bigEnd) {
var type = file.getUint16(entryOffset + 2, !bigEnd), numValues = file.getUint32(entryOffset + 4, !bigEnd);
return 3 === type && 1 === numValues ? file.getUint16(entryOffset + 8, !bigEnd) : null;
}(file, entryOffset, 0, 0, bigEnd));
}
return tags;
}(file, 0, tiffOffset + firstIFDOffset, exifTags, bigEnd);
}(dataView, offset + 4, exifTags);
offset += 2 + dataView.getUint16(offset + 2);
}
return !1;
}(buffer, tags);
}) : Promise.resolve(null);
})(directory, [
"orientation"
]).then(function(tags) {
htmlImagesArray[0].tags = tags, callback(htmlImagesArray);
}).catch(function(e) {
console.log(e), callback(htmlImagesArray);
}) : callback(htmlImagesArray));
}; i < htmlImagesSrcArray.length; i++)img = new Image(), htmlImagesArray.addImage(img), function(img, htmlImagesArray) {
img.onload = function() {
htmlImagesArray.loaded(this);
};
}(img, htmlImagesArray), img.src = htmlImagesSrcArray[i];
};
// CONCATENATED MODULE: ./src/input/input_stream/input_stream_browser.ts
/* eslint-disable @typescript-eslint/no-explicit-any */ var inputStreamFactory = {
createVideoStream: function(video) {
var _calculatedWidth, _calculatedHeight, _config = null, _eventNames = [
"canrecord",
"ended"
], _eventHandlers = {}, _topRight = {
x: 0,
y: 0,
type: "Point"
}, _canvasSize = {
x: 0,
y: 0,
type: "XYSize"
}, inputStream = {
getRealWidth: function() {
return video.videoWidth;
},
getRealHeight: function() {
return video.videoHeight;
},
getWidth: function() {
return _calculatedWidth;
},
getHeight: function() {
return _calculatedHeight;
},
setWidth: function(width) {
_calculatedWidth = width;
},
setHeight: function(height) {
_calculatedHeight = height;
},
setInputStream: function(config) {
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
_config = config, this.setAttribute("src", void 0 !== config.src ? config.src : "");
},
ended: function() {
return video.ended;
},
getConfig: function() {
return _config;
},
setAttribute: function(name, value) {
video && video.setAttribute(name, value);
},
pause: function() {
video.pause();
},
play: function() {
// eslint-disable-next-line @typescript-eslint/no-floating-promises
video.play();
},
setCurrentTime: function(time) {
var _config4;
(null === (_config4 = _config) || void 0 === _config4 ? void 0 : _config4.type) !== "LiveStream" && this.setAttribute("currentTime", time.toString());
},
addEventListener: function(event, f, bool) {
-1 !== _eventNames.indexOf(event) ? (_eventHandlers[event] || (_eventHandlers[event] = []), _eventHandlers[event].push(f)) : video.addEventListener(event, f, bool);
},
clearEventHandlers: function() {
_eventNames.forEach(function(eventName) {
var handlers = _eventHandlers[eventName];
handlers && handlers.length > 0 && handlers.forEach(function(handler) {
video.removeEventListener(eventName, handler);
});
});
},
trigger: function(eventName, args) {
var _config2, _config3, width, height, j, handlers = _eventHandlers[eventName];
if ("canrecord" === eventName && (width = video.videoWidth, height = video.videoHeight, _calculatedWidth = null !== (_config2 = _config) && void 0 !== _config2 && _config2.size ? width / height > 1 ? _config.size : Math.floor(width / height * _config.size) : width, _calculatedHeight = null !== (_config3 = _config) && void 0 !== _config3 && _config3.size ? width / height > 1 ? Math.floor(height / width * _config.size) : _config.size : height, _canvasSize.x = _calculatedWidth, _canvasSize.y = _calculatedHeight), handlers && handlers.length > 0) for(j = 0; j < handlers.length; j++)handlers[j].apply(inputStream, args);
},
setTopRight: function(topRight) {
_topRight.x = topRight.x, _topRight.y = topRight.y;
},
getTopRight: function() {
return _topRight;
},
setCanvasSize: function(size) {
_canvasSize.x = size.x, _canvasSize.y = size.y;
},
getCanvasSize: function() {
return _canvasSize;
},
getFrame: function() {
return video;
}
};
return inputStream;
},
createLiveStream: function(video) {
video && video.setAttribute("autoplay", "true");
var that = inputStreamFactory.createVideoStream(video);
return that.ended = function() {
return !1;
}, that;
},
createImageStream: function() {
var calculatedWidth, calculatedHeight, _config = null, width = 0, height = 0, frameIdx = 0, paused = !0, loaded = !1, imgArray = null, size = 0, baseUrl = null, _ended = !1, _eventNames = [
"canrecord",
"ended"
], _eventHandlers = {}, _topRight = {
x: 0,
y: 0,
type: "Point"
}, _canvasSize = {
x: 0,
y: 0,
type: "XYSize"
};
function publishEvent(eventName, args) {
var j, handlers = _eventHandlers[eventName];
if (handlers && handlers.length > 0) for(j = 0; j < handlers.length; j++)// eslint-disable-next-line @typescript-eslint/no-use-before-define
handlers[j].apply(inputStream, args); // TODO: typescript complains that any[] is not valid for a second arg for apply?!
} // TODO: any code shared with the first InputStream above should be shared not copied
// TODO: publishEvent needs access to inputStream, but inputStream needs access to publishEvent
// TODO: This is why it's a 'var', so it hoists back. This is ugly, and should be changed.
// eslint-disable-next-line no-var,vars-on-top
var inputStream = {
trigger: publishEvent,
getWidth: function() {
return calculatedWidth;
},
getHeight: function() {
return calculatedHeight;
},
setWidth: function(newWidth) {
calculatedWidth = newWidth;
},
setHeight: function(newHeight) {
calculatedHeight = newHeight;
},
getRealWidth: function() {
return width;
},
getRealHeight: function() {
return height;
},
setInputStream: function(stream) {
var _config7;
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
_config = stream, !1 === stream.sequence ? (// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment,@typescript-eslint/no-unsafe-member-access
baseUrl = stream.src, size = 1) : (// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment,@typescript-eslint/no-unsafe-member-access
baseUrl = stream.src, size = stream.length), loaded = !1, ImageLoader.load(baseUrl, function(imgs) {
var _config5, _config6;
if (imgArray = imgs, imgs[0].tags && imgs[0].tags.orientation) // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
switch(imgs[0].tags.orientation){
case 6:
case 8:
width = imgs[0].img.height, height = imgs[0].img.width;
break;
default:
width = imgs[0].img.width, height = imgs[0].img.height;
}
else width = imgs[0].img.width, height = imgs[0].img.height;
// eslint-disable-next-line no-nested-ternary
calculatedWidth = null !== (_config5 = _config) && void 0 !== _config5 && _config5.size ? width / height > 1 ? _config.size : Math.floor(width / height * _config.size) : width, calculatedHeight = null !== (_config6 = _config) && void 0 !== _config6 && _config6.size ? width / height > 1 ? Math.floor(height / width * _config.size) : _config.size : height, _canvasSize.x = calculatedWidth, _canvasSize.y = calculatedHeight, loaded = !0, frameIdx = 0, setTimeout(function() {
// eslint-disable-next-line @typescript-eslint/no-use-before-define
publishEvent("canrecord", []);
}, 0);
}, 1, size, null === (_config7 = _config) || void 0 === _config7 ? void 0 : _config7.sequence);
},
ended: function() {
return _ended;
},
setAttribute: function() {},
getConfig: function() {
return _config;
},
pause: function() {
paused = !0;
},
play: function() {
paused = !1;
},
setCurrentTime: function(time) {
frameIdx = time;
},
addEventListener: function(event, f) {
-1 !== _eventNames.indexOf(event) && (_eventHandlers[event] || (_eventHandlers[event] = []), _eventHandlers[event].push(f));
},
clearEventHandlers: function() {
Object.keys(_eventHandlers).forEach(function(ind) {
return delete _eventHandlers[ind];
});
},
setTopRight: function(topRight) {
_topRight.x = topRight.x, _topRight.y = topRight.y;
},
getTopRight: function() {
return _topRight;
},
setCanvasSize: function(canvasSize) {
_canvasSize.x = canvasSize.x, _canvasSize.y = canvasSize.y;
},
getCanvasSize: function() {
return _canvasSize;
},
getFrame: function() {
var frame, _imgArray;
return loaded ? (!paused && (// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
frame = null === (_imgArray = imgArray) || void 0 === _imgArray ? void 0 : _imgArray[frameIdx], frameIdx < size - 1 ? frameIdx++ : setTimeout(function() {
_ended = !0, publishEvent("ended", []);
}, 0)), frame) : null;
}
};
return inputStream;
}
}, cv_utils = __webpack_require__(8), TO_RADIANS = Math.PI / 180, FrameGrabber = {};
// CONCATENATED MODULE: ./src/quagga/qworker.ts
function qworker_ownKeys(object, enumerableOnly) {
var keys = Object.keys(object);
if (Object.getOwnPropertySymbols) {
var symbols = Object.getOwnPropertySymbols(object);
enumerableOnly && (symbols = symbols.filter(function(sym) {
return Object.getOwnPropertyDescriptor(object, sym).enumerable;
})), keys.push.apply(keys, symbols);
}
return keys;
}
function qworker_objectSpread(target) {
for(var i = 1; i < arguments.length; i++){
var source = null != arguments[i] ? arguments[i] : {};
i % 2 ? qworker_ownKeys(Object(source), !0).forEach(function(key) {
defineProperty_default()(target, key, source[key]);
}) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : qworker_ownKeys(Object(source)).forEach(function(key) {
Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
});
}
return target;
}
FrameGrabber.create = function(inputStream, canvas) {
var _canvas, _that = {}, _streamConfig = inputStream.getConfig(), _videoSize = Object(cv_utils.h)(inputStream.getRealWidth(), inputStream.getRealHeight()), _canvasSize = inputStream.getCanvasSize(), _size = Object(cv_utils.h)(inputStream.getWidth(), inputStream.getHeight()), topRight = inputStream.getTopRight(), _sx = topRight.x, _sy = topRight.y, _ctx = null, _data = null;
return (_canvas = canvas || document.createElement("canvas")).width = _canvasSize.x, _canvas.height = _canvasSize.y, _ctx = _canvas.getContext("2d"), _data = new Uint8Array(_size.x * _size.y), console.log("FrameGrabber", JSON.stringify({
size: _size,
topRight: topRight,
videoSize: _videoSize,
canvasSize: _canvasSize
})), /**
* Uses the given array as frame-buffer
*/ _that.attachData = function(data) {
_data = data;
}, /**
* Returns the used frame-buffer
*/ _that.getData = function() {
return _data;
}, /**
* Fetches a frame from the input-stream and puts into the frame-buffer.
* The image-data is converted to gray-scale and then half-sampled if configured.
*/ _that.grab = function() {
var ctxData, doHalfSample = _streamConfig.halfSample, frame = inputStream.getFrame(), drawable = frame, drawAngle = 0;
if (drawable) {
if (_canvas.width !== _canvasSize.x && (console.log("WARNING: canvas-size needs to be adjusted"), _canvas.width = _canvasSize.x), _canvas.height !== _canvasSize.y && (console.log("WARNING: canvas-size needs to be adjusted"), _canvas.height = _canvasSize.y), "ImageStream" === _streamConfig.type && (drawable = frame.img, frame.tags && frame.tags.orientation)) switch(frame.tags.orientation){
case 6:
drawAngle = 90 * TO_RADIANS;
break;
case 8:
drawAngle = -90 * TO_RADIANS;
}
return 0 !== drawAngle ? (_ctx.translate(_canvasSize.x / 2, _canvasSize.y / 2), _ctx.rotate(drawAngle), _ctx.drawImage(drawable, -_canvasSize.y / 2, -_canvasSize.x / 2, _canvasSize.y, _canvasSize.x), _ctx.rotate(-drawAngle), _ctx.translate(-_canvasSize.x / 2, -_canvasSize.y / 2)) : _ctx.drawImage(drawable, 0, 0, _canvasSize.x, _canvasSize.y), ctxData = _ctx.getImageData(_sx, _sy, _size.x, _size.y).data, doHalfSample ? Object(cv_utils.e)(ctxData, _size, _data) : Object(cv_utils.c)(ctxData, _data, _streamConfig), !0;
}
return !1;
}, _that.getSize = function() {
return _size;
}, _that;
};
/* Worker functions. These are straight from the original quagga.js file.
* Not presently used, as worker support is non-functional. Keeping them around temporarily
* to refer to until it is re-implemented. We may be able to fix/use some of this.
*/ // TODO: need a typescript interface for FrameGrabber
var workerPool = [];
function workerInterface(factory) {
if (factory) {
var imageWrapper, Quagga = factory().default;
if (!Quagga) {
// @ts-ignore
self.postMessage({
event: "error",
message: "Quagga could not be created"
});
return;
}
} // @ts-ignore
function onProcessed(result) {
self.postMessage({
event: "processed",
// @ts-ignore
imageData: imageWrapper.data,
result: result
}, [
imageWrapper.data.buffer
]);
}
function workerInterfaceReady() {
self.postMessage({
event: "initialized",
// @ts-ignore
imageData: imageWrapper.data
}, [
imageWrapper.data.buffer
]);
} // @ts-ignore
self.onmessage = function(e) {
if ("init" === e.data.cmd) {
var config = e.data.config;
config.numOfWorkers = 0, imageWrapper = new Quagga.ImageWrapper({
x: e.data.size.x,
y: e.data.size.y
}, new Uint8Array(e.data.imageData)), Quagga.init(config, workerInterfaceReady, imageWrapper), Quagga.onProcessed(onProcessed);
} else "process" === e.data.cmd ? (// @ts-ignore
imageWrapper.data = new Uint8Array(e.data.imageData), Quagga.start()) : "setReaders" === e.data.cmd ? Quagga.setReaders(e.data.readers) : "registerReader" === e.data.cmd && Quagga.registerReader(e.data.name, e.data.reader);
};
}
function adjustWorkerPool(capacity, config, inputStream, cb) {
var increaseBy = capacity - workerPool.length;
if (0 === increaseBy && cb) cb();
else if (increaseBy < 0) workerPool.slice(increaseBy).forEach(function(workerThread) {
workerThread.worker.terminate(), console.log("Worker terminated!");
}), workerPool = workerPool.slice(0, increaseBy), cb && cb();
else {
var workerInitialized = function(workerThread) {
workerPool.push(workerThread), workerPool.length >= capacity && cb && cb();
};
if (config) for(var i = 0; i < increaseBy; i++)!function(config, inputStream, cb) {
var blob, factorySource, blobURL = ("undefined" != typeof __factorySource__ && // @ts-ignore
(factorySource = __factorySource__), /* jshint ignore:end */ blob = new Blob([
"(" + workerInterface.toString() + ")(" + factorySource + ");"
], {
type: "text/javascript"
}), window.URL.createObjectURL(blob)), workerThread = {
worker: new Worker(blobURL),
imageData: new Uint8Array(inputStream.getWidth() * inputStream.getHeight()),
busy: !0
};
workerThread.worker.onmessage = function(e) {
"initialized" === e.data.event ? (URL.revokeObjectURL(blobURL), workerThread.busy = !1, workerThread.imageData = new Uint8Array(e.data.imageData), console.log("Worker initialized"), cb(workerThread)) : "processed" === e.data.event ? (workerThread.imageData = new Uint8Array(e.data.imageData), workerThread.busy = !1) : "error" === e.data.event && console.log("Worker error: " + e.data.message);
}, workerThread.worker.postMessage({
cmd: "init",
size: {
x: inputStream.getWidth(),
y: inputStream.getHeight()
},
imageData: workerThread.imageData,
config: qworker_objectSpread(qworker_objectSpread({}, config), {}, {
inputStream: qworker_objectSpread(qworker_objectSpread({}, config.inputStream), {}, {
target: null
})
})
}, [
workerThread.imageData.buffer
]);
}(config, inputStream, workerInitialized);
}
}
// CONCATENATED MODULE: ./src/quagga/transform.ts
/* eslint-disable no-param-reassign */ function moveBox(box, xOffset, yOffset) {
for(var corner = box.length; corner--;)box[corner][0] += xOffset, box[corner][1] += yOffset;
}
// CONCATENATED MODULE: ./src/quagga/quagga.ts
var quagga_Quagga = /*#__PURE__*/ function() {
var _stop;
function Quagga() {
var _this = this;
classCallCheck_default()(this, Quagga), defineProperty_default()(this, "context", new QuaggaContext_QuaggaContext()), defineProperty_default()(this, "canRecord", function(callback) {
var _this$context$config;
_this.context.config && (barcode_locator.a.checkImageConstraints(_this.context.inputStream, null === (_this$context$config = _this.context.config) || void 0 === _this$context$config ? void 0 : _this$context$config.locator), _this.initCanvas(), _this.context.framegrabber = FrameGrabber.create(_this.context.inputStream, _this.context.canvasContainer.dom.image), void 0 === _this.context.config.numOfWorkers && (_this.context.config.numOfWorkers = 0), adjustWorkerPool(_this.context.config.numOfWorkers, _this.context.config, _this.context.inputStream, function() {
var _this$context$config2;
(null === (_this$context$config2 = _this.context.config) || void 0 === _this$context$config2 ? void 0 : _this$context$config2.numOfWorkers) === 0 && _this.initializeData(), _this.ready(callback);
}));
}), defineProperty_default()(this, "update", function() {
if (_this.context.onUIThread) {
var frameGrabber, availableWorker, _this$context$inputIm2, _this$context$inputIm, workersUpdated = (frameGrabber = _this.context.framegrabber, workerPool.length ? !!(availableWorker = workerPool.filter(function(workerThread) {
return !workerThread.busy;
})[0]) && (frameGrabber.attachData(availableWorker.imageData), frameGrabber.grab() && (availableWorker.busy = !0, availableWorker.worker.postMessage({
cmd: "process",
imageData: availableWorker.imageData
}, [
availableWorker.imageData.buffer
])), !0) : null);
workersUpdated || (_this.context.framegrabber.attachData(null === (_this$context$inputIm = _this.context.inputImageWrapper) || void 0 === _this$context$inputIm ? void 0 : _this$context$inputIm.data), _this.context.framegrabber.grab() && !workersUpdated && _this.locateAndDecode());
} else _this.context.framegrabber.attachData(null === (_this$context$inputIm2 = _this.context.inputImageWrapper) || void 0 === _this$context$inputIm2 ? void 0 : _this$context$inputIm2.data), _this.context.framegrabber.grab(), _this.locateAndDecode();
});
}
return createClass_default()(Quagga, [
{
key: "initBuffers",
value: function(imageWrapper) {
if (this.context.config) {
var inputStream, locator, inputImageWrapper, boxSize, _initBuffers2 = (inputStream = this.context.inputStream, locator = this.context.config.locator, inputImageWrapper = imageWrapper || new image_wrapper.a({
x: inputStream.getWidth(),
y: inputStream.getHeight(),
type: "XYSize"
}), console.log("image wrapper size ".concat(inputImageWrapper.size)), boxSize = [
Object(gl_vec2.clone)([
0,
0
]),
Object(gl_vec2.clone)([
0,
inputImageWrapper.size.y
]),
Object(gl_vec2.clone)([
inputImageWrapper.size.x,
inputImageWrapper.size.y
]),
Object(gl_vec2.clone)([
inputImageWrapper.size.x,
0
])
], barcode_locator.a.init(inputImageWrapper, locator), {
inputImageWrapper: inputImageWrapper,
boxSize: boxSize
}), inputImageWrapper1 = _initBuffers2.inputImageWrapper, boxSize1 = _initBuffers2.boxSize;
this.context.inputImageWrapper = inputImageWrapper1, this.context.boxSize = boxSize1;
}
}
},
{
key: "initializeData",
value: function(imageWrapper) {
this.context.config && (this.initBuffers(imageWrapper), this.context.decoder = barcode_decoder.create(this.context.config.decoder, this.context.inputImageWrapper));
}
},
{
key: "getViewPort",
value: function() {
return this.context.config && this.context.config.inputStream ? getViewPort_getViewPort(this.context.config.inputStream.target) : null;
}
},
{
key: "ready",
value: function(callback) {
this.context.inputStream.play(), callback();
}
},
{
key: "initCanvas",
value: function() {
var container = function(context) {
var _context$config, _context$config$input, _context$config2, _context$config2$inpu, viewport = getViewPort_getViewPort(null == context ? void 0 : null === (_context$config = context.config) || void 0 === _context$config ? void 0 : null === (_context$config$input = _context$config.inputStream) || void 0 === _context$config$input ? void 0 : _context$config$input.target), type = null == context ? void 0 : null === (_context$config2 = context.config) || void 0 === _context$config2 ? void 0 : null === (_context$config2$inpu = _context$config2.inputStream) || void 0 === _context$config2$inpu ? void 0 : _context$config2$inpu.type;
if (!type) return null;
var container = function(canvasSize) {
if ("undefined" != typeof document) {
var image = getCanvasAndContext("canvas.imgBuffer", "imgBuffer"), overlay = getCanvasAndContext("canvas.drawingBuffer", "drawingBuffer");
return image.canvas.width = overlay.canvas.width = canvasSize.x, image.canvas.height = overlay.canvas.height = canvasSize.y, {
dom: {
image: image.canvas,
overlay: overlay.canvas
},
ctx: {
image: image.context,
overlay: overlay.context
}
};
}
return null;
}(context.inputStream.getCanvasSize());
if (!container) return {
dom: {
image: null,
overlay: null
},
ctx: {
image: null,
overlay: null
}
};
var dom = container.dom;
return "undefined" != typeof document && viewport && ("ImageStream" !== type || viewport.contains(dom.image) || viewport.appendChild(dom.image), viewport.contains(dom.overlay) || viewport.appendChild(dom.overlay)), container;
}(this.context);
if (container) {
var ctx = container.ctx, dom = container.dom;
this.context.canvasContainer.dom.image = dom.image, this.context.canvasContainer.dom.overlay = dom.overlay, this.context.canvasContainer.ctx.image = ctx.image, this.context.canvasContainer.ctx.overlay = ctx.overlay;
}
}
},
{
key: "initInputStream",
value: function(callback) {
if (this.context.config && this.context.config.inputStream) {
var _this$context$config$ = this.context.config.inputStream, inputType = _this$context$config$.type, constraints = _this$context$config$.constraints, _setupInputStream = // CONCATENATED MODULE: ./src/quagga/setupInputStream.ts
// TODO: need to create an InputStream typescript interface, so we don't have an "any" in the next line
function() {
var type = arguments.length > 0 && void 0 !== arguments[0] ? arguments[0] : "LiveStream", viewport = arguments.length > 1 ? arguments[1] : void 0, InputStream = arguments.length > 2 ? arguments[2] : void 0;
switch(type){
case "VideoStream":
var video = document.createElement("video");
return {
video: video,
inputStream: InputStream.createVideoStream(video)
};
case "ImageStream":
return {
inputStream: InputStream.createImageStream()
};
case "LiveStream":
var _video = null;
return !viewport || (_video = viewport.querySelector("video")) || (_video = document.createElement("video"), viewport.appendChild(_video)), {
video: _video,
inputStream: InputStream.createLiveStream(_video)
};
default:
return console.error("* setupInputStream invalid type ".concat(type)), {
video: null,
inputStream: null
};
}
}(inputType, this.getViewPort(), inputStreamFactory), video = _setupInputStream.video, inputStream = _setupInputStream.inputStream;
"LiveStream" === inputType && video && camera_access.request(video, constraints).then(function() {
return inputStream.trigger("canrecord");
}).catch(function(err) {
return callback(err);
}), inputStream.setAttribute("preload", "auto"), inputStream.setInputStream(this.context.config.inputStream), inputStream.addEventListener("canrecord", this.canRecord.bind(void 0, callback)), this.context.inputStream = inputStream;
}
}
},
{
key: "getBoundingBoxes",
value: function() {
var _this$context$config3;
return null !== (_this$context$config3 = this.context.config) && void 0 !== _this$context$config3 && _this$context$config3.locate ? barcode_locator.a.locate() : [
[
Object(gl_vec2.clone)(this.context.boxSize[0]),
Object(gl_vec2.clone)(this.context.boxSize[1]),
Object(gl_vec2.clone)(this.context.boxSize[2]),
Object(gl_vec2.clone)(this.context.boxSize[3])
]
];
}
},
{
key: "transformResult",
value: function(result) {
var line, _this2 = this, topRight = this.context.inputStream.getTopRight(), xOffset = topRight.x, yOffset = topRight.y;
if ((0 !== xOffset || 0 !== yOffset) && (result.barcodes && // TODO: BarcodeInfo may not be the right type here.
result.barcodes.forEach(function(barcode) {
return _this2.transformResult(barcode);
}), result.line && 2 === result.line.length && (line = result.line, line[0].x += xOffset, line[0].y += yOffset, line[1].x += xOffset, line[1].y += yOffset), result.box && moveBox(result.box, xOffset, yOffset), result.boxes && result.boxes.length > 0)) for(var i = 0; i < result.boxes.length; i++)moveBox(result.boxes[i], xOffset, yOffset);
}
},
{
key: "addResult",
value: function(result, imageData) {
var _this3 = this;
imageData && this.context.resultCollector && (result.barcodes ? result.barcodes.filter(function(barcode) {
return barcode.codeResult;
}).forEach(function(barcode) {
return _this3.addResult(barcode, imageData);
}) : result.codeResult && this.context.resultCollector.addResult(imageData, this.context.inputStream.getCanvasSize(), result.codeResult)); // TODO: Figure out what data structure holds a "barcodes" result, if any...
}
},
{
key: "hasCodeResult",
value: function(result) {
return !!(result && (result.barcodes ? result.barcodes.some(function(barcode) {
return barcode.codeResult;
}) : result.codeResult));
}
},
{
key: "publishResult",
value: function() {
var result = arguments.length > 0 && void 0 !== arguments[0] ? arguments[0] : null, imageData = arguments.length > 1 ? arguments[1] : void 0, resultToPublish = result;
result && this.context.onUIThread && (this.transformResult(result), this.addResult(result, imageData), resultToPublish = result.barcodes || result), events.publish("processed", resultToPublish), this.hasCodeResult(result) && events.publish("detected", resultToPublish);
}
},
{
key: "locateAndDecode",
value: function() {
var boxes = this.getBoundingBoxes();
if (boxes) {
var _this$context$inputIm3, decodeResult = this.context.decoder.decodeFromBoundingBoxes(boxes) || {};
decodeResult.boxes = boxes, this.publishResult(decodeResult, null === (_this$context$inputIm3 = this.context.inputImageWrapper) || void 0 === _this$context$inputIm3 ? void 0 : _this$context$inputIm3.data);
} else {
var _this$context$inputIm4, imageResult = this.context.decoder.decodeFromImage(this.context.inputImageWrapper);
imageResult ? this.publishResult(imageResult, null === (_this$context$inputIm4 = this.context.inputImageWrapper) || void 0 === _this$context$inputIm4 ? void 0 : _this$context$inputIm4.data) : this.publishResult();
}
}
},
{
key: "startContinuousUpdate",
value: function() {
var _this$context$config4, _this4 = this, next = null, delay = 1000 / ((null === (_this$context$config4 = this.context.config) || void 0 === _this$context$config4 ? void 0 : _this$context$config4.frequency) || 60);
this.context.stopped = !1;
var context = this.context;
!function newFrame(timestamp) {
next = next || timestamp, context.stopped || (timestamp >= next && (next += delay, _this4.update()), window.requestAnimationFrame(newFrame));
}(performance.now());
}
},
{
key: "start",
value: function() {
var _this$context$config5, _this$context$config6;
this.context.onUIThread && (null === (_this$context$config5 = this.context.config) || void 0 === _this$context$config5 ? void 0 : null === (_this$context$config6 = _this$context$config5.inputStream) || void 0 === _this$context$config6 ? void 0 : _this$context$config6.type) === "LiveStream" ? this.startContinuousUpdate() : this.update();
}
},
{
key: "stop",
value: (_stop = asyncToGenerator_default()(/*#__PURE__*/ regenerator_default.a.mark(function _callee() {
var _this$context$config7;
return regenerator_default.a.wrap(function(_context) {
for(;;)switch(_context.prev = _context.next){
case 0:
if (this.context.stopped = !0, adjustWorkerPool(0), !(null !== (_this$context$config7 = this.context.config) && void 0 !== _this$context$config7 && _this$context$config7.inputStream && "LiveStream" === this.context.config.inputStream.type)) {
_context.next = 6;
break;
}
return _context.next = 5, camera_access.release();
case 5:
this.context.inputStream.clearEventHandlers();
case 6:
case "end":
return _context.stop();
}
}, _callee, this);
})), function() {
return _stop.apply(this, arguments);
})
},
{
key: "setReaders",
value: function(readers) {
this.context.decoder && this.context.decoder.setReaders(readers), workerPool.forEach(function(workerThread) {
return workerThread.worker.postMessage({
cmd: "setReaders",
readers: readers
});
});
}
},
{
key: "registerReader",
value: function(name, reader) {
barcode_decoder.registerReader(name, reader), this.context.decoder && this.context.decoder.registerReader(name, reader), workerPool.forEach(function(workerThread) {
return workerThread.worker.postMessage({
cmd: "registerReader",
name: name,
reader: reader
});
});
}
}
]), Quagga;
}(), instance = new quagga_Quagga(), quagga_context = instance.context, QuaggaJSStaticInterface = {
init: function(config, cb, imageWrapper) {
var promise, quaggaInstance = arguments.length > 3 && void 0 !== arguments[3] ? arguments[3] : instance;
return cb || (promise = new Promise(function(resolve, reject) {
cb = function(err) {
err ? reject(err) : resolve();
};
})), quaggaInstance.context.config = merge_default()({}, config_config, config), quaggaInstance.context.config.numOfWorkers > 0 && (quaggaInstance.context.config.numOfWorkers = 0), imageWrapper ? (quaggaInstance.context.onUIThread = !1, quaggaInstance.initializeData(imageWrapper), cb && cb()) : quaggaInstance.initInputStream(cb), promise;
},
start: function() {
return instance.start();
},
stop: function() {
return instance.stop();
},
pause: function() {
quagga_context.stopped = !0;
},
onDetected: function(callback) {
if (!callback || "function" != typeof callback && ("object" !== typeof_default()(callback) || !callback.callback)) {
console.trace("* warning: Quagga.onDetected called with invalid callback, ignoring");
return;
}
events.subscribe("detected", callback);
},
offDetected: function(callback) {
events.unsubscribe("detected", callback);
},
onProcessed: function(callback) {
if (!callback || "function" != typeof callback && ("object" !== typeof_default()(callback) || !callback.callback)) {
console.trace("* warning: Quagga.onProcessed called with invalid callback, ignoring");
return;
}
events.subscribe("processed", callback);
},
offProcessed: function(callback) {
events.unsubscribe("processed", callback);
},
setReaders: function(readers) {
if (!readers) {
console.trace("* warning: Quagga.setReaders called with no readers, ignoring");
return;
}
instance.setReaders(readers);
},
registerReader: function(name, reader) {
if (!name) {
console.trace("* warning: Quagga.registerReader called with no name, ignoring");
return;
}
if (!reader) {
console.trace("* warning: Quagga.registerReader called with no reader, ignoring");
return;
}
instance.registerReader(name, reader);
},
registerResultCollector: function(resultCollector) {
resultCollector && "function" == typeof resultCollector.addResult && (quagga_context.resultCollector = resultCollector);
},
get canvas () {
return quagga_context.canvasContainer;
},
decodeSingle: function(config, resultCallback) {
var _this = this, quaggaInstance = new quagga_Quagga();
return (config = merge_default()({
inputStream: {
type: "ImageStream",
sequence: !1,
size: 800,
src: config.src
},
numOfWorkers: +!config.debug,
locator: {
halfSample: !1
}
}, config)).numOfWorkers > 0 && (config.numOfWorkers = 0), config.numOfWorkers > 0 && ("undefined" == typeof Blob || "undefined" == typeof Worker) && (console.warn("* no Worker and/or Blob support - forcing numOfWorkers to 0"), config.numOfWorkers = 0), new Promise(function(resolve, reject) {
try {
_this.init(config, function() {
events.once("processed", function(result) {
quaggaInstance.stop(), resultCallback && resultCallback.call(null, result), resolve(result);
}, !0), quaggaInstance.start();
}, null, quaggaInstance);
} catch (err) {
reject(err);
}
});
},
// add the usually expected "default" for use with require, build step won't allow us to
// write to module.exports so do it here.
get default () {
return QuaggaJSStaticInterface;
},
Readers: reader_namespaceObject,
CameraAccess: camera_access,
ImageDebug: image_debug.a,
ImageWrapper: image_wrapper.a,
ResultCollector: result_collector
};
__webpack_exports__.default = QuaggaJSStaticInterface;
/***/ }
]).default;
});
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_minifier/tests/fixture/issues/react-autosuggest/1/input.js | JavaScript | "use strict";
Object.defineProperty(exports, "__esModule", {
value: true,
});
exports["default"] = void 0;
var _react = _interopRequireWildcard(require("react"));
var _propTypes = _interopRequireDefault(require("prop-types"));
var _Item = _interopRequireDefault(require("./Item"));
var _compareObjects = _interopRequireDefault(require("./compareObjects"));
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : { default: obj };
}
function _getRequireWildcardCache() {
if (typeof WeakMap !== "function") return null;
var cache = new WeakMap();
_getRequireWildcardCache = function _getRequireWildcardCache() {
return cache;
};
return cache;
}
function _interopRequireWildcard(obj) {
if (obj && obj.__esModule) {
return obj;
}
if (
obj === null ||
(_typeof(obj) !== "object" && typeof obj !== "function")
) {
return { default: obj };
}
var cache = _getRequireWildcardCache();
if (cache && cache.has(obj)) {
return cache.get(obj);
}
var newObj = {};
var hasPropertyDescriptor =
Object.defineProperty && Object.getOwnPropertyDescriptor;
for (var key in obj) {
if (Object.prototype.hasOwnProperty.call(obj, key)) {
var desc = hasPropertyDescriptor
? Object.getOwnPropertyDescriptor(obj, key)
: null;
if (desc && (desc.get || desc.set)) {
Object.defineProperty(newObj, key, desc);
} else {
newObj[key] = obj[key];
}
}
}
newObj["default"] = obj;
if (cache) {
cache.set(obj, newObj);
}
return newObj;
}
function _typeof(obj) {
"@babel/helpers - typeof";
if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
_typeof = function _typeof(obj) {
return typeof obj;
};
} else {
_typeof = function _typeof(obj) {
return obj &&
typeof Symbol === "function" &&
obj.constructor === Symbol &&
obj !== Symbol.prototype
? "symbol"
: typeof obj;
};
}
return _typeof(obj);
}
function _extends() {
_extends =
Object.assign ||
function (target) {
for (var i = 1; i < arguments.length; i++) {
var source = arguments[i];
for (var key in source) {
if (Object.prototype.hasOwnProperty.call(source, key)) {
target[key] = source[key];
}
}
}
return target;
};
return _extends.apply(this, arguments);
}
function ownKeys(object, enumerableOnly) {
var keys = Object.keys(object);
if (Object.getOwnPropertySymbols) {
var symbols = Object.getOwnPropertySymbols(object);
if (enumerableOnly)
symbols = symbols.filter(function (sym) {
return Object.getOwnPropertyDescriptor(object, sym).enumerable;
});
keys.push.apply(keys, symbols);
}
return keys;
}
function _objectSpread(target) {
for (var i = 1; i < arguments.length; i++) {
var source = arguments[i] != null ? arguments[i] : {};
if (i % 2) {
ownKeys(Object(source), true).forEach(function (key) {
_defineProperty(target, key, source[key]);
});
} else if (Object.getOwnPropertyDescriptors) {
Object.defineProperties(
target,
Object.getOwnPropertyDescriptors(source)
);
} else {
ownKeys(Object(source)).forEach(function (key) {
Object.defineProperty(
target,
key,
Object.getOwnPropertyDescriptor(source, key)
);
});
}
}
return target;
}
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor) descriptor.writable = true;
Object.defineProperty(target, descriptor.key, descriptor);
}
}
function _createClass(Constructor, protoProps, staticProps) {
if (protoProps) _defineProperties(Constructor.prototype, protoProps);
if (staticProps) _defineProperties(Constructor, staticProps);
return Constructor;
}
function _createSuper(Derived) {
return function () {
var Super = _getPrototypeOf(Derived),
result;
if (_isNativeReflectConstruct()) {
var NewTarget = _getPrototypeOf(this).constructor;
result = Reflect.construct(Super, arguments, NewTarget);
} else {
result = Super.apply(this, arguments);
}
return _possibleConstructorReturn(this, result);
};
}
function _possibleConstructorReturn(self, call) {
if (call && (_typeof(call) === "object" || typeof call === "function")) {
return call;
}
return _assertThisInitialized(self);
}
function _assertThisInitialized(self) {
if (self === void 0) {
throw new ReferenceError(
"this hasn't been initialised - super() hasn't been called"
);
}
return self;
}
function _isNativeReflectConstruct() {
if (typeof Reflect === "undefined" || !Reflect.construct) return false;
if (Reflect.construct.sham) return false;
if (typeof Proxy === "function") return true;
try {
Date.prototype.toString.call(
Reflect.construct(Date, [], function () {})
);
return true;
} catch (e) {
return false;
}
}
function _getPrototypeOf(o) {
_getPrototypeOf = Object.setPrototypeOf
? Object.getPrototypeOf
: function _getPrototypeOf(o) {
return o.__proto__ || Object.getPrototypeOf(o);
};
return _getPrototypeOf(o);
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError(
"Super expression must either be null or a function"
);
}
subClass.prototype = Object.create(superClass && superClass.prototype, {
constructor: { value: subClass, writable: true, configurable: true },
});
if (superClass) _setPrototypeOf(subClass, superClass);
}
function _setPrototypeOf(o, p) {
_setPrototypeOf =
Object.setPrototypeOf ||
function _setPrototypeOf(o, p) {
o.__proto__ = p;
return o;
};
return _setPrototypeOf(o, p);
}
function _defineProperty(obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true,
});
} else {
obj[key] = value;
}
return obj;
}
var ItemsList = /*#__PURE__*/ (function (_Component) {
_inherits(ItemsList, _Component);
var _super = _createSuper(ItemsList);
function ItemsList() {
var _this;
_classCallCheck(this, ItemsList);
for (
var _len = arguments.length, args = new Array(_len), _key = 0;
_key < _len;
_key++
) {
args[_key] = arguments[_key];
}
_this = _super.call.apply(_super, [this].concat(args));
_defineProperty(
_assertThisInitialized(_this),
"storeHighlightedItemReference",
function (highlightedItem) {
_this.props.onHighlightedItemChange(
highlightedItem === null ? null : highlightedItem.item
);
}
);
return _this;
}
_createClass(ItemsList, [
{
key: "shouldComponentUpdate",
value: function shouldComponentUpdate(nextProps) {
return (0, _compareObjects["default"])(nextProps, this.props, [
"itemProps",
]);
},
},
{
key: "render",
value: function render() {
var _this2 = this;
var _this$props = this.props,
items = _this$props.items,
itemProps = _this$props.itemProps,
renderItem = _this$props.renderItem,
renderItemData = _this$props.renderItemData,
sectionIndex = _this$props.sectionIndex,
highlightedItemIndex = _this$props.highlightedItemIndex,
getItemId = _this$props.getItemId,
theme = _this$props.theme,
keyPrefix = _this$props.keyPrefix;
var sectionPrefix =
sectionIndex === null
? keyPrefix
: ""
.concat(keyPrefix, "section-")
.concat(sectionIndex, "-");
var isItemPropsFunction = typeof itemProps === "function";
return /*#__PURE__*/ _react["default"].createElement(
"ul",
_extends(
{
role: "listbox",
},
theme(
"".concat(sectionPrefix, "items-list"),
"itemsList"
)
),
items.map(function (item, itemIndex) {
var isFirst = itemIndex === 0;
var isHighlighted = itemIndex === highlightedItemIndex;
var itemKey = ""
.concat(sectionPrefix, "item-")
.concat(itemIndex);
var itemPropsObj = isItemPropsFunction
? itemProps({
sectionIndex: sectionIndex,
itemIndex: itemIndex,
})
: itemProps;
var allItemProps = _objectSpread(
{
id: getItemId(sectionIndex, itemIndex),
"aria-selected": isHighlighted,
},
theme(
itemKey,
"item",
isFirst && "itemFirst",
isHighlighted && "itemHighlighted"
),
{},
itemPropsObj
);
if (isHighlighted) {
allItemProps.ref =
_this2.storeHighlightedItemReference;
} // `key` is provided by theme()
/* eslint-disable react/jsx-key */
return /*#__PURE__*/ _react["default"].createElement(
_Item["default"],
_extends({}, allItemProps, {
sectionIndex: sectionIndex,
isHighlighted: isHighlighted,
itemIndex: itemIndex,
item: item,
renderItem: renderItem,
renderItemData: renderItemData,
})
);
/* eslint-enable react/jsx-key */
})
);
},
},
]);
return ItemsList;
})(_react.Component);
exports["default"] = ItemsList;
_defineProperty(ItemsList, "propTypes", {
items: _propTypes["default"].array.isRequired,
itemProps: _propTypes["default"].oneOfType([
_propTypes["default"].object,
_propTypes["default"].func,
]),
renderItem: _propTypes["default"].func.isRequired,
renderItemData: _propTypes["default"].object.isRequired,
sectionIndex: _propTypes["default"].number,
highlightedItemIndex: _propTypes["default"].number,
onHighlightedItemChange: _propTypes["default"].func.isRequired,
getItemId: _propTypes["default"].func.isRequired,
theme: _propTypes["default"].func.isRequired,
keyPrefix: _propTypes["default"].string.isRequired,
});
_defineProperty(ItemsList, "defaultProps", {
sectionIndex: null,
});
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_minifier/tests/fixture/issues/react-autosuggest/1/output.js | JavaScript | "use strict";
Object.defineProperty(exports, "__esModule", {
value: !0
}), exports.default = void 0;
var _react = function(obj) {
if (obj && obj.__esModule) return obj;
if (null === obj || "object" !== _typeof(obj) && "function" != typeof obj) return {
default: obj
};
var cache = _getRequireWildcardCache();
if (cache && cache.has(obj)) return cache.get(obj);
var newObj = {}, hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor;
for(var key in obj)if (Object.prototype.hasOwnProperty.call(obj, key)) {
var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null;
desc && (desc.get || desc.set) ? Object.defineProperty(newObj, key, desc) : newObj[key] = obj[key];
}
return newObj.default = obj, cache && cache.set(obj, newObj), newObj;
}(require("react")), _propTypes = _interopRequireDefault(require("prop-types")), _Item = _interopRequireDefault(require("./Item")), _compareObjects = _interopRequireDefault(require("./compareObjects"));
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
function _getRequireWildcardCache() {
if ("function" != typeof WeakMap) return null;
var cache = new WeakMap();
return _getRequireWildcardCache = function() {
return cache;
}, cache;
}
function _typeof(obj) {
return (_typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(obj) {
return typeof obj;
} : function(obj) {
return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
})(obj);
}
function _extends() {
return (_extends = Object.assign || function(target) {
for(var i = 1; i < arguments.length; i++){
var source = arguments[i];
for(var key in source)Object.prototype.hasOwnProperty.call(source, key) && (target[key] = source[key]);
}
return target;
}).apply(this, arguments);
}
function ownKeys(object, enumerableOnly) {
var keys = Object.keys(object);
if (Object.getOwnPropertySymbols) {
var symbols = Object.getOwnPropertySymbols(object);
enumerableOnly && (symbols = symbols.filter(function(sym) {
return Object.getOwnPropertyDescriptor(object, sym).enumerable;
})), keys.push.apply(keys, symbols);
}
return keys;
}
function _assertThisInitialized(self) {
if (void 0 === self) throw ReferenceError("this hasn't been initialised - super() hasn't been called");
return self;
}
function _getPrototypeOf(o) {
return (_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function(o) {
return o.__proto__ || Object.getPrototypeOf(o);
})(o);
}
function _setPrototypeOf(o, p) {
return (_setPrototypeOf = Object.setPrototypeOf || function(o, p) {
return o.__proto__ = p, o;
})(o, p);
}
function _defineProperty(obj, key, value) {
return key in obj ? Object.defineProperty(obj, key, {
value: value,
enumerable: !0,
configurable: !0,
writable: !0
}) : obj[key] = value, obj;
}
var ItemsList = /*#__PURE__*/ function(_Component) {
!function(subClass, superClass) {
if ("function" != typeof superClass && null !== superClass) throw TypeError("Super expression must either be null or a function");
subClass.prototype = Object.create(superClass && superClass.prototype, {
constructor: {
value: subClass,
writable: !0,
configurable: !0
}
}), superClass && _setPrototypeOf(subClass, superClass);
}(ItemsList, _Component);
var protoProps, _super = function() {
var result, Super = _getPrototypeOf(ItemsList);
return result = !function() {
if ("undefined" == typeof Reflect || !Reflect.construct || Reflect.construct.sham) return !1;
if ("function" == typeof Proxy) return !0;
try {
return Date.prototype.toString.call(Reflect.construct(Date, [], function() {})), !0;
} catch (e) {
return !1;
}
}() ? Super.apply(this, arguments) : Reflect.construct(Super, arguments, _getPrototypeOf(this).constructor), result && ("object" === _typeof(result) || "function" == typeof result) ? result : _assertThisInitialized(this);
};
function ItemsList() {
var _this;
!function(instance, Constructor) {
if (!(instance instanceof Constructor)) throw TypeError("Cannot call a class as a function");
}(this, ItemsList);
for(var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++)args[_key] = arguments[_key];
return _defineProperty(_assertThisInitialized(_this = _super.call.apply(_super, [
this
].concat(args))), "storeHighlightedItemReference", function(highlightedItem) {
_this.props.onHighlightedItemChange(null === highlightedItem ? null : highlightedItem.item);
}), _this;
}
return protoProps = [
{
key: "shouldComponentUpdate",
value: function(nextProps) {
return (0, _compareObjects.default)(nextProps, this.props, [
"itemProps"
]);
}
},
{
key: "render",
value: function() {
var _this2 = this, _this$props = this.props, items = _this$props.items, itemProps = _this$props.itemProps, renderItem = _this$props.renderItem, renderItemData = _this$props.renderItemData, sectionIndex = _this$props.sectionIndex, highlightedItemIndex = _this$props.highlightedItemIndex, getItemId = _this$props.getItemId, theme = _this$props.theme, keyPrefix = _this$props.keyPrefix, sectionPrefix = null === sectionIndex ? keyPrefix : "".concat(keyPrefix, "section-").concat(sectionIndex, "-"), isItemPropsFunction = "function" == typeof itemProps;
return /*#__PURE__*/ _react.default.createElement("ul", _extends({
role: "listbox"
}, theme("".concat(sectionPrefix, "items-list"), "itemsList")), items.map(function(item, itemIndex) {
var isFirst = 0 === itemIndex, isHighlighted = itemIndex === highlightedItemIndex, itemKey = "".concat(sectionPrefix, "item-").concat(itemIndex), itemPropsObj = isItemPropsFunction ? itemProps({
sectionIndex: sectionIndex,
itemIndex: itemIndex
}) : itemProps, allItemProps = function(target) {
for(var i = 1; i < arguments.length; i++){
var source = null != arguments[i] ? arguments[i] : {};
i % 2 ? ownKeys(Object(source), !0).forEach(function(key) {
_defineProperty(target, key, source[key]);
}) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function(key) {
Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
});
}
return target;
}({
id: getItemId(sectionIndex, itemIndex),
"aria-selected": isHighlighted
}, theme(itemKey, "item", isFirst && "itemFirst", isHighlighted && "itemHighlighted"), {}, itemPropsObj);
/* eslint-disable react/jsx-key */ return isHighlighted && (allItemProps.ref = _this2.storeHighlightedItemReference), /*#__PURE__*/ _react.default.createElement(_Item.default, _extends({}, allItemProps, {
sectionIndex: sectionIndex,
isHighlighted: isHighlighted,
itemIndex: itemIndex,
item: item,
renderItem: renderItem,
renderItemData: renderItemData
}));
/* eslint-enable react/jsx-key */ }));
}
}
], function(target, props) {
for(var i = 0; i < props.length; i++){
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || !1, descriptor.configurable = !0, "value" in descriptor && (descriptor.writable = !0), Object.defineProperty(target, descriptor.key, descriptor);
}
}(ItemsList.prototype, protoProps), ItemsList;
}(_react.Component);
exports.default = ItemsList, _defineProperty(ItemsList, "propTypes", {
items: _propTypes.default.array.isRequired,
itemProps: _propTypes.default.oneOfType([
_propTypes.default.object,
_propTypes.default.func
]),
renderItem: _propTypes.default.func.isRequired,
renderItemData: _propTypes.default.object.isRequired,
sectionIndex: _propTypes.default.number,
highlightedItemIndex: _propTypes.default.number,
onHighlightedItemChange: _propTypes.default.func.isRequired,
getItemId: _propTypes.default.func.isRequired,
theme: _propTypes.default.func.isRequired,
keyPrefix: _propTypes.default.string.isRequired
}), _defineProperty(ItemsList, "defaultProps", {
sectionIndex: null
});
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_minifier/tests/fixture/issues/react-autowhatever/1/input.js | JavaScript | import { jsx as _jsx } from "react/jsx-runtime";
import React, { Component } from "react";
import PropTypes from "prop-types";
import Item from "./Item";
import compareObjects from "./compareObjects";
function _assertThisInitialized(self) {
if (self === void 0) {
throw new ReferenceError(
"this hasn't been initialised - super() hasn't been called"
);
}
return self;
}
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor) descriptor.writable = true;
Object.defineProperty(target, descriptor.key, descriptor);
}
}
function _createClass(Constructor, protoProps, staticProps) {
if (protoProps) _defineProperties(Constructor.prototype, protoProps);
if (staticProps) _defineProperties(Constructor, staticProps);
return Constructor;
}
function _defineProperty(obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true,
});
} else {
obj[key] = value;
}
return obj;
}
function _getPrototypeOf(o) {
_getPrototypeOf = Object.setPrototypeOf
? Object.getPrototypeOf
: function _getPrototypeOf(o) {
return o.__proto__ || Object.getPrototypeOf(o);
};
return _getPrototypeOf(o);
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError(
"Super expression must either be null or a function"
);
}
subClass.prototype = Object.create(superClass && superClass.prototype, {
constructor: {
value: subClass,
writable: true,
configurable: true,
},
});
if (superClass) _setPrototypeOf(subClass, superClass);
}
function _objectSpread(target) {
for (var i = 1; i < arguments.length; i++) {
var source = arguments[i] != null ? arguments[i] : {};
var ownKeys = Object.keys(source);
if (typeof Object.getOwnPropertySymbols === "function") {
ownKeys = ownKeys.concat(
Object.getOwnPropertySymbols(source).filter(function (sym) {
return Object.getOwnPropertyDescriptor(
source,
sym
).enumerable;
})
);
}
ownKeys.forEach(function (key) {
_defineProperty(target, key, source[key]);
});
}
return target;
}
function _possibleConstructorReturn(self, call) {
if (call && (_typeof(call) === "object" || typeof call === "function")) {
return call;
}
return _assertThisInitialized(self);
}
function _setPrototypeOf(o, p) {
_setPrototypeOf =
Object.setPrototypeOf ||
function _setPrototypeOf(o, p) {
o.__proto__ = p;
return o;
};
return _setPrototypeOf(o, p);
}
var _typeof = function (obj) {
return obj && typeof Symbol !== "undefined" && obj.constructor === Symbol
? "symbol"
: typeof obj;
};
var ItemsList = /*#__PURE__*/ (function (Component) {
"use strict";
_inherits(ItemsList, Component);
function ItemsList() {
_classCallCheck(this, ItemsList);
var _this;
_this = _possibleConstructorReturn(
this,
_getPrototypeOf(ItemsList).apply(this, arguments)
);
_this.storeHighlightedItemReference = function (highlightedItem) {
_this.props.onHighlightedItemChange(
highlightedItem === null ? null : highlightedItem.item
);
};
return _this;
}
_createClass(ItemsList, [
{
key: "shouldComponentUpdate",
value: function shouldComponentUpdate(nextProps) {
return compareObjects(nextProps, this.props, ["itemProps"]);
},
},
{
key: "render",
value: function render() {
var _this = this;
var _props = this.props,
items = _props.items,
itemProps = _props.itemProps,
renderItem = _props.renderItem,
renderItemData = _props.renderItemData,
sectionIndex = _props.sectionIndex,
highlightedItemIndex = _props.highlightedItemIndex,
getItemId = _props.getItemId,
theme = _props.theme,
keyPrefix = _props.keyPrefix;
var sectionPrefix =
sectionIndex === null
? keyPrefix
: ""
.concat(keyPrefix, "section-")
.concat(sectionIndex, "-");
var isItemPropsFunction = typeof itemProps === "function";
return /*#__PURE__*/ _jsx(
"ul",
_objectSpread(
{
role: "listbox",
},
theme(
"".concat(sectionPrefix, "items-list"),
"itemsList"
),
{
children: items.map(function (item, itemIndex) {
var isFirst = itemIndex === 0;
var isHighlighted =
itemIndex === highlightedItemIndex;
var itemKey = ""
.concat(sectionPrefix, "item-")
.concat(itemIndex);
var itemPropsObj = isItemPropsFunction
? itemProps({
sectionIndex: sectionIndex,
itemIndex: itemIndex,
})
: itemProps;
var allItemProps = _objectSpread(
{
id: getItemId(sectionIndex, itemIndex),
"aria-selected": isHighlighted,
},
theme(
itemKey,
"item",
isFirst && "itemFirst",
isHighlighted && "itemHighlighted"
),
itemPropsObj
);
if (isHighlighted) {
allItemProps.ref =
_this.storeHighlightedItemReference;
}
// `key` is provided by theme()
/* eslint-disable react/jsx-key */ return /*#__PURE__*/ _jsx(
Item,
_objectSpread({}, allItemProps, {
sectionIndex: sectionIndex,
isHighlighted: isHighlighted,
itemIndex: itemIndex,
item: item,
renderItem: renderItem,
renderItemData: renderItemData,
})
);
/* eslint-enable react/jsx-key */
}),
}
)
);
},
},
]);
return ItemsList;
})(Component);
ItemsList.propTypes = {
items: PropTypes.array.isRequired,
itemProps: PropTypes.oneOfType([PropTypes.object, PropTypes.func]),
renderItem: PropTypes.func.isRequired,
renderItemData: PropTypes.object.isRequired,
sectionIndex: PropTypes.number,
highlightedItemIndex: PropTypes.number,
onHighlightedItemChange: PropTypes.func.isRequired,
getItemId: PropTypes.func.isRequired,
theme: PropTypes.func.isRequired,
keyPrefix: PropTypes.string.isRequired,
};
ItemsList.defaultProps = {
sectionIndex: null,
};
export { ItemsList as default };
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_minifier/tests/fixture/issues/react-autowhatever/1/output.js | JavaScript | import { jsx as _jsx } from "react/jsx-runtime";
import { Component } from "react";
import PropTypes from "prop-types";
import Item from "./Item";
import compareObjects from "./compareObjects";
function _getPrototypeOf(o) {
return (_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function(o) {
return o.__proto__ || Object.getPrototypeOf(o);
})(o);
}
function _objectSpread(target) {
for(var i = 1; i < arguments.length; i++){
var source = null != arguments[i] ? arguments[i] : {}, ownKeys = Object.keys(source);
"function" == typeof Object.getOwnPropertySymbols && (ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function(sym) {
return Object.getOwnPropertyDescriptor(source, sym).enumerable;
}))), ownKeys.forEach(function(key) {
var value;
value = source[key], key in target ? Object.defineProperty(target, key, {
value: value,
enumerable: !0,
configurable: !0,
writable: !0
}) : target[key] = value;
});
}
return target;
}
function _setPrototypeOf(o, p) {
return (_setPrototypeOf = Object.setPrototypeOf || function(o, p) {
return o.__proto__ = p, o;
})(o, p);
}
var ItemsList = /*#__PURE__*/ function(Component) {
"use strict";
var protoProps;
function ItemsList() {
var _this, call;
return !function(instance, Constructor) {
if (!(instance instanceof Constructor)) throw TypeError("Cannot call a class as a function");
}(this, ItemsList), call = _getPrototypeOf(ItemsList).apply(this, arguments), (_this = call && ("object" == (call && "undefined" != typeof Symbol && call.constructor === Symbol ? "symbol" : typeof call) || "function" == typeof call) ? call : function(self) {
if (void 0 === self) throw ReferenceError("this hasn't been initialised - super() hasn't been called");
return self;
}(this)).storeHighlightedItemReference = function(highlightedItem) {
_this.props.onHighlightedItemChange(null === highlightedItem ? null : highlightedItem.item);
}, _this;
}
return !function(subClass, superClass) {
if ("function" != typeof superClass && null !== superClass) throw TypeError("Super expression must either be null or a function");
subClass.prototype = Object.create(superClass && superClass.prototype, {
constructor: {
value: subClass,
writable: !0,
configurable: !0
}
}), superClass && _setPrototypeOf(subClass, superClass);
}(ItemsList, Component), protoProps = [
{
key: "shouldComponentUpdate",
value: function(nextProps) {
return compareObjects(nextProps, this.props, [
"itemProps"
]);
}
},
{
key: "render",
value: function() {
var _this = this, _props = this.props, items = _props.items, itemProps = _props.itemProps, renderItem = _props.renderItem, renderItemData = _props.renderItemData, sectionIndex = _props.sectionIndex, highlightedItemIndex = _props.highlightedItemIndex, getItemId = _props.getItemId, theme = _props.theme, keyPrefix = _props.keyPrefix, sectionPrefix = null === sectionIndex ? keyPrefix : "".concat(keyPrefix, "section-").concat(sectionIndex, "-"), isItemPropsFunction = "function" == typeof itemProps;
return /*#__PURE__*/ _jsx("ul", _objectSpread({
role: "listbox"
}, theme("".concat(sectionPrefix, "items-list"), "itemsList"), {
children: items.map(function(item, itemIndex) {
var isFirst = 0 === itemIndex, isHighlighted = itemIndex === highlightedItemIndex, itemKey = "".concat(sectionPrefix, "item-").concat(itemIndex), itemPropsObj = isItemPropsFunction ? itemProps({
sectionIndex: sectionIndex,
itemIndex: itemIndex
}) : itemProps, allItemProps = _objectSpread({
id: getItemId(sectionIndex, itemIndex),
"aria-selected": isHighlighted
}, theme(itemKey, "item", isFirst && "itemFirst", isHighlighted && "itemHighlighted"), itemPropsObj);
// `key` is provided by theme()
/* eslint-disable react/jsx-key */ return isHighlighted && (allItemProps.ref = _this.storeHighlightedItemReference), /*#__PURE__*/ _jsx(Item, _objectSpread({}, allItemProps, {
sectionIndex: sectionIndex,
isHighlighted: isHighlighted,
itemIndex: itemIndex,
item: item,
renderItem: renderItem,
renderItemData: renderItemData
}));
/* eslint-enable react/jsx-key */ })
}));
}
}
], function(target, props) {
for(var i = 0; i < props.length; i++){
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || !1, descriptor.configurable = !0, "value" in descriptor && (descriptor.writable = !0), Object.defineProperty(target, descriptor.key, descriptor);
}
}(ItemsList.prototype, protoProps), ItemsList;
}(Component);
ItemsList.propTypes = {
items: PropTypes.array.isRequired,
itemProps: PropTypes.oneOfType([
PropTypes.object,
PropTypes.func
]),
renderItem: PropTypes.func.isRequired,
renderItemData: PropTypes.object.isRequired,
sectionIndex: PropTypes.number,
highlightedItemIndex: PropTypes.number,
onHighlightedItemChange: PropTypes.func.isRequired,
getItemId: PropTypes.func.isRequired,
theme: PropTypes.func.isRequired,
keyPrefix: PropTypes.string.isRequired
}, ItemsList.defaultProps = {
sectionIndex: null
};
export { ItemsList as default };
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_minifier/tests/fixture/issues/react-countup/1/input.js | JavaScript | (self["webpackChunk_N_E"] = self["webpackChunk_N_E"] || []).push([
[463],
{
/***/
8273:
/***/
function (
__unused_webpack_module,
__webpack_exports__,
__webpack_require__
) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */
__webpack_require__.d(__webpack_exports__, {
/* harmony export */
CountUp: function () {
return /* binding */ CountUp;
},
/* harmony export */
});
var __assign =
(undefined && undefined.__assign) ||
function () {
return (__assign =
Object.assign ||
function (t) {
for (
var i, a = 1, s = arguments.length;
a < s;
a++
)
for (var n in (i = arguments[a]))
Object.prototype.hasOwnProperty.call(
i,
n
) && (t[n] = i[n]);
return t;
}).apply(this, arguments);
},
CountUp = (function () {
function t(t, i, a) {
var s = this;
(this.target = t),
(this.endVal = i),
(this.options = a),
(this.version = "2.0.8"),
(this.defaults = {
startVal: 0,
decimalPlaces: 0,
duration: 2,
useEasing: !0,
useGrouping: !0,
smartEasingThreshold: 999,
smartEasingAmount: 333,
separator: ",",
decimal: ".",
prefix: "",
suffix: "",
}),
(this.finalEndVal = null),
(this.useEasing = !0),
(this.countDown = !1),
(this.error = ""),
(this.startVal = 0),
(this.paused = !0),
(this.count = function (t) {
s.startTime || (s.startTime = t);
var i = t - s.startTime;
(s.remaining = s.duration - i),
s.useEasing
? s.countDown
? (s.frameVal =
s.startVal -
s.easingFn(
i,
0,
s.startVal - s.endVal,
s.duration
))
: (s.frameVal = s.easingFn(
i,
s.startVal,
s.endVal - s.startVal,
s.duration
))
: s.countDown
? (s.frameVal =
s.startVal -
(s.startVal - s.endVal) *
(i / s.duration))
: (s.frameVal =
s.startVal +
(s.endVal - s.startVal) *
(i / s.duration)),
s.countDown
? (s.frameVal =
s.frameVal < s.endVal
? s.endVal
: s.frameVal)
: (s.frameVal =
s.frameVal > s.endVal
? s.endVal
: s.frameVal),
(s.frameVal = Number(
s.frameVal.toFixed(
s.options.decimalPlaces
)
)),
s.printValue(s.frameVal),
i < s.duration
? (s.rAF = requestAnimationFrame(
s.count
))
: null !== s.finalEndVal
? s.update(s.finalEndVal)
: s.callback && s.callback();
}),
(this.formatNumber = function (t) {
var i,
a,
n,
e,
r = t < 0 ? "-" : "";
i = Math.abs(t).toFixed(
s.options.decimalPlaces
);
var o = (i += "").split(".");
if (
((a = o[0]),
(n =
o.length > 1
? s.options.decimal + o[1]
: ""),
s.options.useGrouping)
) {
e = "";
for (
var l = 0, h = a.length;
l < h;
++l
)
0 !== l &&
l % 3 == 0 &&
(e = s.options.separator + e),
(e = a[h - l - 1] + e);
a = e;
}
return (
s.options.numerals &&
s.options.numerals.length &&
((a = a.replace(
/[0-9]/g,
function (t) {
return s.options.numerals[
+t
];
}
)),
(n = n.replace(
/[0-9]/g,
function (t) {
return s.options.numerals[
+t
];
}
))),
r +
s.options.prefix +
a +
n +
s.options.suffix
);
}),
(this.easeOutExpo = function (t, i, a, s) {
return (
(a *
(1 - Math.pow(2, (-10 * t) / s)) *
1024) /
1023 +
i
);
}),
(this.options = __assign(
__assign({}, this.defaults),
a
)),
(this.formattingFn = this.options.formattingFn
? this.options.formattingFn
: this.formatNumber),
(this.easingFn = this.options.easingFn
? this.options.easingFn
: this.easeOutExpo),
(this.startVal = this.validateValue(
this.options.startVal
)),
(this.frameVal = this.startVal),
(this.endVal = this.validateValue(i)),
(this.options.decimalPlaces = Math.max(
this.options.decimalPlaces
)),
this.resetDuration(),
(this.options.separator = String(
this.options.separator
)),
(this.useEasing = this.options.useEasing),
"" === this.options.separator &&
(this.options.useGrouping = !1),
(this.el =
"string" == typeof t
? document.getElementById(t)
: t),
this.el
? this.printValue(this.startVal)
: (this.error =
"[CountUp] target is null or undefined");
}
return (
(t.prototype.determineDirectionAndSmartEasing =
function () {
var t = this.finalEndVal
? this.finalEndVal
: this.endVal;
this.countDown = this.startVal > t;
var i = t - this.startVal;
if (
Math.abs(i) >
this.options.smartEasingThreshold
) {
this.finalEndVal = t;
var a = this.countDown ? 1 : -1;
(this.endVal =
t +
a * this.options.smartEasingAmount),
(this.duration = this.duration / 2);
} else
(this.endVal = t),
(this.finalEndVal = null);
this.finalEndVal
? (this.useEasing = !1)
: (this.useEasing =
this.options.useEasing);
}),
(t.prototype.start = function (t) {
this.error ||
((this.callback = t),
this.duration > 0
? (this.determineDirectionAndSmartEasing(),
(this.paused = !1),
(this.rAF = requestAnimationFrame(
this.count
)))
: this.printValue(this.endVal));
}),
(t.prototype.pauseResume = function () {
this.paused
? ((this.startTime = null),
(this.duration = this.remaining),
(this.startVal = this.frameVal),
this.determineDirectionAndSmartEasing(),
(this.rAF = requestAnimationFrame(
this.count
)))
: cancelAnimationFrame(this.rAF),
(this.paused = !this.paused);
}),
(t.prototype.reset = function () {
cancelAnimationFrame(this.rAF),
(this.paused = !0),
this.resetDuration(),
(this.startVal = this.validateValue(
this.options.startVal
)),
(this.frameVal = this.startVal),
this.printValue(this.startVal);
}),
(t.prototype.update = function (t) {
cancelAnimationFrame(this.rAF),
(this.startTime = null),
(this.endVal = this.validateValue(t)),
this.endVal !== this.frameVal &&
((this.startVal = this.frameVal),
this.finalEndVal ||
this.resetDuration(),
(this.finalEndVal = null),
this.determineDirectionAndSmartEasing(),
(this.rAF = requestAnimationFrame(
this.count
)));
}),
(t.prototype.printValue = function (t) {
var i = this.formattingFn(t);
"INPUT" === this.el.tagName
? (this.el.value = i)
: "text" === this.el.tagName ||
"tspan" === this.el.tagName
? (this.el.textContent = i)
: (this.el.innerHTML = i);
}),
(t.prototype.ensureNumber = function (t) {
return "number" == typeof t && !isNaN(t);
}),
(t.prototype.validateValue = function (t) {
var i = Number(t);
return this.ensureNumber(i)
? i
: ((this.error =
"[CountUp] invalid start or end value: " +
t),
null);
}),
(t.prototype.resetDuration = function () {
(this.startTime = null),
(this.duration =
1e3 * Number(this.options.duration)),
(this.remaining = this.duration);
}),
t
);
})();
/***/
},
/***/
8045:
/***/
function (__unused_webpack_module, exports, __webpack_require__) {
"use strict";
var __webpack_unused_export__;
function _arrayWithHoles(arr) {
if (Array.isArray(arr)) return arr;
}
function _arrayWithoutHoles(arr) {
if (Array.isArray(arr)) {
for (
var i = 0, arr2 = new Array(arr.length);
i < arr.length;
i++
) {
arr2[i] = arr[i];
}
return arr2;
}
}
function _iterableToArray(iter) {
if (
Symbol.iterator in Object(iter) ||
Object.prototype.toString.call(iter) ===
"[object Arguments]"
)
return Array.from(iter);
}
function _iterableToArrayLimit(arr, i) {
var _arr = [];
var _n = true;
var _d = false;
var _e = undefined;
try {
for (
var _i = arr[Symbol.iterator](), _s;
!(_n = (_s = _i.next()).done);
_n = true
) {
_arr.push(_s.value);
if (i && _arr.length === i) break;
}
} catch (err) {
_d = true;
_e = err;
} finally {
try {
if (!_n && _i["return"] != null) _i["return"]();
} finally {
if (_d) throw _e;
}
}
return _arr;
}
function _nonIterableRest() {
throw new TypeError(
"Invalid attempt to destructure non-iterable instance"
);
}
function _nonIterableSpread() {
throw new TypeError(
"Invalid attempt to spread non-iterable instance"
);
}
function _slicedToArray(arr, i) {
return (
_arrayWithHoles(arr) ||
_iterableToArrayLimit(arr, i) ||
_nonIterableRest()
);
}
function _toConsumableArray(arr) {
return (
_arrayWithoutHoles(arr) ||
_iterableToArray(arr) ||
_nonIterableSpread()
);
}
__webpack_unused_export__ = {
value: true,
};
exports["default"] = Image;
var _react = _interopRequireDefault(__webpack_require__(7294));
var _head = _interopRequireDefault(__webpack_require__(5443));
var _toBase64 = __webpack_require__(6978);
var _imageConfig = __webpack_require__(5809);
var _useIntersection = __webpack_require__(7190);
function _defineProperty(obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true,
});
} else {
obj[key] = value;
}
return obj;
}
function _interopRequireDefault(obj) {
return obj && obj.__esModule
? obj
: {
default: obj,
};
}
function _objectSpread(target) {
var _arguments = arguments,
_loop = function (i) {
var source =
_arguments[i] != null ? _arguments[i] : {};
var ownKeys = Object.keys(source);
if (
typeof Object.getOwnPropertySymbols ===
"function"
) {
ownKeys = ownKeys.concat(
Object.getOwnPropertySymbols(source).filter(
function (sym) {
return Object.getOwnPropertyDescriptor(
source,
sym
).enumerable;
}
)
);
}
ownKeys.forEach(function (key) {
_defineProperty(target, key, source[key]);
});
};
for (var i = 1; i < arguments.length; i++) _loop(i);
return target;
}
function _objectWithoutProperties(source, excluded) {
if (source == null) return {};
var target = _objectWithoutPropertiesLoose(
source,
excluded
);
var key, i;
if (Object.getOwnPropertySymbols) {
var sourceSymbolKeys =
Object.getOwnPropertySymbols(source);
for (i = 0; i < sourceSymbolKeys.length; i++) {
key = sourceSymbolKeys[i];
if (excluded.indexOf(key) >= 0) continue;
if (
!Object.prototype.propertyIsEnumerable.call(
source,
key
)
)
continue;
target[key] = source[key];
}
}
return target;
}
function _objectWithoutPropertiesLoose(source, excluded) {
if (source == null) return {};
var target = {};
var sourceKeys = Object.keys(source);
var key, i;
for (i = 0; i < sourceKeys.length; i++) {
key = sourceKeys[i];
if (excluded.indexOf(key) >= 0) continue;
target[key] = source[key];
}
return target;
}
var loadedImageURLs = new Set();
var allImgs = new Map();
var perfObserver;
var emptyDataURL =
"data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7";
if (false) {
}
var VALID_LOADING_VALUES = ["lazy", "eager", undefined];
var loaders = new Map([
["default", defaultLoader],
["imgix", imgixLoader],
["cloudinary", cloudinaryLoader],
["akamai", akamaiLoader],
["custom", customLoader],
]);
var VALID_LAYOUT_VALUES = [
"fill",
"fixed",
"intrinsic",
"responsive",
undefined,
];
function isStaticRequire(src) {
return src.default !== undefined;
}
function isStaticImageData(src) {
return src.src !== undefined;
}
function isStaticImport(src) {
return (
typeof src === "object" &&
(isStaticRequire(src) || isStaticImageData(src))
);
}
var ref1 =
{
deviceSizes: [
640, 750, 828, 1080, 1200, 1920, 2048, 3840,
],
imageSizes: [16, 32, 48, 64, 96, 128, 256, 384],
path: "/_next/image",
loader: "default",
} || _imageConfig.imageConfigDefault,
configDeviceSizes = ref1.deviceSizes,
configImageSizes = ref1.imageSizes,
configLoader = ref1.loader,
configPath = ref1.path,
configDomains = ref1.domains;
// sort smallest to largest
var allSizes = _toConsumableArray(configDeviceSizes).concat(
_toConsumableArray(configImageSizes)
);
configDeviceSizes.sort(function (a, b) {
return a - b;
});
allSizes.sort(function (a, b) {
return a - b;
});
function getWidths(width, layout, sizes) {
if (
sizes &&
(layout === "fill" || layout === "responsive")
) {
// Find all the "vw" percent sizes used in the sizes prop
var viewportWidthRe = /(^|\s)(1?\d?\d)vw/g;
var percentSizes = [];
for (
var match;
(match = viewportWidthRe.exec(sizes));
match
) {
percentSizes.push(parseInt(match[2]));
}
if (percentSizes.length) {
var _Math;
var smallestRatio =
(_Math = Math).min.apply(
_Math,
_toConsumableArray(percentSizes)
) * 0.01;
return {
widths: allSizes.filter(function (s) {
return (
s >=
configDeviceSizes[0] * smallestRatio
);
}),
kind: "w",
};
}
return {
widths: allSizes,
kind: "w",
};
}
if (
typeof width !== "number" ||
layout === "fill" ||
layout === "responsive"
) {
return {
widths: configDeviceSizes,
kind: "w",
};
}
var widths = _toConsumableArray(
new Set( // > are actually 3x in the green color, but only 1.5x in the red and
// > blue colors. Showing a 3x resolution image in the app vs a 2x
// > resolution image will be visually the same, though the 3x image
// > takes significantly more data. Even true 3x resolution screens are
// > wasteful as the human eye cannot see that level of detail without
// > something like a magnifying glass.
// https://blog.twitter.com/engineering/en_us/topics/infrastructure/2019/capping-image-fidelity-on-ultra-high-resolution-devices.html
[width, width * 2 /*, width * 3*/].map(function (
w
) {
return (
allSizes.find(function (p) {
return p >= w;
}) || allSizes[allSizes.length - 1]
);
})
)
);
return {
widths: widths,
kind: "x",
};
}
function generateImgAttrs(param) {
var src = param.src,
unoptimized = param.unoptimized,
layout = param.layout,
width = param.width,
quality = param.quality,
sizes = param.sizes,
loader = param.loader;
if (unoptimized) {
return {
src: src,
srcSet: undefined,
sizes: undefined,
};
}
var ref = getWidths(width, layout, sizes),
widths = ref.widths,
kind = ref.kind;
var last = widths.length - 1;
return {
sizes: !sizes && kind === "w" ? "100vw" : sizes,
srcSet: widths
.map(function (w, i) {
return ""
.concat(
loader({
src: src,
quality: quality,
width: w,
}),
" "
)
.concat(kind === "w" ? w : i + 1)
.concat(kind);
})
.join(", "),
// It's intended to keep `src` the last attribute because React updates
// attributes in order. If we keep `src` the first one, Safari will
// immediately start to fetch `src`, before `sizes` and `srcSet` are even
// updated by React. That causes multiple unnecessary requests if `srcSet`
// and `sizes` are defined.
// This bug cannot be reproduced in Chrome or Firefox.
src: loader({
src: src,
quality: quality,
width: widths[last],
}),
};
}
function getInt(x) {
if (typeof x === "number") {
return x;
}
if (typeof x === "string") {
return parseInt(x, 10);
}
return undefined;
}
function defaultImageLoader(loaderProps) {
var load = loaders.get(configLoader);
if (load) {
return load(
_objectSpread(
{
root: configPath,
},
loaderProps
)
);
}
throw new Error(
'Unknown "loader" found in "next.config.js". Expected: '
.concat(
_imageConfig.VALID_LOADERS.join(", "),
". Received: "
)
.concat(configLoader)
);
}
// See https://stackoverflow.com/q/39777833/266535 for why we use this ref
// handler instead of the img's onLoad attribute.
function handleLoading(
img,
src,
layout,
placeholder,
onLoadingComplete
) {
if (!img) {
return;
}
var handleLoad = function () {
if (img.src !== emptyDataURL) {
var p =
"decode" in img
? img.decode()
: Promise.resolve();
p.catch(function () {}).then(function () {
if (placeholder === "blur") {
img.style.filter = "none";
img.style.backgroundSize = "none";
img.style.backgroundImage = "none";
}
loadedImageURLs.add(src);
if (onLoadingComplete) {
var naturalWidth = img.naturalWidth,
naturalHeight = img.naturalHeight;
// Pass back read-only primitive values but not the
// underlying DOM element because it could be misused.
onLoadingComplete({
naturalWidth: naturalWidth,
naturalHeight: naturalHeight,
});
}
if (false) {
var parent, ref;
}
});
}
};
if (img.complete) {
// If the real image fails to load, this will still remove the placeholder.
// This is the desired behavior for now, and will be revisited when error
// handling is worked on for the image component itself.
handleLoad();
} else {
img.onload = handleLoad;
}
}
function Image(_param) {
var src = _param.src,
sizes = _param.sizes,
_unoptimized = _param.unoptimized,
unoptimized =
_unoptimized === void 0 ? false : _unoptimized,
_priority = _param.priority,
priority = _priority === void 0 ? false : _priority,
loading = _param.loading,
_lazyBoundary = _param.lazyBoundary,
lazyBoundary =
_lazyBoundary === void 0 ? "200px" : _lazyBoundary,
className = _param.className,
quality = _param.quality,
width = _param.width,
height = _param.height,
objectFit = _param.objectFit,
objectPosition = _param.objectPosition,
onLoadingComplete = _param.onLoadingComplete,
_loader = _param.loader,
loader =
_loader === void 0 ? defaultImageLoader : _loader,
_placeholder = _param.placeholder,
placeholder =
_placeholder === void 0 ? "empty" : _placeholder,
blurDataURL = _param.blurDataURL,
all = _objectWithoutProperties(_param, [
"src",
"sizes",
"unoptimized",
"priority",
"loading",
"lazyBoundary",
"className",
"quality",
"width",
"height",
"objectFit",
"objectPosition",
"onLoadingComplete",
"loader",
"placeholder",
"blurDataURL",
]);
var rest = all;
var layout = sizes ? "responsive" : "intrinsic";
if ("layout" in rest) {
// Override default layout if the user specified one:
if (rest.layout) layout = rest.layout;
// Remove property so it's not spread into image:
delete rest["layout"];
}
var staticSrc = "";
if (isStaticImport(src)) {
var staticImageData = isStaticRequire(src)
? src.default
: src;
if (!staticImageData.src) {
throw new Error(
"An object should only be passed to the image component src parameter if it comes from a static image import. It must include src. Received ".concat(
JSON.stringify(staticImageData)
)
);
}
blurDataURL =
blurDataURL || staticImageData.blurDataURL;
staticSrc = staticImageData.src;
if (!layout || layout !== "fill") {
height = height || staticImageData.height;
width = width || staticImageData.width;
if (
!staticImageData.height ||
!staticImageData.width
) {
throw new Error(
"An object should only be passed to the image component src parameter if it comes from a static image import. It must include height and width. Received ".concat(
JSON.stringify(staticImageData)
)
);
}
}
}
src = typeof src === "string" ? src : staticSrc;
var widthInt = getInt(width);
var heightInt = getInt(height);
var qualityInt = getInt(quality);
var isLazy =
!priority &&
(loading === "lazy" || typeof loading === "undefined");
if (src.startsWith("data:") || src.startsWith("blob:")) {
// https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URIs
unoptimized = true;
isLazy = false;
}
if (true && loadedImageURLs.has(src)) {
isLazy = false;
}
if (false) {
var url, urlStr, VALID_BLUR_EXT;
}
var ref2 = _slicedToArray(
(0, _useIntersection).useIntersection({
rootMargin: lazyBoundary,
disabled: !isLazy,
}),
2
),
setRef = ref2[0],
isIntersected = ref2[1];
var isVisible = !isLazy || isIntersected;
var wrapperStyle = {
boxSizing: "border-box",
display: "block",
overflow: "hidden",
width: "initial",
height: "initial",
background: "none",
opacity: 1,
border: 0,
margin: 0,
padding: 0,
};
var sizerStyle = {
boxSizing: "border-box",
display: "block",
width: "initial",
height: "initial",
background: "none",
opacity: 1,
border: 0,
margin: 0,
padding: 0,
};
var hasSizer = false;
var sizerSvg;
var imgStyle = {
position: "absolute",
top: 0,
left: 0,
bottom: 0,
right: 0,
boxSizing: "border-box",
padding: 0,
border: "none",
margin: "auto",
display: "block",
width: 0,
height: 0,
minWidth: "100%",
maxWidth: "100%",
minHeight: "100%",
maxHeight: "100%",
objectFit: objectFit,
objectPosition: objectPosition,
};
var blurStyle =
placeholder === "blur"
? {
filter: "blur(20px)",
backgroundSize: objectFit || "cover",
backgroundImage: 'url("'.concat(
blurDataURL,
'")'
),
backgroundPosition: objectPosition || "0% 0%",
}
: {};
if (layout === "fill") {
// <Image src="i.png" layout="fill" />
wrapperStyle.display = "block";
wrapperStyle.position = "absolute";
wrapperStyle.top = 0;
wrapperStyle.left = 0;
wrapperStyle.bottom = 0;
wrapperStyle.right = 0;
} else if (
typeof widthInt !== "undefined" &&
typeof heightInt !== "undefined"
) {
// <Image src="i.png" width="100" height="100" />
var quotient = heightInt / widthInt;
var paddingTop = isNaN(quotient)
? "100%"
: "".concat(quotient * 100, "%");
if (layout === "responsive") {
// <Image src="i.png" width="100" height="100" layout="responsive" />
wrapperStyle.display = "block";
wrapperStyle.position = "relative";
hasSizer = true;
sizerStyle.paddingTop = paddingTop;
} else if (layout === "intrinsic") {
// <Image src="i.png" width="100" height="100" layout="intrinsic" />
wrapperStyle.display = "inline-block";
wrapperStyle.position = "relative";
wrapperStyle.maxWidth = "100%";
hasSizer = true;
sizerStyle.maxWidth = "100%";
sizerSvg = '<svg width="'
.concat(widthInt, '" height="')
.concat(
heightInt,
'" xmlns="http://www.w3.org/2000/svg" version="1.1"/>'
);
} else if (layout === "fixed") {
// <Image src="i.png" width="100" height="100" layout="fixed" />
wrapperStyle.display = "inline-block";
wrapperStyle.position = "relative";
wrapperStyle.width = widthInt;
wrapperStyle.height = heightInt;
}
} else {
// <Image src="i.png" />
if (false) {
}
}
var imgAttributes = {
src: emptyDataURL,
srcSet: undefined,
sizes: undefined,
};
if (isVisible) {
imgAttributes = generateImgAttrs({
src: src,
unoptimized: unoptimized,
layout: layout,
width: widthInt,
quality: qualityInt,
sizes: sizes,
loader: loader,
});
}
var srcString = src;
if (false) {
var fullUrl;
}
return /*#__PURE__*/ _react.default.createElement(
"span",
{
style: wrapperStyle,
},
hasSizer
? /*#__PURE__*/ _react.default.createElement(
"span",
{
style: sizerStyle,
},
sizerSvg
? /*#__PURE__*/ _react.default.createElement(
"img",
{
style: {
display: "block",
maxWidth: "100%",
width: "initial",
height: "initial",
background: "none",
opacity: 1,
border: 0,
margin: 0,
padding: 0,
},
alt: "",
"aria-hidden": true,
src: "data:image/svg+xml;base64,".concat(
(0, _toBase64).toBase64(
sizerSvg
)
),
}
)
: null
)
: null,
/*#__PURE__*/ _react.default.createElement(
"img",
Object.assign({}, rest, imgAttributes, {
decoding: "async",
"data-nimg": layout,
className: className,
ref: function (img) {
setRef(img);
handleLoading(
img,
srcString,
layout,
placeholder,
onLoadingComplete
);
},
style: _objectSpread({}, imgStyle, blurStyle),
})
),
/*#__PURE__*/ _react.default.createElement(
"noscript",
null,
/*#__PURE__*/ _react.default.createElement(
"img",
Object.assign(
{},
rest,
generateImgAttrs({
src: src,
unoptimized: unoptimized,
layout: layout,
width: widthInt,
quality: qualityInt,
sizes: sizes,
loader: loader,
}),
{
decoding: "async",
"data-nimg": layout,
style: imgStyle,
className: className,
// @ts-ignore - TODO: upgrade to `@types/react@17`
loading: loading || "lazy",
}
)
)
),
priority // for browsers that do not support `imagesrcset`, and in those cases
? // it would likely cause the incorrect image to be preloaded.
//
// https://html.spec.whatwg.org/multipage/semantics.html#attr-link-imagesrcset
/*#__PURE__*/
_react.default.createElement(
_head.default,
null,
/*#__PURE__*/ _react.default.createElement(
"link",
{
key:
"__nimg-" +
imgAttributes.src +
imgAttributes.srcSet +
imgAttributes.sizes,
rel: "preload",
as: "image",
href: imgAttributes.srcSet
? undefined
: imgAttributes.src,
// @ts-ignore: imagesrcset is not yet in the link element type.
imagesrcset: imgAttributes.srcSet,
// @ts-ignore: imagesizes is not yet in the link element type.
imagesizes: imgAttributes.sizes,
}
)
)
: null
);
}
function normalizeSrc(src) {
return src[0] === "/" ? src.slice(1) : src;
}
function imgixLoader(param) {
var root = param.root,
src = param.src,
width = param.width,
quality = param.quality;
// Demo: https://static.imgix.net/daisy.png?auto=format&fit=max&w=300
var url = new URL(
"".concat(root).concat(normalizeSrc(src))
);
var params = url.searchParams;
params.set("auto", params.get("auto") || "format");
params.set("fit", params.get("fit") || "max");
params.set("w", params.get("w") || width.toString());
if (quality) {
params.set("q", quality.toString());
}
return url.href;
}
function akamaiLoader(param) {
var root = param.root,
src = param.src,
width = param.width;
return ""
.concat(root)
.concat(normalizeSrc(src), "?imwidth=")
.concat(width);
}
function cloudinaryLoader(param) {
var root = param.root,
src = param.src,
width = param.width,
quality = param.quality;
// Demo: https://res.cloudinary.com/demo/image/upload/w_300,c_limit,q_auto/turtles.jpg
var params = [
"f_auto",
"c_limit",
"w_" + width,
"q_" + (quality || "auto"),
];
var paramsString = params.join(",") + "/";
return ""
.concat(root)
.concat(paramsString)
.concat(normalizeSrc(src));
}
function customLoader(param) {
var src = param.src;
throw new Error(
'Image with src "'.concat(
src,
'" is missing "loader" prop.'
) +
"\nRead more: https://nextjs.org/docs/messages/next-image-missing-loader"
);
}
function defaultLoader(param) {
var root = param.root,
src = param.src,
width = param.width,
quality = param.quality;
if (false) {
var parsedSrc, missingValues;
}
return ""
.concat(root, "?url=")
.concat(encodeURIComponent(src), "&w=")
.concat(width, "&q=")
.concat(quality || 75);
} //# sourceMappingURL=image.js.map
/***/
},
/***/
7190:
/***/
function (__unused_webpack_module, exports, __webpack_require__) {
"use strict";
function _arrayWithHoles(arr) {
if (Array.isArray(arr)) return arr;
}
function _iterableToArrayLimit(arr, i) {
var _arr = [];
var _n = true;
var _d = false;
var _e = undefined;
try {
for (
var _i = arr[Symbol.iterator](), _s;
!(_n = (_s = _i.next()).done);
_n = true
) {
_arr.push(_s.value);
if (i && _arr.length === i) break;
}
} catch (err) {
_d = true;
_e = err;
} finally {
try {
if (!_n && _i["return"] != null) _i["return"]();
} finally {
if (_d) throw _e;
}
}
return _arr;
}
function _nonIterableRest() {
throw new TypeError(
"Invalid attempt to destructure non-iterable instance"
);
}
function _slicedToArray(arr, i) {
return (
_arrayWithHoles(arr) ||
_iterableToArrayLimit(arr, i) ||
_nonIterableRest()
);
}
Object.defineProperty(exports, "__esModule", {
value: true,
});
exports.useIntersection = useIntersection;
var _react = __webpack_require__(7294);
var _requestIdleCallback = __webpack_require__(9311);
var hasIntersectionObserver =
typeof IntersectionObserver !== "undefined";
function useIntersection(param) {
var rootMargin = param.rootMargin,
disabled = param.disabled;
var isDisabled = disabled || !hasIntersectionObserver;
var unobserve = (0, _react).useRef();
var ref = _slicedToArray((0, _react).useState(false), 2),
visible = ref[0],
setVisible = ref[1];
var setRef = (0, _react).useCallback(
function (el) {
if (unobserve.current) {
unobserve.current();
unobserve.current = undefined;
}
if (isDisabled || visible) return;
if (el && el.tagName) {
unobserve.current = observe(
el,
function (isVisible) {
return (
isVisible && setVisible(isVisible)
);
},
{
rootMargin: rootMargin,
}
);
}
},
[isDisabled, rootMargin, visible]
);
(0, _react).useEffect(
function () {
if (!hasIntersectionObserver) {
if (!visible) {
var idleCallback = (0,
_requestIdleCallback).requestIdleCallback(
function () {
return setVisible(true);
}
);
return function () {
return (0,
_requestIdleCallback).cancelIdleCallback(
idleCallback
);
};
}
}
},
[visible]
);
return [setRef, visible];
}
function observe(element, callback, options) {
var ref = createObserver(options),
id = ref.id,
observer = ref.observer,
elements = ref.elements;
elements.set(element, callback);
observer.observe(element);
return function unobserve() {
elements.delete(element);
observer.unobserve(element);
// Destroy observer when there's nothing left to watch:
if (elements.size === 0) {
observer.disconnect();
observers.delete(id);
}
};
}
var observers = new Map();
function createObserver(options) {
var id = options.rootMargin || "";
var instance = observers.get(id);
if (instance) {
return instance;
}
var elements = new Map();
var observer = new IntersectionObserver(function (entries) {
entries.forEach(function (entry) {
var callback = elements.get(entry.target);
var isVisible =
entry.isIntersecting ||
entry.intersectionRatio > 0;
if (callback && isVisible) {
callback(isVisible);
}
});
}, options);
observers.set(
id,
(instance = {
id: id,
observer: observer,
elements: elements,
})
);
return instance;
} //# sourceMappingURL=use-intersection.js.map
/***/
},
/***/
6978:
/***/
function (__unused_webpack_module, exports) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true,
});
exports.toBase64 = toBase64;
function toBase64(str) {
if (false) {
} else {
return window.btoa(str);
}
} //# sourceMappingURL=to-base-64.js.map
/***/
},
/***/
5809:
/***/
function (__unused_webpack_module, exports) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true,
});
exports.imageConfigDefault = exports.VALID_LOADERS = void 0;
const VALID_LOADERS = [
"default",
"imgix",
"cloudinary",
"akamai",
"custom",
];
exports.VALID_LOADERS = VALID_LOADERS;
const imageConfigDefault = {
deviceSizes: [640, 750, 828, 1080, 1200, 1920, 2048, 3840],
imageSizes: [16, 32, 48, 64, 96, 128, 256, 384],
path: "/_next/image",
loader: "default",
domains: [],
disableStaticImages: false,
minimumCacheTTL: 60,
formats: ["image/webp"],
};
exports.imageConfigDefault = imageConfigDefault;
//# sourceMappingURL=image-config.js.map
/***/
},
/***/
9008:
/***/
function (module, __unused_webpack_exports, __webpack_require__) {
module.exports = __webpack_require__(5443);
/***/
},
/***/
5675:
/***/
function (module, __unused_webpack_exports, __webpack_require__) {
module.exports = __webpack_require__(8045);
/***/
},
/***/
7857:
/***/
function (__unused_webpack_module, exports, __webpack_require__) {
"use strict";
var __webpack_unused_export__;
__webpack_unused_export__ = {
value: true,
};
var React = __webpack_require__(7294);
var countup_js = __webpack_require__(8273);
function _interopDefaultLegacy(e) {
return e && typeof e === "object" && "default" in e
? e
: {
default: e,
};
}
var React__default = /*#__PURE__*/ _interopDefaultLegacy(React);
function ownKeys(object, enumerableOnly) {
var keys = Object.keys(object);
if (Object.getOwnPropertySymbols) {
var symbols = Object.getOwnPropertySymbols(object);
if (enumerableOnly) {
symbols = symbols.filter(function (sym) {
return Object.getOwnPropertyDescriptor(
object,
sym
).enumerable;
});
}
keys.push.apply(keys, symbols);
}
return keys;
}
function _objectSpread2(target) {
for (var i = 1; i < arguments.length; i++) {
var source = arguments[i] != null ? arguments[i] : {};
if (i % 2) {
ownKeys(Object(source), true).forEach(function (
key
) {
_defineProperty(target, key, source[key]);
});
} else if (Object.getOwnPropertyDescriptors) {
Object.defineProperties(
target,
Object.getOwnPropertyDescriptors(source)
);
} else {
ownKeys(Object(source)).forEach(function (key) {
Object.defineProperty(
target,
key,
Object.getOwnPropertyDescriptor(source, key)
);
});
}
}
return target;
}
function _defineProperty(obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true,
});
} else {
obj[key] = value;
}
return obj;
}
function _extends() {
_extends =
Object.assign ||
function (target) {
for (var i = 1; i < arguments.length; i++) {
var source = arguments[i];
for (var key in source) {
if (
Object.prototype.hasOwnProperty.call(
source,
key
)
) {
target[key] = source[key];
}
}
}
return target;
};
return _extends.apply(this, arguments);
}
function _objectWithoutPropertiesLoose(source, excluded) {
if (source == null) return {};
var target = {};
var sourceKeys = Object.keys(source);
var key, i;
for (i = 0; i < sourceKeys.length; i++) {
key = sourceKeys[i];
if (excluded.indexOf(key) >= 0) continue;
target[key] = source[key];
}
return target;
}
function _objectWithoutProperties(source, excluded) {
if (source == null) return {};
var target = _objectWithoutPropertiesLoose(
source,
excluded
);
var key, i;
if (Object.getOwnPropertySymbols) {
var sourceSymbolKeys =
Object.getOwnPropertySymbols(source);
for (i = 0; i < sourceSymbolKeys.length; i++) {
key = sourceSymbolKeys[i];
if (excluded.indexOf(key) >= 0) continue;
if (
!Object.prototype.propertyIsEnumerable.call(
source,
key
)
)
continue;
target[key] = source[key];
}
}
return target;
}
/**
* Silence SSR Warnings.
* Borrowed from Formik v2.1.1, Licensed MIT.
*
* https://github.com/formium/formik/blob/9316a864478f8fcd4fa99a0735b1d37afdf507dc/LICENSE
*/
var useIsomorphicLayoutEffect =
typeof window !== "undefined" &&
typeof window.document !== "undefined" &&
typeof window.document.createElement !== "undefined"
? React.useLayoutEffect
: React.useEffect;
/* eslint-disable @typescript-eslint/no-explicit-any */
/**
* Create a stable reference to a callback which is updated after each render is committed.
* Typed version borrowed from Formik v2.2.1. Licensed MIT.
*
* https://github.com/formium/formik/blob/9316a864478f8fcd4fa99a0735b1d37afdf507dc/LICENSE
*/
function useEventCallback(fn) {
var ref = React.useRef(fn); // we copy a ref to the callback scoped to the current state/props on each render
useIsomorphicLayoutEffect(function () {
ref.current = fn;
});
return React.useCallback(function () {
for (
var _len = arguments.length,
args = new Array(_len),
_key = 0;
_key < _len;
_key++
) {
args[_key] = arguments[_key];
}
return ref.current.apply(void 0, args);
}, []);
}
var createCountUpInstance = function createCountUpInstance(
el,
props
) {
var decimal = props.decimal,
decimals = props.decimals,
duration = props.duration,
easingFn = props.easingFn,
end = props.end,
formattingFn = props.formattingFn,
numerals = props.numerals,
prefix = props.prefix,
separator = props.separator,
start = props.start,
suffix = props.suffix,
useEasing = props.useEasing;
return new countup_js.CountUp(el, end, {
startVal: start,
duration: duration,
decimal: decimal,
decimalPlaces: decimals,
easingFn: easingFn,
formattingFn: formattingFn,
numerals: numerals,
separator: separator,
prefix: prefix,
suffix: suffix,
useEasing: useEasing,
useGrouping: !!separator,
});
};
var _excluded$1 = [
"ref",
"startOnMount",
"enableReinitialize",
"delay",
"onEnd",
"onStart",
"onPauseResume",
"onReset",
"onUpdate",
];
var DEFAULTS = {
decimal: ".",
delay: null,
prefix: "",
suffix: "",
start: 0,
startOnMount: true,
enableReinitialize: true,
};
var useCountUp = function useCountUp(props) {
var _useMemo = React.useMemo(
function () {
return _objectSpread2(
_objectSpread2({}, DEFAULTS),
props
);
},
[props]
),
ref = _useMemo.ref,
startOnMount = _useMemo.startOnMount,
enableReinitialize = _useMemo.enableReinitialize,
delay = _useMemo.delay,
onEnd = _useMemo.onEnd,
onStart = _useMemo.onStart,
onPauseResume = _useMemo.onPauseResume,
onReset = _useMemo.onReset,
onUpdate = _useMemo.onUpdate,
instanceProps = _objectWithoutProperties(
_useMemo,
_excluded$1
);
var countUpRef = React.useRef();
var timerRef = React.useRef();
var isInitializedRef = React.useRef(false);
var createInstance = useEventCallback(function () {
return createCountUpInstance(
typeof ref === "string" ? ref : ref.current,
instanceProps
);
});
var getCountUp = useEventCallback(function (recreate) {
var countUp = countUpRef.current;
if (countUp && !recreate) {
return countUp;
}
var newCountUp = createInstance();
countUpRef.current = newCountUp;
return newCountUp;
});
var start = useEventCallback(function () {
var run = function run() {
return getCountUp(true).start(function () {
onEnd === null || onEnd === void 0
? void 0
: onEnd({
pauseResume: pauseResume,
reset: reset,
start: restart,
update: update,
});
});
};
if (delay && delay > 0) {
timerRef.current = setTimeout(run, delay * 1000);
} else {
run();
}
onStart === null || onStart === void 0
? void 0
: onStart({
pauseResume: pauseResume,
reset: reset,
update: update,
});
});
var pauseResume = useEventCallback(function () {
getCountUp().pauseResume();
onPauseResume === null || onPauseResume === void 0
? void 0
: onPauseResume({
reset: reset,
start: restart,
update: update,
});
});
var reset = useEventCallback(function () {
timerRef.current && clearTimeout(timerRef.current);
getCountUp().reset();
onReset === null || onReset === void 0
? void 0
: onReset({
pauseResume: pauseResume,
start: restart,
update: update,
});
});
var update = useEventCallback(function (newEnd) {
getCountUp().update(newEnd);
onUpdate === null || onUpdate === void 0
? void 0
: onUpdate({
pauseResume: pauseResume,
reset: reset,
start: restart,
});
});
var restart = useEventCallback(function () {
reset();
start();
});
var maybeInitialize = useEventCallback(function (
shouldReset
) {
if (startOnMount) {
if (shouldReset) {
reset();
}
start();
}
});
React.useEffect(
function () {
if (!isInitializedRef.current) {
isInitializedRef.current = true;
maybeInitialize();
} else if (enableReinitialize) {
maybeInitialize(true);
}
},
[
enableReinitialize,
isInitializedRef,
maybeInitialize,
delay,
props.start,
props.suffix,
props.prefix,
props.duration,
props.separator,
props.decimals,
props.decimal,
props.formattingFn,
]
);
React.useEffect(
function () {
return function () {
reset();
};
},
[reset]
);
return {
start: restart,
pauseResume: pauseResume,
reset: reset,
update: update,
getCountUp: getCountUp,
};
};
var _excluded = [
"className",
"redraw",
"containerProps",
"children",
"style",
];
var CountUp = function CountUp(props) {
var className = props.className,
redraw = props.redraw,
containerProps = props.containerProps,
children = props.children,
style = props.style,
useCountUpProps = _objectWithoutProperties(
props,
_excluded
);
var containerRef = React__default["default"].useRef(null);
var isInitializedRef =
React__default["default"].useRef(false);
var _useCountUp = useCountUp(
_objectSpread2(
_objectSpread2({}, useCountUpProps),
{},
{
ref: containerRef,
startOnMount:
typeof children !== "function" ||
props.delay === 0,
// component manually restarts
enableReinitialize: false,
}
)
),
start = _useCountUp.start,
reset = _useCountUp.reset,
updateCountUp = _useCountUp.update,
pauseResume = _useCountUp.pauseResume,
getCountUp = _useCountUp.getCountUp;
var restart = useEventCallback(function () {
start();
});
var update = useEventCallback(function (end) {
if (!props.preserveValue) {
reset();
}
updateCountUp(end);
});
var initializeOnMount = useEventCallback(function () {
if (typeof props.children === "function") {
// Warn when user didn't use containerRef at all
if (!(containerRef.current instanceof Element)) {
console.error(
'Couldn\'t find attached element to hook the CountUp instance into! Try to attach "containerRef" from the render prop to a an Element, eg. <span ref={containerRef} />.'
);
return;
}
} // unlike the hook, the CountUp component initializes on mount
getCountUp();
});
React.useEffect(
function () {
initializeOnMount();
},
[initializeOnMount]
);
React.useEffect(
function () {
if (isInitializedRef.current) {
update(props.end);
}
},
[props.end, update]
);
var redrawDependencies = redraw && props; // if props.redraw, call this effect on every props change
React.useEffect(
function () {
if (redraw && isInitializedRef.current) {
restart();
}
},
[restart, redraw, redrawDependencies]
); // if not props.redraw, call this effect only when certain props are changed
React.useEffect(
function () {
if (!redraw && isInitializedRef.current) {
restart();
}
},
[
restart,
redraw,
props.start,
props.suffix,
props.prefix,
props.duration,
props.separator,
props.decimals,
props.decimal,
props.className,
props.formattingFn,
]
);
React.useEffect(function () {
isInitializedRef.current = true;
}, []);
if (typeof children === "function") {
// TypeScript forces functional components to return JSX.Element | null.
return children({
countUpRef: containerRef,
start: start,
reset: reset,
update: updateCountUp,
pauseResume: pauseResume,
getCountUp: getCountUp,
});
}
return /*#__PURE__*/ React__default[
"default"
].createElement(
"span",
_extends(
{
className: className,
ref: containerRef,
style: style,
},
containerProps
)
);
};
exports.ZP = CountUp;
__webpack_unused_export__ = useCountUp;
/***/
},
},
]);
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_minifier/tests/fixture/issues/react-countup/1/output.js | JavaScript | (self.webpackChunk_N_E = self.webpackChunk_N_E || []).push([
[
463
],
{
/***/ 8273: /***/ function(__unused_webpack_module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__), /* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ CountUp: function() {
return /* binding */ CountUp;
}
});
var __assign = function() {
return (__assign = Object.assign || function(t) {
for(var i, a = 1, s = arguments.length; a < s; a++)for(var n in i = arguments[a])Object.prototype.hasOwnProperty.call(i, n) && (t[n] = i[n]);
return t;
}).apply(this, arguments);
}, CountUp = function() {
function t(t, i, a) {
var s = this;
this.target = t, this.endVal = i, this.options = a, this.version = "2.0.8", this.defaults = {
startVal: 0,
decimalPlaces: 0,
duration: 2,
useEasing: !0,
useGrouping: !0,
smartEasingThreshold: 999,
smartEasingAmount: 333,
separator: ",",
decimal: ".",
prefix: "",
suffix: ""
}, this.finalEndVal = null, this.useEasing = !0, this.countDown = !1, this.error = "", this.startVal = 0, this.paused = !0, this.count = function(t) {
s.startTime || (s.startTime = t);
var i = t - s.startTime;
s.remaining = s.duration - i, s.useEasing ? s.countDown ? s.frameVal = s.startVal - s.easingFn(i, 0, s.startVal - s.endVal, s.duration) : s.frameVal = s.easingFn(i, s.startVal, s.endVal - s.startVal, s.duration) : s.countDown ? s.frameVal = s.startVal - (s.startVal - s.endVal) * (i / s.duration) : s.frameVal = s.startVal + (s.endVal - s.startVal) * (i / s.duration), s.countDown ? s.frameVal = s.frameVal < s.endVal ? s.endVal : s.frameVal : s.frameVal = s.frameVal > s.endVal ? s.endVal : s.frameVal, s.frameVal = Number(s.frameVal.toFixed(s.options.decimalPlaces)), s.printValue(s.frameVal), i < s.duration ? s.rAF = requestAnimationFrame(s.count) : null !== s.finalEndVal ? s.update(s.finalEndVal) : s.callback && s.callback();
}, this.formatNumber = function(t) {
var a, n, e, o = (Math.abs(t).toFixed(s.options.decimalPlaces) + "").split(".");
if (a = o[0], n = o.length > 1 ? s.options.decimal + o[1] : "", s.options.useGrouping) {
e = "";
for(var l = 0, h = a.length; l < h; ++l)0 !== l && l % 3 == 0 && (e = s.options.separator + e), e = a[h - l - 1] + e;
a = e;
}
return s.options.numerals && s.options.numerals.length && (a = a.replace(/[0-9]/g, function(t) {
return s.options.numerals[+t];
}), n = n.replace(/[0-9]/g, function(t) {
return s.options.numerals[+t];
})), (t < 0 ? "-" : "") + s.options.prefix + a + n + s.options.suffix;
}, this.easeOutExpo = function(t, i, a, s) {
return a * (1 - Math.pow(2, -10 * t / s)) * 1024 / 1023 + i;
}, this.options = __assign(__assign({}, this.defaults), a), this.formattingFn = this.options.formattingFn ? this.options.formattingFn : this.formatNumber, this.easingFn = this.options.easingFn ? this.options.easingFn : this.easeOutExpo, this.startVal = this.validateValue(this.options.startVal), this.frameVal = this.startVal, this.endVal = this.validateValue(i), this.options.decimalPlaces = Math.max(this.options.decimalPlaces), this.resetDuration(), this.options.separator = String(this.options.separator), this.useEasing = this.options.useEasing, "" === this.options.separator && (this.options.useGrouping = !1), this.el = "string" == typeof t ? document.getElementById(t) : t, this.el ? this.printValue(this.startVal) : this.error = "[CountUp] target is null or undefined";
}
return t.prototype.determineDirectionAndSmartEasing = function() {
var t = this.finalEndVal ? this.finalEndVal : this.endVal;
if (this.countDown = this.startVal > t, Math.abs(t - this.startVal) > this.options.smartEasingThreshold) {
this.finalEndVal = t;
var a = this.countDown ? 1 : -1;
this.endVal = t + a * this.options.smartEasingAmount, this.duration = this.duration / 2;
} else this.endVal = t, this.finalEndVal = null;
this.finalEndVal ? this.useEasing = !1 : this.useEasing = this.options.useEasing;
}, t.prototype.start = function(t) {
this.error || (this.callback = t, this.duration > 0 ? (this.determineDirectionAndSmartEasing(), this.paused = !1, this.rAF = requestAnimationFrame(this.count)) : this.printValue(this.endVal));
}, t.prototype.pauseResume = function() {
this.paused ? (this.startTime = null, this.duration = this.remaining, this.startVal = this.frameVal, this.determineDirectionAndSmartEasing(), this.rAF = requestAnimationFrame(this.count)) : cancelAnimationFrame(this.rAF), this.paused = !this.paused;
}, t.prototype.reset = function() {
cancelAnimationFrame(this.rAF), this.paused = !0, this.resetDuration(), this.startVal = this.validateValue(this.options.startVal), this.frameVal = this.startVal, this.printValue(this.startVal);
}, t.prototype.update = function(t) {
cancelAnimationFrame(this.rAF), this.startTime = null, this.endVal = this.validateValue(t), this.endVal !== this.frameVal && (this.startVal = this.frameVal, this.finalEndVal || this.resetDuration(), this.finalEndVal = null, this.determineDirectionAndSmartEasing(), this.rAF = requestAnimationFrame(this.count));
}, t.prototype.printValue = function(t) {
var i = this.formattingFn(t);
"INPUT" === this.el.tagName ? this.el.value = i : "text" === this.el.tagName || "tspan" === this.el.tagName ? this.el.textContent = i : this.el.innerHTML = i;
}, t.prototype.ensureNumber = function(t) {
return "number" == typeof t && !isNaN(t);
}, t.prototype.validateValue = function(t) {
var i = Number(t);
return this.ensureNumber(i) ? i : (this.error = "[CountUp] invalid start or end value: " + t, null);
}, t.prototype.resetDuration = function() {
this.startTime = null, this.duration = 1e3 * Number(this.options.duration), this.remaining = this.duration;
}, t;
}();
/***/ },
/***/ 8045: /***/ function(__unused_webpack_module, exports, __webpack_require__) {
"use strict";
function _toConsumableArray(arr) {
return function(arr) {
if (Array.isArray(arr)) {
for(var i = 0, arr2 = Array(arr.length); i < arr.length; i++)arr2[i] = arr[i];
return arr2;
}
}(arr) || function(iter) {
if (Symbol.iterator in Object(iter) || "[object Arguments]" === Object.prototype.toString.call(iter)) return Array.from(iter);
}(arr) || function() {
throw TypeError("Invalid attempt to spread non-iterable instance");
}();
}
exports.default = function(_param) {
var src, arr, sizerSvg, src1 = _param.src, sizes = _param.sizes, _unoptimized = _param.unoptimized, unoptimized = void 0 !== _unoptimized && _unoptimized, _priority = _param.priority, priority = void 0 !== _priority && _priority, loading = _param.loading, _lazyBoundary = _param.lazyBoundary, className = _param.className, quality = _param.quality, width = _param.width, height = _param.height, objectFit = _param.objectFit, objectPosition = _param.objectPosition, onLoadingComplete = _param.onLoadingComplete, _loader = _param.loader, loader = void 0 === _loader ? defaultImageLoader : _loader, _placeholder = _param.placeholder, placeholder = void 0 === _placeholder ? "empty" : _placeholder, blurDataURL = _param.blurDataURL, all = function(source, excluded) {
if (null == source) return {};
var key, i, target = function(source, excluded) {
if (null == source) return {};
var key, i, target = {}, sourceKeys = Object.keys(source);
for(i = 0; i < sourceKeys.length; i++)key = sourceKeys[i], excluded.indexOf(key) >= 0 || (target[key] = source[key]);
return target;
}(source, excluded);
if (Object.getOwnPropertySymbols) {
var sourceSymbolKeys = Object.getOwnPropertySymbols(source);
for(i = 0; i < sourceSymbolKeys.length; i++)key = sourceSymbolKeys[i], !(excluded.indexOf(key) >= 0) && Object.prototype.propertyIsEnumerable.call(source, key) && (target[key] = source[key]);
}
return target;
}(_param, [
"src",
"sizes",
"unoptimized",
"priority",
"loading",
"lazyBoundary",
"className",
"quality",
"width",
"height",
"objectFit",
"objectPosition",
"onLoadingComplete",
"loader",
"placeholder",
"blurDataURL"
]), layout = sizes ? "responsive" : "intrinsic";
"layout" in all && (all.layout && (layout = all.layout), // Remove property so it's not spread into image:
delete all.layout);
var staticSrc = "";
if ("object" == typeof (src = src1) && (isStaticRequire(src) || void 0 !== src.src)) {
var staticImageData = isStaticRequire(src1) ? src1.default : src1;
if (!staticImageData.src) throw Error("An object should only be passed to the image component src parameter if it comes from a static image import. It must include src. Received ".concat(JSON.stringify(staticImageData)));
if (blurDataURL = blurDataURL || staticImageData.blurDataURL, staticSrc = staticImageData.src, (!layout || "fill" !== layout) && (height = height || staticImageData.height, width = width || staticImageData.width, !staticImageData.height || !staticImageData.width)) throw Error("An object should only be passed to the image component src parameter if it comes from a static image import. It must include height and width. Received ".concat(JSON.stringify(staticImageData)));
}
src1 = "string" == typeof src1 ? src1 : staticSrc;
var widthInt = getInt(width), heightInt = getInt(height), qualityInt = getInt(quality), isLazy = !priority && ("lazy" === loading || void 0 === loading);
(src1.startsWith("data:") || src1.startsWith("blob:")) && (// https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URIs
unoptimized = !0, isLazy = !1), loadedImageURLs.has(src1) && (isLazy = !1);
var ref2 = function(arr) {
if (Array.isArray(arr)) return arr;
}(arr = _useIntersection.useIntersection({
rootMargin: void 0 === _lazyBoundary ? "200px" : _lazyBoundary,
disabled: !isLazy
})) || function(arr, i) {
var _arr = [], _n = !0, _d = !1, _e = void 0;
try {
for(var _s, _i = arr[Symbol.iterator](); !(_n = (_s = _i.next()).done) && (_arr.push(_s.value), 2 !== _arr.length); _n = !0);
} catch (err) {
_d = !0, _e = err;
} finally{
try {
_n || null == _i.return || _i.return();
} finally{
if (_d) throw _e;
}
}
return _arr;
}(arr, 0) || function() {
throw TypeError("Invalid attempt to destructure non-iterable instance");
}(), setRef = ref2[0], isIntersected = ref2[1], isVisible = !isLazy || isIntersected, wrapperStyle = {
boxSizing: "border-box",
display: "block",
overflow: "hidden",
width: "initial",
height: "initial",
background: "none",
opacity: 1,
border: 0,
margin: 0,
padding: 0
}, sizerStyle = {
boxSizing: "border-box",
display: "block",
width: "initial",
height: "initial",
background: "none",
opacity: 1,
border: 0,
margin: 0,
padding: 0
}, hasSizer = !1, imgStyle = {
position: "absolute",
top: 0,
left: 0,
bottom: 0,
right: 0,
boxSizing: "border-box",
padding: 0,
border: "none",
margin: "auto",
display: "block",
width: 0,
height: 0,
minWidth: "100%",
maxWidth: "100%",
minHeight: "100%",
maxHeight: "100%",
objectFit: objectFit,
objectPosition: objectPosition
}, blurStyle = "blur" === placeholder ? {
filter: "blur(20px)",
backgroundSize: objectFit || "cover",
backgroundImage: 'url("'.concat(blurDataURL, '")'),
backgroundPosition: objectPosition || "0% 0%"
} : {};
if ("fill" === layout) // <Image src="i.png" layout="fill" />
wrapperStyle.display = "block", wrapperStyle.position = "absolute", wrapperStyle.top = 0, wrapperStyle.left = 0, wrapperStyle.bottom = 0, wrapperStyle.right = 0;
else if (void 0 !== widthInt && void 0 !== heightInt) {
// <Image src="i.png" width="100" height="100" />
var quotient = heightInt / widthInt, paddingTop = isNaN(quotient) ? "100%" : "".concat(100 * quotient, "%");
"responsive" === layout ? (// <Image src="i.png" width="100" height="100" layout="responsive" />
wrapperStyle.display = "block", wrapperStyle.position = "relative", hasSizer = !0, sizerStyle.paddingTop = paddingTop) : "intrinsic" === layout ? (// <Image src="i.png" width="100" height="100" layout="intrinsic" />
wrapperStyle.display = "inline-block", wrapperStyle.position = "relative", wrapperStyle.maxWidth = "100%", hasSizer = !0, sizerStyle.maxWidth = "100%", sizerSvg = '<svg width="'.concat(widthInt, '" height="').concat(heightInt, '" xmlns="http://www.w3.org/2000/svg" version="1.1"/>')) : "fixed" === layout && (// <Image src="i.png" width="100" height="100" layout="fixed" />
wrapperStyle.display = "inline-block", wrapperStyle.position = "relative", wrapperStyle.width = widthInt, wrapperStyle.height = heightInt);
}
var imgAttributes = {
src: emptyDataURL,
srcSet: void 0,
sizes: void 0
};
isVisible && (imgAttributes = generateImgAttrs({
src: src1,
unoptimized: unoptimized,
layout: layout,
width: widthInt,
quality: qualityInt,
sizes: sizes,
loader: loader
}));
var srcString = src1;
return /*#__PURE__*/ _react.default.createElement("span", {
style: wrapperStyle
}, hasSizer ? /*#__PURE__*/ _react.default.createElement("span", {
style: sizerStyle
}, sizerSvg ? /*#__PURE__*/ _react.default.createElement("img", {
style: {
display: "block",
maxWidth: "100%",
width: "initial",
height: "initial",
background: "none",
opacity: 1,
border: 0,
margin: 0,
padding: 0
},
alt: "",
"aria-hidden": !0,
src: "data:image/svg+xml;base64,".concat(_toBase64.toBase64(sizerSvg))
}) : null) : null, /*#__PURE__*/ _react.default.createElement("img", Object.assign({}, all, imgAttributes, {
decoding: "async",
"data-nimg": layout,
className: className,
ref: function(img) {
setRef(img), // See https://stackoverflow.com/q/39777833/266535 for why we use this ref
// handler instead of the img's onLoad attribute.
function(img, src, layout, placeholder, onLoadingComplete) {
if (img) {
var handleLoad = function() {
img.src !== emptyDataURL && ("decode" in img ? img.decode() : Promise.resolve()).catch(function() {}).then(function() {
"blur" === placeholder && (img.style.filter = "none", img.style.backgroundSize = "none", img.style.backgroundImage = "none"), loadedImageURLs.add(src), onLoadingComplete && // Pass back read-only primitive values but not the
// underlying DOM element because it could be misused.
onLoadingComplete({
naturalWidth: img.naturalWidth,
naturalHeight: img.naturalHeight
});
});
};
img.complete ? // If the real image fails to load, this will still remove the placeholder.
// This is the desired behavior for now, and will be revisited when error
// handling is worked on for the image component itself.
handleLoad() : img.onload = handleLoad;
}
}(img, srcString, 0, placeholder, onLoadingComplete);
},
style: _objectSpread({}, imgStyle, blurStyle)
})), /*#__PURE__*/ _react.default.createElement("noscript", null, /*#__PURE__*/ _react.default.createElement("img", Object.assign({}, all, generateImgAttrs({
src: src1,
unoptimized: unoptimized,
layout: layout,
width: widthInt,
quality: qualityInt,
sizes: sizes,
loader: loader
}), {
decoding: "async",
"data-nimg": layout,
style: imgStyle,
className: className,
// @ts-ignore - TODO: upgrade to `@types/react@17`
loading: loading || "lazy"
}))), priority // for browsers that do not support `imagesrcset`, and in those cases
? //
// https://html.spec.whatwg.org/multipage/semantics.html#attr-link-imagesrcset
/*#__PURE__*/ _react.default.createElement(_head.default, null, /*#__PURE__*/ _react.default.createElement("link", {
key: "__nimg-" + imgAttributes.src + imgAttributes.srcSet + imgAttributes.sizes,
rel: "preload",
as: "image",
href: imgAttributes.srcSet ? void 0 : imgAttributes.src,
// @ts-ignore: imagesrcset is not yet in the link element type.
imagesrcset: imgAttributes.srcSet,
// @ts-ignore: imagesizes is not yet in the link element type.
imagesizes: imgAttributes.sizes
})) : null);
};
var _react = _interopRequireDefault(__webpack_require__(7294)), _head = _interopRequireDefault(__webpack_require__(5443)), _toBase64 = __webpack_require__(6978), _imageConfig = __webpack_require__(5809), _useIntersection = __webpack_require__(7190);
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
function _objectSpread(target) {
for(var _arguments = arguments, i = 1; i < arguments.length; i++)!function(i) {
var source = null != _arguments[i] ? _arguments[i] : {}, ownKeys = Object.keys(source);
"function" == typeof Object.getOwnPropertySymbols && (ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function(sym) {
return Object.getOwnPropertyDescriptor(source, sym).enumerable;
}))), ownKeys.forEach(function(key) {
var value;
value = source[key], key in target ? Object.defineProperty(target, key, {
value: value,
enumerable: !0,
configurable: !0,
writable: !0
}) : target[key] = value;
});
}(i);
return target;
}
var loadedImageURLs = new Set(), emptyDataURL = "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7", loaders = new Map([
[
"default",
function(param) {
var root = param.root, src = param.src, width = param.width, quality = param.quality;
return "".concat(root, "?url=").concat(encodeURIComponent(src), "&w=").concat(width, "&q=").concat(quality || 75);
} //# sourceMappingURL=image.js.map
],
[
"imgix",
function(param) {
var root = param.root, src = param.src, width = param.width, quality = param.quality, url = new URL("".concat(root).concat(normalizeSrc(src))), params = url.searchParams;
return params.set("auto", params.get("auto") || "format"), params.set("fit", params.get("fit") || "max"), params.set("w", params.get("w") || width.toString()), quality && params.set("q", quality.toString()), url.href;
}
],
[
"cloudinary",
function(param) {
var root = param.root, src = param.src, paramsString = [
"f_auto",
"c_limit",
"w_" + param.width,
"q_" + (param.quality || "auto")
].join(",") + "/";
return "".concat(root).concat(paramsString).concat(normalizeSrc(src));
}
],
[
"akamai",
function(param) {
var root = param.root, src = param.src, width = param.width;
return "".concat(root).concat(normalizeSrc(src), "?imwidth=").concat(width);
}
],
[
"custom",
function(param) {
var src = param.src;
throw Error('Image with src "'.concat(src, '" is missing "loader" prop.') + "\nRead more: https://nextjs.org/docs/messages/next-image-missing-loader");
}
]
]);
function isStaticRequire(src) {
return void 0 !== src.default;
}
var ref1 = {
deviceSizes: [
640,
750,
828,
1080,
1200,
1920,
2048,
3840
],
imageSizes: [
16,
32,
48,
64,
96,
128,
256,
384
],
path: "/_next/image",
loader: "default"
}, configDeviceSizes = ref1.deviceSizes, configImageSizes = ref1.imageSizes, configLoader = ref1.loader, configPath = ref1.path;
ref1.domains;
// sort smallest to largest
var allSizes = _toConsumableArray(configDeviceSizes).concat(_toConsumableArray(configImageSizes));
function generateImgAttrs(param) {
var src = param.src, unoptimized = param.unoptimized, layout = param.layout, width = param.width, quality = param.quality, sizes = param.sizes, loader = param.loader;
if (unoptimized) return {
src: src,
srcSet: void 0,
sizes: void 0
};
var ref = function(width, layout, sizes) {
if (sizes && ("fill" === layout || "responsive" === layout)) {
for(// Find all the "vw" percent sizes used in the sizes prop
var viewportWidthRe = /(^|\s)(1?\d?\d)vw/g, percentSizes = []; match = viewportWidthRe.exec(sizes); match)percentSizes.push(parseInt(match[2]));
if (percentSizes.length) {
var match, _Math, smallestRatio = 0.01 * (_Math = Math).min.apply(_Math, _toConsumableArray(percentSizes));
return {
widths: allSizes.filter(function(s) {
return s >= configDeviceSizes[0] * smallestRatio;
}),
kind: "w"
};
}
return {
widths: allSizes,
kind: "w"
};
}
return "number" != typeof width || "fill" === layout || "responsive" === layout ? {
widths: configDeviceSizes,
kind: "w"
} : {
widths: _toConsumableArray(new Set(// > blue colors. Showing a 3x resolution image in the app vs a 2x
// > resolution image will be visually the same, though the 3x image
// > takes significantly more data. Even true 3x resolution screens are
// > wasteful as the human eye cannot see that level of detail without
// > something like a magnifying glass.
// https://blog.twitter.com/engineering/en_us/topics/infrastructure/2019/capping-image-fidelity-on-ultra-high-resolution-devices.html
[
width,
2 /*, width * 3*/ * width
].map(function(w) {
return allSizes.find(function(p) {
return p >= w;
}) || allSizes[allSizes.length - 1];
}))),
kind: "x"
};
}(width, layout, sizes), widths = ref.widths, kind = ref.kind, last = widths.length - 1;
return {
sizes: sizes || "w" !== kind ? sizes : "100vw",
srcSet: widths.map(function(w, i) {
return "".concat(loader({
src: src,
quality: quality,
width: w
}), " ").concat("w" === kind ? w : i + 1).concat(kind);
}).join(", "),
// It's intended to keep `src` the last attribute because React updates
// attributes in order. If we keep `src` the first one, Safari will
// immediately start to fetch `src`, before `sizes` and `srcSet` are even
// updated by React. That causes multiple unnecessary requests if `srcSet`
// and `sizes` are defined.
// This bug cannot be reproduced in Chrome or Firefox.
src: loader({
src: src,
quality: quality,
width: widths[last]
})
};
}
function getInt(x) {
return "number" == typeof x ? x : "string" == typeof x ? parseInt(x, 10) : void 0;
}
function defaultImageLoader(loaderProps) {
var load = loaders.get(configLoader);
if (load) return load(_objectSpread({
root: configPath
}, loaderProps));
throw Error('Unknown "loader" found in "next.config.js". Expected: '.concat(_imageConfig.VALID_LOADERS.join(", "), ". Received: ").concat(configLoader));
}
function normalizeSrc(src) {
return "/" === src[0] ? src.slice(1) : src;
}
configDeviceSizes.sort(function(a, b) {
return a - b;
}), allSizes.sort(function(a, b) {
return a - b;
});
/***/ },
/***/ 7190: /***/ function(__unused_webpack_module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: !0
}), exports.useIntersection = function(param) {
var arr, rootMargin = param.rootMargin, isDisabled = param.disabled || !hasIntersectionObserver, unobserve = _react.useRef(), ref = function(arr) {
if (Array.isArray(arr)) return arr;
}(arr = _react.useState(!1)) || function(arr, i) {
var _arr = [], _n = !0, _d = !1, _e = void 0;
try {
for(var _s, _i = arr[Symbol.iterator](); !(_n = (_s = _i.next()).done) && (_arr.push(_s.value), 2 !== _arr.length); _n = !0);
} catch (err) {
_d = !0, _e = err;
} finally{
try {
_n || null == _i.return || _i.return();
} finally{
if (_d) throw _e;
}
}
return _arr;
}(arr, 0) || function() {
throw TypeError("Invalid attempt to destructure non-iterable instance");
}(), visible = ref[0], setVisible = ref[1], setRef = _react.useCallback(function(el) {
var ref, id, observer, elements;
unobserve.current && (unobserve.current(), unobserve.current = void 0), !isDisabled && !visible && el && el.tagName && (id = (ref = function(options) {
var id = options.rootMargin || "", instance = observers.get(id);
if (instance) return instance;
var elements = new Map(), observer = new IntersectionObserver(function(entries) {
entries.forEach(function(entry) {
var callback = elements.get(entry.target), isVisible = entry.isIntersecting || entry.intersectionRatio > 0;
callback && isVisible && callback(isVisible);
});
}, options);
return observers.set(id, instance = {
id: id,
observer: observer,
elements: elements
}), instance;
} //# sourceMappingURL=use-intersection.js.map
({
rootMargin: rootMargin
})).id, observer = ref.observer, (elements = ref.elements).set(el, function(isVisible) {
return isVisible && setVisible(isVisible);
}), observer.observe(el), unobserve.current = function() {
elements.delete(el), observer.unobserve(el), 0 === elements.size && (observer.disconnect(), observers.delete(id));
});
}, [
isDisabled,
rootMargin,
visible
]);
return _react.useEffect(function() {
if (!hasIntersectionObserver && !visible) {
var idleCallback = _requestIdleCallback.requestIdleCallback(function() {
return setVisible(!0);
});
return function() {
return _requestIdleCallback.cancelIdleCallback(idleCallback);
};
}
}, [
visible
]), [
setRef,
visible
];
};
var _react = __webpack_require__(7294), _requestIdleCallback = __webpack_require__(9311), hasIntersectionObserver = "undefined" != typeof IntersectionObserver, observers = new Map();
/***/ },
/***/ 6978: /***/ function(__unused_webpack_module, exports) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: !0
}), exports.toBase64 = function(str) {
return window.btoa(str);
} //# sourceMappingURL=to-base-64.js.map
;
/***/ },
/***/ 5809: /***/ function(__unused_webpack_module, exports) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: !0
}), exports.imageConfigDefault = exports.VALID_LOADERS = void 0, exports.VALID_LOADERS = [
"default",
"imgix",
"cloudinary",
"akamai",
"custom"
], exports.imageConfigDefault = {
deviceSizes: [
640,
750,
828,
1080,
1200,
1920,
2048,
3840
],
imageSizes: [
16,
32,
48,
64,
96,
128,
256,
384
],
path: "/_next/image",
loader: "default",
domains: [],
disableStaticImages: !1,
minimumCacheTTL: 60,
formats: [
"image/webp"
]
};
//# sourceMappingURL=image-config.js.map
/***/ },
/***/ 9008: /***/ function(module, __unused_webpack_exports, __webpack_require__) {
module.exports = __webpack_require__(5443);
/***/ },
/***/ 5675: /***/ function(module, __unused_webpack_exports, __webpack_require__) {
module.exports = __webpack_require__(8045);
/***/ },
/***/ 7857: /***/ function(__unused_webpack_module, exports, __webpack_require__) {
"use strict";
var React = __webpack_require__(7294), countup_js = __webpack_require__(8273), React__default = React && "object" == typeof React && "default" in React ? React : {
default: React
};
function ownKeys(object, enumerableOnly) {
var keys = Object.keys(object);
if (Object.getOwnPropertySymbols) {
var symbols = Object.getOwnPropertySymbols(object);
enumerableOnly && (symbols = symbols.filter(function(sym) {
return Object.getOwnPropertyDescriptor(object, sym).enumerable;
})), keys.push.apply(keys, symbols);
}
return keys;
}
function _objectSpread2(target) {
for(var i = 1; i < arguments.length; i++){
var source = null != arguments[i] ? arguments[i] : {};
i % 2 ? ownKeys(Object(source), !0).forEach(function(key) {
var value;
value = source[key], key in target ? Object.defineProperty(target, key, {
value: value,
enumerable: !0,
configurable: !0,
writable: !0
}) : target[key] = value;
}) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function(key) {
Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
});
}
return target;
}
function _extends() {
return (_extends = Object.assign || function(target) {
for(var i = 1; i < arguments.length; i++){
var source = arguments[i];
for(var key in source)Object.prototype.hasOwnProperty.call(source, key) && (target[key] = source[key]);
}
return target;
}).apply(this, arguments);
}
function _objectWithoutProperties(source, excluded) {
if (null == source) return {};
var key, i, target = function(source, excluded) {
if (null == source) return {};
var key, i, target = {}, sourceKeys = Object.keys(source);
for(i = 0; i < sourceKeys.length; i++)key = sourceKeys[i], excluded.indexOf(key) >= 0 || (target[key] = source[key]);
return target;
}(source, excluded);
if (Object.getOwnPropertySymbols) {
var sourceSymbolKeys = Object.getOwnPropertySymbols(source);
for(i = 0; i < sourceSymbolKeys.length; i++)key = sourceSymbolKeys[i], !(excluded.indexOf(key) >= 0) && Object.prototype.propertyIsEnumerable.call(source, key) && (target[key] = source[key]);
}
return target;
}
/**
* Silence SSR Warnings.
* Borrowed from Formik v2.1.1, Licensed MIT.
*
* https://github.com/formium/formik/blob/9316a864478f8fcd4fa99a0735b1d37afdf507dc/LICENSE
*/ var useIsomorphicLayoutEffect = "undefined" != typeof window && void 0 !== window.document && void 0 !== window.document.createElement ? React.useLayoutEffect : React.useEffect;
/* eslint-disable @typescript-eslint/no-explicit-any */ /**
* Create a stable reference to a callback which is updated after each render is committed.
* Typed version borrowed from Formik v2.2.1. Licensed MIT.
*
* https://github.com/formium/formik/blob/9316a864478f8fcd4fa99a0735b1d37afdf507dc/LICENSE
*/ function useEventCallback(fn) {
var ref = React.useRef(fn); // we copy a ref to the callback scoped to the current state/props on each render
return useIsomorphicLayoutEffect(function() {
ref.current = fn;
}), React.useCallback(function() {
for(var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++)args[_key] = arguments[_key];
return ref.current.apply(void 0, args);
}, []);
}
var createCountUpInstance = function(el, props) {
var decimal = props.decimal, decimals = props.decimals, duration = props.duration, easingFn = props.easingFn, end = props.end, formattingFn = props.formattingFn, numerals = props.numerals, prefix = props.prefix, separator = props.separator, start = props.start, suffix = props.suffix, useEasing = props.useEasing;
return new countup_js.CountUp(el, end, {
startVal: start,
duration: duration,
decimal: decimal,
decimalPlaces: decimals,
easingFn: easingFn,
formattingFn: formattingFn,
numerals: numerals,
separator: separator,
prefix: prefix,
suffix: suffix,
useEasing: useEasing,
useGrouping: !!separator
});
}, _excluded$1 = [
"ref",
"startOnMount",
"enableReinitialize",
"delay",
"onEnd",
"onStart",
"onPauseResume",
"onReset",
"onUpdate"
], DEFAULTS = {
decimal: ".",
delay: null,
prefix: "",
suffix: "",
start: 0,
startOnMount: !0,
enableReinitialize: !0
}, useCountUp = function(props) {
var _useMemo = React.useMemo(function() {
return _objectSpread2(_objectSpread2({}, DEFAULTS), props);
}, [
props
]), ref = _useMemo.ref, startOnMount = _useMemo.startOnMount, enableReinitialize = _useMemo.enableReinitialize, delay = _useMemo.delay, onEnd = _useMemo.onEnd, onStart = _useMemo.onStart, onPauseResume = _useMemo.onPauseResume, onReset = _useMemo.onReset, onUpdate = _useMemo.onUpdate, instanceProps = _objectWithoutProperties(_useMemo, _excluded$1), countUpRef = React.useRef(), timerRef = React.useRef(), isInitializedRef = React.useRef(!1), createInstance = useEventCallback(function() {
return createCountUpInstance("string" == typeof ref ? ref : ref.current, instanceProps);
}), getCountUp = useEventCallback(function(recreate) {
var countUp = countUpRef.current;
if (countUp && !recreate) return countUp;
var newCountUp = createInstance();
return countUpRef.current = newCountUp, newCountUp;
}), start = useEventCallback(function() {
var run = function() {
return getCountUp(!0).start(function() {
null == onEnd || onEnd({
pauseResume: pauseResume,
reset: reset,
start: restart,
update: update
});
});
};
delay && delay > 0 ? timerRef.current = setTimeout(run, 1000 * delay) : run(), null == onStart || onStart({
pauseResume: pauseResume,
reset: reset,
update: update
});
}), pauseResume = useEventCallback(function() {
getCountUp().pauseResume(), null == onPauseResume || onPauseResume({
reset: reset,
start: restart,
update: update
});
}), reset = useEventCallback(function() {
timerRef.current && clearTimeout(timerRef.current), getCountUp().reset(), null == onReset || onReset({
pauseResume: pauseResume,
start: restart,
update: update
});
}), update = useEventCallback(function(newEnd) {
getCountUp().update(newEnd), null == onUpdate || onUpdate({
pauseResume: pauseResume,
reset: reset,
start: restart
});
}), restart = useEventCallback(function() {
reset(), start();
}), maybeInitialize = useEventCallback(function(shouldReset) {
startOnMount && (shouldReset && reset(), start());
});
return React.useEffect(function() {
isInitializedRef.current ? enableReinitialize && maybeInitialize(!0) : (isInitializedRef.current = !0, maybeInitialize());
}, [
enableReinitialize,
isInitializedRef,
maybeInitialize,
delay,
props.start,
props.suffix,
props.prefix,
props.duration,
props.separator,
props.decimals,
props.decimal,
props.formattingFn
]), React.useEffect(function() {
return function() {
reset();
};
}, [
reset
]), {
start: restart,
pauseResume: pauseResume,
reset: reset,
update: update,
getCountUp: getCountUp
};
}, _excluded = [
"className",
"redraw",
"containerProps",
"children",
"style"
];
exports.ZP = function(props) {
var className = props.className, redraw = props.redraw, containerProps = props.containerProps, children = props.children, style = props.style, useCountUpProps = _objectWithoutProperties(props, _excluded), containerRef = React__default.default.useRef(null), isInitializedRef = React__default.default.useRef(!1), _useCountUp = useCountUp(_objectSpread2(_objectSpread2({}, useCountUpProps), {}, {
ref: containerRef,
startOnMount: "function" != typeof children || 0 === props.delay,
// component manually restarts
enableReinitialize: !1
})), start = _useCountUp.start, reset = _useCountUp.reset, updateCountUp = _useCountUp.update, pauseResume = _useCountUp.pauseResume, getCountUp = _useCountUp.getCountUp, restart = useEventCallback(function() {
start();
}), update = useEventCallback(function(end) {
props.preserveValue || reset(), updateCountUp(end);
}), initializeOnMount = useEventCallback(function() {
if ("function" == typeof props.children && !(containerRef.current instanceof Element)) {
console.error('Couldn\'t find attached element to hook the CountUp instance into! Try to attach "containerRef" from the render prop to a an Element, eg. <span ref={containerRef} />.');
return;
} // unlike the hook, the CountUp component initializes on mount
getCountUp();
});
React.useEffect(function() {
initializeOnMount();
}, [
initializeOnMount
]), React.useEffect(function() {
isInitializedRef.current && update(props.end);
}, [
props.end,
update
]);
var redrawDependencies = redraw && props; // if props.redraw, call this effect on every props change
return (React.useEffect(function() {
redraw && isInitializedRef.current && restart();
}, [
restart,
redraw,
redrawDependencies
]), React.useEffect(function() {
!redraw && isInitializedRef.current && restart();
}, [
restart,
redraw,
props.start,
props.suffix,
props.prefix,
props.duration,
props.separator,
props.decimals,
props.decimal,
props.className,
props.formattingFn
]), React.useEffect(function() {
isInitializedRef.current = !0;
}, []), "function" == typeof children) ? children({
countUpRef: containerRef,
start: start,
reset: reset,
update: updateCountUp,
pauseResume: pauseResume,
getCountUp: getCountUp
}) : /*#__PURE__*/ React__default.default.createElement("span", _extends({
className: className,
ref: containerRef,
style: style
}, containerProps));
};
/***/ }
}
]);
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_minifier/tests/fixture/issues/react-countup/2/input.js | JavaScript | export function formatNumber(t) {
var i,
a,
n,
e,
r = t < 0 ? "-" : "";
i = Math.abs(t).toFixed(s.options.decimalPlaces);
var o = (i += "").split(".");
if (
((a = o[0]),
(n = o.length > 1 ? s.options.decimal + o[1] : ""),
s.options.useGrouping)
) {
e = "";
for (var l = 0, h = a.length; l < h; ++l)
0 !== l && l % 3 == 0 && (e = s.options.separator + e),
(e = a[h - l - 1] + e);
a = e;
}
return (
s.options.numerals &&
s.options.numerals.length &&
((a = a.replace(/[0-9]/g, function (t) {
return s.options.numerals[+t];
})),
(n = n.replace(/[0-9]/g, function (t) {
return s.options.numerals[+t];
}))),
r + s.options.prefix + a + n + s.options.suffix
);
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_minifier/tests/fixture/issues/react-countup/2/output.js | JavaScript | export function formatNumber(t) {
var a, n, e, o = (Math.abs(t).toFixed(s.options.decimalPlaces) + "").split(".");
if (a = o[0], n = o.length > 1 ? s.options.decimal + o[1] : "", s.options.useGrouping) {
e = "";
for(var l = 0, h = a.length; l < h; ++l)0 !== l && l % 3 == 0 && (e = s.options.separator + e), e = a[h - l - 1] + e;
a = e;
}
return s.options.numerals && s.options.numerals.length && (a = a.replace(/[0-9]/g, function(t) {
return s.options.numerals[+t];
}), n = n.replace(/[0-9]/g, function(t) {
return s.options.numerals[+t];
})), (t < 0 ? "-" : "") + s.options.prefix + a + n + s.options.suffix;
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_minifier/tests/fixture/issues/react-instancesearch/001/input.js | JavaScript | import { defer } from "./utils";
export default function createWidgetsManager(onWidgetsUpdate) {
const widgets = [];
// Is an update scheduled?
let scheduled = false;
// The state manager's updates need to be batched since more than one
// component can register or unregister widgets during the same tick.
function scheduleUpdate() {
if (scheduled) {
return;
}
scheduled = true;
defer(() => {
scheduled = false;
onWidgetsUpdate();
});
}
return {
registerWidget(widget) {
widgets.push(widget);
scheduleUpdate();
return function unregisterWidget() {
widgets.splice(widgets.indexOf(widget), 1);
scheduleUpdate();
};
},
update: scheduleUpdate,
getWidgets() {
return widgets;
},
};
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_minifier/tests/fixture/issues/react-instancesearch/001/output.js | JavaScript | import { defer } from "./utils";
export default function createWidgetsManager(onWidgetsUpdate) {
const widgets = [];
// Is an update scheduled?
let scheduled = !1;
// The state manager's updates need to be batched since more than one
// component can register or unregister widgets during the same tick.
function scheduleUpdate() {
scheduled || (scheduled = !0, defer(()=>{
scheduled = !1, onWidgetsUpdate();
}));
}
return {
registerWidget: (widget)=>(widgets.push(widget), scheduleUpdate(), function() {
widgets.splice(widgets.indexOf(widget), 1), scheduleUpdate();
}),
update: scheduleUpdate,
getWidgets: ()=>widgets
};
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_minifier/tests/fixture/issues/react-instancesearch/002/input.js | JavaScript | import algoliasearchHelper from "algoliasearch-helper";
import createWidgetsManager from "./createWidgetsManager";
import createStore from "./createStore";
import { HIGHLIGHT_TAGS } from "./highlight";
import { hasMultipleIndices } from "./indexUtils";
import { version as ReactVersion } from "react";
import version from "./version";
function addAlgoliaAgents(searchClient) {
if (typeof searchClient.addAlgoliaAgent === "function") {
searchClient.addAlgoliaAgent(`react (${ReactVersion})`);
searchClient.addAlgoliaAgent(`react-instantsearch (${version})`);
}
}
const isMultiIndexContext = (widget) =>
hasMultipleIndices({
ais: widget.props.contextValue,
multiIndexContext: widget.props.indexContextValue,
});
const isTargetedIndexEqualIndex = (widget, indexId) =>
widget.props.indexContextValue.targetedIndex === indexId;
// Relying on the `indexId` is a bit brittle to detect the `Index` widget.
// Since it's a class we could rely on `instanceof` or similar. We never
// had an issue though. Works for now.
const isIndexWidget = (widget) => Boolean(widget.props.indexId);
const isIndexWidgetEqualIndex = (widget, indexId) =>
widget.props.indexId === indexId;
const sortIndexWidgetsFirst = (firstWidget, secondWidget) => {
const isFirstWidgetIndex = isIndexWidget(firstWidget);
const isSecondWidgetIndex = isIndexWidget(secondWidget);
if (isFirstWidgetIndex && !isSecondWidgetIndex) {
return -1;
}
if (!isFirstWidgetIndex && isSecondWidgetIndex) {
return 1;
}
return 0;
};
// This function is copied from the algoliasearch v4 API Client. If modified,
// consider updating it also in `serializeQueryParameters` from `@algolia/transporter`.
function serializeQueryParameters(parameters) {
const isObjectOrArray = (value) =>
Object.prototype.toString.call(value) === "[object Object]" ||
Object.prototype.toString.call(value) === "[object Array]";
const encode = (format, ...args) => {
let i = 0;
return format.replace(/%s/g, () => encodeURIComponent(args[i++]));
};
return Object.keys(parameters)
.map((key) =>
encode(
"%s=%s",
key,
isObjectOrArray(parameters[key])
? JSON.stringify(parameters[key])
: parameters[key]
)
)
.join("&");
}
/**
* Creates a new instance of the InstantSearchManager which controls the widgets and
* trigger the search when the widgets are updated.
* @param {string} indexName - the main index name
* @param {object} initialState - initial widget state
* @param {object} SearchParameters - optional additional parameters to send to the algolia API
* @param {number} stalledSearchDelay - time (in ms) after the search is stalled
* @return {InstantSearchManager} a new instance of InstantSearchManager
*/
export default function createInstantSearchManager({
indexName,
initialState = {},
searchClient,
resultsState,
stalledSearchDelay,
}) {
const helper = algoliasearchHelper(searchClient, indexName, {
...HIGHLIGHT_TAGS,
});
addAlgoliaAgents(searchClient);
helper
.on("search", handleNewSearch)
.on("result", handleSearchSuccess({ indexId: indexName }))
.on("error", handleSearchError);
let skip = false;
let stalledSearchTimer = null;
let initialSearchParameters = helper.state;
const widgetsManager = createWidgetsManager(onWidgetsUpdate);
hydrateSearchClient(searchClient, resultsState);
const store = createStore({
widgets: initialState,
metadata: hydrateMetadata(resultsState),
results: hydrateResultsState(resultsState),
error: null,
searching: false,
isSearchStalled: true,
searchingForFacetValues: false,
});
function skipSearch() {
skip = true;
}
function updateClient(client) {
addAlgoliaAgents(client);
helper.setClient(client);
search();
}
function clearCache() {
helper.clearCache();
search();
}
function getMetadata(state) {
return widgetsManager
.getWidgets()
.filter((widget) => Boolean(widget.getMetadata))
.map((widget) => widget.getMetadata(state));
}
function getSearchParameters() {
const sharedParameters = widgetsManager
.getWidgets()
.filter((widget) => Boolean(widget.getSearchParameters))
.filter(
(widget) =>
!isMultiIndexContext(widget) && !isIndexWidget(widget)
)
.reduce(
(res, widget) => widget.getSearchParameters(res),
initialSearchParameters
);
const mainParameters = widgetsManager
.getWidgets()
.filter((widget) => Boolean(widget.getSearchParameters))
.filter((widget) => {
const targetedIndexEqualMainIndex =
isMultiIndexContext(widget) &&
isTargetedIndexEqualIndex(widget, indexName);
const subIndexEqualMainIndex =
isIndexWidget(widget) &&
isIndexWidgetEqualIndex(widget, indexName);
return targetedIndexEqualMainIndex || subIndexEqualMainIndex;
})
// We have to sort the `Index` widgets first so the `index` parameter
// is correctly set in the `reduce` function for the following widgets
.sort(sortIndexWidgetsFirst)
.reduce(
(res, widget) => widget.getSearchParameters(res),
sharedParameters
);
const derivedIndices = widgetsManager
.getWidgets()
.filter((widget) => Boolean(widget.getSearchParameters))
.filter((widget) => {
const targetedIndexNotEqualMainIndex =
isMultiIndexContext(widget) &&
!isTargetedIndexEqualIndex(widget, indexName);
const subIndexNotEqualMainIndex =
isIndexWidget(widget) &&
!isIndexWidgetEqualIndex(widget, indexName);
return (
targetedIndexNotEqualMainIndex || subIndexNotEqualMainIndex
);
})
// We have to sort the `Index` widgets first so the `index` parameter
// is correctly set in the `reduce` function for the following widgets
.sort(sortIndexWidgetsFirst)
.reduce((indices, widget) => {
const indexId = isMultiIndexContext(widget)
? widget.props.indexContextValue.targetedIndex
: widget.props.indexId;
const widgets = indices[indexId] || [];
return {
...indices,
[indexId]: widgets.concat(widget),
};
}, {});
const derivedParameters = Object.keys(derivedIndices).map(
(indexId) => ({
parameters: derivedIndices[indexId].reduce(
(res, widget) => widget.getSearchParameters(res),
sharedParameters
),
indexId,
})
);
return {
mainParameters,
derivedParameters,
};
}
function search() {
if (!skip) {
const { mainParameters, derivedParameters } = getSearchParameters(
helper.state
);
// We have to call `slice` because the method `detach` on the derived
// helpers mutates the value `derivedHelpers`. The `forEach` loop does
// not iterate on each value and we're not able to correctly clear the
// previous derived helpers (memory leak + useless requests).
helper.derivedHelpers.slice().forEach((derivedHelper) => {
// Since we detach the derived helpers on **every** new search they
// won't receive intermediate results in case of a stalled search.
// Only the last result is dispatched by the derived helper because
// they are not detached yet:
//
// - a -> main helper receives results
// - ap -> main helper receives results
// - app -> main helper + derived helpers receive results
//
// The quick fix is to avoid to detach them on search but only once they
// received the results. But it means that in case of a stalled search
// all the derived helpers not detached yet register a new search inside
// the helper. The number grows fast in case of a bad network and it's
// not deterministic.
derivedHelper.detach();
});
derivedParameters.forEach(({ indexId, parameters }) => {
const derivedHelper = helper.derive(() => parameters);
derivedHelper
.on("result", handleSearchSuccess({ indexId }))
.on("error", handleSearchError);
});
helper.setState(mainParameters);
helper.search();
}
}
function handleSearchSuccess({ indexId }) {
return (event) => {
const state = store.getState();
const isDerivedHelpersEmpty = !helper.derivedHelpers.length;
let results = state.results ? state.results : {};
// Switching from mono index to multi index and vice versa must reset the
// results to an empty object, otherwise we keep reference of stalled and
// unused results.
results =
!isDerivedHelpersEmpty && results.getFacetByName ? {} : results;
if (!isDerivedHelpersEmpty) {
results = { ...results, [indexId]: event.results };
} else {
results = event.results;
}
const currentState = store.getState();
let nextIsSearchStalled = currentState.isSearchStalled;
if (!helper.hasPendingRequests()) {
clearTimeout(stalledSearchTimer);
stalledSearchTimer = null;
nextIsSearchStalled = false;
}
const { resultsFacetValues, ...partialState } = currentState;
store.setState({
...partialState,
results,
isSearchStalled: nextIsSearchStalled,
searching: false,
error: null,
});
};
}
function handleSearchError({ error }) {
const currentState = store.getState();
let nextIsSearchStalled = currentState.isSearchStalled;
if (!helper.hasPendingRequests()) {
clearTimeout(stalledSearchTimer);
nextIsSearchStalled = false;
}
const { resultsFacetValues, ...partialState } = currentState;
store.setState({
...partialState,
isSearchStalled: nextIsSearchStalled,
error,
searching: false,
});
}
function handleNewSearch() {
if (!stalledSearchTimer) {
stalledSearchTimer = setTimeout(() => {
const { resultsFacetValues, ...partialState } =
store.getState();
store.setState({
...partialState,
isSearchStalled: true,
});
}, stalledSearchDelay);
}
}
function hydrateSearchClient(client, results) {
if (!results) {
return;
}
// Disable cache hydration on:
// - Algoliasearch API Client < v4 with cache disabled
// - Third party clients (detected by the `addAlgoliaAgent` function missing)
if (
(!client.transporter || client._cacheHydrated) &&
(!client._useCache || typeof client.addAlgoliaAgent !== "function")
) {
return;
}
// Algoliasearch API Client >= v4
// To hydrate the client we need to populate the cache with the data from
// the server (done in `hydrateSearchClientWithMultiIndexRequest` or
// `hydrateSearchClientWithSingleIndexRequest`). But since there is no way
// for us to compute the key the same way as `algoliasearch-client` we need
// to populate it on a custom key and override the `search` method to
// search on it first.
if (client.transporter && !client._cacheHydrated) {
client._cacheHydrated = true;
const baseMethod = client.search;
client.search = (requests, ...methodArgs) => {
const requestsWithSerializedParams = requests.map(
(request) => ({
...request,
params: serializeQueryParameters(request.params),
})
);
return client.transporter.responsesCache.get(
{
method: "search",
args: [requestsWithSerializedParams, ...methodArgs],
},
() => {
return baseMethod(requests, ...methodArgs);
}
);
};
}
if (Array.isArray(results.results)) {
hydrateSearchClientWithMultiIndexRequest(client, results.results);
return;
}
hydrateSearchClientWithSingleIndexRequest(client, results);
}
function hydrateSearchClientWithMultiIndexRequest(client, results) {
// Algoliasearch API Client >= v4
// Populate the cache with the data from the server
if (client.transporter) {
client.transporter.responsesCache.set(
{
method: "search",
args: [
results.reduce(
(acc, result) =>
acc.concat(
result.rawResults.map((request) => ({
indexName: request.index,
params: request.params,
}))
),
[]
),
],
},
{
results: results.reduce(
(acc, result) => acc.concat(result.rawResults),
[]
),
}
);
return;
}
// Algoliasearch API Client < v4
// Prior to client v4 we didn't have a proper API to hydrate the client
// cache from the outside. The following code populates the cache with
// a single-index result. You can find more information about the
// computation of the key inside the client (see link below).
// https://github.com/algolia/algoliasearch-client-javascript/blob/c27e89ff92b2a854ae6f40dc524bffe0f0cbc169/src/AlgoliaSearchCore.js#L232-L240
const key = `/1/indexes/*/queries_body_${JSON.stringify({
requests: results.reduce(
(acc, result) =>
acc.concat(
result.rawResults.map((request) => ({
indexName: request.index,
params: request.params,
}))
),
[]
),
})}`;
client.cache = {
...client.cache,
[key]: JSON.stringify({
results: results.reduce(
(acc, result) => acc.concat(result.rawResults),
[]
),
}),
};
}
function hydrateSearchClientWithSingleIndexRequest(client, results) {
// Algoliasearch API Client >= v4
// Populate the cache with the data from the server
if (client.transporter) {
client.transporter.responsesCache.set(
{
method: "search",
args: [
results.rawResults.map((request) => ({
indexName: request.index,
params: request.params,
})),
],
},
{
results: results.rawResults,
}
);
return;
}
// Algoliasearch API Client < v4
// Prior to client v4 we didn't have a proper API to hydrate the client
// cache from the outside. The following code populates the cache with
// a single-index result. You can find more information about the
// computation of the key inside the client (see link below).
// https://github.com/algolia/algoliasearch-client-javascript/blob/c27e89ff92b2a854ae6f40dc524bffe0f0cbc169/src/AlgoliaSearchCore.js#L232-L240
const key = `/1/indexes/*/queries_body_${JSON.stringify({
requests: results.rawResults.map((request) => ({
indexName: request.index,
params: request.params,
})),
})}`;
client.cache = {
...client.cache,
[key]: JSON.stringify({
results: results.rawResults,
}),
};
}
function hydrateResultsState(results) {
if (!results) {
return null;
}
if (Array.isArray(results.results)) {
return results.results.reduce(
(acc, result) => ({
...acc,
[result._internalIndexId]:
new algoliasearchHelper.SearchResults(
new algoliasearchHelper.SearchParameters(
result.state
),
result.rawResults
),
}),
{}
);
}
return new algoliasearchHelper.SearchResults(
new algoliasearchHelper.SearchParameters(results.state),
results.rawResults
);
}
// Called whenever a widget has been rendered with new props.
function onWidgetsUpdate() {
const metadata = getMetadata(store.getState().widgets);
store.setState({
...store.getState(),
metadata,
searching: true,
});
// Since the `getSearchParameters` method of widgets also depends on props,
// the result search parameters might have changed.
search();
}
function transitionState(nextSearchState) {
const searchState = store.getState().widgets;
return widgetsManager
.getWidgets()
.filter((widget) => Boolean(widget.transitionState))
.reduce(
(res, widget) => widget.transitionState(searchState, res),
nextSearchState
);
}
function onExternalStateUpdate(nextSearchState) {
const metadata = getMetadata(nextSearchState);
store.setState({
...store.getState(),
widgets: nextSearchState,
metadata,
searching: true,
});
search();
}
function onSearchForFacetValues({ facetName, query, maxFacetHits = 10 }) {
// The values 1, 100 are the min / max values that the engine accepts.
// see: https://www.algolia.com/doc/api-reference/api-parameters/maxFacetHits
const maxFacetHitsWithinRange = Math.max(
1,
Math.min(maxFacetHits, 100)
);
store.setState({
...store.getState(),
searchingForFacetValues: true,
});
helper
.searchForFacetValues(facetName, query, maxFacetHitsWithinRange)
.then(
(content) => {
store.setState({
...store.getState(),
error: null,
searchingForFacetValues: false,
resultsFacetValues: {
...store.getState().resultsFacetValues,
[facetName]: content.facetHits,
query,
},
});
},
(error) => {
store.setState({
...store.getState(),
searchingForFacetValues: false,
error,
});
}
)
.catch((error) => {
// Since setState is synchronous, any error that occurs in the render of a
// component will be swallowed by this promise.
// This is a trick to make the error show up correctly in the console.
// See http://stackoverflow.com/a/30741722/969302
setTimeout(() => {
throw error;
});
});
}
function updateIndex(newIndex) {
initialSearchParameters = initialSearchParameters.setIndex(newIndex);
// No need to trigger a new search here as the widgets will also update and trigger it if needed.
}
function getWidgetsIds() {
return store
.getState()
.metadata.reduce(
(res, meta) =>
typeof meta.id !== "undefined" ? res.concat(meta.id) : res,
[]
);
}
return {
store,
widgetsManager,
getWidgetsIds,
getSearchParameters,
onSearchForFacetValues,
onExternalStateUpdate,
transitionState,
updateClient,
updateIndex,
clearCache,
skipSearch,
};
}
function hydrateMetadata(resultsState) {
if (!resultsState) {
return [];
}
// add a value noop, which gets replaced once the widgets are mounted
return resultsState.metadata.map((datum) => ({
value: () => ({}),
...datum,
items:
datum.items &&
datum.items.map((item) => ({
value: () => ({}),
...item,
items:
item.items &&
item.items.map((nestedItem) => ({
value: () => ({}),
...nestedItem,
})),
})),
}));
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_minifier/tests/fixture/issues/react-instancesearch/002/output.js | JavaScript | import algoliasearchHelper from "algoliasearch-helper";
import createWidgetsManager from "./createWidgetsManager";
import createStore from "./createStore";
import { HIGHLIGHT_TAGS } from "./highlight";
import { hasMultipleIndices } from "./indexUtils";
import { version as ReactVersion } from "react";
import version from "./version";
function addAlgoliaAgents(searchClient) {
"function" == typeof searchClient.addAlgoliaAgent && (searchClient.addAlgoliaAgent(`react (${ReactVersion})`), searchClient.addAlgoliaAgent(`react-instantsearch (${version})`));
}
const isMultiIndexContext = (widget)=>hasMultipleIndices({
ais: widget.props.contextValue,
multiIndexContext: widget.props.indexContextValue
}), isTargetedIndexEqualIndex = (widget, indexId)=>widget.props.indexContextValue.targetedIndex === indexId, isIndexWidget = (widget)=>!!widget.props.indexId, isIndexWidgetEqualIndex = (widget, indexId)=>widget.props.indexId === indexId, sortIndexWidgetsFirst = (firstWidget, secondWidget)=>{
const isFirstWidgetIndex = isIndexWidget(firstWidget), isSecondWidgetIndex = isIndexWidget(secondWidget);
return isFirstWidgetIndex && !isSecondWidgetIndex ? -1 : !isFirstWidgetIndex && isSecondWidgetIndex ? 1 : 0;
};
/**
* Creates a new instance of the InstantSearchManager which controls the widgets and
* trigger the search when the widgets are updated.
* @param {string} indexName - the main index name
* @param {object} initialState - initial widget state
* @param {object} SearchParameters - optional additional parameters to send to the algolia API
* @param {number} stalledSearchDelay - time (in ms) after the search is stalled
* @return {InstantSearchManager} a new instance of InstantSearchManager
*/ export default function createInstantSearchManager({ indexName, initialState = {}, searchClient, resultsState, stalledSearchDelay }) {
const helper = algoliasearchHelper(searchClient, indexName, {
...HIGHLIGHT_TAGS
});
addAlgoliaAgents(searchClient), helper.on("search", function() {
stalledSearchTimer || (stalledSearchTimer = setTimeout(()=>{
const { resultsFacetValues, ...partialState } = store.getState();
store.setState({
...partialState,
isSearchStalled: !0
});
}, stalledSearchDelay));
}).on("result", handleSearchSuccess({
indexId: indexName
})).on("error", handleSearchError);
let skip = !1, stalledSearchTimer = null, initialSearchParameters = helper.state;
const widgetsManager = createWidgetsManager(// Called whenever a widget has been rendered with new props.
function() {
const metadata = getMetadata(store.getState().widgets);
store.setState({
...store.getState(),
metadata,
searching: !0
}), // Since the `getSearchParameters` method of widgets also depends on props,
// the result search parameters might have changed.
search();
});
!function(client, results) {
if (results && (client.transporter && !client._cacheHydrated || client._useCache && "function" == typeof client.addAlgoliaAgent)) {
// Algoliasearch API Client >= v4
// To hydrate the client we need to populate the cache with the data from
// the server (done in `hydrateSearchClientWithMultiIndexRequest` or
// `hydrateSearchClientWithSingleIndexRequest`). But since there is no way
// for us to compute the key the same way as `algoliasearch-client` we need
// to populate it on a custom key and override the `search` method to
// search on it first.
if (client.transporter && !client._cacheHydrated) {
client._cacheHydrated = !0;
const baseMethod = client.search;
client.search = (requests, ...methodArgs)=>{
const requestsWithSerializedParams = requests.map((request)=>({
...request,
params: // This function is copied from the algoliasearch v4 API Client. If modified,
// consider updating it also in `serializeQueryParameters` from `@algolia/transporter`.
function(parameters) {
const isObjectOrArray = (value)=>"[object Object]" === Object.prototype.toString.call(value) || "[object Array]" === Object.prototype.toString.call(value), encode = (format, ...args)=>{
let i = 0;
return format.replace(/%s/g, ()=>encodeURIComponent(args[i++]));
};
return Object.keys(parameters).map((key)=>encode("%s=%s", key, isObjectOrArray(parameters[key]) ? JSON.stringify(parameters[key]) : parameters[key])).join("&");
}(request.params)
}));
return client.transporter.responsesCache.get({
method: "search",
args: [
requestsWithSerializedParams,
...methodArgs
]
}, ()=>baseMethod(requests, ...methodArgs));
};
}
if (Array.isArray(results.results)) {
!function(client, results) {
// Algoliasearch API Client >= v4
// Populate the cache with the data from the server
if (client.transporter) {
client.transporter.responsesCache.set({
method: "search",
args: [
results.reduce((acc, result)=>acc.concat(result.rawResults.map((request)=>({
indexName: request.index,
params: request.params
}))), [])
]
}, {
results: results.reduce((acc, result)=>acc.concat(result.rawResults), [])
});
return;
}
// Algoliasearch API Client < v4
// Prior to client v4 we didn't have a proper API to hydrate the client
// cache from the outside. The following code populates the cache with
// a single-index result. You can find more information about the
// computation of the key inside the client (see link below).
// https://github.com/algolia/algoliasearch-client-javascript/blob/c27e89ff92b2a854ae6f40dc524bffe0f0cbc169/src/AlgoliaSearchCore.js#L232-L240
const key = `/1/indexes/*/queries_body_${JSON.stringify({
requests: results.reduce((acc, result)=>acc.concat(result.rawResults.map((request)=>({
indexName: request.index,
params: request.params
}))), [])
})}`;
client.cache = {
...client.cache,
[key]: JSON.stringify({
results: results.reduce((acc, result)=>acc.concat(result.rawResults), [])
})
};
}(client, results.results);
return;
}
!function(client, results) {
// Algoliasearch API Client >= v4
// Populate the cache with the data from the server
if (client.transporter) {
client.transporter.responsesCache.set({
method: "search",
args: [
results.rawResults.map((request)=>({
indexName: request.index,
params: request.params
}))
]
}, {
results: results.rawResults
});
return;
}
// Algoliasearch API Client < v4
// Prior to client v4 we didn't have a proper API to hydrate the client
// cache from the outside. The following code populates the cache with
// a single-index result. You can find more information about the
// computation of the key inside the client (see link below).
// https://github.com/algolia/algoliasearch-client-javascript/blob/c27e89ff92b2a854ae6f40dc524bffe0f0cbc169/src/AlgoliaSearchCore.js#L232-L240
const key = `/1/indexes/*/queries_body_${JSON.stringify({
requests: results.rawResults.map((request)=>({
indexName: request.index,
params: request.params
}))
})}`;
client.cache = {
...client.cache,
[key]: JSON.stringify({
results: results.rawResults
})
};
}(client, results);
}
}(searchClient, resultsState);
const store = createStore({
widgets: initialState,
metadata: resultsState ? resultsState.metadata.map((datum)=>({
value: ()=>({}),
...datum,
items: datum.items && datum.items.map((item)=>({
value: ()=>({}),
...item,
items: item.items && item.items.map((nestedItem)=>({
value: ()=>({}),
...nestedItem
}))
}))
})) : [],
results: resultsState ? Array.isArray(resultsState.results) ? resultsState.results.reduce((acc, result)=>({
...acc,
[result._internalIndexId]: new algoliasearchHelper.SearchResults(new algoliasearchHelper.SearchParameters(result.state), result.rawResults)
}), {}) : new algoliasearchHelper.SearchResults(new algoliasearchHelper.SearchParameters(resultsState.state), resultsState.rawResults) : null,
error: null,
searching: !1,
isSearchStalled: !0,
searchingForFacetValues: !1
});
function getMetadata(state) {
return widgetsManager.getWidgets().filter((widget)=>!!widget.getMetadata).map((widget)=>widget.getMetadata(state));
}
function getSearchParameters() {
const sharedParameters = widgetsManager.getWidgets().filter((widget)=>!!widget.getSearchParameters).filter((widget)=>!isMultiIndexContext(widget) && !isIndexWidget(widget)).reduce((res, widget)=>widget.getSearchParameters(res), initialSearchParameters), mainParameters = widgetsManager.getWidgets().filter((widget)=>!!widget.getSearchParameters).filter((widget)=>{
const targetedIndexEqualMainIndex = isMultiIndexContext(widget) && isTargetedIndexEqualIndex(widget, indexName), subIndexEqualMainIndex = isIndexWidget(widget) && isIndexWidgetEqualIndex(widget, indexName);
return targetedIndexEqualMainIndex || subIndexEqualMainIndex;
})// We have to sort the `Index` widgets first so the `index` parameter
// is correctly set in the `reduce` function for the following widgets
.sort(sortIndexWidgetsFirst).reduce((res, widget)=>widget.getSearchParameters(res), sharedParameters), derivedIndices = widgetsManager.getWidgets().filter((widget)=>!!widget.getSearchParameters).filter((widget)=>{
const targetedIndexNotEqualMainIndex = isMultiIndexContext(widget) && !isTargetedIndexEqualIndex(widget, indexName), subIndexNotEqualMainIndex = isIndexWidget(widget) && !isIndexWidgetEqualIndex(widget, indexName);
return targetedIndexNotEqualMainIndex || subIndexNotEqualMainIndex;
})// We have to sort the `Index` widgets first so the `index` parameter
// is correctly set in the `reduce` function for the following widgets
.sort(sortIndexWidgetsFirst).reduce((indices, widget)=>{
const indexId = isMultiIndexContext(widget) ? widget.props.indexContextValue.targetedIndex : widget.props.indexId, widgets = indices[indexId] || [];
return {
...indices,
[indexId]: widgets.concat(widget)
};
}, {});
return {
mainParameters,
derivedParameters: Object.keys(derivedIndices).map((indexId)=>({
parameters: derivedIndices[indexId].reduce((res, widget)=>widget.getSearchParameters(res), sharedParameters),
indexId
}))
};
}
function search() {
if (!skip) {
const { mainParameters, derivedParameters } = getSearchParameters(helper.state);
// We have to call `slice` because the method `detach` on the derived
// helpers mutates the value `derivedHelpers`. The `forEach` loop does
// not iterate on each value and we're not able to correctly clear the
// previous derived helpers (memory leak + useless requests).
helper.derivedHelpers.slice().forEach((derivedHelper)=>{
// Since we detach the derived helpers on **every** new search they
// won't receive intermediate results in case of a stalled search.
// Only the last result is dispatched by the derived helper because
// they are not detached yet:
//
// - a -> main helper receives results
// - ap -> main helper receives results
// - app -> main helper + derived helpers receive results
//
// The quick fix is to avoid to detach them on search but only once they
// received the results. But it means that in case of a stalled search
// all the derived helpers not detached yet register a new search inside
// the helper. The number grows fast in case of a bad network and it's
// not deterministic.
derivedHelper.detach();
}), derivedParameters.forEach(({ indexId, parameters })=>{
helper.derive(()=>parameters).on("result", handleSearchSuccess({
indexId
})).on("error", handleSearchError);
}), helper.setState(mainParameters), helper.search();
}
}
function handleSearchSuccess({ indexId }) {
return (event)=>{
const state = store.getState(), isDerivedHelpersEmpty = !helper.derivedHelpers.length;
let results = state.results ? state.results : {};
// Switching from mono index to multi index and vice versa must reset the
// results to an empty object, otherwise we keep reference of stalled and
// unused results.
results = !isDerivedHelpersEmpty && results.getFacetByName ? {} : results, results = isDerivedHelpersEmpty ? event.results : {
...results,
[indexId]: event.results
};
const currentState = store.getState();
let nextIsSearchStalled = currentState.isSearchStalled;
helper.hasPendingRequests() || (clearTimeout(stalledSearchTimer), stalledSearchTimer = null, nextIsSearchStalled = !1);
const { resultsFacetValues, ...partialState } = currentState;
store.setState({
...partialState,
results,
isSearchStalled: nextIsSearchStalled,
searching: !1,
error: null
});
};
}
function handleSearchError({ error }) {
const currentState = store.getState();
let nextIsSearchStalled = currentState.isSearchStalled;
helper.hasPendingRequests() || (clearTimeout(stalledSearchTimer), nextIsSearchStalled = !1);
const { resultsFacetValues, ...partialState } = currentState;
store.setState({
...partialState,
isSearchStalled: nextIsSearchStalled,
error,
searching: !1
});
}
return {
store,
widgetsManager,
getWidgetsIds: function() {
return store.getState().metadata.reduce((res, meta)=>void 0 !== meta.id ? res.concat(meta.id) : res, []);
},
getSearchParameters,
onSearchForFacetValues: function({ facetName, query, maxFacetHits = 10 }) {
// The values 1, 100 are the min / max values that the engine accepts.
// see: https://www.algolia.com/doc/api-reference/api-parameters/maxFacetHits
const maxFacetHitsWithinRange = Math.max(1, Math.min(maxFacetHits, 100));
store.setState({
...store.getState(),
searchingForFacetValues: !0
}), helper.searchForFacetValues(facetName, query, maxFacetHitsWithinRange).then((content)=>{
store.setState({
...store.getState(),
error: null,
searchingForFacetValues: !1,
resultsFacetValues: {
...store.getState().resultsFacetValues,
[facetName]: content.facetHits,
query
}
});
}, (error)=>{
store.setState({
...store.getState(),
searchingForFacetValues: !1,
error
});
}).catch((error)=>{
// Since setState is synchronous, any error that occurs in the render of a
// component will be swallowed by this promise.
// This is a trick to make the error show up correctly in the console.
// See http://stackoverflow.com/a/30741722/969302
setTimeout(()=>{
throw error;
});
});
},
onExternalStateUpdate: function(nextSearchState) {
const metadata = getMetadata(nextSearchState);
store.setState({
...store.getState(),
widgets: nextSearchState,
metadata,
searching: !0
}), search();
},
transitionState: function(nextSearchState) {
const searchState = store.getState().widgets;
return widgetsManager.getWidgets().filter((widget)=>!!widget.transitionState).reduce((res, widget)=>widget.transitionState(searchState, res), nextSearchState);
},
updateClient: function(client) {
addAlgoliaAgents(client), helper.setClient(client), search();
},
updateIndex: function(newIndex) {
initialSearchParameters = initialSearchParameters.setIndex(newIndex);
// No need to trigger a new search here as the widgets will also update and trigger it if needed.
},
clearCache: function() {
helper.clearCache(), search();
},
skipSearch: function() {
skip = !0;
}
};
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_minifier/tests/fixture/issues/react-instancesearch/003/input.js | JavaScript | import algoliasearchHelper from "algoliasearch-helper";
import createStore from "./createStore";
import { HIGHLIGHT_TAGS } from "./highlight";
import { hasMultipleIndices } from "./indexUtils";
import { version as ReactVersion } from "react";
import version from "./version";
import { defer } from "./utils";
function createWidgetsManager(onWidgetsUpdate) {
const widgets = [];
// Is an update scheduled?
let scheduled = false;
// The state manager's updates need to be batched since more than one
// component can register or unregister widgets during the same tick.
function scheduleUpdate() {
if (scheduled) {
return;
}
scheduled = true;
defer(() => {
scheduled = false;
onWidgetsUpdate();
});
}
return {
registerWidget(widget) {
widgets.push(widget);
scheduleUpdate();
return function unregisterWidget() {
widgets.splice(widgets.indexOf(widget), 1);
scheduleUpdate();
};
},
update: scheduleUpdate,
getWidgets() {
return widgets;
},
};
}
function addAlgoliaAgents(searchClient) {
if (typeof searchClient.addAlgoliaAgent === "function") {
searchClient.addAlgoliaAgent(`react (${ReactVersion})`);
searchClient.addAlgoliaAgent(`react-instantsearch (${version})`);
}
}
const isMultiIndexContext = (widget) =>
hasMultipleIndices({
ais: widget.props.contextValue,
multiIndexContext: widget.props.indexContextValue,
});
const isTargetedIndexEqualIndex = (widget, indexId) =>
widget.props.indexContextValue.targetedIndex === indexId;
// Relying on the `indexId` is a bit brittle to detect the `Index` widget.
// Since it's a class we could rely on `instanceof` or similar. We never
// had an issue though. Works for now.
const isIndexWidget = (widget) => Boolean(widget.props.indexId);
const isIndexWidgetEqualIndex = (widget, indexId) =>
widget.props.indexId === indexId;
const sortIndexWidgetsFirst = (firstWidget, secondWidget) => {
const isFirstWidgetIndex = isIndexWidget(firstWidget);
const isSecondWidgetIndex = isIndexWidget(secondWidget);
if (isFirstWidgetIndex && !isSecondWidgetIndex) {
return -1;
}
if (!isFirstWidgetIndex && isSecondWidgetIndex) {
return 1;
}
return 0;
};
// This function is copied from the algoliasearch v4 API Client. If modified,
// consider updating it also in `serializeQueryParameters` from `@algolia/transporter`.
function serializeQueryParameters(parameters) {
const isObjectOrArray = (value) =>
Object.prototype.toString.call(value) === "[object Object]" ||
Object.prototype.toString.call(value) === "[object Array]";
const encode = (format, ...args) => {
let i = 0;
return format.replace(/%s/g, () => encodeURIComponent(args[i++]));
};
return Object.keys(parameters)
.map((key) =>
encode(
"%s=%s",
key,
isObjectOrArray(parameters[key])
? JSON.stringify(parameters[key])
: parameters[key]
)
)
.join("&");
}
/**
* Creates a new instance of the InstantSearchManager which controls the widgets and
* trigger the search when the widgets are updated.
* @param {string} indexName - the main index name
* @param {object} initialState - initial widget state
* @param {object} SearchParameters - optional additional parameters to send to the algolia API
* @param {number} stalledSearchDelay - time (in ms) after the search is stalled
* @return {InstantSearchManager} a new instance of InstantSearchManager
*/
export default function createInstantSearchManager({
indexName,
initialState = {},
searchClient,
resultsState,
stalledSearchDelay,
}) {
const helper = algoliasearchHelper(searchClient, indexName, {
...HIGHLIGHT_TAGS,
});
addAlgoliaAgents(searchClient);
helper
.on("search", handleNewSearch)
.on("result", handleSearchSuccess({ indexId: indexName }))
.on("error", handleSearchError);
let skip = false;
let stalledSearchTimer = null;
let initialSearchParameters = helper.state;
const widgetsManager = createWidgetsManager(onWidgetsUpdate);
hydrateSearchClient(searchClient, resultsState);
const store = createStore({
widgets: initialState,
metadata: hydrateMetadata(resultsState),
results: hydrateResultsState(resultsState),
error: null,
searching: false,
isSearchStalled: true,
searchingForFacetValues: false,
});
function skipSearch() {
skip = true;
}
function updateClient(client) {
addAlgoliaAgents(client);
helper.setClient(client);
search();
}
function clearCache() {
helper.clearCache();
search();
}
function getMetadata(state) {
return widgetsManager
.getWidgets()
.filter((widget) => Boolean(widget.getMetadata))
.map((widget) => widget.getMetadata(state));
}
function getSearchParameters() {
const sharedParameters = widgetsManager
.getWidgets()
.filter((widget) => Boolean(widget.getSearchParameters))
.filter(
(widget) =>
!isMultiIndexContext(widget) && !isIndexWidget(widget)
)
.reduce(
(res, widget) => widget.getSearchParameters(res),
initialSearchParameters
);
const mainParameters = widgetsManager
.getWidgets()
.filter((widget) => Boolean(widget.getSearchParameters))
.filter((widget) => {
const targetedIndexEqualMainIndex =
isMultiIndexContext(widget) &&
isTargetedIndexEqualIndex(widget, indexName);
const subIndexEqualMainIndex =
isIndexWidget(widget) &&
isIndexWidgetEqualIndex(widget, indexName);
return targetedIndexEqualMainIndex || subIndexEqualMainIndex;
})
// We have to sort the `Index` widgets first so the `index` parameter
// is correctly set in the `reduce` function for the following widgets
.sort(sortIndexWidgetsFirst)
.reduce(
(res, widget) => widget.getSearchParameters(res),
sharedParameters
);
const derivedIndices = widgetsManager
.getWidgets()
.filter((widget) => Boolean(widget.getSearchParameters))
.filter((widget) => {
const targetedIndexNotEqualMainIndex =
isMultiIndexContext(widget) &&
!isTargetedIndexEqualIndex(widget, indexName);
const subIndexNotEqualMainIndex =
isIndexWidget(widget) &&
!isIndexWidgetEqualIndex(widget, indexName);
return (
targetedIndexNotEqualMainIndex || subIndexNotEqualMainIndex
);
})
// We have to sort the `Index` widgets first so the `index` parameter
// is correctly set in the `reduce` function for the following widgets
.sort(sortIndexWidgetsFirst)
.reduce((indices, widget) => {
const indexId = isMultiIndexContext(widget)
? widget.props.indexContextValue.targetedIndex
: widget.props.indexId;
const widgets = indices[indexId] || [];
return {
...indices,
[indexId]: widgets.concat(widget),
};
}, {});
const derivedParameters = Object.keys(derivedIndices).map(
(indexId) => ({
parameters: derivedIndices[indexId].reduce(
(res, widget) => widget.getSearchParameters(res),
sharedParameters
),
indexId,
})
);
return {
mainParameters,
derivedParameters,
};
}
function search() {
if (!skip) {
const { mainParameters, derivedParameters } = getSearchParameters(
helper.state
);
// We have to call `slice` because the method `detach` on the derived
// helpers mutates the value `derivedHelpers`. The `forEach` loop does
// not iterate on each value and we're not able to correctly clear the
// previous derived helpers (memory leak + useless requests).
helper.derivedHelpers.slice().forEach((derivedHelper) => {
// Since we detach the derived helpers on **every** new search they
// won't receive intermediate results in case of a stalled search.
// Only the last result is dispatched by the derived helper because
// they are not detached yet:
//
// - a -> main helper receives results
// - ap -> main helper receives results
// - app -> main helper + derived helpers receive results
//
// The quick fix is to avoid to detach them on search but only once they
// received the results. But it means that in case of a stalled search
// all the derived helpers not detached yet register a new search inside
// the helper. The number grows fast in case of a bad network and it's
// not deterministic.
derivedHelper.detach();
});
derivedParameters.forEach(({ indexId, parameters }) => {
const derivedHelper = helper.derive(() => parameters);
derivedHelper
.on("result", handleSearchSuccess({ indexId }))
.on("error", handleSearchError);
});
helper.setState(mainParameters);
helper.search();
}
}
function handleSearchSuccess({ indexId }) {
return (event) => {
const state = store.getState();
const isDerivedHelpersEmpty = !helper.derivedHelpers.length;
let results = state.results ? state.results : {};
// Switching from mono index to multi index and vice versa must reset the
// results to an empty object, otherwise we keep reference of stalled and
// unused results.
results =
!isDerivedHelpersEmpty && results.getFacetByName ? {} : results;
if (!isDerivedHelpersEmpty) {
results = { ...results, [indexId]: event.results };
} else {
results = event.results;
}
const currentState = store.getState();
let nextIsSearchStalled = currentState.isSearchStalled;
if (!helper.hasPendingRequests()) {
clearTimeout(stalledSearchTimer);
stalledSearchTimer = null;
nextIsSearchStalled = false;
}
const { resultsFacetValues, ...partialState } = currentState;
store.setState({
...partialState,
results,
isSearchStalled: nextIsSearchStalled,
searching: false,
error: null,
});
};
}
function handleSearchError({ error }) {
const currentState = store.getState();
let nextIsSearchStalled = currentState.isSearchStalled;
if (!helper.hasPendingRequests()) {
clearTimeout(stalledSearchTimer);
nextIsSearchStalled = false;
}
const { resultsFacetValues, ...partialState } = currentState;
store.setState({
...partialState,
isSearchStalled: nextIsSearchStalled,
error,
searching: false,
});
}
function handleNewSearch() {
if (!stalledSearchTimer) {
stalledSearchTimer = setTimeout(() => {
const { resultsFacetValues, ...partialState } =
store.getState();
store.setState({
...partialState,
isSearchStalled: true,
});
}, stalledSearchDelay);
}
}
function hydrateSearchClient(client, results) {
if (!results) {
return;
}
// Disable cache hydration on:
// - Algoliasearch API Client < v4 with cache disabled
// - Third party clients (detected by the `addAlgoliaAgent` function missing)
if (
(!client.transporter || client._cacheHydrated) &&
(!client._useCache || typeof client.addAlgoliaAgent !== "function")
) {
return;
}
// Algoliasearch API Client >= v4
// To hydrate the client we need to populate the cache with the data from
// the server (done in `hydrateSearchClientWithMultiIndexRequest` or
// `hydrateSearchClientWithSingleIndexRequest`). But since there is no way
// for us to compute the key the same way as `algoliasearch-client` we need
// to populate it on a custom key and override the `search` method to
// search on it first.
if (client.transporter && !client._cacheHydrated) {
client._cacheHydrated = true;
const baseMethod = client.search;
client.search = (requests, ...methodArgs) => {
const requestsWithSerializedParams = requests.map(
(request) => ({
...request,
params: serializeQueryParameters(request.params),
})
);
return client.transporter.responsesCache.get(
{
method: "search",
args: [requestsWithSerializedParams, ...methodArgs],
},
() => {
return baseMethod(requests, ...methodArgs);
}
);
};
}
if (Array.isArray(results.results)) {
hydrateSearchClientWithMultiIndexRequest(client, results.results);
return;
}
hydrateSearchClientWithSingleIndexRequest(client, results);
}
function hydrateSearchClientWithMultiIndexRequest(client, results) {
// Algoliasearch API Client >= v4
// Populate the cache with the data from the server
if (client.transporter) {
client.transporter.responsesCache.set(
{
method: "search",
args: [
results.reduce(
(acc, result) =>
acc.concat(
result.rawResults.map((request) => ({
indexName: request.index,
params: request.params,
}))
),
[]
),
],
},
{
results: results.reduce(
(acc, result) => acc.concat(result.rawResults),
[]
),
}
);
return;
}
// Algoliasearch API Client < v4
// Prior to client v4 we didn't have a proper API to hydrate the client
// cache from the outside. The following code populates the cache with
// a single-index result. You can find more information about the
// computation of the key inside the client (see link below).
// https://github.com/algolia/algoliasearch-client-javascript/blob/c27e89ff92b2a854ae6f40dc524bffe0f0cbc169/src/AlgoliaSearchCore.js#L232-L240
const key = `/1/indexes/*/queries_body_${JSON.stringify({
requests: results.reduce(
(acc, result) =>
acc.concat(
result.rawResults.map((request) => ({
indexName: request.index,
params: request.params,
}))
),
[]
),
})}`;
client.cache = {
...client.cache,
[key]: JSON.stringify({
results: results.reduce(
(acc, result) => acc.concat(result.rawResults),
[]
),
}),
};
}
function hydrateSearchClientWithSingleIndexRequest(client, results) {
// Algoliasearch API Client >= v4
// Populate the cache with the data from the server
if (client.transporter) {
client.transporter.responsesCache.set(
{
method: "search",
args: [
results.rawResults.map((request) => ({
indexName: request.index,
params: request.params,
})),
],
},
{
results: results.rawResults,
}
);
return;
}
// Algoliasearch API Client < v4
// Prior to client v4 we didn't have a proper API to hydrate the client
// cache from the outside. The following code populates the cache with
// a single-index result. You can find more information about the
// computation of the key inside the client (see link below).
// https://github.com/algolia/algoliasearch-client-javascript/blob/c27e89ff92b2a854ae6f40dc524bffe0f0cbc169/src/AlgoliaSearchCore.js#L232-L240
const key = `/1/indexes/*/queries_body_${JSON.stringify({
requests: results.rawResults.map((request) => ({
indexName: request.index,
params: request.params,
})),
})}`;
client.cache = {
...client.cache,
[key]: JSON.stringify({
results: results.rawResults,
}),
};
}
function hydrateResultsState(results) {
if (!results) {
return null;
}
if (Array.isArray(results.results)) {
return results.results.reduce(
(acc, result) => ({
...acc,
[result._internalIndexId]:
new algoliasearchHelper.SearchResults(
new algoliasearchHelper.SearchParameters(
result.state
),
result.rawResults
),
}),
{}
);
}
return new algoliasearchHelper.SearchResults(
new algoliasearchHelper.SearchParameters(results.state),
results.rawResults
);
}
// Called whenever a widget has been rendered with new props.
function onWidgetsUpdate() {
const metadata = getMetadata(store.getState().widgets);
store.setState({
...store.getState(),
metadata,
searching: true,
});
// Since the `getSearchParameters` method of widgets also depends on props,
// the result search parameters might have changed.
search();
}
function transitionState(nextSearchState) {
const searchState = store.getState().widgets;
return widgetsManager
.getWidgets()
.filter((widget) => Boolean(widget.transitionState))
.reduce(
(res, widget) => widget.transitionState(searchState, res),
nextSearchState
);
}
function onExternalStateUpdate(nextSearchState) {
const metadata = getMetadata(nextSearchState);
store.setState({
...store.getState(),
widgets: nextSearchState,
metadata,
searching: true,
});
search();
}
function onSearchForFacetValues({ facetName, query, maxFacetHits = 10 }) {
// The values 1, 100 are the min / max values that the engine accepts.
// see: https://www.algolia.com/doc/api-reference/api-parameters/maxFacetHits
const maxFacetHitsWithinRange = Math.max(
1,
Math.min(maxFacetHits, 100)
);
store.setState({
...store.getState(),
searchingForFacetValues: true,
});
helper
.searchForFacetValues(facetName, query, maxFacetHitsWithinRange)
.then(
(content) => {
store.setState({
...store.getState(),
error: null,
searchingForFacetValues: false,
resultsFacetValues: {
...store.getState().resultsFacetValues,
[facetName]: content.facetHits,
query,
},
});
},
(error) => {
store.setState({
...store.getState(),
searchingForFacetValues: false,
error,
});
}
)
.catch((error) => {
// Since setState is synchronous, any error that occurs in the render of a
// component will be swallowed by this promise.
// This is a trick to make the error show up correctly in the console.
// See http://stackoverflow.com/a/30741722/969302
setTimeout(() => {
throw error;
});
});
}
function updateIndex(newIndex) {
initialSearchParameters = initialSearchParameters.setIndex(newIndex);
// No need to trigger a new search here as the widgets will also update and trigger it if needed.
}
function getWidgetsIds() {
return store
.getState()
.metadata.reduce(
(res, meta) =>
typeof meta.id !== "undefined" ? res.concat(meta.id) : res,
[]
);
}
return {
store,
widgetsManager,
getWidgetsIds,
getSearchParameters,
onSearchForFacetValues,
onExternalStateUpdate,
transitionState,
updateClient,
updateIndex,
clearCache,
skipSearch,
};
}
function hydrateMetadata(resultsState) {
if (!resultsState) {
return [];
}
// add a value noop, which gets replaced once the widgets are mounted
return resultsState.metadata.map((datum) => ({
value: () => ({}),
...datum,
items:
datum.items &&
datum.items.map((item) => ({
value: () => ({}),
...item,
items:
item.items &&
item.items.map((nestedItem) => ({
value: () => ({}),
...nestedItem,
})),
})),
}));
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_minifier/tests/fixture/issues/react-instancesearch/003/output.js | JavaScript | import algoliasearchHelper from "algoliasearch-helper";
import createStore from "./createStore";
import { HIGHLIGHT_TAGS } from "./highlight";
import { hasMultipleIndices } from "./indexUtils";
import { version as ReactVersion } from "react";
import version from "./version";
import { defer } from "./utils";
function addAlgoliaAgents(searchClient) {
"function" == typeof searchClient.addAlgoliaAgent && (searchClient.addAlgoliaAgent(`react (${ReactVersion})`), searchClient.addAlgoliaAgent(`react-instantsearch (${version})`));
}
const isMultiIndexContext = (widget)=>hasMultipleIndices({
ais: widget.props.contextValue,
multiIndexContext: widget.props.indexContextValue
}), isTargetedIndexEqualIndex = (widget, indexId)=>widget.props.indexContextValue.targetedIndex === indexId, isIndexWidget = (widget)=>!!widget.props.indexId, isIndexWidgetEqualIndex = (widget, indexId)=>widget.props.indexId === indexId, sortIndexWidgetsFirst = (firstWidget, secondWidget)=>{
const isFirstWidgetIndex = isIndexWidget(firstWidget), isSecondWidgetIndex = isIndexWidget(secondWidget);
return isFirstWidgetIndex && !isSecondWidgetIndex ? -1 : !isFirstWidgetIndex && isSecondWidgetIndex ? 1 : 0;
};
/**
* Creates a new instance of the InstantSearchManager which controls the widgets and
* trigger the search when the widgets are updated.
* @param {string} indexName - the main index name
* @param {object} initialState - initial widget state
* @param {object} SearchParameters - optional additional parameters to send to the algolia API
* @param {number} stalledSearchDelay - time (in ms) after the search is stalled
* @return {InstantSearchManager} a new instance of InstantSearchManager
*/ export default function createInstantSearchManager({ indexName, initialState = {}, searchClient, resultsState, stalledSearchDelay }) {
const helper = algoliasearchHelper(searchClient, indexName, {
...HIGHLIGHT_TAGS
});
addAlgoliaAgents(searchClient), helper.on("search", function() {
stalledSearchTimer || (stalledSearchTimer = setTimeout(()=>{
const { resultsFacetValues, ...partialState } = store.getState();
store.setState({
...partialState,
isSearchStalled: !0
});
}, stalledSearchDelay));
}).on("result", handleSearchSuccess({
indexId: indexName
})).on("error", handleSearchError);
let skip = !1, stalledSearchTimer = null, initialSearchParameters = helper.state;
const widgetsManager = function(onWidgetsUpdate) {
const widgets = [];
// Is an update scheduled?
let scheduled = !1;
// The state manager's updates need to be batched since more than one
// component can register or unregister widgets during the same tick.
function scheduleUpdate() {
scheduled || (scheduled = !0, defer(()=>{
scheduled = !1, onWidgetsUpdate();
}));
}
return {
registerWidget: (widget)=>(widgets.push(widget), scheduleUpdate(), function() {
widgets.splice(widgets.indexOf(widget), 1), scheduleUpdate();
}),
update: scheduleUpdate,
getWidgets: ()=>widgets
};
}(// Called whenever a widget has been rendered with new props.
function() {
const metadata = getMetadata(store.getState().widgets);
store.setState({
...store.getState(),
metadata,
searching: !0
}), // Since the `getSearchParameters` method of widgets also depends on props,
// the result search parameters might have changed.
search();
});
!function(client, results) {
if (results && (client.transporter && !client._cacheHydrated || client._useCache && "function" == typeof client.addAlgoliaAgent)) {
// Algoliasearch API Client >= v4
// To hydrate the client we need to populate the cache with the data from
// the server (done in `hydrateSearchClientWithMultiIndexRequest` or
// `hydrateSearchClientWithSingleIndexRequest`). But since there is no way
// for us to compute the key the same way as `algoliasearch-client` we need
// to populate it on a custom key and override the `search` method to
// search on it first.
if (client.transporter && !client._cacheHydrated) {
client._cacheHydrated = !0;
const baseMethod = client.search;
client.search = (requests, ...methodArgs)=>{
const requestsWithSerializedParams = requests.map((request)=>({
...request,
params: // This function is copied from the algoliasearch v4 API Client. If modified,
// consider updating it also in `serializeQueryParameters` from `@algolia/transporter`.
function(parameters) {
const isObjectOrArray = (value)=>"[object Object]" === Object.prototype.toString.call(value) || "[object Array]" === Object.prototype.toString.call(value), encode = (format, ...args)=>{
let i = 0;
return format.replace(/%s/g, ()=>encodeURIComponent(args[i++]));
};
return Object.keys(parameters).map((key)=>encode("%s=%s", key, isObjectOrArray(parameters[key]) ? JSON.stringify(parameters[key]) : parameters[key])).join("&");
}(request.params)
}));
return client.transporter.responsesCache.get({
method: "search",
args: [
requestsWithSerializedParams,
...methodArgs
]
}, ()=>baseMethod(requests, ...methodArgs));
};
}
if (Array.isArray(results.results)) {
!function(client, results) {
// Algoliasearch API Client >= v4
// Populate the cache with the data from the server
if (client.transporter) {
client.transporter.responsesCache.set({
method: "search",
args: [
results.reduce((acc, result)=>acc.concat(result.rawResults.map((request)=>({
indexName: request.index,
params: request.params
}))), [])
]
}, {
results: results.reduce((acc, result)=>acc.concat(result.rawResults), [])
});
return;
}
// Algoliasearch API Client < v4
// Prior to client v4 we didn't have a proper API to hydrate the client
// cache from the outside. The following code populates the cache with
// a single-index result. You can find more information about the
// computation of the key inside the client (see link below).
// https://github.com/algolia/algoliasearch-client-javascript/blob/c27e89ff92b2a854ae6f40dc524bffe0f0cbc169/src/AlgoliaSearchCore.js#L232-L240
const key = `/1/indexes/*/queries_body_${JSON.stringify({
requests: results.reduce((acc, result)=>acc.concat(result.rawResults.map((request)=>({
indexName: request.index,
params: request.params
}))), [])
})}`;
client.cache = {
...client.cache,
[key]: JSON.stringify({
results: results.reduce((acc, result)=>acc.concat(result.rawResults), [])
})
};
}(client, results.results);
return;
}
!function(client, results) {
// Algoliasearch API Client >= v4
// Populate the cache with the data from the server
if (client.transporter) {
client.transporter.responsesCache.set({
method: "search",
args: [
results.rawResults.map((request)=>({
indexName: request.index,
params: request.params
}))
]
}, {
results: results.rawResults
});
return;
}
// Algoliasearch API Client < v4
// Prior to client v4 we didn't have a proper API to hydrate the client
// cache from the outside. The following code populates the cache with
// a single-index result. You can find more information about the
// computation of the key inside the client (see link below).
// https://github.com/algolia/algoliasearch-client-javascript/blob/c27e89ff92b2a854ae6f40dc524bffe0f0cbc169/src/AlgoliaSearchCore.js#L232-L240
const key = `/1/indexes/*/queries_body_${JSON.stringify({
requests: results.rawResults.map((request)=>({
indexName: request.index,
params: request.params
}))
})}`;
client.cache = {
...client.cache,
[key]: JSON.stringify({
results: results.rawResults
})
};
}(client, results);
}
}(searchClient, resultsState);
const store = createStore({
widgets: initialState,
metadata: resultsState ? resultsState.metadata.map((datum)=>({
value: ()=>({}),
...datum,
items: datum.items && datum.items.map((item)=>({
value: ()=>({}),
...item,
items: item.items && item.items.map((nestedItem)=>({
value: ()=>({}),
...nestedItem
}))
}))
})) : [],
results: resultsState ? Array.isArray(resultsState.results) ? resultsState.results.reduce((acc, result)=>({
...acc,
[result._internalIndexId]: new algoliasearchHelper.SearchResults(new algoliasearchHelper.SearchParameters(result.state), result.rawResults)
}), {}) : new algoliasearchHelper.SearchResults(new algoliasearchHelper.SearchParameters(resultsState.state), resultsState.rawResults) : null,
error: null,
searching: !1,
isSearchStalled: !0,
searchingForFacetValues: !1
});
function getMetadata(state) {
return widgetsManager.getWidgets().filter((widget)=>!!widget.getMetadata).map((widget)=>widget.getMetadata(state));
}
function getSearchParameters() {
const sharedParameters = widgetsManager.getWidgets().filter((widget)=>!!widget.getSearchParameters).filter((widget)=>!isMultiIndexContext(widget) && !isIndexWidget(widget)).reduce((res, widget)=>widget.getSearchParameters(res), initialSearchParameters), mainParameters = widgetsManager.getWidgets().filter((widget)=>!!widget.getSearchParameters).filter((widget)=>{
const targetedIndexEqualMainIndex = isMultiIndexContext(widget) && isTargetedIndexEqualIndex(widget, indexName), subIndexEqualMainIndex = isIndexWidget(widget) && isIndexWidgetEqualIndex(widget, indexName);
return targetedIndexEqualMainIndex || subIndexEqualMainIndex;
})// We have to sort the `Index` widgets first so the `index` parameter
// is correctly set in the `reduce` function for the following widgets
.sort(sortIndexWidgetsFirst).reduce((res, widget)=>widget.getSearchParameters(res), sharedParameters), derivedIndices = widgetsManager.getWidgets().filter((widget)=>!!widget.getSearchParameters).filter((widget)=>{
const targetedIndexNotEqualMainIndex = isMultiIndexContext(widget) && !isTargetedIndexEqualIndex(widget, indexName), subIndexNotEqualMainIndex = isIndexWidget(widget) && !isIndexWidgetEqualIndex(widget, indexName);
return targetedIndexNotEqualMainIndex || subIndexNotEqualMainIndex;
})// We have to sort the `Index` widgets first so the `index` parameter
// is correctly set in the `reduce` function for the following widgets
.sort(sortIndexWidgetsFirst).reduce((indices, widget)=>{
const indexId = isMultiIndexContext(widget) ? widget.props.indexContextValue.targetedIndex : widget.props.indexId, widgets = indices[indexId] || [];
return {
...indices,
[indexId]: widgets.concat(widget)
};
}, {});
return {
mainParameters,
derivedParameters: Object.keys(derivedIndices).map((indexId)=>({
parameters: derivedIndices[indexId].reduce((res, widget)=>widget.getSearchParameters(res), sharedParameters),
indexId
}))
};
}
function search() {
if (!skip) {
const { mainParameters, derivedParameters } = getSearchParameters(helper.state);
// We have to call `slice` because the method `detach` on the derived
// helpers mutates the value `derivedHelpers`. The `forEach` loop does
// not iterate on each value and we're not able to correctly clear the
// previous derived helpers (memory leak + useless requests).
helper.derivedHelpers.slice().forEach((derivedHelper)=>{
// Since we detach the derived helpers on **every** new search they
// won't receive intermediate results in case of a stalled search.
// Only the last result is dispatched by the derived helper because
// they are not detached yet:
//
// - a -> main helper receives results
// - ap -> main helper receives results
// - app -> main helper + derived helpers receive results
//
// The quick fix is to avoid to detach them on search but only once they
// received the results. But it means that in case of a stalled search
// all the derived helpers not detached yet register a new search inside
// the helper. The number grows fast in case of a bad network and it's
// not deterministic.
derivedHelper.detach();
}), derivedParameters.forEach(({ indexId, parameters })=>{
helper.derive(()=>parameters).on("result", handleSearchSuccess({
indexId
})).on("error", handleSearchError);
}), helper.setState(mainParameters), helper.search();
}
}
function handleSearchSuccess({ indexId }) {
return (event)=>{
const state = store.getState(), isDerivedHelpersEmpty = !helper.derivedHelpers.length;
let results = state.results ? state.results : {};
// Switching from mono index to multi index and vice versa must reset the
// results to an empty object, otherwise we keep reference of stalled and
// unused results.
results = !isDerivedHelpersEmpty && results.getFacetByName ? {} : results, results = isDerivedHelpersEmpty ? event.results : {
...results,
[indexId]: event.results
};
const currentState = store.getState();
let nextIsSearchStalled = currentState.isSearchStalled;
helper.hasPendingRequests() || (clearTimeout(stalledSearchTimer), stalledSearchTimer = null, nextIsSearchStalled = !1);
const { resultsFacetValues, ...partialState } = currentState;
store.setState({
...partialState,
results,
isSearchStalled: nextIsSearchStalled,
searching: !1,
error: null
});
};
}
function handleSearchError({ error }) {
const currentState = store.getState();
let nextIsSearchStalled = currentState.isSearchStalled;
helper.hasPendingRequests() || (clearTimeout(stalledSearchTimer), nextIsSearchStalled = !1);
const { resultsFacetValues, ...partialState } = currentState;
store.setState({
...partialState,
isSearchStalled: nextIsSearchStalled,
error,
searching: !1
});
}
return {
store,
widgetsManager,
getWidgetsIds: function() {
return store.getState().metadata.reduce((res, meta)=>void 0 !== meta.id ? res.concat(meta.id) : res, []);
},
getSearchParameters,
onSearchForFacetValues: function({ facetName, query, maxFacetHits = 10 }) {
// The values 1, 100 are the min / max values that the engine accepts.
// see: https://www.algolia.com/doc/api-reference/api-parameters/maxFacetHits
const maxFacetHitsWithinRange = Math.max(1, Math.min(maxFacetHits, 100));
store.setState({
...store.getState(),
searchingForFacetValues: !0
}), helper.searchForFacetValues(facetName, query, maxFacetHitsWithinRange).then((content)=>{
store.setState({
...store.getState(),
error: null,
searchingForFacetValues: !1,
resultsFacetValues: {
...store.getState().resultsFacetValues,
[facetName]: content.facetHits,
query
}
});
}, (error)=>{
store.setState({
...store.getState(),
searchingForFacetValues: !1,
error
});
}).catch((error)=>{
// Since setState is synchronous, any error that occurs in the render of a
// component will be swallowed by this promise.
// This is a trick to make the error show up correctly in the console.
// See http://stackoverflow.com/a/30741722/969302
setTimeout(()=>{
throw error;
});
});
},
onExternalStateUpdate: function(nextSearchState) {
const metadata = getMetadata(nextSearchState);
store.setState({
...store.getState(),
widgets: nextSearchState,
metadata,
searching: !0
}), search();
},
transitionState: function(nextSearchState) {
const searchState = store.getState().widgets;
return widgetsManager.getWidgets().filter((widget)=>!!widget.transitionState).reduce((res, widget)=>widget.transitionState(searchState, res), nextSearchState);
},
updateClient: function(client) {
addAlgoliaAgents(client), helper.setClient(client), search();
},
updateIndex: function(newIndex) {
initialSearchParameters = initialSearchParameters.setIndex(newIndex);
// No need to trigger a new search here as the widgets will also update and trigger it if needed.
},
clearCache: function() {
helper.clearCache(), search();
},
skipSearch: function() {
skip = !0;
}
};
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_minifier/tests/fixture/issues/react-instancesearch/004/input.js | JavaScript | import * as swcHelpers from "@swc/helpers";
import algoliasearchHelper from "algoliasearch-helper";
import createWidgetsManager from "./createWidgetsManager";
import { HIGHLIGHT_TAGS } from "./highlight";
import { hasMultipleIndices } from "./indexUtils";
import { version as ReactVersion } from "react";
import version from "./version";
function addAlgoliaAgents(searchClient) {
if (typeof searchClient.addAlgoliaAgent === "function") {
searchClient.addAlgoliaAgent("react (".concat(ReactVersion, ")"));
searchClient.addAlgoliaAgent(
"react-instantsearch (".concat(version, ")")
);
}
}
var isMultiIndexContext = function (widget) {
return hasMultipleIndices({
ais: widget.props.contextValue,
multiIndexContext: widget.props.indexContextValue,
});
};
var isTargetedIndexEqualIndex = function (widget, indexId) {
return widget.props.indexContextValue.targetedIndex === indexId;
};
// Relying on the `indexId` is a bit brittle to detect the `Index` widget.
// Since it's a class we could rely on `instanceof` or similar. We never
// had an issue though. Works for now.
var isIndexWidget = function (widget) {
return Boolean(widget.props.indexId);
};
var isIndexWidgetEqualIndex = function (widget, indexId) {
return widget.props.indexId === indexId;
};
var sortIndexWidgetsFirst = function (firstWidget, secondWidget) {
var isFirstWidgetIndex = isIndexWidget(firstWidget);
var isSecondWidgetIndex = isIndexWidget(secondWidget);
if (isFirstWidgetIndex && !isSecondWidgetIndex) {
return -1;
}
if (!isFirstWidgetIndex && isSecondWidgetIndex) {
return 1;
}
return 0;
};
// This function is copied from the algoliasearch v4 API Client. If modified,
// consider updating it also in `serializeQueryParameters` from `@algolia/transporter`.
function serializeQueryParameters(parameters) {
var isObjectOrArray = function (value) {
return (
Object.prototype.toString.call(value) === "[object Object]" ||
Object.prototype.toString.call(value) === "[object Array]"
);
};
var encode = function (format) {
for (
var _len = arguments.length,
args = new Array(_len > 1 ? _len - 1 : 0),
_key = 1;
_key < _len;
_key++
) {
args[_key - 1] = arguments[_key];
}
var i = 0;
return format.replace(/%s/g, function () {
return encodeURIComponent(args[i++]);
});
};
return Object.keys(parameters)
.map(function (key) {
return encode(
"%s=%s",
key,
isObjectOrArray(parameters[key])
? JSON.stringify(parameters[key])
: parameters[key]
);
})
.join("&");
}
var _obj;
/**
* Creates a new instance of the InstantSearchManager which controls the widgets and
* trigger the search when the widgets are updated.
* @param {string} indexName - the main index name
* @param {object} initialState - initial widget state
* @param {object} SearchParameters - optional additional parameters to send to the algolia API
* @param {number} stalledSearchDelay - time (in ms) after the search is stalled
* @return {InstantSearchManager} a new instance of InstantSearchManager
*/ export default function createInstantSearchManager(param) {
var indexName = param.indexName,
_initialState = param.initialState,
initialState = _initialState === void 0 ? {} : _initialState,
searchClient = param.searchClient,
resultsState = param.resultsState,
stalledSearchDelay = param.stalledSearchDelay;
var createStore = function createStore(initialState) {
var state = initialState;
var listeners = [];
return {
getState: function () {
return state;
},
setState: function (nextState) {
state = nextState;
listeners.forEach(function (listener) {
return listener();
});
},
subscribe: function (listener) {
listeners.push(listener);
return function unsubscribe() {
listeners.splice(listeners.indexOf(listener), 1);
};
},
};
};
var skipSearch = function skipSearch() {
skip = true;
};
var updateClient = function updateClient(client) {
addAlgoliaAgents(client);
helper.setClient(client);
search();
};
var clearCache = function clearCache() {
helper.clearCache();
search();
};
var getMetadata = function getMetadata(state) {
return widgetsManager
.getWidgets()
.filter(function (widget) {
return Boolean(widget.getMetadata);
})
.map(function (widget) {
return widget.getMetadata(state);
});
};
var getSearchParameters = function getSearchParameters() {
var sharedParameters = widgetsManager
.getWidgets()
.filter(function (widget) {
return Boolean(widget.getSearchParameters);
})
.filter(function (widget) {
return !isMultiIndexContext(widget) && !isIndexWidget(widget);
})
.reduce(function (res, widget) {
return widget.getSearchParameters(res);
}, initialSearchParameters);
var mainParameters = widgetsManager
.getWidgets()
.filter(function (widget) {
return Boolean(widget.getSearchParameters);
})
.filter(function (widget) {
var targetedIndexEqualMainIndex =
isMultiIndexContext(widget) &&
isTargetedIndexEqualIndex(widget, indexName);
var subIndexEqualMainIndex =
isIndexWidget(widget) &&
isIndexWidgetEqualIndex(widget, indexName);
return targetedIndexEqualMainIndex || subIndexEqualMainIndex;
}) // We have to sort the `Index` widgets first so the `index` parameter
// is correctly set in the `reduce` function for the following widgets
.sort(sortIndexWidgetsFirst)
.reduce(function (res, widget) {
return widget.getSearchParameters(res);
}, sharedParameters);
var derivedIndices = widgetsManager
.getWidgets()
.filter(function (widget) {
return Boolean(widget.getSearchParameters);
})
.filter(function (widget) {
var targetedIndexNotEqualMainIndex =
isMultiIndexContext(widget) &&
!isTargetedIndexEqualIndex(widget, indexName);
var subIndexNotEqualMainIndex =
isIndexWidget(widget) &&
!isIndexWidgetEqualIndex(widget, indexName);
return (
targetedIndexNotEqualMainIndex || subIndexNotEqualMainIndex
);
}) // We have to sort the `Index` widgets first so the `index` parameter
// is correctly set in the `reduce` function for the following widgets
.sort(sortIndexWidgetsFirst)
.reduce(function (indices, widget) {
var indexId = isMultiIndexContext(widget)
? widget.props.indexContextValue.targetedIndex
: widget.props.indexId;
var widgets = indices[indexId] || [];
return swcHelpers.objectSpread(
{},
indices,
swcHelpers.defineProperty(
{},
indexId,
widgets.concat(widget)
)
);
}, {});
var derivedParameters = Object.keys(derivedIndices).map(function (
indexId
) {
return {
parameters: derivedIndices[indexId].reduce(function (
res,
widget
) {
return widget.getSearchParameters(res);
},
sharedParameters),
indexId: indexId,
};
});
return {
mainParameters: mainParameters,
derivedParameters: derivedParameters,
};
};
var search = function search() {
if (!skip) {
var ref = getSearchParameters(helper.state),
mainParameters = ref.mainParameters,
derivedParameters = ref.derivedParameters;
// We have to call `slice` because the method `detach` on the derived
// helpers mutates the value `derivedHelpers`. The `forEach` loop does
// not iterate on each value and we're not able to correctly clear the
// previous derived helpers (memory leak + useless requests).
helper.derivedHelpers.slice().forEach(function (derivedHelper) {
// Since we detach the derived helpers on **every** new search they
// won't receive intermediate results in case of a stalled search.
// Only the last result is dispatched by the derived helper because
// they are not detached yet:
//
// - a -> main helper receives results
// - ap -> main helper receives results
// - app -> main helper + derived helpers receive results
//
// The quick fix is to avoid to detach them on search but only once they
// received the results. But it means that in case of a stalled search
// all the derived helpers not detached yet register a new search inside
// the helper. The number grows fast in case of a bad network and it's
// not deterministic.
derivedHelper.detach();
});
derivedParameters.forEach(function (param) {
var indexId = param.indexId,
parameters = param.parameters;
var derivedHelper = helper.derive(function () {
return parameters;
});
derivedHelper
.on(
"result",
handleSearchSuccess({
indexId: indexId,
})
)
.on("error", handleSearchError);
});
helper.setState(mainParameters);
helper.search();
}
};
var handleSearchSuccess = function handleSearchSuccess(param) {
var indexId = param.indexId;
return function (event) {
var state = store.getState();
var isDerivedHelpersEmpty = !helper.derivedHelpers.length;
var results = state.results ? state.results : {};
// Switching from mono index to multi index and vice versa must reset the
// results to an empty object, otherwise we keep reference of stalled and
// unused results.
results =
!isDerivedHelpersEmpty && results.getFacetByName ? {} : results;
if (!isDerivedHelpersEmpty) {
results = swcHelpers.objectSpread(
{},
results,
swcHelpers.defineProperty({}, indexId, event.results)
);
} else {
results = event.results;
}
var currentState = store.getState();
var nextIsSearchStalled = currentState.isSearchStalled;
if (!helper.hasPendingRequests()) {
clearTimeout(stalledSearchTimer);
stalledSearchTimer = null;
nextIsSearchStalled = false;
}
var resultsFacetValues = currentState.resultsFacetValues,
partialState = swcHelpers.objectWithoutProperties(
currentState,
["resultsFacetValues"]
);
store.setState(
swcHelpers.objectSpread({}, partialState, {
results: results,
isSearchStalled: nextIsSearchStalled,
searching: false,
error: null,
})
);
};
};
var handleSearchError = function handleSearchError(param) {
var error = param.error;
var currentState = store.getState();
var nextIsSearchStalled = currentState.isSearchStalled;
if (!helper.hasPendingRequests()) {
clearTimeout(stalledSearchTimer);
nextIsSearchStalled = false;
}
var resultsFacetValues = currentState.resultsFacetValues,
partialState = swcHelpers.objectWithoutProperties(currentState, [
"resultsFacetValues",
]);
store.setState(
swcHelpers.objectSpread({}, partialState, {
isSearchStalled: nextIsSearchStalled,
error: error,
searching: false,
})
);
};
var handleNewSearch = function handleNewSearch() {
if (!stalledSearchTimer) {
stalledSearchTimer = setTimeout(function () {
var _ref = store.getState(),
resultsFacetValues = _ref.resultsFacetValues,
partialState = swcHelpers.objectWithoutProperties(_ref, [
"resultsFacetValues",
]);
store.setState(
swcHelpers.objectSpread({}, partialState, {
isSearchStalled: true,
})
);
}, stalledSearchDelay);
}
};
var hydrateSearchClient = function hydrateSearchClient(client, results) {
if (!results) {
return;
}
// Disable cache hydration on:
// - Algoliasearch API Client < v4 with cache disabled
// - Third party clients (detected by the `addAlgoliaAgent` function missing)
if (
(!client.transporter || client._cacheHydrated) &&
(!client._useCache || typeof client.addAlgoliaAgent !== "function")
) {
return;
}
// Algoliasearch API Client >= v4
// To hydrate the client we need to populate the cache with the data from
// the server (done in `hydrateSearchClientWithMultiIndexRequest` or
// `hydrateSearchClientWithSingleIndexRequest`). But since there is no way
// for us to compute the key the same way as `algoliasearch-client` we need
// to populate it on a custom key and override the `search` method to
// search on it first.
if (client.transporter && !client._cacheHydrated) {
client._cacheHydrated = true;
var baseMethod = client.search;
client.search = function (requests) {
for (
var _len = arguments.length,
methodArgs = new Array(_len > 1 ? _len - 1 : 0),
_key = 1;
_key < _len;
_key++
) {
methodArgs[_key - 1] = arguments[_key];
}
var requestsWithSerializedParams = requests.map(function (
request
) {
return swcHelpers.objectSpread({}, request, {
params: serializeQueryParameters(request.params),
});
});
return client.transporter.responsesCache.get(
{
method: "search",
args: [requestsWithSerializedParams].concat(
swcHelpers.toConsumableArray(methodArgs)
),
},
function () {
return baseMethod.apply(
void 0,
[requests].concat(
swcHelpers.toConsumableArray(methodArgs)
)
);
}
);
};
}
if (Array.isArray(results.results)) {
hydrateSearchClientWithMultiIndexRequest(client, results.results);
return;
}
hydrateSearchClientWithSingleIndexRequest(client, results);
};
var hydrateSearchClientWithMultiIndexRequest =
function hydrateSearchClientWithMultiIndexRequest(client, results) {
// Algoliasearch API Client >= v4
// Populate the cache with the data from the server
if (client.transporter) {
client.transporter.responsesCache.set(
{
method: "search",
args: [
results.reduce(function (acc, result) {
return acc.concat(
result.rawResults.map(function (request) {
return {
indexName: request.index,
params: request.params,
};
})
);
}, []),
],
},
{
results: results.reduce(function (acc, result) {
return acc.concat(result.rawResults);
}, []),
}
);
return;
}
// Algoliasearch API Client < v4
// Prior to client v4 we didn't have a proper API to hydrate the client
// cache from the outside. The following code populates the cache with
// a single-index result. You can find more information about the
// computation of the key inside the client (see link below).
// https://github.com/algolia/algoliasearch-client-javascript/blob/c27e89ff92b2a854ae6f40dc524bffe0f0cbc169/src/AlgoliaSearchCore.js#L232-L240
var key = "/1/indexes/*/queries_body_".concat(
JSON.stringify({
requests: results.reduce(function (acc, result) {
return acc.concat(
result.rawResults.map(function (request) {
return {
indexName: request.index,
params: request.params,
};
})
);
}, []),
})
);
client.cache = swcHelpers.objectSpread(
{},
client.cache,
swcHelpers.defineProperty(
{},
key,
JSON.stringify({
results: results.reduce(function (acc, result) {
return acc.concat(result.rawResults);
}, []),
})
)
);
};
var hydrateSearchClientWithSingleIndexRequest =
function hydrateSearchClientWithSingleIndexRequest(client, results) {
// Algoliasearch API Client >= v4
// Populate the cache with the data from the server
if (client.transporter) {
client.transporter.responsesCache.set(
{
method: "search",
args: [
results.rawResults.map(function (request) {
return {
indexName: request.index,
params: request.params,
};
}),
],
},
{
results: results.rawResults,
}
);
return;
}
// Algoliasearch API Client < v4
// Prior to client v4 we didn't have a proper API to hydrate the client
// cache from the outside. The following code populates the cache with
// a single-index result. You can find more information about the
// computation of the key inside the client (see link below).
// https://github.com/algolia/algoliasearch-client-javascript/blob/c27e89ff92b2a854ae6f40dc524bffe0f0cbc169/src/AlgoliaSearchCore.js#L232-L240
var key = "/1/indexes/*/queries_body_".concat(
JSON.stringify({
requests: results.rawResults.map(function (request) {
return {
indexName: request.index,
params: request.params,
};
}),
})
);
client.cache = swcHelpers.objectSpread(
{},
client.cache,
swcHelpers.defineProperty(
{},
key,
JSON.stringify({
results: results.rawResults,
})
)
);
};
var hydrateResultsState = function hydrateResultsState(results) {
if (!results) {
return null;
}
if (Array.isArray(results.results)) {
return results.results.reduce(function (acc, result) {
return swcHelpers.objectSpread(
{},
acc,
swcHelpers.defineProperty(
{},
result._internalIndexId,
new algoliasearchHelper.SearchResults(
new algoliasearchHelper.SearchParameters(
result.state
),
result.rawResults
)
)
);
}, {});
}
return new algoliasearchHelper.SearchResults(
new algoliasearchHelper.SearchParameters(results.state),
results.rawResults
);
};
var onWidgetsUpdate = // Called whenever a widget has been rendered with new props.
function onWidgetsUpdate() {
var metadata = getMetadata(store.getState().widgets);
store.setState(
swcHelpers.objectSpread({}, store.getState(), {
metadata: metadata,
searching: true,
})
);
// Since the `getSearchParameters` method of widgets also depends on props,
// the result search parameters might have changed.
search();
};
var transitionState = function transitionState(nextSearchState) {
var searchState = store.getState().widgets;
return widgetsManager
.getWidgets()
.filter(function (widget) {
return Boolean(widget.transitionState);
})
.reduce(function (res, widget) {
return widget.transitionState(searchState, res);
}, nextSearchState);
};
var onExternalStateUpdate = function onExternalStateUpdate(
nextSearchState
) {
var metadata = getMetadata(nextSearchState);
store.setState(
swcHelpers.objectSpread({}, store.getState(), {
widgets: nextSearchState,
metadata: metadata,
searching: true,
})
);
search();
};
var onSearchForFacetValues = function onSearchForFacetValues(param) {
var facetName = param.facetName,
query = param.query,
_maxFacetHits = param.maxFacetHits,
maxFacetHits = _maxFacetHits === void 0 ? 10 : _maxFacetHits;
// The values 1, 100 are the min / max values that the engine accepts.
// see: https://www.algolia.com/doc/api-reference/api-parameters/maxFacetHits
var maxFacetHitsWithinRange = Math.max(1, Math.min(maxFacetHits, 100));
store.setState(
swcHelpers.objectSpread({}, store.getState(), {
searchingForFacetValues: true,
})
);
helper
.searchForFacetValues(facetName, query, maxFacetHitsWithinRange)
.then(
function (content) {
store.setState(
swcHelpers.objectSpread({}, store.getState(), {
error: null,
searchingForFacetValues: false,
resultsFacetValues: swcHelpers.objectSpread(
{},
store.getState().resultsFacetValues,
((_obj = {}),
swcHelpers.defineProperty(
_obj,
facetName,
content.facetHits
),
swcHelpers.defineProperty(_obj, "query", query),
_obj)
),
})
);
},
function (error) {
store.setState(
swcHelpers.objectSpread({}, store.getState(), {
searchingForFacetValues: false,
error: error,
})
);
}
)
.catch(function (error) {
// Since setState is synchronous, any error that occurs in the render of a
// component will be swallowed by this promise.
// This is a trick to make the error show up correctly in the console.
// See http://stackoverflow.com/a/30741722/969302
setTimeout(function () {
throw error;
});
});
};
var updateIndex = function updateIndex(newIndex) {
initialSearchParameters = initialSearchParameters.setIndex(newIndex);
// No need to trigger a new search here as the widgets will also update and trigger it if needed.
};
var getWidgetsIds = function getWidgetsIds() {
return store.getState().metadata.reduce(function (res, meta) {
return typeof meta.id !== "undefined" ? res.concat(meta.id) : res;
}, []);
};
var helper = algoliasearchHelper(
searchClient,
indexName,
swcHelpers.objectSpread({}, HIGHLIGHT_TAGS)
);
addAlgoliaAgents(searchClient);
helper
.on("search", handleNewSearch)
.on(
"result",
handleSearchSuccess({
indexId: indexName,
})
)
.on("error", handleSearchError);
var skip = false;
var stalledSearchTimer = null;
var initialSearchParameters = helper.state;
var widgetsManager = createWidgetsManager(onWidgetsUpdate);
hydrateSearchClient(searchClient, resultsState);
var store = createStore({
widgets: initialState,
metadata: hydrateMetadata(resultsState),
results: hydrateResultsState(resultsState),
error: null,
searching: false,
isSearchStalled: true,
searchingForFacetValues: false,
});
return {
store: store,
widgetsManager: widgetsManager,
getWidgetsIds: getWidgetsIds,
getSearchParameters: getSearchParameters,
onSearchForFacetValues: onSearchForFacetValues,
onExternalStateUpdate: onExternalStateUpdate,
transitionState: transitionState,
updateClient: updateClient,
updateIndex: updateIndex,
clearCache: clearCache,
skipSearch: skipSearch,
};
}
function hydrateMetadata(resultsState) {
if (!resultsState) {
return [];
}
// add a value noop, which gets replaced once the widgets are mounted
return resultsState.metadata.map(function (datum) {
return swcHelpers.objectSpread(
{
value: function () {
return {};
},
},
datum,
{
items:
datum.items &&
datum.items.map(function (item) {
return swcHelpers.objectSpread(
{
value: function () {
return {};
},
},
item,
{
items:
item.items &&
item.items.map(function (nestedItem) {
return swcHelpers.objectSpread(
{
value: function () {
return {};
},
},
nestedItem
);
}),
}
);
}),
}
);
});
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_minifier/tests/fixture/issues/react-instancesearch/004/output.js | JavaScript | import * as swcHelpers from "@swc/helpers";
import algoliasearchHelper from "algoliasearch-helper";
import createWidgetsManager from "./createWidgetsManager";
import { HIGHLIGHT_TAGS } from "./highlight";
import { hasMultipleIndices } from "./indexUtils";
import { version as ReactVersion } from "react";
import version from "./version";
function addAlgoliaAgents(searchClient) {
"function" == typeof searchClient.addAlgoliaAgent && (searchClient.addAlgoliaAgent("react (".concat(ReactVersion, ")")), searchClient.addAlgoliaAgent("react-instantsearch (".concat(version, ")")));
}
var _obj, isMultiIndexContext = function(widget) {
return hasMultipleIndices({
ais: widget.props.contextValue,
multiIndexContext: widget.props.indexContextValue
});
}, isTargetedIndexEqualIndex = function(widget, indexId) {
return widget.props.indexContextValue.targetedIndex === indexId;
}, isIndexWidget = function(widget) {
return !!widget.props.indexId;
}, isIndexWidgetEqualIndex = function(widget, indexId) {
return widget.props.indexId === indexId;
}, sortIndexWidgetsFirst = function(firstWidget, secondWidget) {
var isFirstWidgetIndex = isIndexWidget(firstWidget), isSecondWidgetIndex = isIndexWidget(secondWidget);
return isFirstWidgetIndex && !isSecondWidgetIndex ? -1 : !isFirstWidgetIndex && isSecondWidgetIndex ? 1 : 0;
};
/**
* Creates a new instance of the InstantSearchManager which controls the widgets and
* trigger the search when the widgets are updated.
* @param {string} indexName - the main index name
* @param {object} initialState - initial widget state
* @param {object} SearchParameters - optional additional parameters to send to the algolia API
* @param {number} stalledSearchDelay - time (in ms) after the search is stalled
* @return {InstantSearchManager} a new instance of InstantSearchManager
*/ export default function createInstantSearchManager(param) {
var state, listeners, indexName = param.indexName, _initialState = param.initialState, searchClient = param.searchClient, resultsState = param.resultsState, stalledSearchDelay = param.stalledSearchDelay, getMetadata = function(state) {
return widgetsManager.getWidgets().filter(function(widget) {
return !!widget.getMetadata;
}).map(function(widget) {
return widget.getMetadata(state);
});
}, getSearchParameters = function() {
var sharedParameters = widgetsManager.getWidgets().filter(function(widget) {
return !!widget.getSearchParameters;
}).filter(function(widget) {
return !isMultiIndexContext(widget) && !isIndexWidget(widget);
}).reduce(function(res, widget) {
return widget.getSearchParameters(res);
}, initialSearchParameters), mainParameters = widgetsManager.getWidgets().filter(function(widget) {
return !!widget.getSearchParameters;
}).filter(function(widget) {
var targetedIndexEqualMainIndex = isMultiIndexContext(widget) && isTargetedIndexEqualIndex(widget, indexName), subIndexEqualMainIndex = isIndexWidget(widget) && isIndexWidgetEqualIndex(widget, indexName);
return targetedIndexEqualMainIndex || subIndexEqualMainIndex;
}) // We have to sort the `Index` widgets first so the `index` parameter
// is correctly set in the `reduce` function for the following widgets
.sort(sortIndexWidgetsFirst).reduce(function(res, widget) {
return widget.getSearchParameters(res);
}, sharedParameters), derivedIndices = widgetsManager.getWidgets().filter(function(widget) {
return !!widget.getSearchParameters;
}).filter(function(widget) {
var targetedIndexNotEqualMainIndex = isMultiIndexContext(widget) && !isTargetedIndexEqualIndex(widget, indexName), subIndexNotEqualMainIndex = isIndexWidget(widget) && !isIndexWidgetEqualIndex(widget, indexName);
return targetedIndexNotEqualMainIndex || subIndexNotEqualMainIndex;
}) // We have to sort the `Index` widgets first so the `index` parameter
// is correctly set in the `reduce` function for the following widgets
.sort(sortIndexWidgetsFirst).reduce(function(indices, widget) {
var indexId = isMultiIndexContext(widget) ? widget.props.indexContextValue.targetedIndex : widget.props.indexId, widgets = indices[indexId] || [];
return swcHelpers.objectSpread({}, indices, swcHelpers.defineProperty({}, indexId, widgets.concat(widget)));
}, {});
return {
mainParameters: mainParameters,
derivedParameters: Object.keys(derivedIndices).map(function(indexId) {
return {
parameters: derivedIndices[indexId].reduce(function(res, widget) {
return widget.getSearchParameters(res);
}, sharedParameters),
indexId: indexId
};
})
};
}, search = function() {
if (!skip) {
var ref = getSearchParameters(helper.state), mainParameters = ref.mainParameters, derivedParameters = ref.derivedParameters;
// We have to call `slice` because the method `detach` on the derived
// helpers mutates the value `derivedHelpers`. The `forEach` loop does
// not iterate on each value and we're not able to correctly clear the
// previous derived helpers (memory leak + useless requests).
helper.derivedHelpers.slice().forEach(function(derivedHelper) {
// Since we detach the derived helpers on **every** new search they
// won't receive intermediate results in case of a stalled search.
// Only the last result is dispatched by the derived helper because
// they are not detached yet:
//
// - a -> main helper receives results
// - ap -> main helper receives results
// - app -> main helper + derived helpers receive results
//
// The quick fix is to avoid to detach them on search but only once they
// received the results. But it means that in case of a stalled search
// all the derived helpers not detached yet register a new search inside
// the helper. The number grows fast in case of a bad network and it's
// not deterministic.
derivedHelper.detach();
}), derivedParameters.forEach(function(param) {
var indexId = param.indexId, parameters = param.parameters;
helper.derive(function() {
return parameters;
}).on("result", handleSearchSuccess({
indexId: indexId
})).on("error", handleSearchError);
}), helper.setState(mainParameters), helper.search();
}
}, handleSearchSuccess = function(param) {
var indexId = param.indexId;
return function(event) {
var state = store.getState(), isDerivedHelpersEmpty = !helper.derivedHelpers.length, results = state.results ? state.results : {};
// Switching from mono index to multi index and vice versa must reset the
// results to an empty object, otherwise we keep reference of stalled and
// unused results.
results = !isDerivedHelpersEmpty && results.getFacetByName ? {} : results, results = isDerivedHelpersEmpty ? event.results : swcHelpers.objectSpread({}, results, swcHelpers.defineProperty({}, indexId, event.results));
var currentState = store.getState(), nextIsSearchStalled = currentState.isSearchStalled;
helper.hasPendingRequests() || (clearTimeout(stalledSearchTimer), stalledSearchTimer = null, nextIsSearchStalled = !1), currentState.resultsFacetValues;
var partialState = swcHelpers.objectWithoutProperties(currentState, [
"resultsFacetValues"
]);
store.setState(swcHelpers.objectSpread({}, partialState, {
results: results,
isSearchStalled: nextIsSearchStalled,
searching: !1,
error: null
}));
};
}, handleSearchError = function(param) {
var error = param.error, currentState = store.getState(), nextIsSearchStalled = currentState.isSearchStalled;
helper.hasPendingRequests() || (clearTimeout(stalledSearchTimer), nextIsSearchStalled = !1), currentState.resultsFacetValues;
var partialState = swcHelpers.objectWithoutProperties(currentState, [
"resultsFacetValues"
]);
store.setState(swcHelpers.objectSpread({}, partialState, {
isSearchStalled: nextIsSearchStalled,
error: error,
searching: !1
}));
}, hydrateSearchClientWithMultiIndexRequest = function(client, results) {
// Algoliasearch API Client >= v4
// Populate the cache with the data from the server
if (client.transporter) {
client.transporter.responsesCache.set({
method: "search",
args: [
results.reduce(function(acc, result) {
return acc.concat(result.rawResults.map(function(request) {
return {
indexName: request.index,
params: request.params
};
}));
}, [])
]
}, {
results: results.reduce(function(acc, result) {
return acc.concat(result.rawResults);
}, [])
});
return;
}
// Algoliasearch API Client < v4
// Prior to client v4 we didn't have a proper API to hydrate the client
// cache from the outside. The following code populates the cache with
// a single-index result. You can find more information about the
// computation of the key inside the client (see link below).
// https://github.com/algolia/algoliasearch-client-javascript/blob/c27e89ff92b2a854ae6f40dc524bffe0f0cbc169/src/AlgoliaSearchCore.js#L232-L240
var key = "/1/indexes/*/queries_body_".concat(JSON.stringify({
requests: results.reduce(function(acc, result) {
return acc.concat(result.rawResults.map(function(request) {
return {
indexName: request.index,
params: request.params
};
}));
}, [])
}));
client.cache = swcHelpers.objectSpread({}, client.cache, swcHelpers.defineProperty({}, key, JSON.stringify({
results: results.reduce(function(acc, result) {
return acc.concat(result.rawResults);
}, [])
})));
}, hydrateSearchClientWithSingleIndexRequest = function(client, results) {
// Algoliasearch API Client >= v4
// Populate the cache with the data from the server
if (client.transporter) {
client.transporter.responsesCache.set({
method: "search",
args: [
results.rawResults.map(function(request) {
return {
indexName: request.index,
params: request.params
};
})
]
}, {
results: results.rawResults
});
return;
}
// Algoliasearch API Client < v4
// Prior to client v4 we didn't have a proper API to hydrate the client
// cache from the outside. The following code populates the cache with
// a single-index result. You can find more information about the
// computation of the key inside the client (see link below).
// https://github.com/algolia/algoliasearch-client-javascript/blob/c27e89ff92b2a854ae6f40dc524bffe0f0cbc169/src/AlgoliaSearchCore.js#L232-L240
var key = "/1/indexes/*/queries_body_".concat(JSON.stringify({
requests: results.rawResults.map(function(request) {
return {
indexName: request.index,
params: request.params
};
})
}));
client.cache = swcHelpers.objectSpread({}, client.cache, swcHelpers.defineProperty({}, key, JSON.stringify({
results: results.rawResults
})));
}, helper = algoliasearchHelper(searchClient, indexName, swcHelpers.objectSpread({}, HIGHLIGHT_TAGS));
addAlgoliaAgents(searchClient), helper.on("search", function() {
stalledSearchTimer || (stalledSearchTimer = setTimeout(function() {
var _ref = store.getState(), partialState = (_ref.resultsFacetValues, swcHelpers.objectWithoutProperties(_ref, [
"resultsFacetValues"
]));
store.setState(swcHelpers.objectSpread({}, partialState, {
isSearchStalled: !0
}));
}, stalledSearchDelay));
}).on("result", handleSearchSuccess({
indexId: indexName
})).on("error", handleSearchError);
var skip = !1, stalledSearchTimer = null, initialSearchParameters = helper.state, widgetsManager = createWidgetsManager(function() {
var metadata = getMetadata(store.getState().widgets);
store.setState(swcHelpers.objectSpread({}, store.getState(), {
metadata: metadata,
searching: !0
})), // Since the `getSearchParameters` method of widgets also depends on props,
// the result search parameters might have changed.
search();
});
!function(client, results) {
if (results && (client.transporter && !client._cacheHydrated || client._useCache && "function" == typeof client.addAlgoliaAgent)) {
// Algoliasearch API Client >= v4
// To hydrate the client we need to populate the cache with the data from
// the server (done in `hydrateSearchClientWithMultiIndexRequest` or
// `hydrateSearchClientWithSingleIndexRequest`). But since there is no way
// for us to compute the key the same way as `algoliasearch-client` we need
// to populate it on a custom key and override the `search` method to
// search on it first.
if (client.transporter && !client._cacheHydrated) {
client._cacheHydrated = !0;
var baseMethod = client.search;
client.search = function(requests) {
for(var _len = arguments.length, methodArgs = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++)methodArgs[_key - 1] = arguments[_key];
var requestsWithSerializedParams = requests.map(function(request) {
var parameters, encode;
return swcHelpers.objectSpread({}, request, {
params: (parameters = request.params, encode = function(format) {
for(var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++)args[_key - 1] = arguments[_key];
var i = 0;
return format.replace(/%s/g, function() {
return encodeURIComponent(args[i++]);
});
}, Object.keys(parameters).map(function(key) {
var value;
return encode("%s=%s", key, (value = parameters[key], "[object Object]" === Object.prototype.toString.call(value) || "[object Array]" === Object.prototype.toString.call(value)) ? JSON.stringify(parameters[key]) : parameters[key]);
}).join("&"))
});
});
return client.transporter.responsesCache.get({
method: "search",
args: [
requestsWithSerializedParams
].concat(swcHelpers.toConsumableArray(methodArgs))
}, function() {
return baseMethod.apply(void 0, [
requests
].concat(swcHelpers.toConsumableArray(methodArgs)));
});
};
}
if (Array.isArray(results.results)) {
hydrateSearchClientWithMultiIndexRequest(client, results.results);
return;
}
hydrateSearchClientWithSingleIndexRequest(client, results);
}
}(searchClient, resultsState);
var store = (state = {
widgets: void 0 === _initialState ? {} : _initialState,
metadata: resultsState ? resultsState.metadata.map(function(datum) {
return swcHelpers.objectSpread({
value: function() {
return {};
}
}, datum, {
items: datum.items && datum.items.map(function(item) {
return swcHelpers.objectSpread({
value: function() {
return {};
}
}, item, {
items: item.items && item.items.map(function(nestedItem) {
return swcHelpers.objectSpread({
value: function() {
return {};
}
}, nestedItem);
})
});
})
});
}) : [],
results: resultsState ? Array.isArray(resultsState.results) ? resultsState.results.reduce(function(acc, result) {
return swcHelpers.objectSpread({}, acc, swcHelpers.defineProperty({}, result._internalIndexId, new algoliasearchHelper.SearchResults(new algoliasearchHelper.SearchParameters(result.state), result.rawResults)));
}, {}) : new algoliasearchHelper.SearchResults(new algoliasearchHelper.SearchParameters(resultsState.state), resultsState.rawResults) : null,
error: null,
searching: !1,
isSearchStalled: !0,
searchingForFacetValues: !1
}, listeners = [], {
getState: function() {
return state;
},
setState: function(nextState) {
state = nextState, listeners.forEach(function(listener) {
return listener();
});
},
subscribe: function(listener) {
return listeners.push(listener), function() {
listeners.splice(listeners.indexOf(listener), 1);
};
}
});
return {
store: store,
widgetsManager: widgetsManager,
getWidgetsIds: function() {
return store.getState().metadata.reduce(function(res, meta) {
return void 0 !== meta.id ? res.concat(meta.id) : res;
}, []);
},
getSearchParameters: getSearchParameters,
onSearchForFacetValues: function(param) {
var facetName = param.facetName, query = param.query, _maxFacetHits = param.maxFacetHits, maxFacetHitsWithinRange = Math.max(1, Math.min(void 0 === _maxFacetHits ? 10 : _maxFacetHits, 100));
store.setState(swcHelpers.objectSpread({}, store.getState(), {
searchingForFacetValues: !0
})), helper.searchForFacetValues(facetName, query, maxFacetHitsWithinRange).then(function(content) {
store.setState(swcHelpers.objectSpread({}, store.getState(), {
error: null,
searchingForFacetValues: !1,
resultsFacetValues: swcHelpers.objectSpread({}, store.getState().resultsFacetValues, (_obj = {}, swcHelpers.defineProperty(_obj, facetName, content.facetHits), swcHelpers.defineProperty(_obj, "query", query), _obj))
}));
}, function(error) {
store.setState(swcHelpers.objectSpread({}, store.getState(), {
searchingForFacetValues: !1,
error: error
}));
}).catch(function(error) {
// Since setState is synchronous, any error that occurs in the render of a
// component will be swallowed by this promise.
// This is a trick to make the error show up correctly in the console.
// See http://stackoverflow.com/a/30741722/969302
setTimeout(function() {
throw error;
});
});
},
onExternalStateUpdate: function(nextSearchState) {
var metadata = getMetadata(nextSearchState);
store.setState(swcHelpers.objectSpread({}, store.getState(), {
widgets: nextSearchState,
metadata: metadata,
searching: !0
})), search();
},
transitionState: function(nextSearchState) {
var searchState = store.getState().widgets;
return widgetsManager.getWidgets().filter(function(widget) {
return !!widget.transitionState;
}).reduce(function(res, widget) {
return widget.transitionState(searchState, res);
}, nextSearchState);
},
updateClient: function(client) {
addAlgoliaAgents(client), helper.setClient(client), search();
},
updateIndex: function(newIndex) {
initialSearchParameters = initialSearchParameters.setIndex(newIndex);
// No need to trigger a new search here as the widgets will also update and trigger it if needed.
},
clearCache: function() {
helper.clearCache(), search();
},
skipSearch: function() {
skip = !0;
}
};
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_minifier/tests/fixture/issues/react/hooks/1/input.js | JavaScript | import { jsx as _jsx, Fragment as _Fragment } from "react/jsx-runtime";
import { useRouter } from "next/router";
import { useProject } from "@swr/use-project";
import useTeam from "@swr/use-team";
export default function MyComp() {
var _query = useRouter().query,
projectName = _query.project;
var ref = useProject(projectName),
projectInfo = ref.data;
var ref1 = useTeam(),
teamSlug = ref1.teamSlug;
var projectId =
projectInfo === null || projectInfo === void 0
? void 0
: projectInfo.id;
var ref2 = useProjectBranches(projectId),
branches = ref2.data;
return /*#__PURE__*/ _jsx(_Fragment, {});
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_minifier/tests/fixture/issues/react/hooks/1/output.js | JavaScript | import { jsx as _jsx, Fragment as _Fragment } from "react/jsx-runtime";
import { useRouter } from "next/router";
import { useProject } from "@swr/use-project";
import useTeam from "@swr/use-team";
export default function MyComp() {
var projectInfo = useProject(useRouter().query.project).data;
return useTeam().teamSlug, useProjectBranches(null == projectInfo ? void 0 : projectInfo.id).data, /*#__PURE__*/ _jsx(_Fragment, {});
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_minifier/tests/fixture/issues/react/hooks/2/input.js | JavaScript | function useProjectBranches(projectId, opts) {
var token = (0, authenticate /* getToken */.LP)();
var ref = (0, use_team /* default */.ZP)(),
team = ref.team;
var teamId = team === null || team === void 0 ? void 0 : team.id;
return (0, index_esm /* default */.ZP)(
projectId
? ""
.concat(
api_endpoints /* API_INTEGRATION_CONTROLLER */.Ms,
"/git-branches"
)
.concat(
(0, qs /* encode */.c)({
projectId: projectId,
teamId: teamId,
})
)
: "",
function (endpoint) {
return (0, fetch_api /* default */.Z)(endpoint, token, {
throwOnHTTPError: true,
});
},
opts
);
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_minifier/tests/fixture/issues/react/hooks/3/input.js | JavaScript | "use strict";
__webpack_require__.d(__webpack_exports__, {
Z: function () {
return /* binding */ EnvironmentsSelector;
},
});
var router = __webpack_require__(86677);
var index_esm = __webpack_require__(45205);
var use_team = __webpack_require__(502);
var fetch_api = __webpack_require__(78869);
var authenticate = __webpack_require__(16966);
var api_endpoints = __webpack_require__(96236);
var qs = __webpack_require__(70326);
function useProjectBranches(projectId, opts) {
var token = (0, authenticate /* getToken */.LP)();
var ref = (0, use_team /* default */.ZP)(),
team = ref.team;
var teamId = team === null || team === void 0 ? void 0 : team.id;
return (0, index_esm /* default */.ZP)(
projectId
? ""
.concat(
api_endpoints /* API_INTEGRATION_CONTROLLER */.Ms,
"/git-branches"
)
.concat(
(0, qs /* encode */.c)({
projectId: projectId,
teamId: teamId,
})
)
: "",
function (endpoint) {
return (0, fetch_api /* default */.Z)(endpoint, token, {
throwOnHTTPError: true,
});
},
opts
);
}
var use_project = __webpack_require__(76246);
export function EnvironmentsSelector(param) {
var _query = (0, router.useRouter)().query,
projectName = _query.project;
var ref = (0, use_project.useProject)(projectName),
projectInfo = ref.data;
var ref1 = (0, use_team /* default */.ZP)(),
teamSlug = ref1.teamSlug;
var projectId =
projectInfo === null || projectInfo === void 0
? void 0
: projectInfo.id;
var ref2 = useProjectBranches(projectId),
branches = ref2.data;
return {};
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_minifier/tests/fixture/issues/react/hooks/3/output.js | JavaScript | "use strict";
__webpack_require__.d(__webpack_exports__, {
Z: function() {
return /* binding */ EnvironmentsSelector;
}
});
var router = __webpack_require__(86677), index_esm = __webpack_require__(45205), use_team = __webpack_require__(502), fetch_api = __webpack_require__(78869), authenticate = __webpack_require__(16966), api_endpoints = __webpack_require__(96236), qs = __webpack_require__(70326), use_project = __webpack_require__(76246);
export function EnvironmentsSelector(param) {
var projectId, token, team, teamId, projectName = (0, router.useRouter)().query.project, projectInfo = (0, use_project.useProject)(projectName).data;
return (0, use_team /* default */ .ZP)().teamSlug, (projectId = null == projectInfo ? void 0 : projectInfo.id, token = (0, authenticate /* getToken */ .LP)(), teamId = null == (team = (0, use_team /* default */ .ZP)().team) ? void 0 : team.id, (0, index_esm /* default */ .ZP)(projectId ? "".concat(api_endpoints /* API_INTEGRATION_CONTROLLER */ .Ms, "/git-branches").concat((0, qs /* encode */ .c)({
projectId: projectId,
teamId: teamId
})) : "", function(endpoint) {
return (0, fetch_api /* default */ .Z)(endpoint, token, {
throwOnHTTPError: !0
});
}, void 0)).data, {};
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_minifier/tests/fixture/issues/react/hooks/4/input.js | JavaScript | "use strict";
var router = __webpack_require__(86677);
var index_esm = __webpack_require__(45205);
var use_team = __webpack_require__(502);
var fetch_api = __webpack_require__(78869);
var authenticate = __webpack_require__(16966);
var api_endpoints = __webpack_require__(96236);
var qs = __webpack_require__(70326);
export function useProjectBranches(projectId, opts) {
var token = (0, authenticate /* getToken */.LP)();
var ref = (0, use_team /* default */.ZP)(),
team = ref.team;
var teamId = team === null || team === void 0 ? void 0 : team.id;
return (0, index_esm /* default */.ZP)(
projectId
? ""
.concat(
api_endpoints /* API_INTEGRATION_CONTROLLER */.Ms,
"/git-branches"
)
.concat(
(0, qs /* encode */.c)({
projectId: projectId,
teamId: teamId,
})
)
: "",
function (endpoint) {
return (0, fetch_api /* default */.Z)(endpoint, token, {
throwOnHTTPError: true,
});
},
opts
);
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_minifier/tests/fixture/issues/react/hooks/4/output.js | JavaScript | "use strict";
__webpack_require__(86677);
var index_esm = __webpack_require__(45205), use_team = __webpack_require__(502), fetch_api = __webpack_require__(78869), authenticate = __webpack_require__(16966), api_endpoints = __webpack_require__(96236), qs = __webpack_require__(70326);
export function useProjectBranches(projectId, opts) {
var token = (0, authenticate /* getToken */ .LP)(), team = (0, use_team /* default */ .ZP)().team, teamId = null == team ? void 0 : team.id;
return (0, index_esm /* default */ .ZP)(projectId ? "".concat(api_endpoints /* API_INTEGRATION_CONTROLLER */ .Ms, "/git-branches").concat((0, qs /* encode */ .c)({
projectId: projectId,
teamId: teamId
})) : "", function(endpoint) {
return (0, fetch_api /* default */ .Z)(endpoint, token, {
throwOnHTTPError: !0
});
}, opts);
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_minifier/tests/fixture/issues/react/hooks/5/input.js | JavaScript | const CONST_1 = "const1";
const CONST_2 = "const2";
function useHook1() {
const [v1, v1_set] = useState(undefined);
useEffect(() => {
if (GLOBALS.get(CONST_1) && GLOBALS.get(CONST_2)) {
v1_set(true);
} else {
v1_set(false);
}
}, []);
return v1;
}
function useHook2() {
const [a1, a1_set] = useState({});
useEffect(() => {
a1_set(JSON.parse(GLOBALS.get(CONST1) || "{}"));
}, []);
return a1;
}
export function HeaderCTA() {
const varB = useHook2();
const varA = useHook1();
// Loading...
if (varA === undefined) {
return null;
}
if (varA) {
return use(varB.field);
}
return pure();
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_minifier/tests/fixture/issues/react/hooks/5/output.js | JavaScript | export function HeaderCTA() {
const varB = function() {
const [a1, a1_set] = useState({});
return useEffect(()=>{
a1_set(JSON.parse(GLOBALS.get(CONST1) || "{}"));
}, []), a1;
}(), varA = function() {
const [v1, v1_set] = useState(void 0);
return useEffect(()=>{
GLOBALS.get("const1") && GLOBALS.get("const2") ? v1_set(!0) : v1_set(!1);
}, []), v1;
}();
return(// Loading...
void 0 === varA ? null : varA ? use(varB.field) : pure());
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.